---
title: Actions
description: Handle button clicks and interactive card events across platforms.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/cards
related:
  - /docs/modals
  - /docs/approvals
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Actions let you handle button clicks, dropdown selections, and other interactive events from [cards](/docs/cards). Register handlers with `onAction` to respond when users interact with your cards.

## Handle a specific action

```typescript title="lib/bot.ts" lineNumbers
bot.onAction("approve", async (event) => {
  await event.thread.post(`Order approved by ${event.user.fullName}!`);
});
```

## Handle multiple actions

```typescript title="lib/bot.ts" lineNumbers
bot.onAction(["approve", "reject"], async (event) => {
  const action = event.actionId === "approve" ? "approved" : "rejected";
  await event.thread.post(`Order ${action} by ${event.user.fullName}`);
});
```

## Catch-all handler

Register a handler without an action ID to catch all actions:

```typescript title="lib/bot.ts" lineNumbers
bot.onAction(async (event) => {
  console.log(`Action: ${event.actionId}, Value: ${event.value}`);
});
```

## ActionEvent

The `event` object passed to action handlers:

| Property    | Type                                                  | Description                                                                        |
| ----------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `actionId`  | `string`                                              | The `id` from the Button or Select component                                       |
| `value`     | `string` (optional)                                   | The `value` from the Button or selected option                                     |
| `user`      | `Author`                                              | The user who clicked                                                               |
| `thread`    | `Thread \| null`                                      | The thread containing the card (null for view-based actions like home tab buttons) |
| `messageId` | `string`                                              | The message containing the card                                                    |
| `threadId`  | `string`                                              | Thread ID                                                                          |
| `adapter`   | `Adapter`                                             | The platform adapter                                                               |
| `triggerId` | `string` (optional)                                   | Platform trigger ID (used for opening modals)                                      |
| `openModal` | `(modal) => Promise<{ viewId: string } \| undefined>` | Open a modal dialog. Resolves to `undefined` if the adapter doesn't support modals |
| `values`    | `Record<string, string>` (optional)                   | The card's own input values, keyed by input ID                                     |
| `raw`       | `unknown`                                             | Platform-specific event payload                                                    |

## Pass data with buttons

Use the `value` prop on buttons to pass extra context to your handler:

```tsx title="lib/bot.tsx"
<Button id="report" value="bug">Report Bug</Button>
<Button id="report" value="feature">Request Feature</Button>
```

```typescript title="lib/bot.ts" lineNumbers
bot.onAction("report", async (event) => {
  if (event.value === "bug") {
    // Open bug report flow
  } else if (event.value === "feature") {
    // Open feature request flow
  }
});
```

## Read a text box on the card

On Teams, a card can carry a [`TextInput`](/docs/cards). What the user typed arrives on the action as `event.values`, keyed by input ID, in the same shape as `ModalSubmitEvent.values`:

```tsx title="lib/bot.tsx" lineNumbers
<Card title="Deploy to production?">
  <TextInput id="notes" label="Notes" multiline optional />
  <Actions>
    <Button id="approve" style="primary">Approve</Button>
  </Actions>
</Card>
```

```typescript title="lib/bot.ts" lineNumbers
bot.onAction("approve", async (event) => {
  const notes = event.values?.notes?.trim().slice(0, 500) ?? "";
  await recordApproval({ userId: event.user.userId, notes });
  await event.thread?.post("Approved");
});
```

`recordApproval` stands in for your own storage or deploy logic. `values` is absent on platforms that cannot put an input on a card, and on cards that have none.

Treat `event.values` as untrusted user input. Teams enforces `optional` and `maxLength` in its own UI, but a value can still arrive missing, empty, or longer than the limit, so validate it in the handler. If you post a value back into the thread, the platform renders any markdown the user typed, such as a link, in a message that appears to come from the bot. Wrapping the value in a code span or sending it as `{ raw }` does not prevent this, so store or process the value instead of echoing it.

## Open a modal from an action

Use `event.openModal()` to open a [modal](/docs/modals) in response to a button click:

```tsx title="lib/bot.tsx" lineNumbers
import { Modal, TextInput, Select, SelectOption } from "chat";

bot.onAction("feedback", async (event) => {
  await event.openModal(
    <Modal callbackId="feedback_form" title="Send Feedback" submitLabel="Send">
      <TextInput id="message" label="Your Feedback" multiline />
      <Select id="category" label="Category">
        <SelectOption label="Bug" value="bug" />
        <SelectOption label="Feature" value="feature" />
      </Select>
    </Modal>
  );
});
```

> Only the Slack and Teams adapters support modals. On other platforms, `event.openModal()`
> logs a warning and resolves to `undefined` without opening anything.

## Callback URLs

Buttons accept a `callbackUrl` prop. When a user clicks the button, the action data is POSTed to that URL in addition to firing any `onAction` handler. With a webhook-based workflow engine, you can build approval flows without an `onAction` handler:

```tsx title="lib/bot.tsx" lineNumbers
bot.onNewMention(async (thread) => {
  const approveUrl = "https://example.com/webhook/approve";
  const denyUrl = "https://example.com/webhook/deny";

  await thread.post(
    <Card title="Deploy v2.4.1?">
      <Actions>
        <Button callbackUrl={approveUrl} id="approve" style="primary">
          Approve
        </Button>
        <Button callbackUrl={denyUrl} id="deny" style="danger">
          Deny
        </Button>
      </Actions>
    </Card>
  );
});
```

Callback tokens are bound to the button action and conversation, expire after seven days, and are consumed on first use. A repeated click or an attempt to move the token to another conversation does not trigger the callback URL again.

### Callback payload

The POST body sent to the `callbackUrl`:

```json
{
  "type": "action",
  "actionId": "approve",
  "user": { "id": "U123", "name": "alice" },
  "threadId": "slack:C123:1234567890.123",
  "messageId": "1234567890.456",
  "receipt": "3f2b8c1e-5d4a-4e7b-9c6f-1a2b3c4d5e6f"
}
```

If the button also has a `value` prop, it is included in the payload as `"value"`.

If the card carried inputs, the payload includes what the user typed as `"values"`, keyed by input ID. This is the same object the handler reads as `event.values`, and it is omitted when the card has no inputs:

```json
{
  "type": "action",
  "actionId": "approve",
  "values": { "notes": "ship it" },
  "user": { "id": "U123", "name": "alice" },
  "threadId": "teams:MTk6YWJjMTIzQHRocmVhZC50YWN2Mg:aHR0cHM6Ly9zbWJhLnRyYWZmaWNtYW5hZ2VyLm5ldC9hbWVyLw",
  "messageId": "1700000012345",
  "receipt": "8a7d6c5b-4e3f-4a2b-8c1d-0e9f8a7b6c5d"
}
```

`receipt` is an opaque identifier for a record of the click that Chat SDK stores in your state adapter for 24 hours, built from the platform's verified event rather than from this body. If Chat SDK can't store the receipt, it doesn't call the callback URL, and the button keeps working so the user can click again. Anyone who knows a callback URL can POST to it, so a request arriving at the URL doesn't prove that someone clicked the button, and a receiver that acts on who clicked shouldn't trust fields like `user` or `actionId` from the body. For approvals, use [`requestApproval`](/docs/approvals#who-can-approve), which redeems the receipt and verifies each click for you. Chat SDK doesn't export a way to redeem receipts in your own receivers.

> Platform limits apply to encoded button data. Discord's `custom_id` has a
> 100-character limit, and posting the card throws a `ValidationError` if the
> action ID plus callback token exceed it. Telegram's `callback_data` has a
> 64-byte limit, and buttons that exceed it also throw a `ValidationError`. Keep
> action IDs short when using `callbackUrl` on these platforms.

For modals, see [callbackUrl on modals](/docs/modals#callback-urls).

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Adapter Catalog
description: "Use @chat-adapter/catalog to list Chat SDK adapters, check their capabilities, and read setup requirements without importing adapter packages."
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
prerequisites:
  - /docs/adapters
related:
  - /docs/platform-adapters
  - /docs/state-adapters
  - /docs/create-chat-sdk
  - /docs/contributing/publishing
  - /docs/contributing/vendor-official
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`@chat-adapter/catalog` is a static catalog of every adapter listed on chat-sdk.dev: official, vendor-official, and community. It imports no adapter packages, so you can use it from websites, setup screens, build scripts, or onboarding flows without pulling in Slack, Teams, Redis, or other platform SDKs. The [Adapters](/adapters) page and [`create-chat-sdk`](/docs/create-chat-sdk) both read from it.

> The `chat/adapters` subpath is deprecated. It re-exports the original official and vendor-official API from `@chat-adapter/catalog`, so existing imports keep working. Import from `@chat-adapter/catalog` in new code.

## Install

```bash
pnpm add @chat-adapter/catalog
```

## List adapters

List adapters and check what each one supports:

```typescript title="scripts/list-adapters.ts" lineNumbers
import { getFeatureSupport, listAdapters } from "@chat-adapter/catalog";

for (const adapter of listAdapters({ type: "platform" })) {
  const streaming = getFeatureSupport(adapter, "streaming");
  console.log(adapter.name, adapter.group, adapter.packageName, streaming);
}
```

`listAdapters()` returns official and vendor-official adapters in the order the Adapters page lists them, followed by community adapters. Pass `group` or `type` to filter the list.

## Read setup requirements

Official and vendor-official entries also describe setup. Use the env helpers when you need to show setup instructions or inject secrets for one adapter:

```typescript lineNumbers
import { getAdapter, getSecretEnvVars } from "@chat-adapter/catalog";

const slack = getAdapter("slack");
const secrets = getSecretEnvVars("slack").map((envVar) => envVar.key);

console.log(slack.name, slack.factoryExport, secrets);
```

Community entries carry listing metadata and capabilities only, so `listEnvVars()` and `getSecretEnvVars()` return an empty array for them.

## Capabilities

Each entry's `features` field records which Chat SDK capabilities the adapter supports. These are the same values the feature tables on each adapter page show. A value is either a status (`"yes"`, `"no"`, or `"partial"`) or an object with a `status` and a short `label`, such as `{ status: "yes", label: "Native" }`. Omitted keys mean `"no"`.

`getFeatureSupport(adapterOrSlug, key)` always returns the object form. `PLATFORM_FEATURE_CATEGORIES` and `STATE_FEATURE_CATEGORIES` list every capability key with a display label, grouped the way the docs tables group them. `getFeatureCategories(type)` returns the categories for `"platform"` or `"state"`.

## Environment specs

Each official and vendor-official entry includes an `env` spec:

- `required` lists variables needed regardless of auth mode.
- `credentialModes` groups mutually exclusive ways to authenticate, such as a bot token or OAuth client credentials.
- `optional` lists tuning variables that are safe to omit.
- `config` lists constructor options that do not have an environment-variable equivalent.

## Types

Official and vendor-official entries are `CatalogAdapter` objects, and community entries are `CommunityAdapter` objects. `CatalogEntry` is the union of the two. Both share these fields:

| Property      | Type                                             | Description                                                                            |
| ------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------- |
| `slug`        | `string`                                         | Stable catalog slug. Matches the key in \`ADAPTERS\` or \`COMMUNITY\_ADAPTERS\`.       |
| `name`        | `string`                                         | Display name.                                                                          |
| `description` | `string`                                         | One-line summary of what the adapter connects to.                                      |
| `packageName` | `string`                                         | npm package that provides the adapter implementation.                                  |
| `type`        | `"platform" \| "state"`                          | Whether the adapter connects to a platform or stores Chat SDK state.                   |
| `group`       | `"official" \| "vendor-official" \| "community"` | Who maintains the adapter. \`CatalogAdapter\` entries are official or vendor-official. |
| `author`      | `string`                                         | Maintainer of a vendor-official or community adapter.                                  |
| `readme`      | `string`                                         | GitHub URL of the adapter's README.                                                    |
| `features`    | `AdapterFeatures`                                | Capability support keyed by capability. Omitted keys mean \`"no"\`.                    |
| `icon`        | `string`                                         | Logo identifier used by chat-sdk.dev.                                                  |

`CatalogAdapter` adds the fields setup tools need:

| Property        | Type                | Description                                                                                                             |
| --------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `factoryExport` | `string`            | Named factory export from \`packageName\`, such as \`createSlackAdapter\`.                                              |
| `importPath`    | `string`            | Module specifier to import the factory from when it ships on a subpath of \`packageName\`. Defaults to \`packageName\`. |
| `peerDeps`      | `readonly string[]` | Runtime packages the adapter expects the consuming app to provide or install alongside it.                              |
| `env`           | `AdapterEnvSpec`    | Environment variables and constructor-only configuration.                                                               |

`AdapterEnvSpec` describes the `env` field:

| Property          | Type                  | Description                                                                         |
| ----------------- | --------------------- | ----------------------------------------------------------------------------------- |
| `required`        | `readonly EnvVar[]`   | Variables needed regardless of credential mode.                                     |
| `credentialModes` | `readonly EnvGroup[]` | Mutually exclusive credential groups. A caller usually satisfies exactly one group. |
| `optional`        | `readonly EnvVar[]`   | Optional environment variables that tune behavior.                                  |
| `config`          | `readonly string[]`   | Constructor options that have no environment-variable equivalent.                   |
| `notes`           | `string`              | Additional caveats that do not fit the structured fields.                           |

`EnvGroup` describes one credential mode:

| Property | Type                | Description                                   |
| -------- | ------------------- | --------------------------------------------- |
| `label`  | `string`            | Human-readable name for this credential mode. |
| `vars`   | `readonly EnvVar[]` | Variables that together satisfy this mode.    |

`EnvVar` describes one environment variable:

| Property      | Type                | Description                                               |
| ------------- | ------------------- | --------------------------------------------------------- |
| `key`         | `string`            | Canonical environment variable name.                      |
| `description` | `string`            | Short description of what the value configures.           |
| `secret`      | `boolean`           | Whether the value should be masked in logs and setup UIs. |
| `aliases`     | `readonly string[]` | Alternative variable names accepted for the same value.   |

## Helpers

- `listAdapters({ group, type })` returns every entry, including community adapters, with optional filters.
- `getCatalogEntry(slug)` returns any entry, including community adapters, or `undefined` for unknown slugs.
- `getAdapter(slug)` returns one official or vendor-official entry, or `undefined` for other slugs.
- `isAdapterSlug(slug)` narrows a string to `AdapterSlug`, the official and vendor-official slugs.
- `listPlatformAdapters()` and `listStateAdapters()` return official and vendor-official entries sorted by slug.
- `getFeatureSupport(adapterOrSlug, key)` returns `{ status, label? }` for one capability.
- `listEnvVars(slug)` flattens required, credential-mode, and optional env vars, de-duplicated by key.
- `getSecretEnvVars(slug)` returns the subset of `listEnvVars(slug)` marked as secrets.

## Example: build a setup checklist

This script combines the catalog helpers into a setup checklist for a set of adapters, which is the core of what [`create-chat-sdk`](/docs/create-chat-sdk) does. Given the adapter slugs a user picked and the capabilities the bot depends on, it prints an install command, a `.env.example` template, and a warning for each platform adapter that doesn't fully support a required capability.

```typescript title="scripts/setup-checklist.ts" lineNumbers
import {
  type FeatureKey,
  getAdapter,
  getFeatureSupport,
  isAdapterSlug,
  listEnvVars,
} from "@chat-adapter/catalog";

// Adapters the user picked, and capabilities the bot depends on.
const selected = ["slack", "teams", "redis"];
const requiredFeatures: FeatureKey[] = ["streaming", "modals"];

const packages = new Set(["chat"]);
const envLines: string[] = [];
const warnings: string[] = [];

for (const slug of selected) {
  if (!isAdapterSlug(slug)) {
    throw new Error(`Unknown adapter: ${slug}`);
  }
  const adapter = getAdapter(slug);

  packages.add(adapter.packageName);
  for (const dependency of adapter.peerDeps) {
    packages.add(dependency);
  }

  envLines.push(`# ${adapter.name}`);
  for (const envVar of listEnvVars(slug)) {
    const secret = envVar.secret ? " (secret)" : "";
    envLines.push(`# ${envVar.description}${secret}`, `${envVar.key}=`);
  }

  if (adapter.type === "platform") {
    for (const feature of requiredFeatures) {
      const { status } = getFeatureSupport(adapter, feature);
      if (status !== "yes") {
        warnings.push(`${adapter.name}: ${feature} is ${status}`);
      }
    }
  }
}

console.log(`npm install ${[...packages].join(" ")}\n`);
console.log(envLines.join("\n"));
for (const warning of warnings) {
  console.warn(`Warning: ${warning}`);
}
```

For Slack, Microsoft Teams, and Redis, the install command includes each adapter's peer dependencies, such as `@slack/web-api` and `redis`, and the script warns that Microsoft Teams streaming is `partial`.

`listEnvVars()` returns every variable an adapter reads, including optional ones and the variables for every credential mode. To show only what a user must set, read `adapter.env.required`, let the user choose one entry from `adapter.env.credentialModes`, and list `adapter.env.optional` separately.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Overview
description: Overview of Chat SDK adapters, adapter tiers, and where to find platform, state, and catalog guides.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
prerequisites:
  - /docs/getting-started
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Adapters connect Chat SDK to messaging platforms and state backends. Install only the adapters you need, then register them on your `Chat` instance.

## Adapter tiers

| Tier            | Who maintains it           |
| --------------- | -------------------------- |
| Official        | Vercel (`@chat-adapter/*`) |
| Vendor-official | The platform vendor        |
| Community       | Third-party developers     |

Browse all three tiers on the [Adapters](/adapters) listing page. To ship your own, start with [Building an adapter](/docs/contributing/building), then list it as a [community](/docs/contributing/publishing#listing-on-chat-sdkdev) or [vendor-official](/docs/contributing/vendor-official) adapter.

These guides cover the details:

- [Adapter Catalog](/docs/adapter-catalog) covers `@chat-adapter/catalog`, a static package that lists every adapter with its capabilities and setup requirements, for websites, setup screens, and build scripts.
- [Platform Adapters](/docs/platform-adapters) covers webhook verification, message parsing, feature support by platform, and bots that run on several platforms.
- [State Adapters](/docs/state-adapters) covers subscriptions, distributed locking, and caching.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Approvals
description: Pause a durable workflow until a human approves it in chat.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/cards
  - /docs/actions
related:
  - /docs/ai/ai-sdk-tools
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`requestApproval` from `chat/workflow` posts a card with Approve/Deny buttons and suspends a [Workflow SDK](https://workflow-sdk.dev) workflow until a user clicks. The wait can last seconds or days and survives deploys and restarts. You don't need an approvals table, an `onAction` handler, or a polling loop.

```typescript title="workflows/deploy.ts" lineNumbers
import { requestApproval } from "chat/workflow";
import type { Thread } from "chat";

export async function deployApproval(opts: { thread: Thread; version: string }) {
  "use workflow";

  const { approved, user, timedOut } = await requestApproval(opts.thread, {
    title: `Deploy ${opts.version}?`,
    fields: { Version: opts.version },
    timeout: "24h",
  });

  if (approved) {
    await deploy(opts.version);
  }
}

async function deploy(version: string) {
  "use step";
  // Trigger your deploy here.
}
```

Start the workflow from any handler. `Thread` instances serialize across the workflow boundary automatically:

```typescript title="lib/bot.ts" lineNumbers
import { start } from "workflow/api";
import { deployApproval } from "@/workflows/deploy";

bot.onNewMention(async (thread, message) => {
  await start(deployApproval, [{ thread, version: "v1.2.3" }]);
});
```

## Setup

Install the optional `workflow` peer dependency and configure your framework for [Workflow SDK](https://workflow-sdk.dev/docs/getting-started). Then register your `Chat` instance as a singleton at startup so threads can be revived on the other side of the workflow boundary:

```typescript title="lib/bot.ts"
chat.registerSingleton();
```

## Options

| Option                       | Type                                                   | Description                                                                   |
| ---------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------- |
| `title`                      | `string`                                               | Card title (required)                                                         |
| `subtitle`                   | `string`                                               | Rendered under the title                                                      |
| `description`                | `string`                                               | Body text (markdown) above the fields                                         |
| `fields`                     | `Record<string, string>`                               | Key/value pairs rendered as a bold-label list                                 |
| `approveLabel` / `denyLabel` | `string`                                               | Button labels. Default: "Approve" / "Deny"                                    |
| `timeout`                    | `` number \| `${number}${"ms"\|"s"\|"m"\|"h"\|"d"}` `` | Give up after this long. Omit to wait indefinitely                            |
| `approvers`                  | `string[]`                                             | User IDs allowed to decide. Clicks from others post a notice and keep waiting |

## Result

| Property   | Type                            | Description                                  |
| ---------- | ------------------------------- | -------------------------------------------- |
| `approved` | `boolean`                       | True when the approve button was clicked     |
| `timedOut` | `boolean`                       | True when `timeout` elapsed with no decision |
| `user`     | `{ id: string; name?: string }` | Who decided. Absent on timeout               |

Once a decision lands (or the timeout elapses), the card is edited in place: the buttons are removed and replaced with an outcome line, leaving an audit trail in the thread and preventing stale clicks.

## Who can approve

Anyone who can see the card can decide the approval. When someone clicks, Chat SDK verifies the platform's signature on the event and stores a receipt in your state adapter that records which button was clicked, by whom, and on which thread. It then calls the workflow's webhook with that receipt. `requestApproval` takes the decision and `user` from the receipt rather than from the webhook request and accepts each receipt only once, so a POST to the webhook URL without a valid receipt is ignored and the workflow keeps waiting.

The `Chat` instance that handles the click and the one that runs the workflow must use the same state adapter, such as Redis or Postgres, so the workflow can find the receipt. The memory state adapter works only when both run in the same process. The thread you pass must also come from Chat SDK, such as the one a handler receives or one from `bot.thread()` or `bot.openDM()`. `requestApproval` throws when given a custom `Thread` implementation.

If only certain people should decide, pass `approvers` with their user IDs. When anyone else clicks, the bot posts a notice in the thread, refreshes the card's buttons so an approver can still decide, and keeps the workflow waiting:

```typescript
await requestApproval(thread, {
  title: `Deploy ${version}?`,
  approvers: ["U_ALICE", "U_BOB"],
});
```

Set `approvers` for anything consequential.

## Custom cards

The card builders are exported for cases the wrapper doesn't cover, such as posting an approval card whose buttons target a webhook you manage yourself:

```typescript
import { buildApprovalCard, buildResolvedCard } from "chat/workflow";

const card = buildApprovalCard(
  { title: "Deploy?", fields: { Version: "v1.2.3" } },
  webhookUrl
);
```

When the buttons target your own webhook, it receives the [callback payload](/docs/actions#callback-payload) directly, and nothing verifies its fields for you. Anyone who knows the URL can POST to it, so don't trust `user` or `actionId` from the body.

> The [Human-in-the-Loop guide](https://vercel.com/kb/guide/human-in-the-loop-with-chat-sdk-and-workflow-sdk)
> walks through the underlying pattern, including multi-stage approvals.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Cards
description: Send rich interactive cards with buttons, fields, and images across all platforms.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/actions
  - /docs/modals
  - /docs/api/cards
  - /docs/emoji
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Cards are structured, interactive messages that each adapter renders in its platform's native format: Block Kit on Slack, Adaptive Cards on Teams, embeds or Components on Discord, and Cards on Google Chat.

## Setup

Configure your `tsconfig.json` to use the Chat SDK JSX runtime:

```json title="tsconfig.json"
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "chat"
  }
}
```

Or use a per-file pragma:

```tsx title="lib/bot.tsx"
/** @jsxImportSource chat */
```

## Basic card

```tsx title="lib/bot.tsx" lineNumbers
import { Card, CardText, Button, Actions } from "chat";

await thread.post(
  <Card title="Order #1234">
    <CardText>Your order has been received!</CardText>
    <Actions>
      <Button id="approve" style="primary">Approve</Button>
      <Button id="reject" style="danger">Reject</Button>
    </Actions>
  </Card>
);
```

## Components

### Card

The top-level container. Accepts `title` and optional `subtitle`.

```tsx title="lib/bot.tsx" lineNumbers
<Card title="My Card" subtitle="Optional subtitle">
  {/* children */}
</Card>
```

Set `width="full"` to ask for a wider card on platforms that can render one. Teams renders it as a full-width Adaptive Card; other adapters ignore the hint.

```tsx title="lib/bot.tsx"
<Card title="Weekly digest" width="full">
  {/* children */}
</Card>
```

### CardText

Renders formatted text. Supports a subset of markdown.

```tsx title="lib/bot.tsx" lineNumbers
<CardText>**Bold** and _italic_ text</CardText>
<CardText style="bold">Bold section header</CardText>
```

> Use `CardText` instead of `Text` when using JSX to avoid conflicts with React's built-in types.

### Section

Groups related content together.

```tsx title="lib/bot.tsx" lineNumbers
<Section>
  <CardText>Section content here</CardText>
</Section>
```

### Fields

Renders key-value pairs in a compact layout.

```tsx title="lib/bot.tsx" lineNumbers
<Fields>
  <Field label="Name" value="John Doe" />
  <Field label="Role" value="Developer" />
  <Field label="Team" value="Platform" />
</Fields>
```

### Button

An action button that triggers an `onAction` handler.

```tsx title="lib/bot.tsx" lineNumbers
<Button id="approve" style="primary">Approve</Button>
<Button id="reject" style="danger">Reject</Button>
<Button id="details">View Details</Button>
```

The `id` maps to your `onAction` handler. Optional `value` passes extra data:

```tsx title="lib/bot.tsx"
<Button id="report" value="bug">Report Bug</Button>
```

Set `actionType="modal"` to indicate the button opens a [modal](/docs/modals). The button still triggers your `onAction` handler, where you call `event.openModal()`. The prop tells adapters such as Teams to wire the button up to open a dialog:

```tsx title="lib/bot.tsx"
<Button id="open-feedback" actionType="modal">Give Feedback</Button>
```

Optional `callbackUrl` causes the action data to be POSTed to a URL when clicked. See [Callback URLs](/docs/actions#callback-urls) for details.

```tsx title="lib/bot.tsx"
<Button callbackUrl={webhook.url} id="approve" style="primary">Approve</Button>
```

Optional `tooltip` is hover text for the button. Teams renders it; other adapters ignore it:

```tsx title="lib/bot.tsx"
<Button id="approve" tooltip="Approve the request">Approve</Button>
```

Optional `visibleTo` lists the user IDs that can see the button. Slack renders it with `visible_to_user_ids`, and everyone else in the conversation won't see the button. Other adapters ignore it and show the button to everyone:

```tsx title="lib/bot.tsx"
<Button id="approve" style="primary" visibleTo={[event.user.userId]}>
  Approve
</Button>
```

> `visibleTo` only controls who sees the button. It doesn't stop other users from triggering the action, so check `event.user` in your `onAction` handler before you act on it.

### CardLink

Inline hyperlink rendered as text. `LinkButton` must be inside `Actions`, but you can place `CardLink` directly in a card alongside other content.

```tsx title="lib/bot.tsx"
<CardLink url="https://example.com/order/1234" label="View order details" />
```

Or with children as the label:

```tsx title="lib/bot.tsx"
<CardLink url="https://example.com/docs">Read the docs</CardLink>
```

> `CardLink` renders as a platform-native link: `<url|label>` on Slack, `[label](url)` on Teams/Discord/GitHub/Linear, and `<a href>` on Google Chat.

### LinkButton

Opens an external URL. No `onAction` handler needed for navigation. On platforms
that emit link-button click events, such as Slack, pass `id` when you need a
stable action identifier for routing or analytics.

```tsx title="lib/bot.tsx"
<LinkButton url="https://example.com/order/1234">View Order</LinkButton>
```

```tsx title="lib/bot.tsx"
<LinkButton id="view_order" url="https://example.com/order/1234">
  View Order
</LinkButton>
```

Optional `tooltip` is hover text for the button. Teams renders it; other adapters ignore it:

```tsx title="lib/bot.tsx"
<LinkButton tooltip="Opens the order in your browser" url="https://example.com/order/1234">
  View Order
</LinkButton>
```

`LinkButton` also accepts `visibleTo`, which works the same way as on `Button`.

### Actions

Container for buttons and interactive elements.

```tsx title="lib/bot.tsx" lineNumbers
<Actions>
  <Button id="approve" style="primary">Approve</Button>
  <Button id="reject" style="danger">Reject</Button>
  <LinkButton url="https://example.com">View</LinkButton>
</Actions>
```

### Select

Inline dropdown menu.

```tsx title="lib/bot.tsx" lineNumbers
<Actions>
  <Select id="priority" label="Priority" placeholder="Select priority">
    <SelectOption label="High" value="high" description="Urgent tasks" />
    <SelectOption label="Medium" value="medium" />
    <SelectOption label="Low" value="low" />
  </Select>
</Actions>
```

Selection triggers an `onAction` handler with the `id` as the `actionId` and the selected value.

### RadioSelect

Radio button group for mutually exclusive choices.

```tsx title="lib/bot.tsx" lineNumbers
<Actions>
  <RadioSelect id="status" label="Status">
    <SelectOption label="Open" value="open" />
    <SelectOption label="In Progress" value="in_progress" />
    <SelectOption label="Done" value="done" />
  </RadioSelect>
</Actions>
```

### TextInput

A text box on the card itself, so a user can type a reply without opening a [modal](/docs/modals). Only Teams renders it. Slack, Google Chat, Discord, GitHub, and Linear show the label as text. WhatsApp, Messenger, Twilio, and X omit the input, so don't make it the only content on the card.

```tsx title="lib/bot.tsx" lineNumbers
<Card title="Deploy to production?">
  <TextInput id="notes" label="Notes" multiline optional placeholder="Anything to flag?" />
  <Actions>
    <Button id="approve" style="primary">Approve</Button>
    <Button id="decline" style="danger">Decline</Button>
  </Actions>
</Card>
```

What the user typed arrives on the action as [`event.values`](/docs/actions), keyed by input ID. Teams validates every input on the card before it lets a button through, so mark an input `optional` unless the buttons beside it should stay blocked until it is filled. A button that opens a modal isn't blocked. On Teams, `actionId`, `value`, and `msteams` are reserved and can't be used as a card input's ID. The Teams client enforces that validation, so treat `event.values` as user input and validate it in the handler too. Pair the input with a `Button`, because the input can't submit anything on its own.

### Table

Structured data display with column headers and rows. Renders as a native table on platforms that support it (Slack, Teams, GitHub, Linear), as GFM markdown in Discord card payloads, and as padded ASCII text elsewhere.

```tsx title="lib/bot.tsx" lineNumbers
<Table
  headers={["Name", "Age", "Role"]}
  rows={[
    ["Alice", "30", "Engineer"],
    ["Bob", "25", "Designer"],
  ]}
/>
```

Optional column alignment:

```tsx title="lib/bot.tsx"
<Table
  headers={["Name", "Amount"]}
  rows={[["Alice", "$100"], ["Bob", "$200"]]}
  align={["left", "right"]}
/>
```

On Teams, tables render as the native Adaptive Card `Table` element: grid lines between cells, columns sized by relative weight and a header row marked for accessibility. The optional `widths`, `verticalAlign`, `gridLines` and `gridStyle` props tune that rendering and are ignored on other platforms:

```tsx title="lib/bot.tsx"
<Table
  headers={["Service", "Status", "Latency"]}
  rows={[
    ["api", "ok", "120 ms"],
    ["worker", "degraded", "840 ms"],
  ]}
  widths={[2, 1, 1]}
  align={["left", "center", "right"]}
  gridStyle="emphasis"
/>
```

Pass `gridLines={false}` for a borderless table. A table with empty `headers` renders without a header row.

On Slack, tables render as paginated, sortable [data tables](https://docs.slack.dev/reference/block-kit/blocks/data-table-block). The optional `caption` (accessible table description) and `pageSize` (rows per page, 1–100) props tune that rendering and are ignored on other platforms:

```tsx title="lib/bot.tsx"
<Table
  headers={["Name", "Score"]}
  rows={[["Alice", "98"], ["Bob", "87"]]}
  caption="Quarterly review scores"
  pageSize={10}
/>
```

### Chart

Data visualization with pie, bar, area, and line charts. Renders as a native [data visualization](https://docs.slack.dev/reference/block-kit/blocks/data-visualization-block) on Slack; other platforms fall back to the chart's data rendered as a text table.

```tsx title="lib/bot.tsx" lineNumbers
<Chart
  title="My Favorite Candy Bars"
  chart={{
    type: "pie",
    segments: [
      { label: "Kit Kat", value: 45 },
      { label: "Twix", value: 28 },
      { label: "Crunch", value: 18 },
    ],
  }}
/>
```

Bar, area, and line charts take named series plotted against shared categories:

```tsx title="lib/bot.tsx" lineNumbers
<Chart
  title="Daily Active Users"
  chart={{
    type: "line",
    categories: ["Mon", "Tue", "Wed"],
    xLabel: "Day",
    yLabel: "Users",
    series: [
      {
        name: "Web",
        data: [
          { label: "Mon", value: 120 },
          { label: "Tue", value: 135 },
          { label: "Wed", value: 128 },
        ],
      },
      {
        name: "Mobile",
        data: [
          { label: "Mon", value: 80 },
          { label: "Tue", value: 95 },
          { label: "Wed", value: 90 },
        ],
      },
    ],
  }}
/>
```

Slack enforces a 50-character title, up to 12 segments or series, up to 20 categories, 20-character labels, and at most 2 charts per message. Charts that exceed these limits fall back to a text rendering of the data instead of being rejected by the API.

### Image

Embeds an image in the card.

```tsx title="lib/bot.tsx"
<Image url="https://example.com/screenshot.png" alt="Screenshot" />
```

### Divider

A visual separator between sections.

```tsx title="lib/bot.tsx" lineNumbers
<CardText>Above the line</CardText>
<Divider />
<CardText>Below the line</CardText>
```

## Full example

```tsx title="lib/bot.tsx" lineNumbers
import {
  Card, CardText, CardLink, Button, LinkButton, Actions,
  Section, Fields, Field, Divider, Image,
  Select, SelectOption, RadioSelect,
} from "chat";

await thread.post(
  <Card title="User Profile" subtitle="Account details">
    <Image url="https://example.com/avatar.png" alt="User avatar" />
    <Fields>
      <Field label="Name" value="Jane Smith" />
      <Field label="Role" value="Engineer" />
      <Field label="Team" value="Platform" />
    </Fields>
    <CardLink url="https://example.com/profile/123">View full profile</CardLink>
    <Divider />
    <Section>
      <CardText>Select an action below to manage this profile.</CardText>
    </Section>
    <Actions>
      <Select id="role" label="Change Role" placeholder="Select role">
        <SelectOption label="Engineer" value="engineer" />
        <SelectOption label="Manager" value="manager" />
        <SelectOption label="Admin" value="admin" />
      </Select>
      <Button id="edit" style="primary">Edit Profile</Button>
      <Button id="deactivate" style="danger">Deactivate</Button>
      <LinkButton url="https://example.com/profile/123">View Full Profile</LinkButton>
    </Actions>
  </Card>
);
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Overlapping Messages
description: Control how overlapping messages on the same thread are handled, with the burst, queue, debounce, drop, and concurrent strategies.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/handling-events
related:
  - /docs/state-adapters
  - /docs/streaming
  - /docs/error-handling
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

When a message arrives on a thread while a handler is still processing an earlier one, the SDK drops the new message by default. The `concurrency` option on `ChatConfig` lets you choose a different strategy.

## Strategies

### Drop (default)

This is the original behavior. If a handler is already running on a thread, the new message is discarded and a `LockError` is thrown. Nothing is queued or retried.

```typescript title="lib/bot.ts"
const bot = new Chat({
  concurrency: "drop",
  // ...
});
```

### Queue

Messages that arrive while a handler is running are enqueued. When the current handler finishes, only the latest queued message is dispatched. The intermediate messages are passed in `context.skipped`, so your handler can see everything that arrived while it was busy.

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  concurrency: "queue",
  // ...
});

bot.onNewMention(async (thread, message, context) => {
  if (context && context.skipped.length > 0) {
    await thread.post(
      `You sent ${context.totalSinceLastHandler} messages while I was thinking. Responding to your latest.`
    );
  }

  const response = await generateAIResponse(message.text);
  await thread.post(response);
});
```

Flow:

```
A arrives  → acquire lock → process A
B arrives  → lock busy → enqueue B
C arrives  → lock busy → enqueue C
D arrives  → lock busy → enqueue D
A done     → drain: [B, C, D] → handler(D, { skipped: [B, C] })
D done     → queue empty → release lock
```

### Burst

Waits for `debounceMs` before the first handler on an idle thread, then drains the collected burst like `queue`. The latest message is dispatched, and earlier messages in the burst are available as `context.skipped`.

Use this for assistant-style bots where users often send one logical turn as several short messages inside a small window and you want one response with full context. Compared to `debounce`, `burst` keeps the earlier messages in `context.skipped` instead of dropping them, and it flushes queued messages that arrive while the handler is running.

Choose `debounce` when the latest message replaces earlier ones, like rapid corrections. Choose `burst` when earlier messages still matter, like "hey", "quick question", and then the actual question. The tradeoff is that even a lone message waits for `debounceMs` before the handler runs.

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  concurrency: { strategy: "burst", debounceMs: 1000 },
  // ...
});

bot.onNewMention(async (thread, message, context) => {
  const turn = [...(context?.skipped ?? []), message]
    .map((m) => m.text)
    .join("\n\n");

  const response = await generateAIResponse(turn);
  await thread.post(response);
});
```

Flow:

```
A arrives  → acquire lock → enqueue A → sleep(debounceMs)
B arrives  → lock busy → enqueue B
C arrives  → lock busy → enqueue C
             ... debounceMs elapses ...
           → drain: [A, B, C] → handler(C, { skipped: [A, B] })
D arrives while C is running → lock busy → enqueue D
E arrives while C is running → lock busy → enqueue E
C done     → drain: [D, E] → handler(E, { skipped: [D] })
E done     → queue empty → release lock
```

### Debounce

The first message waits for `debounceMs`. Messages that arrive during that window replace the pending message, so only the final message in the window is processed.

This helps on platforms like WhatsApp and Telegram, where users tend to send several short messages in quick succession instead of composing one. "hey", "quick question", and "how do I reset my password?" can arrive as three separate webhooks within a few seconds. Without debounce, the bot would respond to "hey" before the actual question even arrives. With debounce, the SDK waits briefly and processes only the final message in the window.

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  concurrency: { strategy: "debounce", debounceMs: 1500 },
  // ...
});
```

> WhatsApp and Telegram adapters default to `lockScope: "channel"`, so debounce applies to the entire conversation rather than a single thread.

Flow:

```
A arrives  → acquire lock → store A as pending → sleep(debounceMs)
B arrives  → lock busy → overwrite pending with B (A dropped)
C arrives  → lock busy → overwrite pending with C (B dropped)
             ... debounceMs elapses with no new message ...
           → process C → release lock
```

Debounce also works well for rapid corrections ("wait, I meant...") and multi-part messages on any platform.

### Concurrent

No locking. Every message is processed immediately in its own handler invocation. Use this for stateless handlers where thread ordering doesn't matter.

```typescript title="lib/bot.ts"
const bot = new Chat({
  concurrency: "concurrent",
  // ...
});
```

## Configuration

To tune queue size, eviction, and timing, pass a `ConcurrencyConfig` object instead of a strategy string:

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  concurrency: {
    strategy: "queue",
    maxQueueSize: 20,          // Max queued messages per thread (default: 10)
    onQueueFull: "drop-oldest", // or "drop-newest" (default: "drop-oldest")
    queueEntryTtlMs: 60_000,  // Discard stale entries after 60s (default: 90s)
  },
  // ...
});
```

### All options

| Option              | Strategies                   | Default         | Description                                                                                                                                                                   |
| ------------------- | ---------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `strategy`          | all                          | `"drop"`        | The concurrency strategy to use                                                                                                                                               |
| `maxQueueSize`      | queue, burst                 | `10`            | Maximum queued messages per thread                                                                                                                                            |
| `onQueueFull`       | queue, burst                 | `"drop-oldest"` | Whether to evict the oldest or reject the newest message when the queue is full                                                                                               |
| `queueEntryTtlMs`   | queue, debounce, burst       | `90000`         | TTL for queued entries in milliseconds. Expired entries are discarded on dequeue                                                                                              |
| `debounceMs`        | debounce, burst              | `1500`          | Debounce window in milliseconds                                                                                                                                               |
| `maxLockLifetimeMs` | drop, queue, debounce, burst | `600000`        | Max total time one handler run may keep renewing its thread lock. After this, renewal stops and the lock lapses at its TTL, so a hung handler cannot block the thread forever |
| `maxConcurrent`     | concurrent                   | `Infinity`      | Max concurrent handlers per thread                                                                                                                                            |

> `maxConcurrent` only applies to the `concurrent` strategy. Pairing it with any other strategy logs a warning and the value is ignored. Setting `maxConcurrent` to a value less than `1` throws at construction time, because `0` would deadlock the strategy.

## MessageContext

All handler types (`onNewMention`, `onSubscribedMessage`, `onNewMessage`) accept an optional `MessageContext` as their last parameter. It is populated when using the `queue` strategy for queued messages, and when using `burst` for a collapsed turn. A lone `burst` message receives `skipped: []` and `totalSinceLastHandler: 1`.

```typescript
interface MessageContext {
  /** Messages that arrived while the previous handler was running, in chronological order. */
  skipped: Message[];
  /** Total messages received since last handler ran (skipped.length + 1). */
  totalSinceLastHandler: number;
}
```

The parameter is optional, so existing handlers that don't use `context` are unaffected.

### Example: Pass all messages to an LLM

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message, context) => {
  // Combine skipped messages with the current one for full context
  const allMessages = [...(context?.skipped ?? []), message];

  const response = await generateAIResponse(
    allMessages.map((m) => m.text).join("\n\n")
  );
  await thread.post(response);
});
```

## Lock scope

By default, locks are scoped to the thread, so messages in different threads are processed independently. For platforms like WhatsApp and Telegram where conversations happen at the channel level rather than in threads, the lock scope defaults to `"channel"`.

You can override this globally:

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  concurrency: "queue",
  lockScope: "channel", // or "thread" (default)
  // ...
});
```

Or resolve it dynamically per message:

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  concurrency: "queue",
  lockScope: ({ isDM, adapter }) => {
    // Use channel scope for DMs, thread scope for group channels
    return isDM ? "channel" : "thread";
  },
  // ...
});
```

## State adapter requirements

The `queue`, `debounce`, and `burst` strategies require three additional methods on your state adapter:

| Method                              | Description                                                            |
| ----------------------------------- | ---------------------------------------------------------------------- |
| `enqueue(threadId, entry, maxSize)` | Atomically append a message to the thread's queue. Returns new depth.  |
| `dequeue(threadId)`                 | Pop the next (oldest) message from the queue. Returns `null` if empty. |
| `queueDepth(threadId)`              | Return the current number of queued messages.                          |

All built-in state adapters (`@chat-adapter/state-memory`, `@chat-adapter/state-redis`, `@chat-adapter/state-ioredis`) implement these methods. The Redis adapters use Lua scripts for atomicity.

> An adapter can namespace these state keys by tenant, so the key passed to your state adapter isn't always the bare thread ID. The [Slack adapter in multi-workspace mode](/adapters/official/slack#using-the-adapter-outside-webhooks) scopes deduplication, locks, queues, concurrency slots, and turn cancellation by installation. If you inspect state or recover from an incident with calls like `queueDepth(threadId)` or `forceReleaseLock(threadId)`, those calls won't reach the namespaced keys. Log events still report the public `threadId`.

## Observability

All strategies emit structured log events at `info` level:

| Event                    | Strategy               | Data                                              |
| ------------------------ | ---------------------- | ------------------------------------------------- |
| `message-queued`         | queue, burst           | threadId, messageId, queueDepth                   |
| `message-dequeued`       | queue, debounce, burst | threadId, messageId, skippedCount for queue/burst |
| `message-dropped`        | drop, queue, burst     | threadId, messageId, reason                       |
| `message-expired`        | queue, debounce, burst | threadId, messageId                               |
| `message-superseded`     | debounce               | threadId, droppedId                               |
| `message-debouncing`     | debounce, burst        | threadId, messageId, debounceMs                   |
| `message-debounce-reset` | debounce               | threadId, messageId                               |

## Choosing a strategy

| Use case                                  | Strategy     | Why                                                                                                           |
| ----------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------- |
| Simple bots, one-shot commands            | `drop`       | No queue to configure and no queue overhead                                                                   |
| AI chatbots, customer support             | `queue`      | Messages that arrive mid-run are queued, up to `maxQueueSize`, and the handler sees them in `context.skipped` |
| AI chatbots with multi-message user turns | `burst`      | Wait for the idle burst window, then respond once with every message in that window                           |
| WhatsApp/Telegram bots, rapid corrections | `debounce`   | Users send many short messages in quick succession; wait briefly and keep only the latest                     |
| Stateless lookups, translations           | `concurrent` | Highest throughput when ordering doesn't matter                                                               |

## Backward compatibility

- The default strategy is `drop`, so existing behavior is unchanged.
- The deprecated `onLockConflict` option continues to work but should be replaced with `concurrency`.
- Handler signatures are backward-compatible; the new `context` parameter is optional.
- Deduplication always runs regardless of strategy.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: CLI
description: Scaffold a Chat SDK bot app with a single command.
docs_index: /llms.txt
lastUpdated: 2026-10-27
related:
  - /docs
  - /docs/getting-started
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`create-chat-sdk` creates a minimal Next.js app for a Chat SDK bot. Based on the adapters you pick from the adapter catalog, it generates your `Chat` configuration, a webhook route, a `.env.example` file, and the dependency list, plus a Web adapter route if you select that adapter.

## Quick start

**npm**

```bash
npm create chat-sdk@latest my-bot
```

**pnpm**

```bash
pnpm create chat-sdk@latest my-bot
```

**yarn**

```bash
yarn create chat-sdk my-bot
```

**bun**

```bash
bunx create-chat-sdk@latest my-bot
```

> `create-chat-sdk` detects when Cursor, Claude Code, or another coding agent runs it. In that case the CLI runs non-interactively: pass at least one platform adapter with `--adapter`, and it uses `memory` as the state adapter and `my-bot` as the project name unless you provide others. Pass `--interactive` to force prompts.

## Non-interactive usage

Pass platform and state adapters with `--adapter`:

```bash
npm create chat-sdk@latest -- my-bot --adapter slack redis -y
```

> With npm, the `--` separator is required because npm consumes flags before it (`-y` is npm's own `--yes`) instead of forwarding them to the CLI. `pnpm create` and `yarn create` forward flags without it.

The interactive prompt lists official adapters by default. Pass `--vendor` to list only vendor-official adapters instead. Scripts and coding agents can skip the prompt and pass any official or vendor-official adapter the CLI supports to `--adapter`.

Adapters that require a long-running process, including Matrix and Lark, cannot run on the webhook-only serverless runtime and are not available through the CLI. Add them to an existing project manually instead.

Examples:

```bash
npm create chat-sdk@latest -- slack-bot --adapter slack memory -y --skip-install
npm create chat-sdk@latest -- gchat-bot --adapter gchat redis -y --pm pnpm
npm create chat-sdk@latest -- email-bot --adapter resend postgres -y --no-git
npm create chat-sdk@latest -- my-bot --adapter slack memory -y --force
```

## What gets generated

The scaffolded app is webhook-only. It does not include pages, layouts, or a client UI.

```txt
src/
  lib/bot.ts                              Bot configuration and handlers
  app/api/webhooks/[platform]/route.ts    Dynamic platform webhook route
  app/api/chat/route.ts                   Web adapter route, only when selected
  app/api/discord/gateway/route.ts        Discord Gateway listener, only when selected
.env.example                              Required environment variables
next.config.ts                            Next.js server config
vercel.json                               Cron schedules, only when needed
.chat-sdk.json                            Generated file ownership for safe reruns
package.json                              Adapter dependencies
```

Webhook endpoints use the selected adapter slug:

```txt
/api/webhooks/slack
/api/webhooks/gchat
/api/webhooks/discord
```

When the [Web adapter](/adapters/official/web) is selected, the CLI also creates `/api/chat` for browser chat requests and a small `getUser` auth stub. Replace the stub with your app's real authentication logic so each web conversation can be associated with the correct user.

When the [Discord adapter](/adapters/official/discord) is selected, the CLI also creates a Gateway listener at `/api/discord/gateway` and a `vercel.json` cron that calls it. Discord delivers slash commands and button clicks to the webhook route, but regular messages and reactions only arrive over the Gateway WebSocket, so the cron keeps that connection alive and forwards events to `/api/webhooks/discord`. Set a `CRON_SECRET` environment variable to authenticate the cron requests. The generated serverless Gateway cron requires [Vercel Pro or Enterprise](https://vercel.com/docs/cron-jobs/usage-and-pricing) because it runs every nine minutes.

## Vercel Connect

[Vercel Connect](/docs/vercel-connect) supplies outbound credentials for the Slack, Discord, GitHub, Linear, Notion, Teams, and Telegram adapters. To scaffold Connect wiring for any selected adapter in that list, pass `--connect` or choose **Vercel Connect** at the interactive auth-mode prompt. Notion and Telegram webhooks stay direct and keep their native verification secrets.

```bash
npm create chat-sdk@latest -- my-bot --adapter slack --connect -y
```

The generated `src/lib/bot.ts` spreads the matching helper from `@vercel/connect/chat` into the adapter factory, `@vercel/connect` is added to dependencies, and `.env.example` lists each connector UID, for example `SLACK_CONNECTOR`.

For Linear, `--adapter linear --connect` explicitly sets `mode: "agent-sessions"`, the recommended setup for Connect bots. Enable **Agent session events** on the Linear app and use an app-actor installation. The adapter itself still defaults to `"comments"` when `mode` is omitted.

For Microsoft Teams, use `--adapter teams --connect`. The generated bot uses
`connectTeamsAdapter(requireEnv("TEAMS_CONNECTOR"))`, and `.env.example` expects
a connector UID such as `microsoft-teams/my-bot` instead of Azure credentials.
Forward Connect triggers to `/api/webhooks/teams`. Microsoft Graph reads require
the bot's resource-specific permissions to be granted when it is installed in a
team. This setup requires releases of both `@vercel/connect` and
`@chat-adapter/teams` that support the Teams Connect helper.

> Vercel Connect provides `VERCEL_OIDC_TOKEN` at runtime. For local development, run `vercel link` then `vercel env pull` to populate it. Connect forwards inbound webhooks only to deployed URLs, so test webhook delivery against a Vercel deployment (such as a preview) rather than localhost.

## Reference

| Option                     | Description                                                                                            |
| -------------------------- | ------------------------------------------------------------------------------------------------------ |
| `[name]`                   | Name of the project.                                                                                   |
| `-d, --description <text>` | Project description.                                                                                   |
| `--adapter <values...>`    | Platform or state adapters to include.                                                                 |
| `--vendor`                 | List only vendor-official adapters in the interactive prompt.                                          |
| `--connect`                | Authenticate Slack, Discord, GitHub, Linear, Notion, Teams, and Telegram adapters with Vercel Connect. |
| `--pm <manager>`           | Package manager to use: `npm`, `yarn`, `pnpm`, or `bun`.                                               |
| `-y, --yes`                | Skip prompts and accept defaults.                                                                      |
| `--interactive`            | Always prompt, even when a coding agent environment is detected.                                       |
| `-f, --force`              | Overwrite generated files in an existing directory.                                                    |
| `-s, --skip-install`       | Skip dependency installation.                                                                          |
| `--no-git`                 | Skip git repository initialization.                                                                    |
| `-q, --quiet`              | Suppress non-essential output.                                                                         |

Color output follows the [NO\_COLOR standard](https://no-color.org/). Set `NO_COLOR=1` to disable colors.

## Customize your bot

Most bot behavior lives in `src/lib/bot.ts`. Start there when you want to:

- Add or change handlers like `onNewMention`, `onSubscribedMessage`, `onNewMessage`, reactions, actions, or slash commands.
- Adjust adapter configuration, for example passing explicit credentials or platform-specific options instead of relying only on environment variables.
- Replace the memory state adapter, if you selected it, with Redis, ioredis, or PostgreSQL before deploying to production.

The generated file includes starter handlers for mentions and subscribed thread replies.

## Next steps

After scaffolding:

```bash
cd my-bot
cp .env.example .env.local
npm run dev
```

Fill in the generated environment variables, expose your local server, and configure each selected platform to call its `/api/webhooks/{adapter}` endpoint.

## Resources

See guides, templates, and examples on the [resources](/resources) page.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Direct Messages
description: Initiate DM conversations with users programmatically.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Use `bot.openDM()` to open a direct message conversation with a user. When the user ID format is unique to one platform, Chat SDK infers the adapter from the ID.

## DM behavior

DMs behave slightly differently from channel messages:

- If you register `onDirectMessage`, every incoming DM routes there before `onSubscribedMessage`, `onNewMention`, and pattern handlers. DM-centric flows such as WhatsApp conversations, Telegram DMs, and web chat then run through one handler.
- If no `onDirectMessage` handlers are registered, DMs continue through normal routing. Unsubscribed DMs are treated as mentions, so existing `onNewMention` bots keep working without the user having to @-mention the bot.
- Each top-level DM starts a new conversation. Thread replies within a DM continue the same conversation, giving you the same per-thread isolation as channels.

## Handle incoming DMs

```typescript title="lib/bot.ts" lineNumbers
bot.onDirectMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});
```

## Open a DM

### From an Author object

The most common pattern is to pass the `author` from an incoming message:

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  if (message.text === "DM me") {
    const dmThread = await bot.openDM(message.author);
    await dmThread.post("Hello! This is a private message.");
  }
});
```

### From a user ID

Pass a user ID string directly. The adapter is inferred from the ID format:

```typescript title="lib/bot.ts"
const dmThread = await bot.openDM("U1234567890"); // Slack
```

| Format          | Platform            |
| --------------- | ------------------- |
| `U...` / `W...` | Slack               |
| `29:...`        | Teams               |
| `users/...`     | Google Chat         |
| Numeric ID      | Discord or Telegram |

> Numeric IDs can be ambiguous when multiple numeric-ID adapters are registered. For platforms whose user IDs are not globally distinguishable, call the adapter directly and wrap the returned thread ID with `bot.thread()`.

```typescript title="lib/bot.ts"
const threadId = await bot.getAdapter("whatsapp").openDM("15551234567");
const dmThread = bot.thread(threadId);
```

## Check if a thread is a DM

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  if (thread.isDM) {
    await thread.post("This is a private conversation.");
  }
});
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Emoji
description: "Type-safe, cross-platform emoji that convert to each platform's format."
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/posting-messages
  - /docs/cards
  - /docs/handling-events
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The `emoji` helper gives you named emoji that convert to each platform's format when posted. On Slack, they render as `:shortcode:` text. On other platforms, they render as Unicode characters.

## Usage

```typescript title="lib/bot.ts" lineNumbers
import { emoji } from "chat";

await thread.post(`${emoji.thumbs_up} Great job!`);
// Slack: ":+1: Great job!"
// Teams/GChat/Discord: "👍 Great job!"
```

Emoji also work in reactions:

```typescript title="lib/bot.ts" lineNumbers
await sent.addReaction(emoji.check);

bot.onReaction(["thumbs_up", "heart", "fire"], async (event) => {
  if (!event.added) return;
  await event.adapter.addReaction(event.threadId, event.messageId, emoji.raised_hands);
});
```

## Available emoji

| Name                 | Emoji | Name                | Emoji |
| -------------------- | ----- | ------------------- | ----- |
| `emoji.thumbs_up`    | 👍    | `emoji.thumbs_down` | 👎    |
| `emoji.heart`        | ❤️    | `emoji.smile`       | 😊    |
| `emoji.laugh`        | 😂    | `emoji.thinking`    | 🤔    |
| `emoji.eyes`         | 👀    | `emoji.fire`        | 🔥    |
| `emoji.check`        | ✅     | `emoji.x`           | ❌     |
| `emoji.question`     | ❓     | `emoji.party`       | 🎉    |
| `emoji.rocket`       | 🚀    | `emoji.star`        | ⭐     |
| `emoji.wave`         | 👋    | `emoji.clap`        | 👏    |
| `emoji["100"]`       | 💯    | `emoji.warning`     | ⚠️    |
| `emoji.raised_hands` | 🙌    | `emoji.muscle`      | 💪    |
| `emoji.ok_hand`      | 👌    | `emoji.sad`         | 😢    |
| `emoji.memo`         | 📝    | `emoji.gear`        | ⚙️    |
| `emoji.wrench`       | 🔧    | `emoji.bug`         | 🐛    |
| `emoji.calendar`     | 📅    | `emoji.clock`       | 🕐    |
| `emoji.sun`          | ☀️    | `emoji.rainbow`     | 🌈    |

For a one-off custom emoji, use `emoji.custom("name")`.

## Custom emoji

For workspace-specific emoji with typed names, use `createEmoji()`:

```typescript title="lib/bot.ts" lineNumbers
import { createEmoji } from "chat";

const myEmoji = createEmoji({
  unicorn: { slack: "unicorn_face", gchat: "🦄" },
  company_logo: { slack: "company", gchat: "🏢" },
});

await thread.post(`${myEmoji.unicorn} Magic! ${myEmoji.company_logo}`);
// Slack: ":unicorn_face: Magic! :company:"
// GChat: "🦄 Magic! 🏢"
```

You can also extend the built-in emoji map with TypeScript module augmentation:

```typescript title="lib/emoji.d.ts" lineNumbers
declare module "chat" {
  interface CustomEmojiMap {
    my_custom: EmojiFormats;
  }
}
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Ephemeral Messages
description: Send messages visible only to a specific user.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/direct-messages
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Ephemeral messages are visible only to a specific user within a thread. They're useful for confirmations, hints, and private notifications.

## Send an ephemeral message

```typescript title="lib/bot.ts" lineNumbers
await thread.postEphemeral(user, "Only you can see this!", {
  fallbackToDM: true,
});
```

The `fallbackToDM` option is required. It controls what happens on platforms without native ephemeral support:

- `fallbackToDM: true`: send the message as a DM instead. If the adapter can't open DMs either, nothing is sent and the call returns `null`.
- `fallbackToDM: false`: don't send anything, and return `null`.

## Platform behavior

| Platform    | Native support | Behavior                         | Persistence                         |
| ----------- | -------------- | -------------------------------- | ----------------------------------- |
| Slack       | Yes            | Ephemeral in channel             | Session-only (disappears on reload) |
| Google Chat | Yes            | Private message in space         | Persists until deleted              |
| Teams       | Yes            | Targeted message in conversation | Teams-managed                       |
| Discord     | No             | DM fallback                      | Persists in DM                      |

Discord slash command responses can be made ephemeral with the Discord adapter's [`interactionFlags` option](/adapters/official/discord#interaction-flags). Outside that interaction flow, `postEphemeral` still follows the fallback behavior.

## Check for fallback

```typescript title="lib/bot.ts" lineNumbers
const result = await thread.postEphemeral(user, "Private notification", {
  fallbackToDM: true,
});

if (result?.usedFallback) {
  console.log("Sent as DM instead of ephemeral");
}
```

## Graceful degradation

To send only when the platform supports native ephemeral messages, set `fallbackToDM` to `false` and check for `null`:

```typescript title="lib/bot.ts" lineNumbers
const result = await thread.postEphemeral(user, "Contextual hint", {
  fallbackToDM: false,
});

if (!result) {
  // Platform doesn't support native ephemeral
  // Message was not sent
}
```

## Ephemeral cards

Cards work with ephemeral messages too:

```tsx title="lib/bot.tsx" lineNumbers
await thread.postEphemeral(
  event.user,
  <Card title="Ephemeral Card">
    <CardText>Only you can see this card.</CardText>
    <Actions>
      <Button id="open_modal" style="primary">Open Modal</Button>
    </Actions>
  </Card>,
  { fallbackToDM: true }
);
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Error Handling
description: Handle rate limits, unsupported features, and other errors from adapters.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Chat SDK throws typed errors for common failures such as rate limits, unsupported features, and lock conflicts. Import the core error classes from the `chat` package.

```typescript
import { ChatError, RateLimitError, NotImplementedError, LockError } from "chat";
```

## Error types

### ChatError

The base class for SDK errors. `RateLimitError`, `NotImplementedError`, and `LockError` all extend `ChatError`. Branch on the machine-readable `code` property:

| Code                     | Thrown by                      | Meaning                                                                                |
| ------------------------ | ------------------------------ | -------------------------------------------------------------------------------------- |
| `NOT_SUPPORTED`          | `bot.openDM`, `bot.getUser`    | The resolved adapter doesn't implement this method                                     |
| `INVALID_THREAD_ID`      | `bot.thread`, internal routing | Thread ID does not match the `adapter:channel:thread` shape                            |
| `INVALID_CHANNEL_ID`     | `bot.channel`                  | Channel ID does not match the `adapter:channel` shape                                  |
| `ADAPTER_NOT_FOUND`      | `bot.thread`, `bot.channel`    | Thread/channel ID references an adapter that wasn't registered on this `Chat` instance |
| `AMBIGUOUS_USER_ID`      | `bot.getUser`, `bot.openDM`    | Numeric user ID could match more than one registered adapter (Discord/Telegram/GitHub) |
| `UNKNOWN_USER_ID_FORMAT` | `bot.getUser`, `bot.openDM`    | The `userId` doesn't match any platform's known ID format                              |
| `RATE_LIMITED`           | Any platform call              | Platform returned 429; see `RateLimitError` below                                      |
| `NOT_IMPLEMENTED`        | Any platform call              | The adapter doesn't implement this feature; see `NotImplementedError` below            |
| `LOCK_FAILED`            | Inbound message routing        | Distributed lock was busy; see `LockError` below                                       |

| Property  | Type                   | Description                                    |
| --------- | ---------------------- | ---------------------------------------------- |
| `message` | `string`               | Human-readable error message.                  |
| `code`    | `string`               | Machine-readable error code (see table above). |
| `cause`   | `unknown \| undefined` | Original error that caused this one.           |

### RateLimitError

Thrown when a platform API returns a 429 response. The `retryAfterMs` property tells you how long to wait before retrying.

```typescript title="lib/bot.ts" lineNumbers
import { RateLimitError } from "chat";

try {
  await thread.post("Hello!");
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`Rate limited, retry after ${error.retryAfterMs}ms`);
  }
}
```

| Property       | Type                  | Description                           |
| -------------- | --------------------- | ------------------------------------- |
| `code`         | `string`              | Always "RATE\_LIMITED".               |
| `retryAfterMs` | `number \| undefined` | Milliseconds to wait before retrying. |

### NotImplementedError

Thrown when you call a feature that a platform doesn't support, such as `addReaction()` on Teams or `schedule()` on an adapter without native scheduling.

```typescript title="lib/bot.ts" lineNumbers
import { NotImplementedError } from "chat";

try {
  await thread.addReaction(emoji.thumbs_up);
} catch (error) {
  if (error instanceof NotImplementedError) {
    console.log(`Feature not supported: ${error.feature}`);
  }
}
```

| Property  | Type                  | Description                      |
| --------- | --------------------- | -------------------------------- |
| `code`    | `string`              | Always "NOT\_IMPLEMENTED".       |
| `feature` | `string \| undefined` | Name of the unsupported feature. |

See the [feature matrix](/docs/platform-adapters) for which features are supported on each platform.

### LockError

Thrown when the SDK can't acquire the distributed lock it uses to stop two messages in the same thread from being processed at once. This happens under the default `drop` [concurrency strategy](/docs/concurrency). To queue, debounce, or run messages in parallel instead, set the `concurrency` option. To release the held lock instead of throwing, set the deprecated [`onLockConflict`](/docs/usage#configuration-options) option to `'force'`.

| Property | Type     | Description            |
| -------- | -------- | ---------------------- |
| `code`   | `string` | Always "LOCK\_FAILED". |

## Adapter errors

Adapters also throw specialized errors from the `@chat-adapter/shared` package:

| Error                   | Code                | Description                                               |
| ----------------------- | ------------------- | --------------------------------------------------------- |
| `AdapterRateLimitError` | `RATE_LIMITED`      | Platform rate limit hit, includes `retryAfter` in seconds |
| `AuthenticationError`   | `AUTH_FAILED`       | Invalid or expired credentials                            |
| `ResourceNotFoundError` | `NOT_FOUND`         | Requested resource (channel, message) doesn't exist       |
| `PermissionError`       | `PERMISSION_DENIED` | Bot lacks required permissions/scopes                     |
| `ValidationError`       | `VALIDATION_ERROR`  | Invalid input data (e.g. message too long)                |
| `NetworkError`          | `NETWORK_ERROR`     | Connectivity issue with platform API                      |

## Catching errors

Use `instanceof` to handle specific error types:

```typescript title="lib/bot.ts" lineNumbers
import { RateLimitError, NotImplementedError } from "chat";

bot.onNewMention(async (thread, message) => {
  try {
    await thread.post("Processing...");
    await thread.addReaction(emoji.eyes);
  } catch (error) {
    if (error instanceof RateLimitError) {
      // Wait and retry
      await new Promise((r) => setTimeout(r, error.retryAfterMs ?? 5000));
      await thread.post("Processing...");
    } else if (error instanceof NotImplementedError) {
      // Skip unsupported features gracefully
    } else {
      throw error;
    }
  }
});
```

## Propagating webhook handler errors

Message, action, and slash command handler errors are logged but, by default, tasks passed to `waitUntil` fulfill. Hosts that collect and await those tasks can opt in to observing failures and choose an error response:

```typescript
const tasks: Promise<unknown>[] = [];
const response = await chat.webhooks.slack(request, {
  waitUntil: (task) => tasks.push(task),
  propagateHandlerErrors: true,
});
const results = await Promise.allSettled(tasks);

return results.some((result) => result.status === "rejected")
  ? new Response("Handler failed", { status: 500 })
  : response;
```

This option only exposes handler failures through the supplied promise. It does not automatically change a webhook response, including when using Vercel's native `waitUntil`.

Keep handlers short when awaiting them before responding. [Slack requires acknowledgement within three seconds](https://docs.slack.dev/apis/events-api/#responding-to-events), so move long-running work outside the webhook response path.

Error propagation does not guarantee retries or durable delivery. SDK deduplication can skip redelivered events after a handler fails, so returning `500` alone does not ensure the handler runs again.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: File Uploads
description: Send and receive files across chat platforms.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Your bot can attach files to the messages it posts and read the attachments on incoming messages.

## Send files

Attach files to messages using the `files` property:

```typescript title="lib/bot.ts" lineNumbers
const reportBuffer = Buffer.from("PDF content");

await thread.post({
  markdown: "Here's the report you requested:",
  files: [
    {
      data: reportBuffer,
      filename: "report.pdf",
      mimeType: "application/pdf",
    },
  ],
});
```

### Typed attachments

Use `attachments` when you already have normalized `Attachment` objects and the adapter supports typed outgoing media. Telegram uses the native media method for the attachment type:

```typescript title="lib/bot.ts" lineNumbers
await thread.post({
  markdown: "Here's the image:",
  attachments: [
    {
      data: imageBuffer,
      name: "diagram.png",
      mimeType: "image/png",
      type: "image",
    },
  ],
});
```

Outgoing `attachments` are available on `{ raw }`, `{ markdown }`, and `{ ast }` messages. Card messages use `files` for uploads, and `files` is also the choice for generic uploads.

On Telegram, `files` always upload as documents, while `attachments` keep their image, audio, video, or file media type. Multiple Telegram `files` or compatible `attachments` are sent as media groups. Use `data` or `fetchData` for private or authenticated files. URL-only attachments must be public URLs that Telegram can fetch directly.

### Multiple files

```typescript title="lib/bot.ts" lineNumbers
await thread.post({
  markdown: "Attached are the images:",
  files: [
    { data: image1, filename: "screenshot1.png" },
    { data: image2, filename: "screenshot2.png" },
  ],
});
```

### Files without text

```typescript title="lib/bot.ts" lineNumbers
await thread.post({
  markdown: "",
  files: [{ data: buffer, filename: "document.xlsx" }],
});
```

## Receive files

Access attachments from incoming messages:

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  for (const attachment of message.attachments ?? []) {
    console.log(`File: ${attachment.name}, Type: ${attachment.mimeType}`);

    if (attachment.fetchData) {
      const data = await attachment.fetchData();
      console.log(`Downloaded ${data.byteLength} bytes`);
    }
  }
});
```

### Attachment properties

| Property        | Type                                              | Description                                                              |
| --------------- | ------------------------------------------------- | ------------------------------------------------------------------------ |
| `type`          | `string`                                          | Attachment type (e.g., "image", "file")                                  |
| `url`           | `string` (optional)                               | Public URL                                                               |
| `name`          | `string` (optional)                               | Filename                                                                 |
| `mimeType`      | `string` (optional)                               | MIME type                                                                |
| `size`          | `number` (optional)                               | File size in bytes                                                       |
| `width`         | `number` (optional)                               | Image width                                                              |
| `height`        | `number` (optional)                               | Image height                                                             |
| `fetchData`     | `() => Promise<Buffer \| ArrayBuffer>` (optional) | Download the file data                                                   |
| `fetchMetadata` | `Record<string, string>` (optional)               | Platform-specific IDs for reconstructing `fetchData` after serialization |

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Getting Started
description: Pick a guide to start building with Chat SDK.
docs_index: /llms.txt
lastUpdated: 2026-10-27
related:
  - /docs/usage
  - /docs/platform-adapters
  - /docs/vercel-connect
  - /docs/create-chat-sdk
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Start with the usage guides to learn how a bot handles incoming events and posts messages, then add the adapters for your chat platforms and state backend.

## Usage

Learn the core patterns for handling incoming events and posting messages back to your users.

#### [Creating a Chat Instance](/docs/usage)

Initialize the Chat class with adapters, state, and configuration options.

#### [Threads, Messages, and Channels](/docs/threads-messages-channels)

Work with threads, messages, and channels across platforms.

#### [Handling Events](/docs/handling-events)

Register handlers for mentions, messages, reactions, and platform-specific events.

#### [Posting Messages](/docs/posting-messages)

Send plain text, markdown, cards, and streams with thread.post().

## Adapters

Connect your bot to chat platforms and persist state across restarts.

#### [Platform Adapters](/docs/platform-adapters)

Connect your bot to messaging platforms with webhook verification, parsing, and native formatting.

#### [State Adapters](/docs/state-adapters)

Pluggable state adapters for thread subscriptions, distributed locking, and caching.

Browse all official, vendor-official, and community adapters on the [Adapters](/adapters) page.

## Resources

- [The Complete Guide to Chat SDK](https://vercel.com/kb/guide/the-complete-guide-to-chat-sdk?utm_source=chat-sdk_site\&utm_medium=docs\&utm_campaign=getting-started\&utm_content=the-complete-guide-to-chat-sdk): an end-to-end walkthrough that takes you from an empty project to a deployed multi-platform bot, covering adapters, state, handlers, cards, and streaming.

See all guides and templates on the [resources](/resources?utm_source=chat-sdk_site\&utm_medium=docs\&utm_campaign=getting-started\&utm_content=resources) page.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Handling Events
description: Register handlers for mentions, messages, reactions, member joins, and platform-specific events.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/getting-started
related:
  - /docs/slash-commands
  - /docs/actions
  - /docs/modals
  - /docs/api/message
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

You register a handler for each type of event your bot cares about, and the SDK routes each incoming webhook to the matching handler.

## How routing works

When a message arrives, the SDK evaluates handlers in this order:

1. Direct messages: if the thread is a DM and any `onDirectMessage` handlers are registered, they fire before `onSubscribedMessage`, `onNewMention`, and pattern handlers.
2. Subscribed threads: if the thread is subscribed, `onSubscribedMessage` fires and no other message handler runs. DMs reach this step only when no `onDirectMessage` handlers are registered.
3. Mentions: if the bot is @-mentioned in an unsubscribed thread, `onNewMention` fires. For backward compatibility, unsubscribed DMs are treated as mentions when no `onDirectMessage` handler is registered.
4. Pattern routing: `onNewMessage` handlers run one after another in registration order. Regex handlers fire when their pattern matches the message text. Handlers registered without a pattern fire for every message that reaches this step, including messages with empty text.

Reactions, slash commands, actions, and modals have their own dedicated routing and are not affected by subscription state.

## Handling @-mentions

`onNewMention` fires when your bot is @-mentioned in a thread it hasn't subscribed to. Most new conversations with your bot start here.

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  await thread.subscribe();
  await thread.post("Hello! I'm now listening to this thread.");
});
```

The handler receives a [`Thread`](/docs/api/thread) and a [`Message`](/docs/api/message). Once you call `thread.subscribe()`, future messages in that thread route to `onSubscribedMessage` instead. If your bot doesn't need ongoing context, respond without subscribing, as the triage bot below does.

### Example: AI assistant with context

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  await thread.subscribe();
  await thread.startTyping();

  const response = await generateAIResponse(message.text);
  await thread.post(response);
});
```

### Example: Triage bot

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  const ticket = await createTicket({
    title: message.text.slice(0, 100),
    reporter: message.author.fullName,
  });

  await thread.post(`Ticket created: ${ticket.url}`);
});
```

## Handling subscribed messages

`onSubscribedMessage` fires for every new message in a non-DM thread your bot has subscribed to. Once subscribed, messages (including @-mentions) route here instead of `onNewMention`.

If an `onDirectMessage` handler is registered, DM messages route there before subscription routing. Without a direct handler, subscribed DMs route to `onSubscribedMessage`.

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  if (message.isMention) {
    await thread.post("You mentioned me!");
    return;
  }

  await thread.post(`Got your message: ${message.text}`);
});
```

> Messages sent by the bot itself do not trigger this handler. You don't need to filter out your own messages.

### Example: Conversational AI with history

```typescript title="lib/bot.ts" lineNumbers
import { toAiMessages } from "chat/ai";

bot.onSubscribedMessage(async (thread, message) => {
  await thread.startTyping();

  // Build conversation history from thread messages
  const messages = [];
  for await (const msg of thread.allMessages) {
    messages.push(msg);
  }

  const history = await toAiMessages(messages);
  const response = await generateAIResponse(history);
  await thread.post(response);
});
```

See [`toAiMessages`](/docs/ai/to-ai-messages) for all options including multi-user name prefixing, message transforms, and attachment handling.

### Example: Unsubscribe on keyword

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  if (message.text.toLowerCase().includes("stop")) {
    await thread.unsubscribe();
    await thread.post("Got it, I'll stop watching this thread.");
    return;
  }

  // Handle other messages...
});
```

### Example: Thread state for multi-step flows

```typescript title="lib/bot.ts" lineNumbers
interface ThreadState {
  step: "awaiting_name" | "awaiting_email" | "done";
}

const bot = new Chat<typeof adapters, ThreadState>({ /* ...config */ });

bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.setState({ step: "awaiting_name" });
  await thread.post("Let's get you set up. What's your name?");
});

bot.onSubscribedMessage(async (thread, message) => {
  const state = await thread.state;

  switch (state?.step) {
    case "awaiting_name":
      await thread.setState({ step: "awaiting_email" });
      await thread.post(`Thanks, ${message.text}! What's your email?`);
      break;
    case "awaiting_email":
      await thread.setState({ step: "done" });
      await thread.post("All set! Your account has been created.");
      await thread.unsubscribe();
      break;
  }
});
```

## Handling pattern matches

`onNewMessage` fires for messages in unsubscribed threads that aren't DMs and don't mention the bot. Pass a regex for keyword-triggered responses that don't need an @-mention:

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMessage(/^help$/i, async (thread, message) => {
  await thread.post("Here's how I can help...");
});
```

The regex is tested against the message text. To receive every message at this step, including attachment-only messages with empty text, pass only a handler:

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMessage(async (thread, message) => {
  await thread.post(`Received: ${message.text || "an attachment"}`);
});
```

When several `onNewMessage` handlers apply to a message, they run one after another in registration order.

The handler-only form doesn't receive DMs or mentions, even when no handler for them is registered. Use `onDirectMessage` and `onNewMention` for those, and `onSubscribedMessage` for threads the bot has subscribed to.

### Example: FAQ auto-responder

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMessage(/\b(deploy|deployment|ship)\b/i, async (thread, message) => {
  await thread.post(
    "Deployments run automatically on push to `main`. " +
    "Check status at https://dashboard.example.com/deploys"
  );
});
```

### Example: Incident detection

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMessage(/\b(outage|down|incident|p[01])\b/i, async (thread, message) => {
  await thread.subscribe();
  await thread.post(
    "I've flagged this as a potential incident and I'm monitoring this thread."
  );

  await notifyOnCallTeam({
    channel: thread.channel.id,
    reporter: message.author.fullName,
    text: message.text,
  });
});
```

## Handling reactions

`onReaction` fires when users add or remove [emoji](/docs/emoji) reactions to messages. You can handle all reactions or filter by specific emoji.

```typescript title="lib/bot.ts" lineNumbers
import { emoji } from "chat";

// Handle specific emoji
bot.onReaction(["thumbs_up", "heart"], async (event) => {
  if (!event.added) return;

  await event.adapter.addReaction(
    event.threadId,
    event.messageId,
    emoji.raised_hands
  );
});

// Handle all reactions
bot.onReaction(async (event) => {
  console.log(`${event.user.userName} ${event.added ? "added" : "removed"} ${event.emoji}`);
});
```

### ReactionEvent

| Property    | Type                 | Description                                         |
| ----------- | -------------------- | --------------------------------------------------- |
| `emoji`     | `EmojiValue`         | Normalized emoji name for cross-platform comparison |
| `rawEmoji`  | `string`             | Platform-specific emoji string                      |
| `added`     | `boolean`            | `true` if added, `false` if removed                 |
| `user`      | `Author`             | The user who reacted                                |
| `message`   | `Message` (optional) | The message that was reacted to                     |
| `thread`    | `Thread`             | Thread for posting replies                          |
| `messageId` | `string`             | ID of the message that was reacted to               |
| `threadId`  | `string`             | Thread ID                                           |
| `adapter`   | `Adapter`            | The platform adapter                                |
| `raw`       | `unknown`            | Platform-specific event payload                     |

### Example: Approval workflow

```typescript title="lib/bot.ts" lineNumbers
bot.onReaction(["thumbs_up", "thumbs_down"], async (event) => {
  if (!event.added) return;

  const approved = event.emoji === "thumbs_up";
  const status = approved ? "approved" : "rejected";

  await event.thread.post(
    `Request ${status} by ${event.user.fullName}`
  );

  await updateRequestStatus(event.messageId, status, event.user.userId);
});
```

### Example: Save to external system

```typescript title="lib/bot.ts" lineNumbers
bot.onReaction(["bookmark"], async (event) => {
  if (!event.added || !event.message) return;

  await saveToDatabase({
    text: event.message.text,
    savedBy: event.user.userId,
    source: event.threadId,
  });

  await event.thread.post(
    `Bookmarked by ${event.user.fullName}`
  );
});
```

## Handling edits and deletes

`onMessageUpdated` fires when a user edits a message, and `onMessageDeleted` when one is removed. Both are lifecycle events: they never route through `onNewMessage`, `onNewMention`, or `onSubscribedMessage`, and the concurrency strategies do not apply to them.

```typescript title="lib/bot.ts" lineNumbers
bot.onMessageUpdated(async (thread, message, previousMessage) => {
  await mirror.update(message.id, message.text);
  if (previousMessage) {
    await audit.record(`"${previousMessage.text}" became "${message.text}"`);
  }
});

bot.onMessageDeleted(async (event) => {
  await mirror.remove(event.messageId);
});
```

`previousMessage` is the message as it read before the edit, supplied when the platform sends it. Slack does, so you can diff the change rather than only seeing the result. Treat it as optional: a platform that reports edits without the prior text leaves it `undefined`.

The bot's own edits are filtered out, so a streamed reply that renders through post-and-edit does not call `onMessageUpdated` back once per delta.

### Why the two shapes differ

`onMessageUpdated` receives `(thread, message, previousMessage?)` like the other message handlers, because an edit carries a full replacement message.

`onMessageDeleted` receives a single event instead. A delete has no message: platforms usually report only the id of what was removed, and `previousMessage` is best-effort. Use `chat.thread(event.threadId)` when you need a `Thread`, for example to post a notice in the conversation:

```typescript title="lib/bot.ts" lineNumbers
bot.onMessageDeleted(async (event) => {
  if (!event.previousMessage) {
    return;
  }
  await chat
    .thread(event.threadId)
    .post(`A message from ${event.previousMessage.author.userName} was deleted`);
});
```

### MessageDeletedEvent

| Property          | Type                   | Description                                              |
| ----------------- | ---------------------- | -------------------------------------------------------- |
| `messageId`       | `string`               | Platform-native id of the deleted message                |
| `threadId`        | `string`               | Thread the message was in                                |
| `channelId`       | `string`               | Channel the message was in                               |
| `platform`        | `string`               | Adapter name, e.g. `"slack"`                             |
| `previousMessage` | `Message \| undefined` | Snapshot, when the platform supplied enough to parse one |
| `deletedAt`       | `Date \| undefined`    | When the delete happened, when reported                  |
| `raw`             | `unknown`              | Platform-specific delete event                           |

> Only the Slack adapter emits these events today. Registering the handlers on another platform is harmless but nothing will call them. Check the **Message edit events** and **Message delete events** rows on each [adapter page](/adapters) before relying on them.

## Handling interactions

For button clicks, slash commands, and modal forms, see the dedicated guides:

- [Slash Commands](/docs/slash-commands): handle `/command` invocations from the message composer.
- [Actions](/docs/actions): handle button clicks and interactive card events.
- [Modals](/docs/modals): collect structured input through modal dialogs with validation.

## Handling Slack-specific events

These handlers are specific to the Slack platform and require the Slack adapter.

### Handling agent session stop and title changes

`onAgentSessionStopped` fires when a user clicks Slack's native stop button.
Chat SDK aborts the active `thread.signal` and transitions the session out of
`processing` before invoking your handler.

```typescript title="lib/bot.ts" lineNumbers
bot.onAgentSessionStopped(async (event) => {
  await releaseExternalResources(event.threadId);
});
```

`onAgentSessionTitleChanged` fires when a user renames a session in Slack:

```typescript title="lib/bot.ts" lineNumbers
bot.onAgentSessionTitleChanged(async (event) => {
  await syncTitle(event.threadId, event.title);
});
```

Subscribe to `agent_session_stopped` and `agent_session_title_changed` in the
Slack app manifest. Model calls should receive `thread.signal` so stop also
cancels upstream generation.

### Handling assistant threads

`onAssistantThreadStarted` fires when a user opens a new assistant thread in Slack. Use it with the [Slack Assistants API](/adapters/official/slack#legacy-slack-assistants-api) to set suggested prompts and status indicators.

```typescript title="lib/bot.ts" lineNumbers
bot.onAssistantThreadStarted(async (event) => {
  const slack = bot.getAdapter("slack") as SlackAdapter;
  await slack.setSuggestedPrompts(event.channelId, event.threadTs, [
    { title: "Get started", message: "What can you help me with?" },
    { title: "Summarize", message: "Summarize the current channel" },
  ]);
});
```

The `event` object includes:

| Property    | Type      | Description                                                           |
| ----------- | --------- | --------------------------------------------------------------------- |
| `channelId` | `string`  | The assistant thread's channel                                        |
| `threadTs`  | `string`  | Thread timestamp                                                      |
| `threadId`  | `string`  | Thread ID                                                             |
| `userId`    | `string`  | User who started the thread                                           |
| `context`   | `object`  | Assistant context (channelId, teamId, enterpriseId, threadEntryPoint) |
| `adapter`   | `Adapter` | The Slack adapter                                                     |

### Handling assistant context changes

`onAssistantContextChanged` fires when the assistant context changes, for example when a user navigates to a different channel while the assistant thread is open.

```typescript title="lib/bot.ts" lineNumbers
bot.onAssistantContextChanged(async (event) => {
  const slack = bot.getAdapter("slack") as SlackAdapter;
  await slack.setAssistantStatus(event.channelId, event.threadTs, "Updating context...");

  // Update prompts based on new context
  const channelName = event.context.channelId ?? "general";
  await slack.setSuggestedPrompts(event.channelId, event.threadTs, [
    { title: "Summarize", message: `Summarize #${channelName}` },
  ]);
});
```

### Handling App Home opens

`onAppHomeOpened` fires when a user opens your bot's Home tab in Slack. Use it to publish a dynamic view.

```typescript title="lib/bot.ts" lineNumbers
bot.onAppHomeOpened(async (event) => {
  const slack = bot.getAdapter("slack") as SlackAdapter;
  await slack.publishHomeView(event.userId, {
    type: "home",
    blocks: [
      {
        type: "section",
        text: { type: "mrkdwn", text: `Welcome, <@${event.userId}>!` },
      },
      {
        type: "actions",
        elements: [
          {
            type: "button",
            text: { type: "plain_text", text: "Open Dashboard" },
            url: "https://dashboard.example.com",
          },
        ],
      },
    ],
  });
});
```

The `event` object includes:

| Property    | Type                              | Description                                                                                                                                                   |
| ----------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`    | `string`                          | User who opened the Home tab                                                                                                                                  |
| `channelId` | `string`                          | Channel context                                                                                                                                               |
| `tab`       | `string \| undefined`             | The opened tab (`"home"` or `"messages"`). Under `agentView` the event fires for every tab, so branch on this to tell a Home-tab open from the DM-open signal |
| `entities`  | `AppContextEntity[] \| undefined` | Folded active-view context (`agentView` only)                                                                                                                 |
| `adapter`   | `Adapter`                         | The Slack adapter                                                                                                                                             |

### Handling active-view context (Agent messaging)

Under Slack's [Agent messaging experience](/adapters/official/slack#agent-messaging-experience) (`agent_view`), `onAppContextChanged` fires when the user's active view changes (opening a channel, DM, or canvas). The event carries normalized `entities` describing what the user is viewing.

```typescript title="lib/bot.ts" lineNumbers
bot.onAppContextChanged((event) => {
  for (const entity of event.entities) {
    if (entity.kind === "channel") {
      // User is viewing channel entity.channelId
    }
  }
});
```

The `event` object includes:

| Property    | Type                 | Description                                                          |
| ----------- | -------------------- | -------------------------------------------------------------------- |
| `channelId` | `string`             | The agent conversation channel                                       |
| `userId`    | `string`             | The user whose view changed                                          |
| `entities`  | `AppContextEntity[]` | Relevance-ordered active-view entities; empty when the view is empty |
| `raw`       | `unknown`            | Platform-specific raw payload                                        |
| `adapter`   | `Adapter`            | The Slack adapter                                                    |

Each `AppContextEntity` is one of: `{ kind: "channel", channelId }`, `{ kind: "canvas", canvasId }`, `{ kind: "list", listId }`, `{ kind: "message", messageTs, channelId }`, or `{ kind: "unknown", type, value }` (all with optional `teamId`/`enterpriseId`).

Slack also folds this context onto the events the user acts through. `onAppHomeOpened` events carry the same normalized `entities`, and so do DM messages. Read the context at message time with `getAppContext`:

```typescript title="lib/bot.ts" lineNumbers
import { getAppContext } from "@chat-adapter/slack";

bot.onDirectMessage((thread, message) => {
  const viewing = getAppContext(message);
  const viewedThread = viewing.find((e) => e.kind === "message");
  // viewedThread?.messageTs is the root ts of the thread the user is viewing
});
```

## Handling member joined channel

`onMemberJoinedChannel` fires when a member joins a channel. Slack emits it for every user who joins a channel the bot can see. Teams emits it only when the bot itself is added to a channel or group chat. Use it to post welcome messages or onboard users automatically.

```typescript title="lib/bot.ts" lineNumbers
bot.onMemberJoinedChannel(async (event) => {
  // Only post when the bot itself joins
  if (event.userId !== event.adapter.botUserId) {
    return;
  }

  await event.adapter.postMessage(
    event.channelId,
    "Hello! I'm now available in this channel. Mention me to get started."
  );
});
```

The `event` object includes:

| Property    | Type                | Description                                                         |
| ----------- | ------------------- | ------------------------------------------------------------------- |
| `adapter`   | `Adapter`           | The adapter that emitted the event (Slack or Teams)                 |
| `channelId` | `string`            | The channel that was joined                                         |
| `userId`    | `string`            | The user who joined. On Teams this is always the bot (`28:<appId>`) |
| `inviterId` | `string` (optional) | The user who invited them                                           |

## Installation lifecycle

`onInstalled` and `onUninstalled` receive bot installation and removal events.
The Teams adapter emits both, for personal, group chat, and team installs. The
Slack adapter emits `onUninstalled` when a workspace or Enterprise Grid org
uninstalls the app.

```typescript
bot.onInstalled(async (event) => {
  if (event.adapter.name !== "teams") return;
  // Persist the destination or start your onboarding flow.
  await recordInstallation(event);
});

bot.onUninstalled(async (event) => {
  if (event.adapter.name !== "teams") return;
  await removeInstallation(event);
});
```

Events include `adapter`, the activity `id`, the `action`, the platform
`conversationId`, `raw`, and the optional actor `userId`, `tenantId`, and
`locale`. The optional `channelId` is the normalized Chat destination; persist it
and post later with `bot.channel(channelId).post()`.

`recordInstallation` and `removeInstallation` are application-owned. For Teams
team installs, use `event.raw.channelData.team.id` as the installation scope;
the install and removal events can carry different `conversationId` values.
Include the bot ID and tenant ID in your persistence key. For Slack,
`conversationId` is the installation key: the `team_id`, or the `enterprise_id`
for org-wide installs. `tenantId` is the Enterprise Grid `enterprise_id` when
the event carries one.

`action` is `add`, `add-upgrade`, `remove`, or `remove-upgrade`. The upgrade
variants mean the app manifest added or removed the bot, so persist and clean
up for both variants. Routine app upgrades do not emit these events.
A Teams team or group chat install also
emits `onMemberJoinedChannel`, so keep each welcome flow in one handler. Make
side effects idempotent for webhook retries. Handler errors are logged, and
asynchronous work is registered with the webhook's `waitUntil`.

See [Teams installation lifecycle](/adapters/official/teams#installation-lifecycle)
for persistence, reinstall cleanup, and proactive messages, and
[Slack uninstalls](/adapters/official/slack#uninstalls) for Slack cleanup.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: History
description: Store and retrieve message history across user, thread, and channel scopes.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/state-adapters
related:
  - /docs/handling-events
  - /docs/api/history
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The History API reads and persists message history in three scopes, keyed by user, thread, or channel. The user scope is stored in your state adapter. Thread history comes from platform APIs, with an optional cache in the state adapter. Channel history reads from the platform through adapter methods.

| Scope   | Access                | Keyed by                | Typical use                                       |
| ------- | --------------------- | ----------------------- | ------------------------------------------------- |
| User    | `bot.history.user`    | Cross-platform user key | LLM context, audit trail, GDPR                    |
| Thread  | `bot.history.thread`  | Thread ID               | Backfill for adapters without server-side history |
| Channel | `bot.history.channel` | Channel ID              | Channel-level summaries, moderation               |

> `bot.history` is the unified successor to `bot.transcripts`. The user scope is a drop-in replacement. See [Migrating from `bot.transcripts`](#migrating-from-bottranscripts) below.

## Setup

All three scopes are available once you configure a state adapter. The user scope also needs an `identity` resolver:

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createDiscordAdapter } from "@chat-adapter/discord";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
    discord: createDiscordAdapter(),
  },
  state: createRedisState({ url: process.env.REDIS_URL! }),

  history: {
    user: {
      // Required. Maps each inbound message to a stable cross-platform key.
      // Return null to skip persistence for that message.
      identity: ({ author }) => author.email ?? null,

      // Storage tuning. retention is the list TTL, refreshed on every append.
      retention: "30d",
      maxPerUser: 200,
    },
  },
});
```

`history.user` requires an identity resolver. Set `history.user.identity`, or keep the deprecated top-level `identity` field during migration. Omitting both when `history.user` (or legacy `transcripts`) is set throws at construction.

Set `history.user.maxPerUser: false` to disable count-based eviction. Omit `retention` as well to keep entries without a TTL. The state adapter must use durable storage to retain history across restarts. The legacy `transcripts.maxPerUser` field also accepts `false`.

Thread and channel scopes are always available on `bot.history`. Use `history.thread` to tune the thread cache, which is used by adapters with `persistThreadHistory: true` such as WhatsApp, and Telegram unless you turn the option off:

```typescript
const bot = new Chat({
  // ...
  history: {
    thread: {
      maxMessages: 200,
      ttlMs: 14 * 24 * 60 * 60 * 1000, // 14 days
    },
  },
});
```

## User history

`bot.history.user` stores a per-user transcript keyed by a stable cross-platform identifier. The same user can talk to your bot on Slack and Discord and see the same accumulated history.

### Building LLM context

The most common pattern is to append the user's message, build a prompt from recent history, post the reply, and then append the reply.

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, msg) => {
  await bot.history.user.append(thread, msg);

  const recent = await bot.history.user.list({
    userKey: msg.userKey!,
    limit: 20,
  });

  const reply = await generateReply(recent, msg);
  await thread.post(reply);

  await bot.history.user.append(
    thread,
    { role: "assistant", text: reply },
    { userKey: msg.userKey! }
  );
});
```

A few details about this pattern:

- The SDK sets `msg.userKey` from your `identity` resolver before your handler runs. If the resolver returned `null`, `msg.userKey` stays `undefined` and `append` does nothing.
- Bot replies are stored only when you append them. The SDK does not capture `thread.post()` output, so you decide what gets persisted. That matters for retries and intermediate streaming chunks.
- `list` returns entries oldest first, the order a model expects. Use `limit` to keep prompts bounded.

### Filtering entries

```typescript
// Recent 50 across all platforms (default)
await bot.history.user.list({ userKey: "mike@acme.com" });

// Newest 20 only
await bot.history.user.list({ userKey: "mike@acme.com", limit: 20 });

// Single platform
await bot.history.user.list({ userKey: "mike@acme.com", platforms: ["slack"] });

// Single thread
await bot.history.user.list({
  userKey: "mike@acme.com",
  threadId: "slack:C123:1234.5678",
});

// Only the user's own messages
await bot.history.user.list({ userKey: "mike@acme.com", roles: ["user"] });
```

### Deleting a user's history

For GDPR data-subject requests or "forget me" flows:

```typescript
await bot.history.user.delete({ userKey: "mike@acme.com" });
// → { deleted: 47 }
```

This deletes every entry stored under the key. Single-entry and time-range deletes are not supported, because the underlying `appendToList` primitive can't do them safely under concurrent writes.

## Thread history

`bot.history.thread` reads thread messages through `adapter.fetchMessages` and keeps a per-thread cache for adapters that lack server-side message history APIs and set `persistThreadHistory: true`, such as Telegram and WhatsApp. For those adapters, `list()` falls back to the cache when the adapter returns an empty first page. For every other adapter, the platform response is authoritative.

Telegram sets `persistThreadHistory: true` by default. If you pass `persistThreadHistory: false` to `createTelegramAdapter`, the SDK doesn't write to the cache or fall back to it, so `list()` returns only the messages the current process has seen. On serverless platforms, that list is empty after a cold start.

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  // bot.history.thread.list() handles both cases: it delegates to
  // adapter.fetchMessages, and on adapters that persist history in the
  // SDK-maintained cache (persistThreadHistory) falls back to that cache
  // when the adapter returns an empty first page.
  const { messages } = await bot.history.thread.list(thread.id, { limit: 20 });

  const reply = await generateReply(messages, message);
  await thread.post(reply);
});
```

> Thread history is populated automatically when `adapter.persistThreadHistory` is `true`. You don't need to append manually. For adapters with server-side history (Slack, Teams, Discord), prefer `thread.messages` or `adapter.fetchMessages`.

## Channel history

`bot.history.channel` reads top-level channel messages and lists threads. It delegates to the adapter, and its methods throw when the adapter doesn't implement the underlying capability, such as `listThreads` on WhatsApp.

```typescript title="lib/bot.ts" lineNumbers
bot.onSubscribedMessage(async (thread, message) => {
  const channelId = thread.channelId;

  const { messages } = await bot.history.channel.listMessages(channelId, {
    limit: 10,
  });

  const { threads } = await bot.history.channel.listThreads(channelId, {
    limit: 20,
  });

  const reply = await generateChannelSummary(messages, threads);
  await thread.post(reply);
});
```

## Identity resolution

The identity resolver can live on `history.user.identity` (preferred) or the deprecated top-level `ChatConfig.identity` field. It runs once per inbound message:

```typescript
history: {
  user: {
    identity: async ({ adapter, author, message }) => {
      if (author.email) {
        return author.email;
      }
      // Map a platform user to an internal ID
      return await lookupUser(adapter, author.userId);
    },
    retention: "30d",
  },
}
```

Return `null` when you can't resolve a key. The SDK won't fall back to a platform-specific ID, because that would split a user's history across platforms without any warning.

If the resolver throws, the SDK logs a warning and dispatches the message without a `userKey`. Handlers still run; only the persistence is skipped.

## Migrating from `bot.transcripts`

`bot.transcripts` is deprecated in favor of `bot.history.user`. The API is identical, so you rename the config key and the call sites:

```typescript
// Before
const bot = new Chat({
  identity: ({ author }) => author.email ?? null,
  transcripts: { retention: "30d", maxPerUser: 200 },
});

await bot.transcripts.append(thread, msg);
const entries = await bot.transcripts.list({ userKey, limit: 20 });
await bot.transcripts.delete({ userKey });

// After: identity on history.user (top-level identity still works during migration)
const bot = new Chat({
  history: {
    user: {
      identity: ({ author }) => author.email ?? null,
      retention: "30d",
      maxPerUser: 200,
    },
  },
});

await bot.history.user.append(thread, msg);
const entries = await bot.history.user.list({ userKey, limit: 20 });
await bot.history.user.delete({ userKey });
```

`bot.transcripts` continues to work and will not be removed in the current major version.

You can migrate one field at a time: when both `history.user` and the legacy `transcripts` block are set, they merge, with `history.user` winning field by field. Settings like `retention` and `maxPerUser` left on `transcripts` keep applying until you move them.

## Storage

The user scope and the thread cache use `StateAdapter.appendToList` and `getList`. Channel scope reads from platform APIs and is not persisted in state by default.

| Scope                  | Storage / source                                  | Key or API                                                     |
| ---------------------- | ------------------------------------------------- | -------------------------------------------------------------- |
| User                   | State adapter                                     | `transcripts:user:{userKey}`                                   |
| Thread cache           | State adapter (when `persistThreadHistory: true`) | `msg-history:{threadId}`                                       |
| Thread / channel reads | Platform adapter                                  | `adapter.fetchMessages`, `fetchChannelMessages`, `listThreads` |

On channel-scoped platforms such as WhatsApp and Telegram, inbound messages may also be appended under `msg-history:{channelId}`. `bot.history.channel.listMessages` reads from that cache only when the adapter doesn't implement `fetchChannelMessages`.

Appends to user and thread cache keys are atomic, so concurrent inbound messages on the same key don't race.

## Reference

See [History API reference](/docs/api/history) for full type signatures, configuration options, and entry shapes.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Introduction
description: A unified SDK for building chat bots across Slack, Microsoft Teams, Google Chat, Discord, Telegram, and more.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
related:
  - /docs/getting-started
  - /docs/usage
  - /docs/api
  - /docs/ai
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Chat SDK is a TypeScript library for building chat bots that run on multiple platforms from one codebase. You write the bot logic once and deploy it to any platform that has an [adapter](/adapters).

## Why Chat SDK?

Each chat platform has its own API, webhook format, and quirks, so supporting several of them usually means maintaining separate code for each. Chat SDK puts those differences behind adapters and gives you one interface for:

- Typed event handlers for mentions, messages, reactions, button clicks, slash commands, and modals
- Thread subscriptions for multi-turn conversations
- Cards, buttons, and modals written in JSX that render natively on each platform
- Streaming LLM responses into a message
- Serverless deployments, with distributed state in Redis and message deduplication

## How it works

Chat SDK has three core concepts:

1. `Chat` coordinates your adapters and routes incoming events to your handlers.
2. [Adapters](/adapters) handle the platform-specific work: parsing webhooks, formatting messages, and calling the platform's API.
3. State is a pluggable persistence layer for thread subscriptions and distributed locking.

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
  },
  state: createRedisState(),
});

bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.post("Hello! I'm listening to this thread.");
});
```

Adapter and state factories read their credentials from environment variables such as `SLACK_BOT_TOKEN`, `SLACK_SIGNING_SECRET`, and `REDIS_URL`, so the example above passes no options. Pass explicit values to override them.

## Adapters

Install only the adapters you need. Browse the full catalog on the [Adapters](/adapters) page, and compare official platform features on [Platform Adapters](/docs/platform-adapters#feature-matrix).

#### [Adapter Catalog](/docs/adapter-catalog)

List every adapter with its capabilities and setup requirements from one dependency-free package.

#### [Platform Adapters](/docs/platform-adapters)

Connect your bot to messaging platforms with webhook verification, parsing, and native formatting.

#### [State Adapters](/docs/state-adapters)

Persist thread subscriptions, distributed locks, and caches across restarts.

## AI coding agents

If you use an AI coding agent such as OpenAI Codex, Claude Code, or Cursor, install the Chat SDK skill so it knows the SDK's APIs, adapter patterns, and project conventions before it writes code.

```bash
npx skills add vercel/chat
```

The skill references bundled documentation in `node_modules/chat/docs`, plus adapter guides and starter templates in the published package.

You can also install the [Vercel Plugin](https://vercel.com/plugin) for a broader agent toolkit. It includes the Chat SDK skill along with specialist agents and slash commands:

```bash
npx plugins add vercel/vercel-plugin
```

For agent-readable documentation, see [llms.txt](/llms.txt) (page index) or [llms-full.txt](/llms-full.txt) (full text).

## Contributing

Ship an adapter for a new platform, or list a vendor-maintained one in the catalog.

#### [Build an adapter](/docs/contributing/building)

Implement the Adapter interface for any messaging platform or state backend.

#### [List a vendor-official adapter](/docs/contributing/vendor-official)

How platform vendors qualify and list a maintained adapter in the Vendor Official tier.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Modals
description: Collect structured user input through modal dialogs with text fields, dropdowns, and validation.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/actions
related:
  - /docs/api/modals
  - /docs/cards
  - /docs/slash-commands
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Modals open form dialogs in response to button clicks or [slash commands](/docs/slash-commands). They support text inputs, dropdowns, radio buttons, and server-side validation. Modals are currently supported on Slack and Teams.

## Open a modal

Modals are opened from [action handlers](/docs/actions) or [slash command handlers](/docs/slash-commands) using `event.openModal()`:

```tsx title="lib/bot.tsx" lineNumbers
import { Modal, TextInput, DateInput, Select, SelectOption } from "chat";

bot.onAction("feedback", async (event) => {
  await event.openModal(
    <Modal
      callbackId="feedback_form"
      title="Send Feedback"
      submitLabel="Send"
      closeLabel="Cancel"
      notifyOnClose
    >
      <TextInput
        id="message"
        label="Your Feedback"
        placeholder="Tell us what you think..."
        multiline
      />
      <Select id="category" label="Category" placeholder="Select a category">
        <SelectOption label="Bug Report" value="bug" />
        <SelectOption label="Feature Request" value="feature" />
        <SelectOption label="General" value="general" />
      </Select>
      <DateInput id="due_date" label="Follow up by" optional />
      <TextInput
        id="email"
        label="Email (optional)"
        placeholder="your@email.com"
        optional
      />
    </Modal>
  );
});
```

## Components

### Modal

The top-level container for the form.

| Prop              | Type                 | Description                                   |
| ----------------- | -------------------- | --------------------------------------------- |
| `callbackId`      | `string`             | Identifier for matching submit/close handlers |
| `title`           | `string`             | Modal title                                   |
| `submitLabel`     | `string` (optional)  | Submit button text (defaults to "Submit")     |
| `closeLabel`      | `string` (optional)  | Cancel button text (defaults to "Cancel")     |
| `notifyOnClose`   | `boolean` (optional) | Fire `onModalClose` when user cancels         |
| `callbackUrl`     | `string` (optional)  | URL to POST form values to on submit          |
| `privateMetadata` | `string` (optional)  | Custom context passed through to handlers     |

### TextInput

A text field for user input.

| Prop           | Type                 | Description                              |
| -------------- | -------------------- | ---------------------------------------- |
| `id`           | `string`             | Field identifier (key in `event.values`) |
| `label`        | `string`             | Field label                              |
| `placeholder`  | `string` (optional)  | Placeholder text                         |
| `initialValue` | `string` (optional)  | Pre-filled value                         |
| `multiline`    | `boolean` (optional) | Render as textarea                       |
| `optional`     | `boolean` (optional) | Allow empty submission                   |
| `maxLength`    | `number` (optional)  | Maximum character count                  |

### DateInput

A date picker. Renders a Slack `datepicker` and an Adaptive Card `Input.Date`.

| Prop           | Type                 | Description                              |
| -------------- | -------------------- | ---------------------------------------- |
| `id`           | `string`             | Field identifier (key in `event.values`) |
| `label`        | `string`             | Field label                              |
| `placeholder`  | `string` (optional)  | Placeholder text                         |
| `initialValue` | `string` (optional)  | Pre-filled date as `YYYY-MM-DD`          |
| `optional`     | `boolean` (optional) | Allow empty submission                   |

The submitted value is an ISO `YYYY-MM-DD` string. An `initialValue` that is not a valid `YYYY-MM-DD` date is ignored with a warning, because Slack rejects a malformed `initial_date` by refusing to open the modal at all.

### NumberInput

A numeric field. Renders a Slack `number_input` and an Adaptive Card `Input.Number`.

| Prop           | Type                 | Description                                |
| -------------- | -------------------- | ------------------------------------------ |
| `id`           | `string`             | Field identifier (key in `event.values`)   |
| `label`        | `string`             | Field label                                |
| `placeholder`  | `string` (optional)  | Placeholder text                           |
| `initialValue` | `number` (optional)  | Pre-filled value                           |
| `min`          | `number` (optional)  | Minimum accepted value                     |
| `max`          | `number` (optional)  | Maximum accepted value                     |
| `decimal`      | `boolean` (optional) | Allow decimals (defaults to integers only) |
| `optional`     | `boolean` (optional) | Allow empty submission                     |

Like every other field, the submitted value arrives in `event.values` as a string. Parse it with `Number(...)` if you need a number.

> `decimal` is enforced by Slack. Adaptive Cards has no decimal switch, so `Input.Number` accepts decimals on Teams regardless. Validate server-side if the distinction matters.

### Select

A dropdown for selecting a single option.

| Prop             | Type                 | Description                                                             |
| ---------------- | -------------------- | ----------------------------------------------------------------------- |
| `id`             | `string`             | Field identifier                                                        |
| `label`          | `string`             | Field label                                                             |
| `placeholder`    | `string` (optional)  | Placeholder text                                                        |
| `initialOption`  | `string` (optional)  | Pre-selected value                                                      |
| `optional`       | `boolean` (optional) | Allow empty submission                                                  |
| `dispatchAction` | `boolean` (optional) | Send selection changes to `onAction` in Slack modals (default: `false`) |

### ExternalSelect

A dropdown that loads its options dynamically from a handler as the user types. Use it for large or remotely stored option sets, such as people, tickets, or records, where a static `<Select>` would be impractical. Slack-only.

| Prop             | Type                          | Description                                                                                                                                                                                                                                           |
| ---------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`             | `string`                      | Field identifier (key in `event.values`)                                                                                                                                                                                                              |
| `label`          | `string`                      | Field label                                                                                                                                                                                                                                           |
| `placeholder`    | `string` (optional)           | Placeholder text                                                                                                                                                                                                                                      |
| `minQueryLength` | `number` (optional)           | Minimum characters before the loader fires (Slack default: 3)                                                                                                                                                                                         |
| `initialOption`  | `{ label, value }` (optional) | Pre-selected option when the modal opens (must match an option returned by the loader). For static `<Select>`, `initialOption` is the value string. For `<ExternalSelect>` it's the full `{ label, value }` object because the loader hasn't run yet. |
| `optional`       | `boolean` (optional)          | Allow empty submission                                                                                                                                                                                                                                |

Register the loader with `onOptionsLoad`:

```tsx title="lib/bot.tsx" lineNumbers
import { ExternalSelect, Modal } from "chat";

bot.onAction("assign", async (event) => {
  await event.openModal(
    <Modal callbackId="assign_form" title="Assign to…">
      <ExternalSelect
        id="assignee"
        label="Assignee"
        placeholder="Search people"
        minQueryLength={1}
      />
    </Modal>
  );
});

bot.onOptionsLoad("assignee", async (event) => {
  const people = await peopleService.search(event.query);
  return people.map((p) => ({ label: p.fullName, value: p.id }));
});

bot.onModalSubmit("assign_form", async (event) => {
  const assigneeId = event.values.assignee;
  // …
});
```

The selected value arrives in `event.values` on submit, the same as for a static `<Select>`.

#### Grouped options

Return an array of groups instead of a flat options array to render headers between sections (e.g. "Recent" / "All"):

```tsx
bot.onOptionsLoad("assignee", async (event) => {
  const [recent, all] = await Promise.all([
    peopleService.recent(event.user.userId),
    peopleService.search(event.query),
  ]);
  return [
    { label: "Recent", options: recent.map((p) => ({ label: p.fullName, value: p.id })) },
    { label: "All", options: all.map((p) => ({ label: p.fullName, value: p.id })) },
  ];
});
```

Slack limits: max 100 groups, max 100 options per group, group label max 75 characters.

> Slack requires a response within 3 seconds for options requests. The adapter caps the loader at \~2.5s and returns an empty result on timeout, so keep your loader fast by caching, prefetching, or narrowing the query server-side.

> On Slack, `ExternalSelect` uses Slack's `block_suggestion` payload, which is dispatched to the **Options Load URL**. In your [Slack app settings](https://api.slack.com/apps) go to **Interactivity & Shortcuts** → **Select Menus** and set the **Options Load URL** to the same endpoint as your Interactivity Request URL (e.g. `https://your-domain.com/api/webhooks/slack`). Without this setting, typing into an external select returns no results and no error.

### RadioSelect

A radio button group for mutually exclusive options.

| Prop             | Type                 | Description                                                             |
| ---------------- | -------------------- | ----------------------------------------------------------------------- |
| `id`             | `string`             | Field identifier                                                        |
| `label`          | `string`             | Field label                                                             |
| `initialOption`  | `string` (optional)  | Pre-selected value                                                      |
| `optional`       | `boolean` (optional) | Allow empty submission                                                  |
| `dispatchAction` | `boolean` (optional) | Send selection changes to `onAction` in Slack modals (default: `false`) |

### SelectOption

An option for `Select` or `RadioSelect`.

| Prop          | Type                | Description               |
| ------------- | ------------------- | ------------------------- |
| `label`       | `string`            | Display text              |
| `value`       | `string`            | Value passed to handler   |
| `description` | `string` (optional) | Help text below the label |

## Handle selection changes

In Slack modals, set `dispatchAction` on `Select` or `RadioSelect` to receive changes before submission:

```tsx
<RadioSelect id="scope" label="Scope" dispatchAction>
  <SelectOption label="Personal" value="personal" />
  <SelectOption label="Team" value="team" />
</RadioSelect>
```

Register `bot.onAction("scope", handler)` to handle the selection. `event.actionId` is the input ID and `event.value` is the selected option's value. Clearing an optional select produces an undefined `event.value`. Modal actions have no `event.thread`; the Slack view ID and form state are available in `event.raw`.

This maps to Slack's [input block `dispatch_action`](https://docs.slack.dev/reference/block-kit/blocks/input-block/). It defaults to `false`, is ignored by other adapters, and does not change the values received by `onModalSubmit`. Text input change events are not supported by this option.

To change dependent fields, update the view using Slack's [views.update](https://docs.slack.dev/reference/methods/views.update/) API. Preserve the view's `private_metadata` and use its `hash` to protect against out-of-order updates. Keep the same input IDs for fields whose existing values should be preserved.

## Handle submissions

Register a handler with `onModalSubmit` using the same `callbackId`:

```typescript title="lib/bot.ts" lineNumbers
bot.onModalSubmit("feedback_form", async (event) => {
  const { message, category, email } = event.values;

  // Validate input and return errors to show in the modal
  if (!message || message.length < 5) {
    return {
      action: "errors",
      errors: { message: "Feedback must be at least 5 characters" },
    };
  }

  // Post confirmation to the original thread
  if (event.relatedThread) {
    await event.relatedThread.post(`Feedback received! Category: ${category}`);
  }

  // Update the message that triggered the modal
  if (event.relatedMessage) {
    await event.relatedMessage.edit("Feedback submitted!");
  }

  // Return nothing (or { action: "close" }) to close the modal
});
```

### Response types

| Response                                               | Description                                               |
| ------------------------------------------------------ | --------------------------------------------------------- |
| `undefined` or `{ action: "close" }`                   | Close the current view (goes back one level in the stack) |
| `{ action: "clear" }`                                  | Close all views and dismiss the modal entirely            |
| `{ action: "errors", errors: { fieldId: "message" } }` | Show validation errors on specific fields                 |
| `{ action: "update", modal: ModalElement }`            | Replace the modal content                                 |
| `{ action: "push", modal: ModalElement }`              | Push a new modal view onto the stack                      |

### ModalSubmitEvent

| Property          | Type                     | Description                                                                         |
| ----------------- | ------------------------ | ----------------------------------------------------------------------------------- |
| `callbackId`      | `string`                 | Modal identifier                                                                    |
| `viewId`          | `string`                 | Platform view ID                                                                    |
| `values`          | `Record<string, string>` | Form field values keyed by input `id`                                               |
| `user`            | `Author`                 | The user who submitted                                                              |
| `privateMetadata` | `string` (optional)      | Custom context from the Modal component                                             |
| `relatedThread`   | `Thread` (optional)      | Thread where the modal was triggered                                                |
| `relatedMessage`  | `SentMessage` (optional) | Message with the button that opened the modal                                       |
| `relatedChannel`  | `Channel` (optional)     | Channel where the modal was triggered (from [slash commands](/docs/slash-commands)) |
| `adapter`         | `Adapter`                | The platform adapter                                                                |
| `raw`             | `unknown`                | Platform-specific payload                                                           |

## Handle cancellation

To run code when a user cancels a modal, register `onModalClose`. The `Modal` component must set `notifyOnClose`:

```typescript title="lib/bot.ts" lineNumbers
bot.onModalClose("feedback_form", async (event) => {
  console.log(`${event.user.userName} cancelled the feedback form`);

  if (event.relatedThread) {
    await event.relatedThread.post("No worries, let us know if you change your mind!");
  }
});
```

## Callback URLs

Like buttons, modals accept a `callbackUrl`. When the modal is submitted, the form values are POSTed to the URL:

```tsx title="lib/bot.tsx" lineNumbers
await event.openModal(
  <Modal callbackUrl={webhook.url} callbackId="intake" title="Request Access" submitLabel="Submit">
    <TextInput id="reason" label="Reason" multiline />
  </Modal>
);
```

The POST body for modal submissions:

```json
{
  "type": "modal_submit",
  "callbackId": "intake",
  "values": { "reason": "Need access to production logs" },
  "user": { "id": "U123", "name": "alice" }
}
```

## Pass context with privateMetadata

Use `privateMetadata` to carry context from the button click through to the submit handler:

```tsx title="lib/bot.tsx" lineNumbers
bot.onAction("report", async (event) => {
  await event.openModal(
    <Modal
      callbackId="report_form"
      title="Report Bug"
      submitLabel="Submit"
      privateMetadata={JSON.stringify({
        reportType: event.value,
        threadId: event.threadId,
      })}
    >
      <TextInput id="title" label="Bug Title" />
      <TextInput id="steps" label="Steps to Reproduce" multiline />
    </Modal>
  );
});

bot.onModalSubmit("report_form", async (event) => {
  const metadata = event.privateMetadata
    ? JSON.parse(event.privateMetadata)
    : {};

  console.log(metadata.reportType); // "bug"
});
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Platform Adapters
description: Platform adapters connect your bot to messaging platforms such as Slack, Teams, and Google Chat.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
prerequisites:
  - /docs/getting-started
  - /docs/adapters
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Platform adapters handle webhook verification, message parsing, and API calls for each messaging platform. Install only the adapters you need. Browse every available adapter, including community-built ones, on the [Adapters](/adapters) page.

Need a browser chat UI? See the [Web adapter](/adapters/official/web). It speaks the AI SDK UI stream protocol and works with React (`@ai-sdk/react`), Vue (`@ai-sdk/vue`), and Svelte (`@ai-sdk/svelte`), so one bot can serve Slack, Teams, and a browser chat UI.

## Feature matrix

This matrix covers Vercel-maintained [official adapters](/adapters) only. For vendor-official and community adapters, see each adapter's page.

> Partial support means the feature works with limitations. See individual adapter pages for details.

## How adapters work

Each adapter implements the `Adapter` interface, which the `Chat` class uses to route events and send messages. When a webhook arrives, the adapter:

1. Verifies the request signature.
2. Parses the platform-specific payload into a normalized `Message`.
3. Passes the message to the `Chat` class, which routes it to your handlers.

When your handler posts a reply, the adapter converts it from markdown, an AST, or a card into the platform's native format.

## Using multiple adapters

Register multiple [adapters](/adapters) and your event handlers work across all of them:

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createTeamsAdapter } from "@chat-adapter/teams";
import { createGoogleChatAdapter } from "@chat-adapter/gchat";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
    teams: createTeamsAdapter(),
    gchat: createGoogleChatAdapter(),
  },
  state: createRedisState(),
});

// This handler fires for mentions on any platform
bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.post("Hello!");
});
```

Each adapter reads its credentials from environment variables, so you only pass config to override them.

> This example uses Redis for state. See [State Adapters](/docs/state-adapters) for all available options.

Each adapter gets a webhook handler at `bot.webhooks.<name>`, keyed by the name you registered it under.

## Customizing an adapter via subclassing

Official adapters expose their extension points as `protected` members, so you can subclass an adapter to override or extend its behavior without forking the package. Use this to handle a payload type the built-in adapter doesn't cover, intercept verification, or wrap an existing handler.

```typescript title="lib/custom-telegram.ts" lineNumbers
import { TelegramAdapter, type TelegramUpdate } from "@chat-adapter/telegram";
import type { WebhookOptions } from "chat";

export class CustomTelegramAdapter extends TelegramAdapter {
  protected override processUpdate(
    update: TelegramUpdate,
    options?: WebhookOptions
  ): void {
    // Handle a payload type the base adapter doesn't, e.g. chat_join_request.
    if ("chat_join_request" in update) {
      this.logger.info("Received chat_join_request", { update });
      return;
    }
    super.processUpdate(update, options);
  }
}
```

Construct your subclass anywhere you'd construct the base adapter, for example `adapters: { telegram: new CustomTelegramAdapter({ ... }) }`. Members marked `private` stay inaccessible. If you need a hook that isn't `protected`, open an issue.

> `protected` members are broader than the public API and are not yet stable. Their signatures may change in minor releases. Pin the adapter version you build against, watch that adapter's changelog, and override the smallest hook that solves your problem so upgrades stay manageable. If you rely on a particular hook, open an issue so we can consider making it a stable, documented extension point.

#### [Build an adapter](/docs/contributing/building)

Implement the Adapter interface for any messaging platform.

#### [List a vendor-official adapter](/docs/contributing/vendor-official)

How platform vendors qualify and list a maintained adapter in the Vendor Official tier.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Posting Messages
description: Different ways to render and send messages with thread.post().
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/cards
  - /docs/streaming
  - /docs/files
  - /docs/api/postable-message
  - /docs/threads-messages-channels
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`thread.post()` accepts several message formats: plain strings, markdown, an mdast AST, interactive cards, and streams. [Choosing a format](#choosing-a-format) compares them.

## Plain text

Pass a string to send it to the platform as-is, without any formatting conversion.

```typescript title="lib/bot.ts" lineNumbers
await thread.post("Hello world");
```

## Markdown

Pass a `{ markdown }` object to have the SDK render standard markdown on each platform. Slack receives it in its native `markdown_text` field, and other adapters convert it to their platform's format.

```typescript title="lib/bot.ts" lineNumbers
await thread.post({
  markdown: "**Bold**, _italic_, and `code`",
});
```

The SDK parses the markdown into an mdast AST, and each adapter either handles it natively or converts it to the platform's format.

## Reply to a message

Use `thread.reply()` when the platform should preserve a native reference to a specific message:

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMessage(/help/i, async (thread, message) => {
  await thread.reply(message, {
    markdown: "Thanks, I can help with that.",
  });
});
```

The target can be a `Message` from the same thread or its message ID. Replies accept the same plain text, markdown, AST, card, file, and stream formats as regular messages. Streams are buffered before the reply is sent.

Adapters without native message replies throw `NotImplementedError`. See the [adapter feature matrix](/docs/platform-adapters) for support.

## AST builders

For programmatic control over message formatting, use the mdast AST builder functions exported from `chat`. This is the recommended approach for most messages, because it gives you fine-grained control without the overhead of card rendering.

```typescript title="lib/bot.ts" lineNumbers
import { root, paragraph, text, strong, link } from "chat";

await thread.post({
  ast: root([
    paragraph([
      strong([text("Deployment complete")]),
      text(" — "),
      link("https://example.com", [text("View site")]),
    ]),
  ]),
});
```

### Available builders

| Builder                       | Description                  | Example                                  |
| ----------------------------- | ---------------------------- | ---------------------------------------- |
| `root(children)`              | Root node (required wrapper) | `root([paragraph([...])])`               |
| `paragraph(children)`         | Paragraph block              | `paragraph([text("Hello")])`             |
| `text(value)`                 | Plain text                   | `text("Hello")`                          |
| `strong(children)`            | **Bold** text                | `strong([text("bold")])`                 |
| `emphasis(children)`          | *Italic* text                | `emphasis([text("italic")])`             |
| `strikethrough(children)`     | ~~Strikethrough~~ text       | `strikethrough([text("done")])`          |
| `inlineCode(value)`           | `Inline code`                | `inlineCode("const x = 1")`              |
| `codeBlock(value, lang?)`     | Fenced code block            | `codeBlock("const x = 1", "ts")`         |
| `link(url, children, title?)` | Hyperlink                    | `link("https://...", [text("click")])`   |
| `blockquote(children)`        | Block quote                  | `blockquote([paragraph([text("...")])])` |

### Parsing markdown to AST

You can also parse a markdown string into an AST, manipulate it, then send it:

```typescript title="lib/bot.ts" lineNumbers
import { parseMarkdown, stringifyMarkdown } from "chat";

const ast = parseMarkdown("**Hello** world");
// Manipulate the AST...
await thread.post({ ast });
```

## Cards

When you need interactive elements like buttons, dropdowns, or structured layouts, use cards. Cards render natively on each platform: Block Kit on Slack, Adaptive Cards on Teams, and Google Chat Cards on Google Chat.

### Function syntax

Use the function-call API for type-safe card construction:

```typescript title="lib/bot.ts" lineNumbers
import { Card, Text, Actions, Button } from "chat";

await thread.post(
  Card({
    title: "Order #1234",
    children: [
      Text("Your order has been received!"),
      Actions([
        Button({ id: "approve", label: "Approve", style: "primary" }),
        Button({ id: "reject", label: "Reject", style: "danger" }),
      ]),
    ],
  })
);
```

### JSX syntax

You can also use JSX if you configure the `chat` JSX runtime:

```json title="tsconfig.json"
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "chat"
  }
}
```

```tsx title="lib/bot.tsx"
import { Card, CardText, Actions, Button } from "chat";

await thread.post(
  <Card title="Order #1234">
    <CardText>Your order has been received!</CardText>
    <Actions>
      <Button id="approve" style="primary">Approve</Button>
      <Button id="reject" style="danger">Reject</Button>
    </Actions>
  </Card>
);
```

> The JSX syntax requires `jsxImportSource: "chat"` in your `tsconfig.json` (or a per-file `/** @jsxImportSource chat */` pragma). Without this, TypeScript won't recognize the card JSX types. If you run into type issues with JSX, use the function-call syntax instead. It produces the same output with better type inference.

See the [Cards](/docs/cards) page for the full list of card components.

## Streaming

Pass an AI SDK or TanStack AI stream to `thread.post()` to stream a message in real time. The SDK uses platform-native streaming where available and falls back to post-then-edit or buffered delivery depending on the platform.

```typescript title="lib/bot.ts" lineNumbers
import { ToolLoopAgent } from "ai";

const agent = new ToolLoopAgent({ model, instructions: "You are a helpful assistant." });
const result = await agent.stream({ prompt: message.text });
await thread.post(result.fullStream);
```

Both `fullStream` and `textStream` are supported. Use `fullStream` with multi-step agents, because it preserves paragraph breaks between steps. Streams returned by TanStack AI's `chat()` are also auto-detected, with a paragraph break inserted between tool-loop turns. Any `AsyncIterable<string>` also works for custom streams.

For multi-turn conversations, use [`toAiMessages()`](/docs/ai/to-ai-messages) to convert thread history into the `{ role, content }[]` format expected by AI SDKs.

To pass platform-specific streaming options, such as Slack task grouping or stop blocks, wrap the stream in a [`StreamingPlan`](/docs/streaming#streaming-with-options) and post that.

See the [Streaming](/docs/streaming) page for details on platform behavior and configuration.

## Attachments and files

Any structured message format (`markdown`, `ast`, or `card`) supports `files` for uploading attachments alongside the message:

```typescript title="lib/bot.ts" lineNumbers
await thread.post({
  markdown: "Here's the report:",
  files: [{ data: buffer, filename: "report.pdf" }],
});
```

Use `attachments` on `{ raw }`, `{ markdown }`, or `{ ast }` when an adapter supports typed media uploads, such as Telegram's image/audio/video/file uploads and media groups.

See the [Files](/docs/files) page for more on attachments.

## Choosing a format

| Format                                                    | Use when                                          | Example                                           |
| --------------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- |
| Plain string                                              | Simple, unformatted text                          | Status updates, acknowledgements                  |
| `{ markdown }`                                            | You have a markdown string (e.g. from a template) | Notifications with links and formatting           |
| `{ ast }`                                                 | You need programmatic formatting control          | Dynamic messages built from data                  |
| Card (function)                                           | You need buttons, fields, or structured layouts   | Approval flows, dashboards                        |
| Card (JSX)                                                | Same as above, with JSX syntax preference         | Same use cases as function cards                  |
| `AsyncIterable`                                           | Streaming AI responses                            | Chat with LLMs                                    |
| [`Plan`](/docs/streaming#plan-api)                        | Step-by-step tasks that mutate after posting      | Multi-step agents, deploy progress                |
| [`StreamingPlan`](/docs/streaming#streaming-with-options) | Streaming with platform-specific options          | Slack streaming with grouped tasks or stop blocks |

For most messages, AST builders give the best balance of control and simplicity. Use cards when you need interactive elements like buttons or dropdowns.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Slash Commands
description: Handle slash command invocations and respond with messages or modals.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/getting-started
related:
  - /docs/modals
  - /adapters/official/slack
  - /adapters/official/discord
  - /adapters/official/telegram
  - /docs/ephemeral-messages
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Slash commands let users invoke your bot with `/command` syntax. Register handlers with `onSlashCommand` to respond to them.

Slash commands are supported on [Slack](/adapters/official/slack), [Discord](/adapters/official/discord), and [Telegram](/adapters/official/telegram).

## Handle a specific command

```typescript title="lib/bot.ts" lineNumbers
bot.onSlashCommand("/status", async (event) => {
  await event.channel.post("All systems operational!");
});
```

## Handle multiple commands

```typescript title="lib/bot.ts" lineNumbers
bot.onSlashCommand(["/help", "/info"], async (event) => {
  await event.channel.post(`You invoked ${event.command}`);
});
```

## Catch-all handler

Register a handler without a command to catch all slash commands:

```typescript title="lib/bot.ts" lineNumbers
bot.onSlashCommand(async (event) => {
  console.log(`Command: ${event.command}, Args: ${event.text}`);
});
```

## SlashCommandEvent

The `event` object passed to slash command handlers:

| Property    | Type                                                  | Description                               |
| ----------- | ----------------------------------------------------- | ----------------------------------------- |
| `command`   | `string`                                              | The command name (e.g., `/status`)        |
| `text`      | `string`                                              | Arguments after the command               |
| `user`      | `Author`                                              | The user who invoked the command          |
| `channel`   | `Channel`                                             | The channel where the command was invoked |
| `adapter`   | `Adapter`                                             | The platform adapter                      |
| `triggerId` | `string` (optional)                                   | Platform trigger ID for opening modals    |
| `openModal` | `(modal) => Promise<{ viewId: string } \| undefined>` | Open a modal dialog                       |
| `raw`       | `unknown`                                             | Platform-specific payload                 |

## Respond to a command

Use `event.channel` to post messages:

```typescript title="lib/bot.ts" lineNumbers
bot.onSlashCommand("/greet", async (event) => {
  // Public message to the channel
  await event.channel.post(`Hello, ${event.user.fullName}!`);

  // Ephemeral message (only visible to the user)
  await event.channel.postEphemeral(
    event.user,
    "This message is just for you!",
    { fallbackToDM: false }
  );
});
```

See [Ephemeral Messages](/docs/ephemeral-messages) for platform support and the `fallbackToDM` option.

## Open a modal

Use `event.openModal()` to open a [modal](/docs/modals) in response to a slash command:

```tsx title="lib/bot.tsx" lineNumbers
import { Modal, TextInput, Select, SelectOption } from "chat";

bot.onSlashCommand("/feedback", async (event) => {
  const result = await event.openModal(
    <Modal callbackId="feedback_form" title="Send Feedback" submitLabel="Send">
      <TextInput id="message" label="Your Feedback" multiline />
      <Select id="category" label="Category">
        <SelectOption label="Bug" value="bug" />
        <SelectOption label="Feature" value="feature" />
      </Select>
    </Modal>
  );

  if (!result) {
    await event.channel.post("Couldn't open the feedback form. Please try again.");
  }
});
```

> When a modal is opened from a slash command, the submit handler receives `relatedChannel` instead of `relatedThread`. Use this to post back to the channel where the command was invoked.

```typescript title="lib/bot.ts" lineNumbers
bot.onModalSubmit("feedback_form", async (event) => {
  const { message, category } = event.values;

  // Post to the channel where the slash command was invoked
  if (event.relatedChannel) {
    await event.relatedChannel.post(`Feedback received! Category: ${category}`);
  }
});
```

## Telegram

Telegram supports bot commands such as `/status` and `/status@mybot`. Register handlers with `onSlashCommand`; commands addressed to another bot are ignored as slash commands and continue through the normal message path.

## Discord

Discord slash commands arrive through [HTTP Interactions](/adapters/official/discord#http-interactions-vs-gateway), so no Gateway connection is needed. The adapter sends Discord a deferred response, then resolves it when your handler calls `event.channel.post()`.

To make selected Discord slash command responses ephemeral, return `DiscordInteractionResponseFlag.Ephemeral` from the Discord adapter's [`interactionFlags` option](/adapters/official/discord#interaction-flags).

### Subcommands

Discord supports subcommand groups and subcommands. The adapter flattens these into the `event.command` path:

| Discord command                       | `event.command`       | `event.text` |
| ------------------------------------- | --------------------- | ------------ |
| `/status`                             | `/status`             | `""`         |
| `/project create --name="Acme"`       | `/project create`     | `Acme`       |
| `/project issue list --status="open"` | `/project issue list` | `open`       |

For full option details such as names and types, read the original Discord interaction payload from `event.raw`.

### Registering commands with Discord

You need to register slash commands with the [Discord API](https://discord.com/developers/docs/interactions/application-commands) before they appear in the client. The Chat SDK handles incoming commands but does not register them for you.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: State Adapters
description: State adapters store thread subscriptions, distributed locks, and cached data for your bot.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
prerequisites:
  - /docs/getting-started
related:
  - /docs/concurrency
  - /docs/history
  - /docs/testing
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

State adapters store thread subscriptions, distributed locks, and cached data. Every `Chat` instance needs one. Browse the available state adapters on the [Adapters](/adapters) page.

## What state adapters manage

### Thread subscriptions

When your bot calls `thread.subscribe()`, the state adapter persists that subscription. On later webhooks, the SDK checks it to route messages to `onSubscribedMessage`. With a production adapter such as Redis or PostgreSQL, subscriptions survive restarts and are shared across instances.

### Distributed locking

When a message arrives, the SDK acquires a lock on its thread, or on its channel for adapters that lock per channel, such as WhatsApp and Telegram. The lock stops two handlers from processing messages in the same thread at once, even when your bot runs on several serverless instances.

The `concurrency` option decides what happens when the lock is already held. By default, the new message is dropped with a `LockError`. You can also queue it, debounce a burst of messages, or skip locking entirely. See [Concurrency](/docs/concurrency) for the strategies and for [lock scope](/docs/concurrency#lock-scope).

The deprecated `onLockConflict` option still works under the default `drop` strategy. Set it to `'force'` to release the held lock and let the new message through, for example so a new message can interrupt a long-running AI response:

```typescript
const chat = new Chat({
  userName: 'my-bot',
  adapters: { slack },
  state: createRedisState(),
  onLockConflict: 'force',
});
```

You can also pass a callback that decides per message:

```typescript
onLockConflict: (threadId, message) => {
  return message.text.includes('stop') ? 'force' : 'drop';
}
```

Force-releasing a lock doesn't cancel the previous handler. It keeps running without the lock, so two handlers can briefly run on the same thread at the same time.

### Caching and storage

State adapters also provide key-value storage with a TTL. The SDK uses it for thread and channel state (`thread.setState()`), for message deduplication, which ignores webhooks a platform delivers more than once, and for internal caches. Lists back the [History API](/docs/history), and queues back the `queue`, `debounce`, and `burst` concurrency strategies.

To build your own state adapter, implement the `StateAdapter` interface exported from `chat`. The `@chat-adapter/state-memory` package is a small implementation you can use as a reference.

## Production state on Vercel

The [Memory](/adapters/official/memory) adapter keeps state in process memory, so it suits local development and tests. In production, use [Redis](/adapters/official/redis), [ioredis](/adapters/official/ioredis), or [PostgreSQL](/adapters/official/postgres) so subscriptions, locks, and cached data are shared across instances and survive restarts.

If you deploy to Vercel, you can provision either database from the [Vercel Marketplace](https://vercel.com/marketplace/category/storage) with the Vercel CLI:

| Provider        | Command                                     | State adapter                                                                                 |
| --------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------- |
| Upstash Redis   | `vercel integration add upstash/upstash-kv` | [Redis](/adapters/official/redis#vercel-marketplace) or [ioredis](/adapters/official/ioredis) |
| Redis Cloud     | `vercel integration add redis`              | [Redis](/adapters/official/redis#vercel-marketplace) or [ioredis](/adapters/official/ioredis) |
| Neon            | `vercel integration add neon`               | [PostgreSQL](/adapters/official/postgres#vercel-marketplace)                                  |
| Supabase        | `vercel integration add supabase`           | [PostgreSQL](/adapters/official/postgres#vercel-marketplace)                                  |
| Prisma Postgres | `vercel integration add prisma`             | [PostgreSQL](/adapters/official/postgres#vercel-marketplace)                                  |
| Nile            | `vercel integration add nile`               | [PostgreSQL](/adapters/official/postgres#vercel-marketplace)                                  |

Run the command from a linked project directory:

```bash
vercel link
vercel integration add upstash/upstash-kv
```

`vercel integration add` creates the database, connects it to the linked project, adds its credentials as environment variables, and pulls them into your local env file. Each adapter page lists the environment variables the adapter reads and how to pass a different one.

#### [List a vendor-official adapter](/docs/contributing/vendor-official)

How platform vendors qualify and list a maintained adapter in the Vendor Official tier.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Streaming
description: Stream real-time text responses from AI models and other async sources to chat platforms.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/api/markdown
  - /docs/concurrency
  - /docs/ai
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Chat SDK accepts any `AsyncIterable<string>` as a message, so you can stream AI responses and other incremental content to chat platforms as it's generated. Streams from the AI SDK and TanStack AI are detected automatically. On platforms with native or structured streaming support, you can also stream `StreamChunk` objects for rich content such as task progress cards and plan updates.

## AI SDK integration

Pass an AI SDK `fullStream` or `textStream` directly to `thread.post()`:

```typescript title="lib/bot.ts" lineNumbers
import { ToolLoopAgent } from "ai";

const agent = new ToolLoopAgent({
  model: "xai/grok-4.5",
  instructions: "You are a helpful assistant.",
});

bot.onNewMention(async (thread, message) => {
  const result = await agent.stream({
    prompt: message.text,
    abortSignal: thread.signal,
  });
  await thread.post(result.fullStream);
});
```

Passing `thread.signal` lets platform cancellation stop model generation. In
Slack Agent messaging, clicking the native stop button aborts this signal even
when the stop webhook is handled by another serverless instance using the same
state adapter.

### Why `fullStream` over `textStream`?

When AI SDK agents make tool calls between text steps, `textStream` concatenates all text without separators, producing `"hello.how are you?"` instead of `"hello.\n\nhow are you?"`. The `fullStream` contains explicit `finish-step` events that Chat SDK uses to inject paragraph breaks between steps automatically.

Both stream types are auto-detected:

```typescript
// Recommended: fullStream preserves step boundaries
await thread.post(result.fullStream);

// Also works: textStream for single-step generation
await thread.post(result.textStream);
```

For a human-in-the-loop turn, wrap the stream in `StreamingPlan` and leave the
Slack Agent Session suspended after the final chunk:

```typescript
await thread.post(
  new StreamingPlan(result.fullStream, {
    sessionStatus: "suspended",
  })
);
```

## TanStack AI integration

The stream returned by `chat()` from `@tanstack/ai` can be passed straight to `thread.post()`:

```typescript title="lib/bot.ts" lineNumbers
import { chat } from "@tanstack/ai";
import { vercelGatewayText } from "@tanstack/ai-vercel-gateway";

bot.onNewMention(async (thread, message) => {
  const abortController = new AbortController();
  thread.signal.addEventListener("abort", () => abortController.abort(), {
    once: true,
  });

  const stream = chat({
    adapter: vercelGatewayText("anthropic/claude-opus-5"),
    messages: [{ role: "user", content: message.text }],
    abortController,
  });
  await thread.post(stream);
});
```

TanStack AI streams follow the AG-UI protocol. Chat SDK extracts the text from `TEXT_MESSAGE_CONTENT` deltas and treats each `TEXT_MESSAGE_END` as a paragraph break, so when the tool loop runs several model turns their text is separated by `\n\n` (the same behavior as `finish-step` for the AI SDK). Tool call, reasoning, run, and step events are skipped.

This is for text responses. A structured-output run (`chat({ ..., outputSchema, stream: true })`) streams its JSON as `TEXT_MESSAGE_CONTENT` deltas, so posting that stream would show raw JSON in the channel. Format the result yourself and post the string instead.

TanStack's `chat()` takes an `AbortController` rather than a signal. Forwarding `thread.signal` to it, as above, lets platform cancellation stop model generation.

To feed prior thread history into `chat()` and give it Chat SDK tools, use `toTanStackMessages` and `createTanStackTools` from `chat/ai/tanstack`, covered in [TanStack AI](/docs/ai/tanstack-ai).

## Custom streams

Any async iterable works:

```typescript title="lib/bot.ts" lineNumbers
const stream = (async function* () {
  yield "Processing";
  yield "...";
  yield " done!";
})();

await thread.post(stream);
```

## Platform behavior

| Platform    | Method                                | Description                                                                                                                                                                                             |
| ----------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Slack       | Native streaming API                  | Uses Slack's `chatStream` to update the message as chunks arrive                                                                                                                                        |
| Telegram    | Post + Edit                           | Posts a message then edits it as chunks arrive (throttled to \~1 edit/s). Set `nativeStreaming: true` to use `sendRichMessageDraft` previews in private chats instead, persisted with `sendRichMessage` |
| Teams       | Native (DMs) / Buffered (group chats) | Uses the Teams SDK's native `stream.emit()` for direct messages; accumulates chunks and posts one final message when no native streamer is active                                                       |
| Google Chat | Post + Edit                           | Posts a message then edits it as chunks arrive                                                                                                                                                          |
| Discord     | Post + Edit                           | Posts a message then edits it as chunks arrive                                                                                                                                                          |
| GitHub      | Buffered                              | Accumulates chunks and posts one final comment                                                                                                                                                          |
| GitLab      | Buffered                              | Accumulates chunks and posts one final comment                                                                                                                                                          |
| Linear      | Agent sessions / Post + Edit          | Uses agent session activities in agent-session threads; falls back to post+edit comments in issue threads                                                                                               |
| Notion      | Post + Edit                           | Posts a comment then edits it as chunks arrive (throttled for \~3 req/s)                                                                                                                                |
| WhatsApp    | Buffered                              | Accumulates chunks and sends one final message                                                                                                                                                          |
| Messenger   | Buffered                              | Accumulates chunks and sends one final message                                                                                                                                                          |
| Twitch      | Buffered                              | Accumulates chunks and sends one final chat message or whisper                                                                                                                                          |

The post+edit fallback throttles edits to avoid rate limits. Configure the update interval when creating your `Chat` instance:

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  // ...
  streamingUpdateIntervalMs: 500, // Default: 500ms
});
```

### Disabling the placeholder message

By default, post+edit adapters send an initial `"..."` placeholder message before the first chunk arrives. You can disable this to wait for real content before posting:

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({
  // ...
  fallbackStreamingPlaceholderText: null,
});
```

You can also customize the placeholder text:

```typescript title="lib/bot.ts"
const bot = new Chat({
  // ...
  fallbackStreamingPlaceholderText: "Thinking...",
});
```

On Teams, a custom placeholder becomes an informative status during native direct-message streaming, while group chats edit the placeholder into the final answer. Leave the option unset to preserve native DM and buffered group-chat behavior, or set it to `null` to disable the status.

## Markdown healing

During streaming, chunks often arrive mid-word or mid-syntax. For example, `**bold` can arrive before the closing `**`. The SDK heals incomplete markdown in intermediate renders using [remend](https://www.npmjs.com/package/remend), so messages display with correct formatting while streaming.

The final message uses the raw accumulated text without healing, so the original markdown is preserved.

## Table buffering

When streamed content contains GFM tables, as LLM output often does, the SDK buffers potential table headers until a separator line (`|---|---|`) confirms them. This stops tables from briefly flashing as raw pipe-delimited text before the table structure is complete. Table buffering needs no configuration.

## Structured streaming chunks

For Slack native streams and Linear agent-session streams, you can yield `StreamChunk` objects alongside plain text for rich progress updates:

```typescript title="lib/bot.ts" lineNumbers
import type { StreamChunk } from "chat";

const stream = (async function* () {
  yield { type: "markdown_text", text: "Searching..." } satisfies StreamChunk;

  yield {
    type: "task_update",
    id: "search-1",
    title: "Searching documents",
    details: "Querying internal docs and ranking the best matches",
    status: "in_progress",
  } satisfies StreamChunk;

  // ... do work ...

  yield {
    type: "task_update",
    id: "search-1",
    title: "Searching documents",
    details: "Ranked 3 relevant results",
    status: "complete",
    output: "Found 3 results",
  } satisfies StreamChunk;

  yield { type: "markdown_text", text: "Here are your results..." } satisfies StreamChunk;
})();

await thread.post(stream);
```

### Chunk types

| Type            | Fields                                         | Description                                                                                                 |
| --------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `markdown_text` | `text`                                         | Streamed text content                                                                                       |
| `task_update`   | `id`, `title`, `status`, `details?`, `output?` | Tool/step progress updates (`pending`, `in_progress`, `complete`, `error`) with optional extra task context |
| `plan_update`   | `title`                                        | Plan title updates on supported platforms                                                                   |

### Streaming with options

Wrap a stream in a `StreamingPlan` to pass platform-specific options through `thread.post()` without dropping down to `adapter.stream()` directly:

```typescript
import { StreamingPlan } from "chat";

const planned = new StreamingPlan(stream, {
  groupTasks: "plan",         // Slack: render task cards as a single grouped block
  endWith: [feedbackBlock],   // Slack: Block Kit elements appended after stream stops
  updateIntervalMs: 750,      // Post+edit cadence on supported adapters
  aiGenerated: true,          // Teams: show the "AI generated" label
});

await thread.post(planned);
```

| Option             | Platform           | Description                                                                                |
| ------------------ | ------------------ | ------------------------------------------------------------------------------------------ |
| `groupTasks`       | Slack              | `"timeline"` (default) renders task cards inline; `"plan"` groups them into one plan block |
| `endWith`          | Slack              | Block Kit elements attached when the stream stops (e.g. retry / feedback buttons)          |
| `updateIntervalMs` | Post+edit adapters | Minimum interval between post+edit cycles in ms (default `500`)                            |
| `aiGenerated`      | Teams              | Show the "AI generated" label on the streamed message                                      |

Adapters without structured chunk support extract text from `markdown_text` chunks and ignore other types. Slack-only options are silently ignored on other platforms.

## Stop blocks (Slack only)

Use `endWith` on `StreamingPlan` to attach Block Kit elements to the final message, such as action buttons that appear after a streamed response completes:

```typescript title="lib/bot.ts" lineNumbers
import { StreamingPlan } from "chat";

const planned = new StreamingPlan(textStream, {
  endWith: [
    {
      type: "actions",
      elements: [{
        type: "button",
        text: { type: "plain_text", text: "Retry" },
        action_id: "retry",
      }],
    },
  ],
});

await thread.post(planned);
```

## Plan API

For step-by-step task progress that lives outside an LLM stream, post a `Plan` directly. `Plan` is a `PostableObject` you can mutate after posting, and each mutation re-renders the block in place.

```typescript title="lib/bot.ts" lineNumbers
import { Plan } from "chat";

const plan = new Plan({ initialMessage: "Researching options..." });
await thread.post(plan);

const lookup = await plan.addTask({ title: "Look up customer record" });
// ...do work...
await plan.updateTask("Found 3 matches");

await plan.addTask({ title: "Summarize findings" });
await plan.complete({ completeMessage: "Done!" });
```

By default `updateTask()` mutates the most recent `in_progress` task. For parallel work, pass `autoCompletePrevious: false` to `addTask()` so earlier tasks stay in progress; then pass `{ id }` to `updateTask()` to target a specific task when updates run out of order:

```typescript
const fetchTask = await plan.addTask({ title: "Fetch data" });
const transformTask = await plan.addTask({
  title: "Transform",
  autoCompletePrevious: false,
});

// Update a specific task by id, even if it isn't the most recent in_progress one.
await plan.updateTask({ id: fetchTask.id, output: "Got 42 rows" });
await plan.updateTask({ id: transformTask.id, status: "complete" });
```

Adapters that don't support PostableObject editing (e.g. WhatsApp) render the plan as a fallback emoji-list message; the plan still posts, but mutations are no-ops.

| Method                                                 | Description                                                                                                                                                 |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `addTask({ title, children?, autoCompletePrevious? })` | Append a new task. When `autoCompletePrevious` is true (default), existing in-progress tasks are marked complete first; pass `false` for parallel workflows |
| `updateTask(input)`                                    | Mutate the current (or `{ id }`-targeted) task's `output`, `status`, or `title`                                                                             |
| `complete({ completeMessage })`                        | Mark all in-progress tasks complete and update the plan title                                                                                               |
| `reset({ initialMessage })`                            | Discard all tasks and start fresh with a new initial message. Use it to reuse a plan handle for a new run                                                   |

## Streaming with conversation history

Combine message history with streaming for multi-turn AI conversations.
Use [`toAiMessages()`](/docs/ai/to-ai-messages) to convert chat messages into the `{ role, content }` format expected by AI SDKs:

```typescript title="lib/bot.ts" lineNumbers
import { toAiMessages } from "chat/ai";

bot.onSubscribedMessage(async (thread, message) => {
  // Fetch recent messages for context
  const result = await thread.adapter.fetchMessages(thread.id, { limit: 20 });

  const history = await toAiMessages(result.messages);

  const response = await agent.stream({ prompt: history });
  await thread.post(response.fullStream);
});
```

See the [`toAiMessages` reference](/docs/ai/to-ai-messages) for all options including `includeNames`, `transformMessage`, and attachment handling.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Message Subject
description: Fetch the parent resource that a message is about.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/handling-events
related:
  - /docs/history
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

When your bot receives a comment on a Linear issue, GitHub PR, GitLab merge request, or Notion page, `message.subject` resolves the parent resource so your handler knows what the conversation is about.

## Usage

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  const subject = await message.subject;

  if (subject) {
    await thread.post(
      `This is about: ${subject.title} (${subject.status})\n${subject.url}`
    );
  }
});
```

On Linear, GitHub, GitLab, and Notion, comment webhooks deliver the comment text but not the full parent resource, so `message.subject` fetches it from the platform API on first access and caches the result on the message instance. Chat platforms have no parent resource, so `message.subject` returns `null` there. It also returns `null` if the API call fails.

See [`MessageSubject`](/docs/api/message#messagesubject) for the full type shape.

### Platform support

| Platform | `message.subject` returns                             |
| -------- | ----------------------------------------------------- |
| Linear   | Parent issue (from comment webhooks)                  |
| GitHub   | Parent issue or PR (from comment webhooks)            |
| GitLab   | Parent merge request or issue (from comment webhooks) |
| Notion   | Parent page (from comment webhooks)                   |

All other platforms return `null`.

## User info

For user profile details, use [`bot.getUser`](/docs/api/chat#getuser):

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  const user = await bot.getUser(message.author);
  if (user) {
    await thread.post(`Hi ${user.fullName} (${user.email})`);
  }
});
```

For anything beyond `message.subject`, access the platform's typed API client via [`bot.getAdapter("github").octokit`](/docs/api/chat#getadapter) or [`bot.getAdapter("linear").linearClient`](/docs/api/chat#getadapter).

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Testing
description: "Test your bot handlers and custom adapters with @chat-adapter/tests, which provides Vitest factories, custom matchers, and a setup file."
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/getting-started
related:
  - /docs/state-adapters
  - /docs/handling-events
  - /docs/contributing/testing
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The [`@chat-adapter/tests`](https://www.npmjs.com/package/@chat-adapter/tests) package gives you Vitest factories, custom matchers, and a setup file for testing bots and custom adapters built on Chat SDK.

## Install

```bash
pnpm add -D @chat-adapter/tests
```

`chat` and `vitest` are peer dependencies, so install them in your project if they aren't there already.

## Setup file (recommended)

Register all matchers automatically by adding the package's setup file to your Vitest config:

```typescript title="vitest.config.ts" lineNumbers
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    setupFiles: ["@chat-adapter/tests/setup"],
  },
});
```

Without the setup file, register matchers manually:

```typescript
import { matchers } from "@chat-adapter/tests/matchers";
expect.extend(matchers);
```

## Mock factories

```typescript
import {
  createMockAdapter,
  createMockChatInstance,
  createMockState,
  createTestMessage,
  mockLogger,
} from "@chat-adapter/tests";
```

| Factory                                   | Returns            | Notes                                                                                            |
| ----------------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------ |
| `createMockAdapter(name?, overrides?)`    | `Adapter`          | Every method is `vi.fn()` with sensible defaults                                                 |
| `createMockChatInstance(options?)`        | `ChatInstance`     | Every `process*` handler is `vi.fn()`; `getState`/`getUserName`/`getLogger` wired up             |
| `createMockState()`                       | `MockStateAdapter` | In-memory `Map`s for subscriptions, locks, KV, lists, queues; `cache` exposes the underlying map |
| `createTestMessage(id, text, overrides?)` | `Message`          | Markdown text is parsed into the formatted AST                                                   |
| `mockLogger` / `createMockLogger()`       | `Logger`           | Shared default vs fresh-per-call                                                                 |

## Matchers

| Matcher                                                           | Asserts                                                                                              |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `expect(adapter).toHavePosted(threadId, textPattern?)`            | `adapter.postMessage` was called for this thread                                                     |
| `expect(adapter).toHaveEdited(threadId, messageId, textPattern?)` | `adapter.editMessage` was called for this message                                                    |
| `expect(adapter).toHaveDeleted(threadId, messageId)`              | `adapter.deleteMessage` was called for this message                                                  |
| `expect(adapter).toHaveReactedWith(threadId, messageId, emoji)`   | `adapter.addReaction` was called with the emoji (string or `EmojiValue.name`)                        |
| `expect(adapter).toHaveStartedTyping(threadId)`                   | `adapter.startTyping` was called for this thread                                                     |
| `expect(adapter).toHavePostedToChannel(channelId, textPattern?)`  | `adapter.postChannelMessage` was called for this channel                                             |
| `expect(chat).toHaveDispatched(handler)`                          | The named `process*` handler on the mock `ChatInstance` was called                                   |
| `expect(state).toBeSubscribedTo(threadId)`                        | `state.isSubscribed(threadId)` resolves to `true`. This matcher is async, so use `await expect(...)` |

Text-pattern matchers extract a comparable string from `AdapterPostableMessage`: strings directly, `PostableMarkdown.markdown`, `PostableRaw.raw`, and `PostableCard.fallbackText`. AST-shaped messages and cards without `fallbackText` can't be matched by text. For those, assert without `textPattern` and inspect `mock.calls` directly.

## Bot authors: test your handlers

If you're building a bot on Chat SDK, you can exercise your handlers with a mock adapter and mock state instead of real platform webhooks:

```typescript title="bot.test.ts"
import { describe, expect, it } from "vitest";
import { Chat } from "chat";
import { createMockAdapter, createMockState } from "@chat-adapter/tests";

describe("bot handlers", () => {
  it("replies with a greeting on mention", async () => {
    const slack = createMockAdapter("slack");
    const state = createMockState();
    const bot = new Chat({
      userName: "mybot",
      adapters: { slack },
      state,
    });

    bot.onNewMention(async (thread) => {
      await thread.post("hello there");
    });

    // Drive a synthesized mention through the bot…
    // (use your adapter's webhook path or a thread-level call)

    expect(slack).toHavePosted("slack:C1:t1", /hello there/);
  });
});
```

## Adapter authors: test webhook → dispatch

If you're building a custom `Adapter`, pass it a mock `ChatInstance` and assert that webhooks route through the right `process*` hook with the right normalized payload:

```typescript title="adapter.test.ts"
import { describe, expect, it } from "vitest";
import { createMockChatInstance } from "@chat-adapter/tests";
import { MyAdapter } from "./adapter";

describe("MyAdapter.handleWebhook", () => {
  it("dispatches incoming messages through processMessage", async () => {
    const chat = createMockChatInstance();
    const adapter = new MyAdapter({ /* config */ });
    await adapter.initialize(chat);

    const request = new Request("https://example.com/webhook", {
      method: "POST",
      body: JSON.stringify({ /* platform-specific payload */ }),
      headers: { "content-type": "application/json" },
    });
    const response = await adapter.handleWebhook(request);

    expect(response.status).toBe(200);
    expect(chat).toHaveDispatched("processMessage");
  });
});
```

## Adapter-specific helpers

Helpers that depend on one platform's wire format, such as signed Slack webhooks or Teams claim builders, live in each adapter's own `/testing` subpath rather than in this package. That way, adopting `@chat-adapter/tests` doesn't pull in adapter dependencies you don't use.

If you're contributing adapters or core to this repo, see the [Testing adapters contributing guide](/docs/contributing/testing) for the hand-rolled patterns used inside `packages/`.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Threads, Messages, and Channels
description: Work with threads, messages, and channels across platforms.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/handling-events
  - /docs/posting-messages
  - /docs/api/thread
  - /docs/api/channel
  - /docs/subject
  - /docs/history
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

A channel holds threads, and each thread holds the messages in one conversation. Your event handlers receive the `Thread` and `Message` for each event, and `thread.channel` returns the `Channel` that contains the thread.

## Threads

A `Thread` represents a conversation thread on any platform. It provides methods for posting messages, managing subscriptions, and accessing message history.

Your event handlers usually receive a `Thread` from the SDK. You can also construct one from a thread ID, which is useful in cron jobs, workflow steps, or any other code that runs outside an inbound webhook:

```typescript title="lib/bot.ts" lineNumbers
const thread = bot.thread("slack:C123ABC:1234567890.123456");
await thread.post("Reminder from a cron job");
```

For DM-style conversations, use [`bot.openDM(userIdOrAuthor)`](/docs/direct-messages) instead. It resolves the right channel and thread for user ID formats the SDK can infer.

### Post a message

```typescript title="lib/bot.ts" lineNumbers
// Plain text
await thread.post("Hello world");

// Markdown (converted to each platform's format)
await thread.post({ markdown: "**Bold** and _italic_ text" });

// Structured message with attachments
await thread.post({
  markdown: "Here's a file:",
  files: [{ data: buffer, filename: "report.pdf" }],
});
```

### Subscribe and unsubscribe

Subscriptions are stored in your state adapter, so they persist across restarts. When a non-DM thread is subscribed, all messages route to `onSubscribedMessage`. DM threads route to `onDirectMessage` first when a direct message handler is registered.

```typescript title="lib/bot.ts" lineNumbers
await thread.subscribe();
await thread.unsubscribe();

const subscribed = await thread.isSubscribed();
```

### Participants

`getParticipants()` returns the unique human authors in a thread and excludes bots. Use it to decide whether to subscribe based on how many people are in the conversation.

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread) => {
  const participants = await thread.getParticipants();
  if (participants.length === 1) {
    await thread.subscribe();
    await thread.post("I'm here to help!");
  }
});

bot.onSubscribedMessage(async (thread) => {
  const participants = await thread.getParticipants();
  if (participants.length > 1) {
    await thread.unsubscribe();
    return;
  }
  // respond...
});
```

> Each call fetches the full message history to find all participants. On threads with long history this makes multiple API calls to the platform. Consider checking `message.author` against a known set before calling `getParticipants()` on every incoming message.

### Typing indicator

```typescript title="lib/bot.ts"
await thread.startTyping();
```

> Not all platforms support typing indicators. The call is a no-op on unsupported platforms. See the [adapter feature matrix](/docs/platform-adapters) for details.

### Mark as read

Inside a message handler, mark the current inbound message as read without passing platform-specific IDs:

```typescript title="lib/bot.ts"
bot.onDirectMessage(async (thread) => {
  await thread.markAsRead();
});
```

You can pass a `Message` or message ID when you need an explicit target:

```typescript
await thread.markAsRead(message);
await thread.markAsRead(message.id);
```

Platforms may advance the conversation's read state through the target message, which also marks earlier messages as read.

> WhatsApp, Messenger, and XChat support marking messages as read. Other adapters throw `NotImplementedError`. See the [adapter feature matrix](/docs/platform-adapters) for details.

### Message history

Access recent messages or iterate through full history:

```typescript title="lib/bot.ts" lineNumbers
// Cached messages from the webhook payload
const recent = thread.recentMessages;

// Newest first (auto-paginates)
for await (const msg of thread.messages) {
  console.log(msg.text);
}

// Oldest first (auto-paginates)
for await (const msg of thread.allMessages) {
  console.log(msg.text);
}
```

For adapters without a server-side history API, such as Telegram and WhatsApp, the SDK keeps a per-thread cache in your state adapter. Read it with `bot.history.thread`:

```typescript title="lib/bot.ts" lineNumbers
// Platform API first, SDK cache fallback when the adapter returns nothing
const { messages } = await bot.history.thread.list(thread.id, { limit: 20 });
```

To persist a cross-platform transcript for each user, for LLM context, auditing, or GDPR requests, see the [History guide](/docs/history).

### Thread state

Store typed, per-thread state that persists across requests. Pass a generic type parameter to `Chat` to get typed thread state across all handlers:

```typescript title="lib/bot.ts" lineNumbers
interface ThreadState {
  aiMode?: boolean;
  context?: string;
}

const bot = new Chat<typeof adapters, ThreadState>({
  // ...config
});

bot.onNewMention(async (thread) => {
  await thread.setState({ aiMode: true });

  const state = await thread.state; // ThreadState | null
  if (state?.aiMode) {
    // AI mode is enabled
  }
});
```

State is stored in your state adapter with a 30-day TTL. Use `{ replace: true }` to replace state entirely instead of merging:

```typescript title="lib/bot.ts"
await thread.setState({ aiMode: false }, { replace: true });
```

### Scheduled messages

Schedule a message for future delivery. The returned `ScheduledMessage` includes a `cancel()` method to abort before it's sent.

```typescript title="lib/bot.ts" lineNumbers
const scheduled = await thread.schedule("Reminder: standup in 5 minutes!", {
  postAt: new Date("2026-03-09T09:00:00Z"),
});

// Cancel before it's sent
await scheduled.cancel();
```

> Scheduled messages are currently only supported by the Slack adapter. Other adapters throw `NotImplementedError`. See the [feature matrix](/docs/platform-adapters) for details.

## Messages

Incoming messages are normalized across platforms into a consistent format:

| Property      | Type                      | Description                                                                                                          |
| ------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `id`          | `string`                  | Platform message ID                                                                                                  |
| `threadId`    | `string`                  | Thread ID in `adapter:channel:thread` format                                                                         |
| `text`        | `string`                  | Plain text content                                                                                                   |
| `formatted`   | `Root`                    | mdast AST representation                                                                                             |
| `raw`         | `unknown`                 | Original platform-specific payload                                                                                   |
| `author`      | `Author`                  | Message author info                                                                                                  |
| `metadata`    | `MessageMetadata`         | Timestamps and edit status                                                                                           |
| `attachments` | `Attachment[]` (optional) | File attachments                                                                                                     |
| `replyTo`     | `Message` (optional)      | Normalized message this message replies to, when provided by the adapter                                             |
| `isMention`   | `boolean` (optional)      | The adapter's mention decision. `true` and `false` are final; `undefined` makes Chat SDK match `@username` in `text` |

### Author

```typescript lineNumbers
interface Author {
  userId: string;
  userName: string;
  fullName: string;
  isBot: boolean | "unknown";
  isMe: boolean; // true if message is from the bot itself
}
```

For richer user info (email, avatar), use [`chat.getUser()`](/docs/api/chat#getuser):

```typescript title="lib/bot.ts"
const user = await bot.getUser(message.author);
console.log(user?.email); // "alice@company.com"
```

### Sent messages

When you post a message, you get back a `SentMessage` with methods to edit, delete, and react:

```typescript title="lib/bot.ts" lineNumbers
const sent = await thread.post("Processing...");
// Do some work...
await sent.edit("Done!");

// Or delete
await sent.delete();

// Add/remove reactions
await sent.addReaction(emoji.check);
await sent.removeReaction(emoji.check);
```

## Channels

A `Channel` is the container that holds threads, such as a Slack channel or a Teams conversation. Get a channel from a thread or look one up by ID:

```typescript title="lib/bot.ts" lineNumbers
// From a thread
const channel = thread.channel;

// Directly by ID
const channel = bot.channel("slack:C123ABC");
```

### List threads

Iterate threads in a channel, most recently active first:

```typescript title="lib/bot.ts" lineNumbers
for await (const thread of channel.threads()) {
  console.log(thread.rootMessage.text, thread.replyCount);
}
```

### Channel messages

Iterate top-level messages (not thread replies):

```typescript title="lib/bot.ts" lineNumbers
for await (const msg of channel.messages) {
  console.log(msg.text);
}
```

### Post to a channel

Post a top-level message (not inside a thread):

```typescript title="lib/bot.ts"
await channel.post("Hello channel!");
```

### Channel metadata

```typescript title="lib/bot.ts"
const info = await channel.fetchMetadata();
console.log(info.name, info.memberCount);
```

### Channel history

Channel-level history comes from the platform adapter and isn't stored in your state adapter by default. Use `bot.history.channel` for promise-based pagination, or the `Channel` iterators above for async iteration.

For channel digests or moderation, the usual pattern is to list threads and then fetch the messages in each one:

```typescript title="lib/bot.ts" lineNumbers
const channelId = "slack:C123ABC";

// Step 1: list recent threads (ThreadSummary: id, rootMessage, replyCount, …)
const { threads, nextCursor } = await bot.history.channel.listThreads(channelId, {
  limit: 20,
});

for (const summary of threads) {
  // Step 2: fetch messages in each thread
  const { messages } = await bot.history.thread.list(summary.id, {
    limit: 50,
    direction: "forward",
  });

  console.log(summary.rootMessage.text, summary.replyCount, messages.length);
}

// Paginate with nextCursor from listThreads when you need more threads
```

The object-oriented equivalent uses the same underlying APIs:

```typescript title="lib/bot.ts" lineNumbers
const channel = bot.channel("slack:C123ABC");

for await (const summary of channel.threads()) {
  const thread = bot.thread(summary.id);

  for await (const msg of thread.allMessages) {
    console.log(msg.text);
  }
}
```

To read top-level channel messages without thread replies, use `listMessages`:

```typescript title="lib/bot.ts" lineNumbers
const { messages } = await bot.history.channel.listMessages(channelId, {
  limit: 20,
});
```

For a one-shot helper that lists threads and prefetches messages for each, see [`bot.history.channel.listThreadsWithMessages`](/docs/api/history#listthreadswithmessages) in the API reference.

> `listThreads` requires adapter support (Slack, Discord, Teams, Google Chat, GitHub). On threadless platforms (WhatsApp, Telegram), `listThreads` throws and `channel.threads()` yields nothing. See the [adapter feature matrix](/docs/adapters) and the [History guide](/docs/history#channel-history) for platform details.

## Thread ID format

All thread IDs follow the pattern `{adapter}:{channel}:{thread}`:

- Slack: `slack:C123ABC:1234567890.123456`
- Teams: `teams:{base64(conversationId)}:{base64(serviceUrl)}[:{conversationType}]`
- Google Chat: `gchat:spaces/ABC123:{base64(threadName)}`
- Discord: `discord:{guildId}:{channelId}[:{threadId}]`

You rarely need to build these yourself, because the threads your event handlers receive already carry them.

## Logging

If you omit the `logger` option, Chat SDK uses `ConsoleLogger("info")`. Each adapter also creates its own child logger.

```typescript title="lib/bot.ts" lineNumbers
// Use defaults (ConsoleLogger at "info" level)
const bot = new Chat({
  // ...
});

// Or set a specific log level
const bot = new Chat({
  // ...
  logger: "debug", // "debug" | "info" | "warn" | "error" | "silent"
});

// Or use a custom ConsoleLogger for child loggers
import { ConsoleLogger } from "chat";

const logger = new ConsoleLogger("info");
const bot = new Chat({
  // ...
  logger,
});
```

You can pass child loggers to adapters for prefixed log output, but adapters create their own child loggers by default:

```typescript title="lib/bot.ts"
createSlackAdapter({
  logger: logger.child("slack"), // optional; auto-created if omitted
});
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Creating a Chat Instance
description: Initialize the Chat class with adapters, state, and configuration options.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/getting-started
related:
  - /docs/handling-events
  - /docs/adapters
  - /docs/state-adapters
  - /docs/api/chat
  - /docs/error-handling
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The `Chat` class is the main entry point for your bot. It coordinates adapters, routes events to your handlers, and manages thread state.

## Basic setup

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
  },
  state: createRedisState(),
});

bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.post("Hello! I'm listening to this thread.");
});
```

> This example uses Redis. Chat SDK also supports [PostgreSQL](/adapters/official/postgres) and [ioredis](/adapters/official/ioredis) as production state adapters. See [State Adapters](/docs/state-adapters) for all options.

Adapter and state factories read their credentials from environment variables such as `SLACK_BOT_TOKEN`, `SLACK_SIGNING_SECRET`, and `REDIS_URL`, so the example above passes no options. Pass explicit values to override them. For setup UIs and build scripts, [`@chat-adapter/catalog`](/docs/adapter-catalog) lists official and vendor-official adapter env specs without importing adapter packages.

## Multiple adapters

Register several [adapters](/adapters) to run the same bot on each of those platforms:

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createTeamsAdapter } from "@chat-adapter/teams";
import { createDiscordAdapter } from "@chat-adapter/discord";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
    teams: createTeamsAdapter(),
    discord: createDiscordAdapter(),
  },
  state: createRedisState(),
});
```

Your event handlers work the same way for every registered adapter, because the SDK normalizes messages, threads, and reactions into one format. Where platforms differ, such as rate limits or unsupported features, the SDK throws typed errors. See [Error Handling](/docs/error-handling).

## Configuration options

| Option                             | Type                                                                              | Default         | Description                                                                                                                                                             |
| ---------------------------------- | --------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userName`                         | `string`                                                                          | *required*      | Default bot username across all adapters                                                                                                                                |
| `adapters`                         | `Record<string, Adapter>`                                                         | *required*      | Map of adapter name to adapter instance                                                                                                                                 |
| `state`                            | `StateAdapter`                                                                    | *required*      | State adapter for subscriptions and locking                                                                                                                             |
| `logger`                           | `Logger \| LogLevel`                                                              | `"info"`        | Logger instance or log level (`"debug"`, `"info"`, `"warn"`, `"error"`, `"silent"`)                                                                                     |
| `dedupeTtlMs`                      | `number`                                                                          | `600000`        | TTL in ms for message deduplication (10 minutes)                                                                                                                        |
| `concurrency`                      | `"drop" \| "queue" \| "debounce" \| "burst" \| "concurrent" \| ConcurrencyConfig` | `"drop"`        | Strategy for overlapping messages on the same thread                                                                                                                    |
| `streamingUpdateIntervalMs`        | `number`                                                                          | `500`           | Update interval in ms for post+edit streaming                                                                                                                           |
| `fallbackStreamingPlaceholderText` | `string \| null`                                                                  | `"..."`         | Placeholder text while streaming starts. Set to `null` to skip                                                                                                          |
| `lockScope`                        | `"thread" \| "channel" \| function`                                               | Adapter default | Whether messages share a lock per thread or per channel. See [Lock scope](/docs/concurrency#lock-scope)                                                                 |
| `history`                          | `HistoryConfig`                                                                   |                 | User, thread, and channel history settings. See [History](/docs/history)                                                                                                |
| `onLockConflict`                   | `'drop' \| 'force' \| (threadId, message) => 'drop' \| 'force'`                   | `"drop"`        | Deprecated: use `concurrency`. Under the `drop` strategy, `'force'` releases the existing lock and re-acquires it so a new message can interrupt a long-running handler |

## Accessing adapters

Use `getAdapter` to access platform-specific APIs when you need functionality beyond the unified interface:

```typescript title="lib/bot.ts" lineNumbers
import type { SlackAdapter } from "@chat-adapter/slack";

const slack = bot.getAdapter("slack") as SlackAdapter;
await slack.setSuggestedPrompts(channelId, threadTs, [
  { title: "Get started", message: "What can you help me with?" },
]);
```

For typed access to the platform's native API client, use the SDK-named getter on each adapter:

```typescript title="lib/bot.ts" lineNumbers
const slack = bot.getAdapter("slack").webClient; // WebClient
const linear = bot.getAdapter("linear").linearClient; // LinearClient
const github = bot.getAdapter("github").octokit; // Octokit
```

The previous `.client` getter still works as a deprecated alias on all three adapters.

See [`getAdapter`](/docs/api/chat#getadapter) for multi-tenant constraints.

## Webhook routing

The `webhooks` property provides a typed handler for each registered adapter. Wire each one to a route in your HTTP framework:

```typescript title="app/api/webhooks/slack/route.ts" lineNumbers
import { after } from "next/server";
import { bot } from "@/lib/bot";

export async function POST(request: Request): Promise<Response> {
  return bot.webhooks.slack(request, {
    waitUntil: (task) => after(() => task),
  });
}
```

```typescript title="app/api/webhooks/teams/route.ts" lineNumbers
import { after } from "next/server";
import { bot } from "@/lib/bot";

export async function POST(request: Request): Promise<Response> {
  return bot.webhooks.teams(request, {
    waitUntil: (task) => after(() => task),
  });
}
```

Your event handlers can keep running after the webhook responds. `waitUntil` keeps the function alive until they finish, so a serverless platform doesn't stop them early. These examples use Next.js `after`. In other Vercel Functions, pass `waitUntil` from `@vercel/functions`.

## Lifecycle

The Chat instance initializes lazily on the first webhook. You can also initialize manually:

```typescript title="lib/bot.ts" lineNumbers
await bot.initialize();
```

For graceful shutdown, such as during serverless teardown, call `shutdown`:

```typescript title="lib/bot.ts" lineNumbers
await bot.shutdown();
```

## Singleton pattern

Register a singleton when you need to access the Chat instance from multiple files:

```typescript title="lib/bot.ts" lineNumbers
const bot = new Chat({ /* ...config */ }).registerSingleton();
export default bot;
```

```typescript title="lib/utils.ts" lineNumbers
import { Chat } from "chat";

const bot = Chat.getSingleton();
```

## Direct messaging

Open a DM thread with a user by passing their platform user ID or an `Author` object:

```typescript title="lib/bot.ts" lineNumbers
const dm = await bot.openDM("U123ABC");
await dm.post("Hey! Just wanted to follow up on your request.");
```

## Channel access

Get a channel directly by its ID:

```typescript title="lib/bot.ts" lineNumbers
const channel = bot.channel("slack:C123ABC");
await channel.post("Announcement: deploy complete!");
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Vercel Connect
description: Authenticate Slack, Microsoft Teams, GitHub, Linear, Discord, Notion, and Telegram adapters with Vercel Connect, using short-lived runtime tokens for outbound calls and OIDC-verified inbound webhooks where supported.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
related:
  - /docs/usage
  - /adapters/official/slack
  - /adapters/official/teams
  - /adapters/official/github
  - /adapters/official/linear
  - /adapters/official/discord
  - /adapters/official/notion
  - /adapters/official/telegram
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

[Vercel Connect](https://vercel.com/docs/connect) lets your bot use a registered connector for adapter authentication instead of storing long-lived provider secrets. You register a connector once, link it to your project and environments, and your code requests scoped, short-lived tokens at runtime.

The `@vercel/connect/chat` subpath ships a helper per platform that you spread into the matching `create*Adapter` factory.

## Adapter support

| Adapter                                     | Helper                   | Outbound field              |
| ------------------------------------------- | ------------------------ | --------------------------- |
| [Slack](/adapters/official/slack)           | `connectSlackAdapter`    | `botToken`                  |
| [Microsoft Teams](/adapters/official/teams) | `connectTeamsAdapter`    | `appId`, `token`            |
| [GitHub](/adapters/official/github)         | `connectGitHubAdapter`   | `installationToken`         |
| [Linear](/adapters/official/linear)         | `connectLinearAdapter`   | `accessToken`               |
| [Discord](/adapters/official/discord)       | `connectDiscordAdapter`  | `botToken`, `applicationId` |
| [Notion](/adapters/official/notion)         | `connectNotionAdapter`   | `token`                     |
| [Telegram](/adapters/official/telegram)     | `connectTelegramAdapter` | `botToken`                  |

Every helper wires outbound credentials. Helpers for trigger-capable providers also wire inbound traffic:

- Outbound, when your bot calls the provider API: the helper sets a function-form token field that resolves a fresh, short-lived token per call via `getToken`.
- Inbound, when the provider calls your bot: trigger-capable helpers include a `webhookVerifier` that validates the Vercel OIDC token Connect attaches to [trigger-forwarded](https://vercel.com/docs/connect/concepts/triggers) webhooks. It replaces the provider's native signature check.

Each helper accepts `(connector, params?, options?)`, where `params` is the [`getToken`](https://vercel.com/docs/connect/ts-sdk-reference) parameters minus `subject`, which is pinned to `{ type: "app" }`. Use `params` to pass supported token parameters such as `installationId` or `validityBufferMs`.

## Install

```bash
pnpm add @vercel/connect
```

`@vercel/connect` reads the deployment's OIDC token automatically. For local development, run `vercel link` followed by `vercel env pull` to download a short-lived token into `.env.local`.

## Scaffold a new bot

To start a new project with Connect already wired, pass `--connect` to [`create-chat-sdk`](/docs/create-chat-sdk#vercel-connect). The generated bot reads each connector UID from an environment variable such as `SLACK_CONNECTOR`:

## Set up a connector

Create a connector in the [Vercel dashboard](https://vercel.com/d?to=%2F%5Bteam%5D%2F~%2Fconnect) or with the [Vercel CLI](https://vercel.com/docs/cli/connect), then attach it to your project.

1. Link your local directory to the Vercel project:

```bash
vercel link
```

2. Create the connector and attach it to the linked project. For Slack, Microsoft Teams, GitHub, Linear, and Discord, enable trigger forwarding and register your Chat SDK webhook route (`/api/webhooks/{platform}`) as the trigger destination. Notion and Telegram webhooks go directly to your app, so create and attach those connectors without triggers and use native webhook verification or polling.

**Slack**

```bash
vercel connect create slack --name acme-slack --triggers
vercel connect attach slack/acme-slack --triggers --trigger-path /api/webhooks/slack
```

**Microsoft Teams**

```bash
vercel connect create microsoft-teams --name acme-teams --triggers
vercel connect attach microsoft-teams/acme-teams --triggers --trigger-path /api/webhooks/teams
```

**GitHub**

```bash
vercel connect create github --name acme-github --triggers
vercel connect attach github/acme-github --triggers --trigger-path /api/webhooks/github
```

**Linear**

```bash
vercel connect create linear --name acme-linear --triggers
vercel connect attach linear/acme-linear --triggers --trigger-path /api/webhooks/linear
```

**Discord**

```bash
vercel connect create discord --name acme-discord --triggers
vercel connect attach discord/acme-discord --triggers --trigger-path /api/webhooks/discord
```

**Notion**

```bash
vercel connect create notion --name acme-notion
vercel connect attach notion/acme-notion
```

**Telegram**

```bash
vercel connect create telegram --name acme-telegram
vercel connect attach telegram/acme-telegram
```

`vercel connect attach` uses the linked project and enables production, preview, and development by default. Pass `--project` or `--environment` to change that. Without `--trigger-branch`, Connect forwards webhooks to your production deployment.

3. Pull a development token locally (deployments get `VERCEL_OIDC_TOKEN` automatically):

```bash
vercel env pull
```

## Wire up the adapter

Spread the helper into the adapter factory. The webhook route stays the same, because Connect forwards verified events to the same handler.

### Slack

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createRedisState } from "@chat-adapter/state-redis";
import { connectSlackAdapter } from "@vercel/connect/chat";

export const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter({
      ...connectSlackAdapter("slack/acme-slack"),
    }),
  },
  state: createRedisState(),
});
```

Replace `slack/acme-slack` with your connector UID from the Connect dashboard or `vercel connect list`. Omit `signingSecret` and `SLACK_SIGNING_SECRET` when using the helper. The OIDC `webhookVerifier` is the freshness boundary instead.

### Microsoft Teams

```typescript title="lib/bot.ts" lineNumbers
import { createTeamsAdapter } from "@chat-adapter/teams";
import { connectTeamsAdapter } from "@vercel/connect/chat";

createTeamsAdapter({
  ...connectTeamsAdapter("microsoft-teams/acme-teams"),
});
```

The helper resolves the bot's `appId` during initialization, requests separate Bot Framework and Microsoft Graph tokens through `token`, and supplies OIDC verification for forwarded webhooks. Enable trigger forwarding to `/api/webhooks/teams`. Omit `TEAMS_APP_ID` and `TEAMS_APP_PASSWORD` when using the helper.

Teams excludes `scopes` from helper parameters: its token callback requests the scope required by each API call.

Graph reads require the appropriate installation and consent permissions. Managed tokens use the bot's home tenant; the adapter's token callback tenant argument does not change that selection. Call `await bot.initialize()` before using adapter methods directly. Chat initializes automatically before processing webhooks.

### GitHub

```typescript title="lib/bot.ts" lineNumbers
import { createGitHubAdapter } from "@chat-adapter/github";
import { connectGitHubAdapter } from "@vercel/connect/chat";

createGitHubAdapter({
  ...connectGitHubAdapter("github/acme-github"),
  userName: "my-bot[bot]",
  botUserId: 12345678, // Numeric ID of your GitHub App bot user
});
```

`installationToken` is the installation access token a GitHub App would normally mint via its private-key JWT exchange. The adapter uses it directly and skips that exchange.

Set `botUserId` to your GitHub App bot user's numeric ID, or set `GITHUB_BOT_USER_ID`. An installation token cannot identify the bot through `/app`, and learning the ID from a posted comment only lasts for that process. Configuring it up front lets every serverless instance recognize its own comments and avoid self-reply loops. See the [GitHub adapter setup](/adapters/official/github#vercel-connect) for how to find the ID.

### Linear

```typescript title="lib/bot.ts" lineNumbers
import { createLinearAdapter } from "@chat-adapter/linear";
import { connectLinearAdapter } from "@vercel/connect/chat";

createLinearAdapter({
  ...connectLinearAdapter("linear/acme-linear"),
  mode: "agent-sessions",
});
```

We recommend `mode: "agent-sessions"` for Linear Connect bots. Enable **Agent session events** on the Linear app and use an app-actor installation. Projects generated with `create-chat-sdk --adapter linear --connect` include this mode explicitly. The adapter still defaults to `"comments"` when `mode` is omitted, so existing bots keep their behavior. For outbound calls outside webhook handling (cron jobs, workflows), wrap them in `withInstallation()` so a request-scoped client is bound:

```typescript title="lib/jobs.ts" lineNumbers
await linear.withInstallation("org-id", async () => {
  await linear.postMessage("linear:issue-id", "Hello from a background job");
});
```

### Discord

```typescript title="lib/bot.ts" lineNumbers
import { createDiscordAdapter } from "@chat-adapter/discord";
import { connectDiscordAdapter } from "@vercel/connect/chat";

createDiscordAdapter({
  ...connectDiscordAdapter("discord/acme-discord"),
});
```

The helper resolves `botToken` and `applicationId` from one Connect token
response. Omit `DISCORD_BOT_TOKEN`, `DISCORD_PUBLIC_KEY`, and
`DISCORD_APPLICATION_ID`. Connect OIDC verification replaces Discord's
Ed25519 public-key check for trigger-forwarded interactions.

### Notion

```typescript title="lib/bot.ts" lineNumbers
import { createNotionAdapter } from "@chat-adapter/notion";
import { connectNotionAdapter } from "@vercel/connect/chat";

createNotionAdapter({
  ...connectNotionAdapter("notion/acme-notion"),
  verificationToken: process.env.NOTION_VERIFICATION_TOKEN,
});
```

`connectNotionAdapter` supplies only the outbound `token`; it does not include a
`webhookVerifier`. Connect does not forward Notion triggers, so configure the
webhook subscription directly in Notion and retain
`NOTION_VERIFICATION_TOKEN` for native HMAC verification. Omit
`NOTION_TOKEN` when using the helper.

### Telegram

```typescript title="lib/bot.ts" lineNumbers
import { createTelegramAdapter } from "@chat-adapter/telegram";
import { connectTelegramAdapter } from "@vercel/connect/chat";

createTelegramAdapter({
  ...connectTelegramAdapter("telegram/acme-telegram"),
  secretToken: process.env.TELEGRAM_WEBHOOK_SECRET_TOKEN,
});
```

`connectTelegramAdapter` supplies only the outbound `botToken`; it does not
include a `webhookVerifier`. The adapter derives webhook deduplication scope
from Telegram's stable bot identity, not the rotating credential. Retain
`TELEGRAM_WEBHOOK_SECRET_TOKEN` for native webhook verification or use polling
mode. Omit `TELEGRAM_BOT_TOKEN` when using the helper.

## Custom webhook verification

Each trigger-capable helper attaches a default verifier that matches the deployment's project and environment. `projectId` defaults to `VERCEL_PROJECT_ID`, and `environment` defaults to `VERCEL_TARGET_ENV`, then `VERCEL_ENV`. As a result, production, preview, and development each accept only their own tokens. Verification fails closed: if those values are absent, every request is rejected. The issuer must be `https://oidc.vercel.com` or a Vercel team issuer beneath `https://oidc.vercel.com/`.

To add constraints, such as accepting multiple environments, build a verifier with `createConnectWebhookVerifier` and override the field:

```typescript title="lib/bot.ts" lineNumbers
import {
  connectSlackAdapter,
  createConnectWebhookVerifier,
} from "@vercel/connect/chat";

createSlackAdapter({
  ...connectSlackAdapter("slack/acme-slack"),
  webhookVerifier: createConnectWebhookVerifier({
    environment: ["production", "preview"],
  }),
});
```

> Avoid hardcoding `environment: "production"` unless you only forward to production. That verifier rejects preview and development deployments.

## Notes and limitations

- The helpers use app-scoped tokens and act as the application itself (`subject: { type: "app" }`). End-user OAuth is a separate concern.
- OIDC verification replaces each provider's native signature and timestamp check. Request freshness relies on the short-lived OIDC token's expiry rather than a signed timestamp, and there is no built-in delivery de-duplication, so keep your webhook handlers idempotent.
- Connect trigger forwarding is HTTP-only, so it doesn't work with the Slack adapter's Socket Mode.
- Connect forwards to deployed URLs, not `localhost`. Test against a preview or development deployment.

## Related resources

- [Vercel Connect Chat SDK documentation](https://vercel.com/docs/connect/frameworks/chat-sdk)
- [The Complete Guide to Vercel Connect](https://vercel.com/kb/guide/vercel-connect)
- [Vercel Connect overview](https://vercel.com/docs/connect)
- [Vercel Connect triggers](https://vercel.com/docs/connect/concepts/triggers)
- [`@vercel/connect` SDK reference](https://vercel.com/docs/connect/ts-sdk-reference)

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: AI SDK Tools
description: Let an AI agent post messages, send DMs, react, edit, and delete inside your workspace, with approval required for writes by default.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/ai
  - /docs/ai/to-ai-messages
  - /docs/streaming
  - /docs/history
  - /docs/approvals
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`createChatTools` exposes Chat SDK operations as [AI SDK](https://ai-sdk.dev) tools so an agent can act inside the same workspaces your bot is connected to: read messages, post replies, send DMs, react, edit, delete, and manage thread subscriptions across every adapter you've registered.

> Building on TanStack AI instead of the AI SDK? `createTanStackTools` in
> `chat/ai/tanstack` returns the same tools for `chat({ tools })`. See
> [TanStack AI](/docs/ai/tanstack-ai).

Write operations and arbitrary `getUser` profile lookups require user approval by default. Turn approval off globally or per tool when you want unattended execution.

## Installation

The tools live in the [`chat/ai`](/docs/ai) subpath of the core `chat` package:

```ts
import { createChatTools } from "chat/ai";
```

`ai` and `zod` are optional peer dependencies. Install them if you haven't already:

```bash
pnpm add ai zod
```

> Pair `createChatTools` with [`toAiMessages`](/docs/ai/to-ai-messages)
> to feed prior thread history into the agent before it picks a tool.
> Both ship from the same `chat/ai` subpath, which keeps the optional
> `ai` / `zod` peer deps out of bundles that don't import them.

## Quick start

Pass your `Chat` instance and the tools you want into any AI SDK call:

```typescript title="lib/agent.ts" lineNumbers
import { Chat } from "chat";
import { createChatTools } from "chat/ai";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createMemoryState } from "@chat-adapter/state-memory";
import { generateText } from "ai";

const chat = new Chat({
  userName: "mybot",
  adapters: { slack: createSlackAdapter() },
  state: createMemoryState(),
});

const result = await generateText({
  model: "xai/grok-4.5",
  tools: createChatTools({
    chat,
    preset: "messenger",
    scope: "slack:C0123ABC",
    requireApproval: false, // unattended script, no human-in-the-loop needed
  }),
  prompt:
    "Post a friendly hello in slack:C0123ABC and react to it with a thumbs up.",
});
```

Each tool resolves the right adapter from the id prefix you give it (`slack:...`, `discord:...`, `gchat:...`), so the same agent can drive any platform your `Chat` instance is wired up to.

## Presets

Pass `preset` to limit the toolset to what an agent needs.

```typescript
// Read-only: fetch messages, threads, channel info, users
createChatTools({ chat, preset: "reader" });

// Basic posting: read + post + DM + react + typing indicator
createChatTools({ chat, preset: "messenger" });

// Full management: everything including edit, delete, subscriptions
createChatTools({ chat, preset: "moderator" });
```

Presets compose. Pass an array to combine them:

```typescript
createChatTools({ chat, preset: ["reader", "messenger"] });
```

Omit `preset` to get every tool, which is the same as `'moderator'`.

| Preset      | Tools included                                                                                                                                                                                       |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `reader`    | `fetchMessages`, `fetchChannelMessages`, `fetchThread`, `listThreads`, `getThreadParticipants`, `getChannelInfo`, `getUser`                                                                          |
| `messenger` | `fetchMessages`, `fetchThread`, `getChannelInfo`, `getUser`, `postMessage`, `postChannelMessage`, `sendDirectMessage`, `addReaction`, `removeReaction`, `startTyping`                                |
| `moderator` | All read tools plus `postMessage`, `postChannelMessage`, `sendDirectMessage`, `editMessage`, `deleteMessage`, `addReaction`, `removeReaction`, `subscribeThread`, `unsubscribeThread`, `startTyping` |

## Limiting what the agent can reach

Read and write tools take a thread or channel id chosen by the model, and they run with your bot's platform access. A bot is usually a member of channels a given user is not, so an agent handling untrusted input can be talked into fetching a conversation the user could never open themselves, repeating it back, or posting into a conversation the user never asked it to touch.

Pass `scope` with the conversation the agent is handling. Tool calls that resolve outside it are rejected before the platform is called. This covers reads and writes that target a thread or channel; `getUser` and `sendDirectMessage` target user ids instead and are gated by approval alone.

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  const tools = createChatTools({
    chat,
    preset: "reader",
    scope: thread,
  });

  const result = await generateText({
    model: "openai/gpt-5",
    tools,
    prompt: message.text,
  });
});
```

`scope` accepts a `Thread`, a `Channel`, or a raw id. By default, scoping is channel-level: a call is allowed when it resolves to the same channel as the scoped conversation. That blocks the cross-channel read described above but, matching a channel-membership model, still lets the agent operate on sibling threads within the channel.

Tools called inside a handler with a conversation use that conversation as their scope, so the common case needs no extra argument:

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  // Tools are confined to this conversation.
  const tools = createChatTools({ chat, preset: "reader" });

  const result = await generateText({
    model: "openai/gpt-5",
    tools,
    prompt: message.text,
  });
});
```

Pass `scope` explicitly when the agent runs outside a handler, such as a queued job that still answers on a user's behalf. Pass a channel id there if the agent legitimately needs to operate across the threads in a channel.

> Inside a handler that has no conversation, such as an action in App Home or inside a modal, an options-load handler, or a modal opened outside a thread or channel, calls without a `scope` are rejected before accessing the platform. Outside any handler, such as a cron job or script, they run workspace-wide and log a warning. Pass `scope` explicitly in both cases. A modal keeps its context while it stays open, so resubmitting after validation errors still has a scope. The context is removed when the modal closes and expires after 24 hours, so a duplicate delivery after that has no scope. On Slack, a pushed view shares its context with the view beneath it, so closing or submitting the pushed view removes the context for both. Use `scope: false` only when workspace-wide access is intended.

### What `scope` does not do

`scope` confines tools to a conversation using your bot's own access. It is not a per-user access check. It doesn't verify that the end user the agent is answering for is a member of the target, because that would require per-platform membership calls the SDK doesn't make.

It also does not cover `getUser` or `sendDirectMessage`, which target user ids rather than conversations. If the agent handles untrusted input, keep approval on for those tools, which is the default.

So within the scope you grant, tools follow the bot's access, not the user's:

- A thread scope still allows reading the parent channel and its sibling threads, matching Slack's channel-membership model, where a user who can see a thread can see the channel around it.
- A channel scope allows any thread in that channel, including independently permissioned threads on Discord or GitHub that the end user may not have access to.

This channel-level default is coarser than the per-thread ACLs on platforms like Discord and GitHub, where one channel or repo holds independently permissioned threads. `scope` alone will not enforce per-user permissions there.

### Tightening to a single thread

Set `strictScope` to confine a thread scope to that thread alone. Sibling threads and the parent channel are both rejected. Use it when the agent handles untrusted input on a platform with per-thread ACLs:

```typescript title="lib/bot.ts" lineNumbers
bot.onNewMention(async (thread, message) => {
  const tools = createChatTools({
    chat,
    preset: "reader",
    scope: thread,
    strictScope: true, // sibling threads and the parent channel are rejected
  });

  const result = await generateText({
    model: "openai/gpt-5",
    tools,
    prompt: message.text,
  });
});
```

Rejecting the parent channel matters most on the platforms this is aimed at, because a channel there is the widest read available. A GitHub channel is an entire repository, so a channel-level read would list every issue and pull request in it, which is broader than any sibling thread the option blocks.

A channel scope is unaffected by `strictScope`. It still allows any thread within the channel, and the channel itself. This is opt-in rather than the default so existing channel-membership-style behavior is preserved; enable it when you want tools confined to the exact thread.

## Approval control

Write operations (posting, editing, deleting, reacting, subscribing) and `getUser` default to `needsApproval: true`. The AI SDK pauses execution and surfaces an approval request that your application confirms before the tool runs. This keeps a human in the loop for anything visible to the workspace or anything that can expose a user profile.

```typescript
// All writes and getUser need approval (default)
createChatTools({ chat });

// No approval needed
createChatTools({ chat, requireApproval: false });

// Per-tool: only destructive actions need approval
createChatTools({
  chat,
  requireApproval: {
    deleteMessage: true,
    editMessage: true,
    getUser: true,
    sendDirectMessage: false,
    postMessage: false,
    addReaction: false,
  },
});
```

Conversation-scoped read tools (`fetchMessages`, `fetchThread`, `getChannelInfo`, …) and the `startTyping` indicator do not require approval. `getUser` is the exception because it accepts arbitrary user ids and can return profile details outside the active conversation.

> `createChatTools` only marks a tool as needing approval. The AI SDK captures
> the decision and can optionally sign it so a resumed approval can't be
> forged. If you round-trip approvals through an
> untrusted client and enable the AI SDK's `experimental_toolApprovalSecret`,
> use a version of `ai` that includes the injective-payload signing fix
> ([vercel/ai#17493](https://github.com/vercel/ai/pull/17493)).

## Cherry-picking tools

Each tool is also exported as a standalone factory you can hand to `tools` directly:

```typescript title="lib/bot.ts" lineNumbers
import { addReaction, fetchMessages, postMessage } from "chat/ai";

bot.onNewMention(async (thread, message) => {
  const result = await generateText({
    model: "openai/gpt-5",
    tools: {
      fetchMessages: fetchMessages(chat),
      postMessage: postMessage(chat, { needsApproval: false }),
      addReaction: addReaction(chat, { needsApproval: false }),
    },
    prompt: message.text,
  });
});
```

Use these when you want a small toolset without going through `createChatTools`.

Factories for tools that target a thread or channel accept the same `scope` and `strictScope` options as `createChatTools` and follow the same rules described in [Limiting what the agent can reach](#limiting-what-the-agent-can-reach). Called inside a handler, they use the conversation being handled. In background jobs, pass a scope:

```typescript title="lib/jobs/digest.ts" lineNumbers
import { fetchChannelMessages, postChannelMessage } from "chat/ai";

const tools = {
  fetchChannelMessages: fetchChannelMessages(chat, { scope: "slack:C123" }),
  postChannelMessage: postChannelMessage(chat, {
    scope: "slack:C123",
    needsApproval: false,
  }),
};
```

Pass `scope: false` only when workspace-wide access is intended. `getUser` and `sendDirectMessage` target user ids, so they take no scope and stay gated by approval. Passing a guard function as the second argument of a read factory, or as `guard` on a write factory, still works but is deprecated in favor of `scope`.

## Tool overrides

Customize any AI SDK [`tool()`](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling) property per tool, keyed by tool name:

```typescript
import type { ChatToolName, ToolOverrides } from "chat/ai";

createChatTools({
  chat,
  overrides: {
    postMessage: {
      description: "Reply in the active customer support thread.",
      needsApproval: false,
    },
    deleteMessage: { needsApproval: true },
  },
});
```

| Property           | Type                  | Description                                                   |
| ------------------ | --------------------- | ------------------------------------------------------------- |
| `description`      | `string`              | Custom tool description shown to the model                    |
| `title`            | `string`              | Human-readable title                                          |
| `strict`           | `boolean`             | Strict mode for input generation                              |
| `inputExamples`    | `array`               | Examples that show the model what tool input should look like |
| `metadata`         | `object`              | Tool metadata propagated to tool call and result parts        |
| `needsApproval`    | `boolean \| function` | Gate execution behind an approval request                     |
| `providerOptions`  | `ProviderOptions`     | Provider-specific metadata                                    |
| `onInputStart`     | `function`            | Callback when argument streaming starts                       |
| `onInputDelta`     | `function`            | Callback on each streaming delta                              |
| `onInputAvailable` | `function`            | Callback when full input is available                         |
| `toModelOutput`    | `function`            | Custom mapping of tool result to model output                 |

Core properties cannot be overridden, so tool semantics stay stable: `execute`, `inputSchema`, `outputSchema`, `supportsDeferredResults`, and the tool-kind fields `type`, `id`, and `args`.

## Available tools

Thread and channel ids use the full Chat SDK form: `slack:C123ABC:1234567890.123456` for a thread and `slack:C123ABC` for a channel. User ids are platform-native, such as `U123456` on Slack or `users/123` on Google Chat. The tools detect the adapter from the id.

### Reading

| Tool                    | Description                                                     |
| ----------------------- | --------------------------------------------------------------- |
| `fetchMessages`         | Fetch recent messages from a thread (paginated)                 |
| `fetchChannelMessages`  | Fetch top-level messages in a channel (not thread replies)      |
| `fetchThread`           | Fetch metadata for a thread (channel id, visibility, DM status) |
| `listThreads`           | List recent threads in a channel with their root message        |
| `getThreadParticipants` | Return the unique non-bot participants in a thread              |
| `getChannelInfo`        | Fetch channel metadata (name, member count, visibility)         |
| `getUser`               | Look up a user's profile by id                                  |

`getUser` requires approval by default; the other read tools do not.

### Writing

| Tool                 | Description                                          | Default approval |
| -------------------- | ---------------------------------------------------- | ---------------- |
| `postMessage`        | Post a reply in an existing thread                   | required         |
| `postChannelMessage` | Post a top-level message in a channel                | required         |
| `sendDirectMessage`  | Open a DM with a user and post in it                 | required         |
| `editMessage`        | Edit a message the bot previously posted             | required         |
| `deleteMessage`      | Delete a message the bot previously posted           | required         |
| `addReaction`        | Add an emoji reaction to a message                   | required         |
| `removeReaction`     | Remove a previously-added reaction                   | required         |
| `subscribeThread`    | Subscribe the bot to all future messages in a thread | required         |
| `unsubscribeThread`  | Stop receiving non-mention messages in a thread      | required         |
| `startTyping`        | Show a typing indicator in a scoped thread           | no approval      |

`postMessage`, `postChannelMessage`, `sendDirectMessage`, and `editMessage` mark `markdown` and `raw` bodies with `aiGenerated: true`, so adapters with a native AI label, such as Teams, show it. Plain-string bodies are sent unchanged and unlabeled, so an `editMessage` call with a string body removes an existing label.

## API

### `createChatTools(options)`

Returns an object of tools that you pass as `tools` to any AI SDK call.

```typescript
type ChatToolsOptions = {
  chat: Chat;
  requireApproval?: boolean | Partial<Record<ChatApprovalToolName, boolean>>;
  preset?: ChatToolPreset | ChatToolPreset[];
  overrides?: Partial<Record<ChatToolName, ToolOverrides>>;
  scope?: ReadScope | false;
  strictScope?: boolean;
};

type ChatToolPreset = "reader" | "messenger" | "moderator";
type ReadScope = string | { id: string };
```

| Option            | Description                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chat`            | The `Chat` instance the tools dispatch operations against. Required.                                                                                                                                                                                                                                                                                                                                                                |
| `preset`          | Preset (or array of presets) restricting which tools are returned. Omit to get every tool.                                                                                                                                                                                                                                                                                                                                          |
| `requireApproval` | `true` (default), `false`, or per-tool overrides. Applies to every write tool and `getUser`; other read tools and `startTyping` do not require approval. `startTyping` still enforces conversation scope.                                                                                                                                                                                                                           |
| `overrides`       | Per-tool customization of AI SDK `tool()` properties. Core properties such as `execute`, `inputSchema`, and `outputSchema` can't be overridden; see the full list above.                                                                                                                                                                                                                                                            |
| `scope`           | Conversation the tools are confined to (reads and writes targeting a thread or channel; `getUser` and `sendDirectMessage` are exempt and approval-gated instead). Defaults to the conversation being handled. When no scope resolves, calls are rejected inside a handler and run with a warning outside one. Pass a `Thread`, `Channel`, raw id, or `false` to reach every conversation the bot can see. Channel-level by default. |
| `strictScope`     | `false` (default). Set `true` to tighten a thread `scope` to that thread alone, rejecting both sibling threads and the parent channel. A channel scope is unaffected.                                                                                                                                                                                                                                                               |

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Overview
description: AI utilities that ship with Chat SDK, including agent tools, message conversion, and supporting types.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The `chat/ai` subpath contains the AI utilities that ship with Chat SDK. Bots built on the [AI SDK](https://ai-sdk.dev) import from `chat/ai`; bots built on [TanStack AI](https://tanstack.com/ai) import the equivalent helpers from `chat/ai/tanstack`.

```ts
import { createChatTools, toAiMessages } from "chat/ai";
import { createTanStackTools, toTanStackMessages } from "chat/ai/tanstack";
```

Add the optional peers if you don't already have them:

```bash
pnpm add ai zod
```

## What's included

| Page                                      | What it gives you                                                                                                                                                                                                                                                                                       |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [AI SDK Tools](/docs/ai/ai-sdk-tools)     | `createChatTools` and standalone tool factories that let an agent post messages, send DMs, react, edit, delete, and manage subscriptions across every adapter your `Chat` instance has registered. Write tools and `getUser` require approval by default, and presets limit which tools the agent gets. |
| [`toAiMessages`](/docs/ai/to-ai-messages) | Convert Chat SDK [`Message[]`](/docs/api/message) into the `{ role, content }[]` shape expected by AI SDK calls. Handles role mapping, attachments, links, sorting, and optional per-message transforms.                                                                                                |
| [TanStack AI](/docs/ai/tanstack-ai)       | `toTanStackMessages` and `createTanStackTools` from `chat/ai/tanstack`: the same history conversion and tools, shaped for `chat()` from `@tanstack/ai`, plus serving a TanStack AI browser chat through the Web adapter. No runtime dependency on `@tanstack/ai`.                                       |
| [Types](/docs/ai/types)                   | Reference for the types exported from `chat/ai`: agent message shapes, tool option contracts, presets, approval config, and the binding type that ties tools to your `Chat` instance.                                                                                                                   |

## Typical flow

A Chat SDK bot wired to a tool-calling agent usually looks like this:

```typescript title="lib/agent.ts" lineNumbers
import { Chat } from "chat";
import { createChatTools, toAiMessages } from "chat/ai";
import { ToolLoopAgent } from "ai";

const chat = new Chat({ /* adapters, state, ... */ });

const agent = new ToolLoopAgent({
  model: "xai/grok-4.5",
  instructions: "You operate inside a chat workspace via Chat SDK tools.",
  tools: createChatTools({ chat, preset: "messenger", requireApproval: true }),
});

chat.onSubscribedMessage(async (thread) => {
  const { messages } = await thread.adapter.fetchMessages(thread.id, {
    limit: 20,
  });
  const history = await toAiMessages(messages);
  const result = await agent.stream({ prompt: history });
  await thread.post(result.fullStream);
});
```

1. [`toAiMessages`](/docs/ai/to-ai-messages) converts messages into an output compatible with AI SDK's `ModelMessage[]`.
2. [`createChatTools`](/docs/ai/ai-sdk-tools) gives the agent AI SDK tools for acting in chat, which you can narrow with presets and customize per tool.
3. [`thread.post(stream)`](/docs/streaming) renders the streamed response back into the thread.

Using TanStack AI instead? The same flow works with `toTanStackMessages` and `createTanStackTools`; see [TanStack AI](/docs/ai/tanstack-ai) for the `chat()` version of this example.

## Backwards compatibility

`toAiMessages` and the related `Ai*` types are still re-exported from the top-level `chat` package so older bots keep working. Those re-exports are marked `@deprecated` in JSDoc, so your editor shows a hint pointing at `chat/ai`. To migrate, change the import:

```diff
- import { toAiMessages } from "chat";
+ import { toAiMessages } from "chat/ai";
```

## Resources

- [Human-in-the-Loop with Chat SDK and Workflow SDK](https://vercel.com/kb/guide/human-in-the-loop-with-chat-sdk-and-workflow-sdk?utm_source=chat-sdk_site\&utm_medium=docs\&utm_campaign=ai\&utm_content=human-in-the-loop-with-chat-sdk-and-workflow-sdk): pause durable workflows on Slack approval cards using Chat SDK and Workflow SDK. The guide uses `createWebhook` to suspend a workflow until a button click, with patterns for multi-stage approvals, timeouts via durable sleep, and approver validation.

See all guides and templates on the [resources](/resources?utm_source=chat-sdk_site\&utm_medium=docs\&utm_campaign=ai\&utm_content=resources) page.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: TanStack AI
description: "Feed thread history into TanStack AI's chat(), give it Chat SDK tools, and serve a TanStack AI browser chat from the same bot."
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/usage
related:
  - /docs/ai
  - /docs/ai/ai-sdk-tools
  - /docs/ai/to-ai-messages
  - /docs/streaming
  - /docs/history
  - /adapters/official/web
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The `chat/ai/tanstack` subpath is the [TanStack AI](https://tanstack.com/ai) counterpart to the [AI SDK helpers](/docs/ai) in `chat/ai`. It gives you two functions:

- `toTanStackMessages` converts Chat SDK [`Message[]`](/docs/api/message) into the `ModelMessage[]` shape that `chat()` from `@tanstack/ai` expects.
- `createTanStackTools` returns the same tools, presets, approval flags, and scope guard as `createChatTools`, shaped for `chat({ tools })`.

The subpath declares its own message and tool types, so it has no runtime dependency on `@tanstack/ai`. To give the same bot a browser chat UI built with TanStack AI's `useChat`, use the [Web adapter](/adapters/official/web) with the AG-UI protocol, covered in [Serving a browser chat](#serving-a-browser-chat).

```ts
import { createTanStackTools, toTanStackMessages } from "chat/ai/tanstack";
```

## Install

Add `@tanstack/ai` and a model adapter. The examples on this page use `@tanstack/ai-vercel-gateway`, which routes requests through [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) so you can switch models by changing the model id. See [TanStack AI with AI Gateway](https://vercel.com/docs/ai-gateway/ecosystem/framework-integrations/tanstack-ai) for the full setup.

```bash
pnpm add @tanstack/ai @tanstack/ai-vercel-gateway zod
```

Create an [AI Gateway API key](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys) and expose it as `AI_GATEWAY_API_KEY`. The gateway adapter reads it automatically and falls back to `VERCEL_OIDC_TOKEN` when deployed on Vercel.

`createTanStackTools` needs zod 4.2 or newer, because TanStack AI converts tool input schemas to JSON Schema through the Standard JSON Schema interface that zod added in 4.2. On an older version, `createTanStackTools` throws an error that says so. `toTanStackMessages` has no zod requirement.

The [TanStack Start example](https://github.com/vercel/chat/tree/main/examples/tanstack-start-chat) puts everything on this page together: a Slack bot and a browser chat that share one set of handlers, with history converted by `toTanStackMessages`, a TanStack AI server tool, and the AI Gateway adapter.

## Converting history

Read recent messages from the thread, convert them, and hand the array to `chat()`. The stream that `chat()` returns can be posted straight back to the thread, as described in [Streaming](/docs/streaming#tanstack-ai-integration).

```typescript title="lib/bot.ts" lineNumbers
import { chat } from "@tanstack/ai";
import { vercelGatewayText } from "@tanstack/ai-vercel-gateway";
import type { Message, Thread } from "chat";
import { toTanStackMessages } from "chat/ai/tanstack";

// thread.messages yields newest first, so collect and reverse.
async function recentMessages(thread: Thread, limit = 20) {
  const history: Message[] = [];
  for await (const message of thread.messages) {
    history.unshift(message);
    if (history.length === limit) {
      break;
    }
  }
  return history;
}

bot.onNewMention(async (thread) => {
  const stream = chat({
    adapter: vercelGatewayText("anthropic/claude-opus-5"),
    systemPrompts: ["You are a helpful assistant in a team chat workspace."],
    messages: await toTanStackMessages(await recentMessages(thread)),
  });
  await thread.post(stream);
});
```

`thread.messages` reads from the platform when it has a history API, such as Slack or Discord. When the adapter returns nothing, it falls back to Chat SDK's [history cache](/docs/history), where adapters without a history API keep prior turns. Calling `thread.adapter.fetchMessages` directly skips that fallback, so with the Web adapter it always returns an empty list.

### What gets converted

- Roles: messages authored by the bot (`author.isMe === true`) become `assistant`, and everything else becomes `user`. Messages are sorted oldest first by `metadata.dateSent`.
- Text: `message.text` becomes string `content`. With `includeNames: true`, user messages are prefixed with `[username]: `.
- Images: image attachments with a working `fetchData()` become `{ type: "image", source: { type: "data", value, mimeType } }` parts, where `value` is base64 with no `data:` prefix. A user message with images gets array `content`, with a leading `{ type: "text", content }` part when there is text.
- Text files: TanStack AI has no file content part, so text-like attachments (`text/*`, JSON, XML, YAML, TOML, JavaScript, TypeScript) are inlined into the message text as `[File: <name> (<mime>)]` followed by the file contents.
- Links: link metadata is appended to the text inside the same untrusted-content fence that `toAiMessages` uses, with third-party titles and descriptions normalized and length-limited.
- Video and audio: skipped, and `onUnsupportedAttachment` is called for each one. Other file types, such as PDF, are skipped silently.
- Empty messages: a message with no text and nothing else the converter can include is dropped.
- System prompt: `ModelMessage` has no system role, so pass system text through `chat({ systemPrompts: [...] })`.

### Options

```typescript
function toTanStackMessages(
  messages: Message[],
  options?: ToTanStackMessagesOptions
): Promise<TanStackMessage[]>
```

| Option                    | Type                                                                                                         | Description                                                                                                              |
| ------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `includeNames`            | `boolean`                                                                                                    | Prefix user messages with `[username]: ` so the model can tell speakers apart. Defaults to `false`.                      |
| `transformMessage`        | `(message: TanStackMessage, source: Message) => TanStackMessage \| null \| Promise<TanStackMessage \| null>` | Runs after default processing for each message. Return the message, modified or as-is, to keep it, or `null` to drop it. |
| `onUnsupportedAttachment` | `(attachment: Attachment, message: Message) => void`                                                         | Called for video and audio attachments. Defaults to `console.warn`.                                                      |

## Giving the agent tools

`createTanStackTools` returns an array of plain tool objects (`name`, `description`, `inputSchema`, `needsApproval`, `execute`) that `chat({ tools })` accepts as-is. TanStack AI runs the tool loop itself, so server tools execute during the same `chat()` call and their results feed back into the model before the stream finishes.

```typescript title="lib/bot.ts" lineNumbers
import { chat } from "@tanstack/ai";
import { vercelGatewayText } from "@tanstack/ai-vercel-gateway";
import { createTanStackTools, toTanStackMessages } from "chat/ai/tanstack";

bot.onNewMention(async (thread) => {
  const stream = chat({
    adapter: vercelGatewayText("anthropic/claude-opus-5"),
    systemPrompts: ["You operate inside a chat workspace via Chat SDK tools."],
    messages: await toTanStackMessages(await recentMessages(thread)),
    tools: createTanStackTools({
      chat: bot,
      preset: "messenger",
      requireApproval: false,
    }),
  });
  await thread.post(stream);
});
```

`recentMessages` is the helper from [Converting history](#converting-history).

### Options

```typescript
type TanStackChatToolsOptions = {
  chat: Chat;
  preset?: ChatToolPreset | ChatToolPreset[];
  requireApproval?: boolean | Partial<Record<ChatApprovalToolName, boolean>>;
  scope?: ReadScope | false;
  strictScope?: boolean;
  overrides?: Partial<Record<ChatToolName, TanStackToolOverrides>>;
};
```

| Option            | Description                                                                                                                                                                                                                                                   |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chat`            | The `Chat` instance the tools dispatch operations against. Required.                                                                                                                                                                                          |
| `preset`          | Preset, or array of presets, restricting which tools are returned. Omit it to get every tool.                                                                                                                                                                 |
| `requireApproval` | `true` (default), `false`, or per-tool overrides. Applies to every write tool and `getUser`. Read [Approval](#approval) before leaving this on.                                                                                                               |
| `scope`           | Conversation the tools are confined to. Defaults to the conversation being handled. When no scope resolves, calls are rejected inside a handler and run with a warning outside one. Pass a `Thread`, `Channel`, raw id, or `false` for workspace-wide access. |
| `strictScope`     | `false` (default). Set it to `true` to tighten a thread `scope` to that thread alone.                                                                                                                                                                         |
| `overrides`       | Per-tool customization keyed by tool name. Only `description`, `needsApproval` (boolean), `metadata`, and `lazy` can be set. `name`, `inputSchema`, `outputSchema`, and `execute` are ignored so tool semantics stay stable.                                  |

### Presets

The `reader`, `messenger`, and `moderator` presets select the same tools as they do for `createChatTools`, and they compose the same way (`preset: ["reader", "messenger"]`). The [AI SDK Tools page](/docs/ai/ai-sdk-tools#presets) lists the tools in each preset and describes [every available tool](/docs/ai/ai-sdk-tools#available-tools).

### Approval

Write tools and `getUser` default to `needsApproval: true`, matching `createChatTools`. In TanStack AI, that flag stops the run: when the model calls an approval-gated tool, `chat()` ends with a `tool-approval` interrupt instead of executing it. To continue, you call `chat()` again with the message history plus a `resume` array that carries the decision and the `parentRunId` of the paused run, as described in [TanStack's tool approval docs](https://tanstack.com/ai/latest/docs/interrupts/tool-approval).

> When you post the stream straight to a thread, nothing collects that
> decision, so an approval-gated tool call ends the run without the tool
> running. This applies to the Web adapter too, because it doesn't forward
> tool events to the browser. Unless you implement the resume flow yourself,
> pass `requireApproval: false` and limit risky tools another way, such as a
> smaller preset, a tighter `scope`, or an approval step before you call
> `chat()`.

### Scope

`scope` and `strictScope` behave the same as they do for `createChatTools`. Tools called inside a handler with a conversation are confined to it, and calls that resolve outside it are rejected before the platform is called. Calls with no scope are rejected inside a handler that has no conversation, and run workspace-wide with a warning outside any handler. Pass an explicit `scope` for background jobs and handlers without a conversation, or `scope: false` when you intend workspace-wide access. `getUser` and `sendDirectMessage` are exempt because they target user ids rather than conversations. Read [Limiting what the agent can reach](/docs/ai/ai-sdk-tools#limiting-what-the-agent-can-reach) for the full model, including what `scope` does not check.

## Serving a browser chat

The [Web adapter](/adapters/official/web) can speak [AG-UI](https://docs.ag-ui.com/concepts/events), the event protocol TanStack AI's `fetchServerSentEvents` connection consumes. With it, TanStack AI's `useChat` in the browser talks to the same Chat SDK handlers as Slack or Discord, and the `chat()` stream you post from a handler is what the browser renders.

### Configure the server

Create the Web adapter with `protocol: "ag-ui"` and register it next to your other adapters. `getUser` resolves the signed-in user from the request; return `null` to respond with HTTP 401.

```typescript title="lib/bot.ts" lineNumbers
import { createWebAdapter } from "@chat-adapter/web";
import { Chat } from "chat";

export const bot = new Chat({
  userName: "mybot",
  adapters: {
    web: createWebAdapter({
      userName: "mybot",
      protocol: "ag-ui",
      getUser: async (request) => {
        const session = await getSession(request);
        return session ? { id: session.userId, name: session.name } : null;
      },
    }),
  },
  state,
});
```

Web messages are routed as direct messages, so handle them in `onDirectMessage`. The handler can be the same function your other platforms use:

```typescript title="lib/bot.ts" lineNumbers
async function respond(thread: Thread) {
  const stream = chat({
    adapter: vercelGatewayText("anthropic/claude-opus-5"),
    systemPrompts: ["You are a helpful assistant."],
    messages: await toTanStackMessages(await recentMessages(thread)),
  });
  await thread.post(stream);
}

bot.onNewMention(respond);
bot.onDirectMessage(respond);
```

Mount `bot.webhooks.web` on a POST route. The [Web adapter page](/adapters/official/web#quick-start) shows the route for each framework.

### Connect the client

Point `useChat` from `@tanstack/ai-react`, or another TanStack AI framework package, at that route with `fetchServerSentEvents`:

```tsx title="app/chat/page.tsx" lineNumbers
"use client";
import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";

export default function ChatPage() {
  const { messages, sendMessage, status, stop } = useChat({
    connection: fetchServerSentEvents("/api/chat"),
    threadId: "support-1",
  });
  // Text parts carry their text in `part.content`.
}
```

`threadId` becomes the conversation id in the Chat SDK thread id, `web:{userId}:{threadId}`. Reuse it to continue a conversation, or generate a new one to start fresh.

### How the browser chat behaves

- History: the adapter reads only the latest user message from the request, because the browser controls the rest of the `messages` array. Prior turns come from the state adapter, which the Web adapter writes to by default, so read them through `thread.messages` as shown in [Converting history](#converting-history).
- Replies: each `thread.post` call arrives in the browser as its own assistant message. Text from every model turn in the `chat()` tool loop streams into that message, and tool call events are not forwarded.
- Tools: server tools, including `createTanStackTools`, run on the server inside `chat()`. TanStack AI client tools aren't supported, because the adapter never sends tool calls to the browser and rejects a request whose last message isn't from the user.
- Reload: `reload()` resends the last user message, and the handler runs again. History keeps the earlier reply alongside the new one.
- Stop: calling `stop()` ends the response, and the adapter stops reading the stream you posted.
- Errors: if the handler throws, the run ends with a `RUN_ERROR` event carrying the error message, which `useChat` exposes as `error`.

## Differences from the AI SDK helpers

|                       | `chat/ai`                                                                                                                                                              | `chat/ai/tanstack`                                                           |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| Tools return type     | Object keyed by tool name, spread into `tools`                                                                                                                         | Array of tool objects, passed as `tools`                                     |
| Tool overrides        | The `ToolOverrides` keys: `description`, `title`, `needsApproval`, `metadata`, `providerOptions`, `strict`, `inputExamples`, `toModelOutput`, and the `onInput*` hooks | `description`, `needsApproval`, `metadata`, and `lazy` only                  |
| Text file attachments | `file` parts with base64 data                                                                                                                                          | Inlined into the message text as `[File: name (mime)]` blocks                |
| Image attachments     | `file` parts with `data` and `mediaType`                                                                                                                               | `image` parts with `source: { type: "data", value, mimeType }`               |
| System prompt         | A `system` message or the call's `system` option                                                                                                                       | `chat({ systemPrompts })` only, because there is no system role              |
| zod requirement       | Any version the AI SDK accepts                                                                                                                                         | 4.2 or newer for `createTanStackTools`                                       |
| Approval flow         | The AI SDK surfaces an approval request your app confirms                                                                                                              | `chat()` pauses with an interrupt you resume with `resume` and `parentRunId` |
| Web adapter protocol  | `"ai-sdk"` (default), for AI SDK `useChat`                                                                                                                             | `"ag-ui"`, for TanStack AI `useChat`                                         |

## Types

Everything below is exported from `chat/ai/tanstack`. The subpath also re-exports the tool option types `ChatToolName`, `ChatToolPreset`, `ChatWriteToolName`, `ChatApprovalToolName`, `ApprovalConfig`, `ReadScope`, and `ChatBinding` from `chat/ai` unchanged. See the [Types](/docs/ai/types) page.

```typescript
type TanStackMessage = TanStackUserMessage | TanStackAssistantMessage;

interface TanStackUserMessage {
  role: "user";
  content: string | TanStackContentPart[];
}

interface TanStackAssistantMessage {
  role: "assistant";
  content: string;
}

type TanStackContentPart = TanStackTextPart | TanStackImagePart;

interface TanStackTextPart {
  type: "text";
  content: string;
}

interface TanStackImagePart {
  type: "image";
  source: { type: "data"; value: string; mimeType: string };
}

interface TanStackTool<TInput = unknown, TOutput = unknown> {
  name: string;
  description: string;
  inputSchema: ZodType<TInput>;
  execute(args: TInput, context?: unknown): Promise<TOutput>;
  needsApproval?: boolean;
  metadata?: Record<string, unknown>;
  lazy?: boolean;
}

type TanStackToolOverrides = Partial<
  Pick<TanStackTool, "description" | "lazy" | "metadata" | "needsApproval">
>;
```

`TanStackMessage[]` is structurally assignable to TanStack AI's `ModelMessage[]`, and `TanStackTool[]` to the `tools` option of `chat()`, without importing anything from `@tanstack/ai`.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: toAiMessages
description: Convert Chat SDK messages to AI SDK conversation format.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/ai
  - /docs/ai/ai-sdk-tools
  - /docs/ai/types
  - /docs/streaming
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Convert an array of [`Message`](/docs/api/message) objects into the `{ role, content }[]` format expected by the AI SDK. The output is structurally compatible with AI SDK's `ModelMessage[]`.

> Using TanStack AI? `toTanStackMessages` in `chat/ai/tanstack` converts the
> same history into the `ModelMessage[]` shape that `chat()` expects. See
> [TanStack AI](/docs/ai/tanstack-ai).

```typescript
import { toAiMessages } from "chat/ai";
```

> `toAiMessages` is also re-exported from the main `chat` entrypoint
> for backwards compatibility and marked `@deprecated` in JSDoc. New
> code should import it from [`chat/ai`](/docs/ai) alongside
> [`createChatTools`](/docs/ai/ai-sdk-tools) and the rest of the AI
> utilities.

## Usage

```typescript title="lib/bot.ts" lineNumbers
import { toAiMessages } from "chat/ai";

bot.onSubscribedMessage(async (thread, message) => {
  const result = await thread.adapter.fetchMessages(thread.id, { limit: 20 });
  const history = await toAiMessages(result.messages);
  const response = await agent.stream({ prompt: history });
  await thread.post(response.fullStream);
});
```

## Signature

```typescript
function toAiMessages(
  messages: Message[],
  options?: ToAiMessagesOptions
): Promise<AiMessage[]>
```

### Parameters

| Property   | Type                  | Description                                                                                                           |
| ---------- | --------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `messages` | `Message[]`           | Array of Chat SDK Message objects. Works with FetchResult.messages, thread.recentMessages, or any collected iterable. |
| `options`  | `ToAiMessagesOptions` | Optional configuration.                                                                                               |

### Options

| Property                  | Type                                                                                         | Description                                                                                 |
| ------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `includeNames`            | `boolean`                                                                                    | Prefix user messages with \[username]: for multi-user context.                              |
| `transformMessage`        | `(aiMessage: AiMessage, source: Message) => AiMessage \| null \| Promise<AiMessage \| null>` | Transform or filter each message after default processing. Return null to skip the message. |
| `onUnsupportedAttachment` | `(attachment: Attachment, message: Message) => void`                                         | Called when an attachment type is not supported (video, audio).                             |

### Returns

`Promise<AiMessage[]>`: an array of messages with `role` and `content` fields, assignable to AI SDK's `ModelMessage[]`.

## Behavior

- Role mapping: messages with `author.isMe === true` become `"assistant"`, and all others become `"user"`.
- Filtering: a message with no text is kept when it has links or attachments the converter can include, meaning images and text files with a working `fetchData()`. Messages with no text whose only attachments are unsupported (video, audio, other file types, or missing `fetchData()`) are removed.
- Sorting: messages are sorted oldest first by `metadata.dateSent`.
- Links: link metadata (URL, title, description, site name) is appended to the message content. Third-party title, description, and site-name fields are normalized, length-limited, escaped, and enclosed in an explicit untrusted-content fence. Embedded message links are labeled `[Embedded message: ...]`.
- Attachments: images and text files (JSON, XML, YAML, and similar) are fetched with `fetchData()` and included as multipart content. When the message has no text, the `content` array contains only attachment parts, with no leading text part. Video and audio attachments trigger `onUnsupportedAttachment`.

## Return types

```typescript
type AiMessage = AiUserMessage | AiAssistantMessage;

interface AiUserMessage {
  role: "user";
  content: string | AiMessagePart[];
}

interface AiAssistantMessage {
  role: "assistant";
  content: string;
}
```

User messages have multipart `content` when attachments are present:

```typescript
type AiMessagePart = AiTextPart | AiImagePart | AiFilePart;

interface AiTextPart {
  type: "text";
  text: string;
}

interface AiImagePart {
  type: "image";
  image: DataContent | URL;
  mediaType?: string;
}

interface AiFilePart {
  type: "file";
  data: DataContent | URL;
  filename?: string;
  mediaType: string;
}
```

## Examples

### Multi-user context

Prefix each user message with the sender's username so the model can tell speakers apart:

```typescript
const history = await toAiMessages(result.messages, { includeNames: true });
// [{ role: "user", content: "[alice]: Hello" },
//  { role: "assistant", content: "Hi there!" },
//  { role: "user", content: "[bob]: Thanks" }]
```

### Transforming messages

Replace raw user IDs with readable names:

```typescript
const history = await toAiMessages(result.messages, {
  transformMessage: (aiMessage) => {
    if (typeof aiMessage.content === "string") {
      return {
        ...aiMessage,
        content: aiMessage.content.replace(/<@U123>/g, "@VercelBot"),
      };
    }
    return aiMessage;
  },
});
```

### Filtering messages

Skip messages from a specific user:

```typescript
const history = await toAiMessages(result.messages, {
  transformMessage: (aiMessage, source) => {
    if (source.author.userId === "U_NOISY_BOT") return null;
    return aiMessage;
  },
});
```

### Handling unsupported attachments

```typescript
const history = await toAiMessages(result.messages, {
  onUnsupportedAttachment: (attachment, message) => {
    logger.warn(`Skipped ${attachment.type} attachment in message ${message.id}`);
  },
});
```

## Supported attachment types

| Type    | MIME types                                                                                                                                  | Included as                                  |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `image` | Any image MIME type                                                                                                                         | `FilePart` with base64 data                  |
| `file`  | `text/*`, `application/json`, `application/xml`, `application/javascript`, `application/typescript`, `application/yaml`, `application/toml` | `FilePart` with base64 data                  |
| `video` | Any                                                                                                                                         | Skipped (triggers `onUnsupportedAttachment`) |
| `audio` | Any                                                                                                                                         | Skipped (triggers `onUnsupportedAttachment`) |
| `file`  | Other (e.g. `application/pdf`)                                                                                                              | Silently skipped                             |

> Attachments require `fetchData()` to be available on the attachment object. Attachments without `fetchData()` are silently skipped.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Types
description: TypeScript types exported from the chat/ai subpath.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/ai
  - /docs/ai/ai-sdk-tools
  - /docs/ai/to-ai-messages
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Types exported from `chat/ai`. Importing from the subpath keeps the optional `ai` and `zod` peer dependencies out of bundles that don't use them.

```ts
import type {
  AiMessage,
  AiUserMessage,
  AiAssistantMessage,
  AiMessagePart,
  AiTextPart,
  AiImagePart,
  AiFilePart,
  ToAiMessagesOptions,
  ChatBinding,
  ChatTools,
  ChatToolName,
  ChatToolPreset,
  ChatWriteToolName,
  ChatApprovalToolName,
  ApprovalConfig,
  ToolOptions,
  ToolScopeOptions,
  ToolOverrides,
  ReadScope,
} from "chat/ai";
```

## Conversation messages

Used by [`toAiMessages`](/docs/ai/to-ai-messages) and any agent prompt you build by hand. The shapes are structurally compatible with AI SDK's `ModelMessage`, so the result can be passed as `prompt` or `messages`.

### AiMessage

```typescript
type AiMessage = AiUserMessage | AiAssistantMessage;
```

A single normalized turn in a conversation. AI SDK calls take an array of them.

### AiUserMessage

```typescript
interface AiUserMessage {
  role: "user";
  content: string | AiMessagePart[];
}
```

User content can be plain text, or a multipart array when attachments are present.

### AiAssistantMessage

```typescript
interface AiAssistantMessage {
  role: "assistant";
  content: string;
}
```

Assistant turns are always plain strings. `toAiMessages` produces one for any message authored by the bot (`author.isMe === true`).

### AiMessagePart

```typescript
type AiMessagePart = AiTextPart | AiImagePart | AiFilePart;
```

The discriminated union used inside multipart user messages.

### AiTextPart

```typescript
interface AiTextPart {
  type: "text";
  text: string;
}
```

### AiImagePart

```typescript
interface AiImagePart {
  type: "image";
  image: DataContent | URL;
  mediaType?: string;
}
```

`DataContent` matches AI SDK's type: `string | Uint8Array | ArrayBuffer | Buffer`.

### AiFilePart

```typescript
interface AiFilePart {
  type: "file";
  data: DataContent | URL;
  filename?: string;
  mediaType: string;
}
```

`toAiMessages` emits image attachments and text-like attachments (JSON, XML, YAML, source files, and similar) as file parts.

### ToAiMessagesOptions

```typescript
interface ToAiMessagesOptions {
  includeNames?: boolean;
  transformMessage?: (
    aiMessage: AiMessage,
    source: Message
  ) => AiMessage | null | Promise<AiMessage | null>;
  onUnsupportedAttachment?: (
    attachment: Attachment,
    message: Message
  ) => void;
}
```

See [`toAiMessages`](/docs/ai/to-ai-messages) for behavior and examples.

## Tools

Returned by [`createChatTools`](/docs/ai/ai-sdk-tools) and used to configure it.

### ChatBinding

```typescript
type ChatBinding = Chat<any, any>;
```

The [`Chat`](/docs/api/chat) instance the tools dispatch operations against. The generics are loose so that any strongly typed `Chat<TAdapters, TState>` is assignable.

### ChatTools

```typescript
type ChatTools = ReturnType<typeof createChatTools>;
```

Alias for the object returned by `createChatTools`. Use it to type a wrapper or pass the toolset around.

### ChatToolPreset

```typescript
type ChatToolPreset = "reader" | "messenger" | "moderator";
```

Predefined toolset scopes. See [Presets](/docs/ai/ai-sdk-tools#presets) for the exact tool list per preset.

### ChatToolName

```typescript
type ChatToolName =
  | "fetchMessages"
  | "fetchChannelMessages"
  | "fetchThread"
  | "listThreads"
  | "getThreadParticipants"
  | "getChannelInfo"
  | "getUser"
  | "startTyping"
  | "postMessage"
  | "postChannelMessage"
  | "sendDirectMessage"
  | "editMessage"
  | "deleteMessage"
  | "addReaction"
  | "removeReaction"
  | "subscribeThread"
  | "unsubscribeThread";
```

The names of every generated tool. Useful when typing per-tool overrides.

### ChatWriteToolName

```typescript
type ChatWriteToolName =
  | "postMessage"
  | "postChannelMessage"
  | "sendDirectMessage"
  | "editMessage"
  | "deleteMessage"
  | "addReaction"
  | "removeReaction"
  | "subscribeThread"
  | "unsubscribeThread";
```

The names of every mutating tool. Useful when wiring per-tool approval overrides.

### ChatApprovalToolName

```typescript
type ChatApprovalToolName = ChatWriteToolName | "getUser";
```

The names of tools that require approval by default: every mutating tool plus the arbitrary user-profile lookup.

### ApprovalConfig

```typescript
type ApprovalConfig =
  | boolean
  | Partial<Record<ChatApprovalToolName, boolean>>;
```

Controls the `requireApproval` option:

- `true` (default): every write tool and `getUser` need approval.
- `false`: no tool needs approval.
- An object: per-tool overrides. Approval-gated tools you leave out fall back to `true`.

### ToolScopeOptions

```typescript
interface ToolScopeOptions {
  scope?: ReadScope | false;
  strictScope?: boolean;
}
```

Options accepted by every standalone factory for a tool that targets a thread or channel, such as `fetchMessages(chat, { scope: thread })`. They work like the `scope` and `strictScope` options on [`createChatTools`](/docs/ai/ai-sdk-tools#limiting-what-the-agent-can-reach). When no scope resolves, calls are rejected inside a handler that has no conversation, and run workspace-wide with a warning outside any handler.

### ToolOptions

```typescript
interface ToolOptions extends ToolScopeOptions {
  /** @deprecated Pass `scope` instead. */
  guard?: (id: string) => void;
  needsApproval?: boolean;
}
```

Options accepted by every standalone factory for a write tool that targets a thread or channel, such as `postMessage(chat, { needsApproval: false })`. `needsApproval` defaults to `true`. `guard` takes precedence over `scope` and is kept for compatibility. `sendDirectMessage` ignores the scope options, because it targets a user id.

### ToolOverrides

```typescript
type ToolOverrides = Partial<
  Pick<
    Tool,
    | "description"
    | "inputExamples"
    | "metadata"
    | "needsApproval"
    | "onInputAvailable"
    | "onInputDelta"
    | "onInputStart"
    | "providerOptions"
    | "strict"
    | "title"
    | "toModelOutput"
  >
>;
```

Per-tool overrides accepted by `createChatTools({ overrides })`. Core fields (`execute`, `inputSchema`, `outputSchema`, `supportsDeferredResults`, `type`, `id`, and `args`) are excluded so tool semantics stay stable across upgrades.

## TanStack AI

The `chat/ai/tanstack` subpath exports its own message and tool shapes, declared locally so nothing from `@tanstack/ai` is imported at runtime:

```ts
import type {
  TanStackMessage,
  TanStackUserMessage,
  TanStackAssistantMessage,
  TanStackContentPart,
  TanStackTextPart,
  TanStackImagePart,
  ToTanStackMessagesOptions,
  TanStackTool,
  TanStackToolOverrides,
  TanStackChatToolsOptions,
} from "chat/ai/tanstack";
```

| Type                        | Purpose                                                                                                                                                     |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TanStackMessage`           | `TanStackUserMessage \| TanStackAssistantMessage`, structurally assignable to TanStack AI's `ModelMessage`. Returned by `toTanStackMessages`.               |
| `TanStackContentPart`       | `TanStackTextPart \| TanStackImagePart`, the parts inside a multipart user message. Text parts use `content`, image parts carry base64 data under `source`. |
| `ToTanStackMessagesOptions` | `includeNames`, `transformMessage`, and `onUnsupportedAttachment`, mirroring `ToAiMessagesOptions`.                                                         |
| `TanStackTool`              | A plain tool object (`name`, `description`, `inputSchema`, `execute`, optional `needsApproval`, `metadata`, `lazy`) accepted by `chat({ tools })`.          |
| `TanStackToolOverrides`     | The subset of `TanStackTool` that `createTanStackTools({ overrides })` lets you change: `description`, `needsApproval`, `metadata`, `lazy`.                 |
| `TanStackChatToolsOptions`  | Options for `createTanStackTools`: `chat`, `preset`, `requireApproval`, `scope`, `strictScope`, `overrides`.                                                |

`ChatToolName`, `ChatToolPreset`, `ChatWriteToolName`, `ChatApprovalToolName`, `ApprovalConfig`, `ReadScope`, and `ChatBinding` are re-exported from `chat/ai/tanstack` unchanged. Their definitions are in [Tools](#tools) above, and `ReadScope` is described in the [`createChatTools` API](/docs/ai/ai-sdk-tools#api). The TanStack-specific shapes are defined in full on the [TanStack AI](/docs/ai/tanstack-ai#types) page.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Cards
description: Rich card components for cross-platform interactive messages.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/cards
  - /docs/actions
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Each adapter renders card components in its platform's native format: Block Kit on Slack, Adaptive Cards on Teams, embeds or Components on Discord, and Cards on Google Chat.

```typescript
import { Card, Text, CardLink, Button, Actions, Section, Fields, Field, Divider, Image, LinkButton, Table, Chart } from "chat";
```

All components support both function-call and JSX syntax. Function-call syntax is recommended for better type inference.

## Card

Top-level container for a rich message.

```typescript
Card({
  title: "Order #1234",
  subtitle: "Pending approval",
  children: [Text("Total: $50.00")],
})
```

| Property   | Type                  | Description                                                                                               |
| ---------- | --------------------- | --------------------------------------------------------------------------------------------------------- |
| `title`    | `string`              | Card title.                                                                                               |
| `subtitle` | `string`              | Card subtitle.                                                                                            |
| `imageUrl` | `string`              | Header image URL.                                                                                         |
| `children` | `CardChild[]`         | Card content elements.                                                                                    |
| `width`    | `"default" \| "full"` | Width hint for platforms that can render a card wider than the default (Teams). Other adapters ignore it. |

## Text

Text content element. Use `CardText` instead of `Text` in JSX to avoid conflicts with React's built-in types.

```typescript
Text("Hello, world!")
Text("Important", { style: "bold" })
Text("Subtle note", { style: "muted" })
```

| Property        | Type                           | Description                    |
| --------------- | ------------------------------ | ------------------------------ |
| `content`       | `string`                       | Text content (first argument). |
| `options.style` | `"plain" \| "bold" \| "muted"` | Text style.                    |

## Button

Interactive button that triggers an `onAction` handler.

```typescript
Button({ id: "approve", label: "Approve", style: "primary" })
Button({ id: "delete", label: "Delete", style: "danger", value: "item-123" })
```

| Property      | Type                                 | Description                                                                            |
| ------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
| `id`          | `string`                             | Unique action ID for callback routing.                                                 |
| `label`       | `string`                             | Button label text.                                                                     |
| `style`       | `"primary" \| "danger" \| "default"` | Visual style.                                                                          |
| `value`       | `string`                             | Optional payload sent with the action callback.                                        |
| `actionType`  | `"action" \| "modal"`                | Hints to adapters like Teams that this button will open a modal via event.openModal(). |
| `callbackUrl` | `string`                             | URL to POST action data to when this button is clicked.                                |
| `tooltip`     | `string`                             | Hover text for the button. Rendered by Teams only; other adapters ignore it.           |

## CardLink

Inline hyperlink rendered as text. Can be placed directly in a card alongside other content, unlike `LinkButton` which must live inside `Actions`.

```typescript
CardLink({ url: "https://example.com", label: "Visit Site" })
```

| Property | Type     | Description      |
| -------- | -------- | ---------------- |
| `url`    | `string` | URL to link to.  |
| `label`  | `string` | Link label text. |

## LinkButton

Button that opens a URL. No `onAction` handler needed for navigation. On
platforms that emit link-button click events, such as Slack, pass `id` when you
need a stable action identifier for routing or analytics.

```typescript
LinkButton({ url: "https://example.com", label: "View Docs" })
LinkButton({ id: "view_docs", url: "https://example.com", label: "View Docs" })
```

| Property  | Type                                 | Description                                                                  |
| --------- | ------------------------------------ | ---------------------------------------------------------------------------- |
| `id`      | `string`                             | Optional action identifier emitted by platforms that report link clicks.     |
| `url`     | `string`                             | URL to open when clicked.                                                    |
| `label`   | `string`                             | Button label text.                                                           |
| `style`   | `"primary" \| "danger" \| "default"` | Visual style.                                                                |
| `tooltip` | `string`                             | Hover text for the button. Rendered by Teams only; other adapters ignore it. |

## Actions

Container for buttons and interactive elements. Required wrapper around `Button`, `LinkButton`, `Select`, and `RadioSelect`.

```typescript
Actions([
  Button({ id: "approve", label: "Approve", style: "primary" }),
  Button({ id: "reject", label: "Reject", style: "danger" }),
  LinkButton({ url: "https://example.com", label: "View" }),
])
```

## Section

Groups related content together.

```typescript
Section([
  Text("Grouped content"),
  Image({ url: "https://example.com/photo.png" }),
])
```

## Fields

Renders key-value pairs in a compact, multi-column layout.

```typescript
Fields([
  Field({ label: "Name", value: "Jane Smith" }),
  Field({ label: "Role", value: "Engineer" }),
])
```

## Field

A single key-value pair. Must be used inside `Fields`.

| Property | Type     | Description  |
| -------- | -------- | ------------ |
| `label`  | `string` | Field label. |
| `value`  | `string` | Field value. |

## Image

Embeds an image in the card.

```typescript
Image({ url: "https://example.com/screenshot.png", alt: "Screenshot" })
```

| Property | Type     | Description                 |
| -------- | -------- | --------------------------- |
| `url`    | `string` | Image URL.                  |
| `alt`    | `string` | Alt text for accessibility. |

## Table

Structured data display with column headers and rows.

```typescript
Table({
  headers: ["Name", "Age", "Role"],
  rows: [
    ["Alice", "30", "Engineer"],
    ["Bob", "25", "Designer"],
  ],
})
```

| Property        | Type                                                                        | Description                                                                                                                        |
| --------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `headers`       | `string[]`                                                                  | Column header labels.                                                                                                              |
| `rows`          | `string[][]`                                                                | Data rows (each row is an array of cell strings).                                                                                  |
| `align`         | `"left" \| "center" \| "right"[]`                                           | Column alignment.                                                                                                                  |
| `caption`       | `string`                                                                    | Accessible table caption (used by platforms with native table support).                                                            |
| `pageSize`      | `number`                                                                    | Rows per page on platforms that paginate tables (Slack: 1-100, default 5).                                                         |
| `widths`        | `number[]`                                                                  | Relative column widths, one positive integer weight per column (default 1 each). Rendered by Teams only; other adapters ignore it. |
| `verticalAlign` | `"top" \| "center" \| "bottom"`                                             | Vertical alignment of cell content. Rendered by Teams only; other adapters ignore it.                                              |
| `gridLines`     | `boolean`                                                                   | Draw grid lines between cells. Rendered by Teams only; other adapters ignore it.                                                   |
| `gridStyle`     | `"default" \| "emphasis" \| "accent" \| "good" \| "attention" \| "warning"` | Style of the grid lines between cells. Rendered by Teams only; other adapters ignore it.                                           |

On platforms with native table support (Slack, Teams, GitHub, Linear), tables render as formatted tables. On Slack, tables render as paginated, sortable data table blocks. On Teams, tables render as the Adaptive Card `Table` element with grid lines and weighted column widths. Discord card payloads preserve GFM markdown tables. On other platforms (Google Chat, Telegram), tables render as padded ASCII text.

## Chart

Data visualization with pie, bar, area, and line charts.

```typescript
Chart({
  title: "My Favorite Candy Bars",
  chart: {
    type: "pie",
    segments: [
      { label: "Kit Kat", value: 45 },
      { label: "Twix", value: 28 },
    ],
  },
})
```

| Property | Type              | Description                                                                         |
| -------- | ----------------- | ----------------------------------------------------------------------------------- |
| `title`  | `string`          | Chart title (Slack: max 50 characters).                                             |
| `chart`  | `ChartDefinition` | Chart definition, discriminated by chart type ("pie" \| "bar" \| "area" \| "line"). |

Pie charts take `segments` (label + value, rendered as percentages of the total). Bar, area, and line charts take `series` (named lists of data points) plotted against shared `categories`, with optional `xLabel`/`yLabel` axis titles.

On Slack, charts render as native data visualization blocks. On other platforms, charts fall back to the underlying data rendered as a text table.

## Divider

A visual separator between sections.

```typescript
Divider()
```

## CardChild types

The `children` array in `Card` and `Section` accepts these element types:

| Type               | Created by    |
| ------------------ | ------------- |
| `TextElement`      | `Text()`      |
| `LinkElement`      | `CardLink()`  |
| `ImageElement`     | `Image()`     |
| `DividerElement`   | `Divider()`   |
| `ActionsElement`   | `Actions()`   |
| `SectionElement`   | `Section()`   |
| `FieldsElement`    | `Fields()`    |
| `TableElement`     | `Table()`     |
| `ChartElement`     | `Chart()`     |
| `TextInputElement` | `TextInput()` |

`TextInput` is the same element [modals](/docs/api/modals) use. On a card, only Teams renders it. Slack, Google Chat, Discord, GitHub, and Linear show its label as text. WhatsApp, Messenger, Twilio, and X omit it.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Channel
description: Channel container that holds threads, with methods for listing, posting, and iteration.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/threads-messages-channels
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

A `Channel` represents a channel or conversation container that holds threads. `Thread` and `Channel` both extend the `Postable` interface, so they share members such as `post()`, `state`, and `messages`.

Get a channel via `thread.channel` or `chat.channel()`:

```typescript
// Navigate from a thread
const channel = thread.channel;

// Get directly by ID
const channel = chat.channel("slack:C123ABC");
```

## Properties

| Property  | Type             | Description                                                                     |
| --------- | ---------------- | ------------------------------------------------------------------------------- |
| `id`      | `string`         | Channel ID, such as "slack:C123ABC" or "gchat:spaces/ABC123".                   |
| `name`    | `string \| null` | Channel name, such as "#general". \`null\` until \`fetchMetadata()\` is called. |
| `adapter` | `Adapter`        | The platform adapter this channel belongs to.                                   |
| `isDM`    | `boolean`        | Whether this is a direct message conversation.                                  |

## Channel ID format

Channel IDs are derived from thread IDs by dropping the thread-specific part. By default, the channel ID is the first two colon-separated segments. Adapters can override this, as the Teams and Discord rows show:

| Platform    | Thread ID                                                                  | Channel ID                                                                 |
| ----------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| Slack       | `slack:C123ABC:1234567890.123456`                                          | `slack:C123ABC`                                                            |
| Teams       | `teams:{base64(conversationId)}:{base64(serviceUrl)}[:{conversationType}]` | `teams:{base64(conversationId)}:{base64(serviceUrl)}[:{conversationType}]` |
| Google Chat | `gchat:spaces/ABC123:{base64}`                                             | `gchat:spaces/ABC123`                                                      |
| Discord     | `discord:{guildId}:{channelId}[:{threadId}]`                               | `discord:{guildId}:{channelId}`                                            |

## messages

Iterate top-level channel messages, newest first. Thread replies are not included. Pages are fetched lazily as you iterate.

```typescript
for await (const msg of channel.messages) {
  console.log(msg.text);
}
```

## threads

Iterate threads in the channel, most recently active first. Returns lightweight `ThreadSummary` objects.

```typescript
for await (const thread of channel.threads()) {
  console.log(thread.rootMessage.text, thread.replyCount);
}
```

### ThreadSummary

| Property      | Type                  | Description                        |
| ------------- | --------------------- | ---------------------------------- |
| `id`          | `string`              | Full thread ID.                    |
| `rootMessage` | `Message`             | The first message of the thread.   |
| `replyCount`  | `number \| undefined` | Number of replies, when available. |
| `lastReplyAt` | `Date \| undefined`   | Timestamp of most recent reply.    |

## post

Post a top-level message to the channel, outside any thread.

```typescript
await channel.post("Hello channel!");
await channel.post({ markdown: "**Announcement**: New release!" });
```

Accepts the same message formats as `thread.post()`. See [PostableMessage](/docs/api/postable-message).

## schedule

Schedule a top-level message to the channel for future delivery. Only the Slack adapter supports this. Other adapters throw `NotImplementedError`.

```typescript
const scheduled = await channel.schedule("Weekly reminder: update your status!", {
  postAt: new Date("2026-03-10T09:00:00Z"),
});

// Cancel before it's sent
await scheduled.cancel();
```

Accepts the same message formats as `channel.post()`, except streams. See [ScheduledMessage](/docs/api/thread#scheduledmessage) for the return type.

## fetchMetadata

Fetch channel metadata from the platform.

```typescript
const info = await channel.fetchMetadata();
console.log(info.name, info.memberCount);
```

### ChannelInfo

| Property      | Type                      | Description                       |
| ------------- | ------------------------- | --------------------------------- |
| `id`          | `string`                  | Channel ID.                       |
| `name`        | `string \| undefined`     | Channel name.                     |
| `isDM`        | `boolean \| undefined`    | Whether this is a direct message. |
| `memberCount` | `number \| undefined`     | Number of members in the channel. |
| `metadata`    | `Record<string, unknown>` | Platform-specific metadata.       |

## state

Store typed, per-channel state. Works the same as thread state, with a 30-day TTL.

```typescript
const state = await channel.state;
await channel.setState({ lastAnnouncement: new Date().toISOString() });
```

## postEphemeral

Post a message visible only to a specific user.

```typescript
await channel.postEphemeral(userId, "Only you can see this", {
  fallbackToDM: true,
});
```

## startTyping

Show a typing indicator. No-op on platforms that don't support it. On Slack, you can pass an optional `status` string to show a custom loading message. This requires the `assistant:write` scope.

```typescript
await channel.startTyping();

// With custom status (Slack only)
await channel.startTyping("Searching documents...");
```

## mentionUser

Get a platform-specific @-mention string.

```typescript
await channel.post(`Hey ${channel.mentionUser(userId)}, check this out!`);
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Chat
description: The class that coordinates adapters, state, and event handlers for a multi-platform chat bot.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/usage
  - /docs/handling-events
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The `Chat` class coordinates adapters, state, and event handlers. Create one instance and register handlers for different event types.

```typescript
import { Chat } from "chat";
```

## Constructor

```typescript
const bot = new Chat(config);
```

| Property                           | Type                                                                                        | Description                                                                                                                                                                                                                                       |
| ---------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userName`                         | `string`                                                                                    | Default bot username across all adapters.                                                                                                                                                                                                         |
| `adapters`                         | `Record<string, Adapter>`                                                                   | Map of adapter name to adapter instance.                                                                                                                                                                                                          |
| `dedupeTtlMs`                      | `number`                                                                                    | TTL for message deduplication entries in milliseconds. The default outlives the last Slack event retry, which arrives about 5 minutes after the original delivery. Increase it if your platform redelivers later than that.                       |
| `state`                            | `StateAdapter`                                                                              | State adapter for subscriptions, locking, and caching.                                                                                                                                                                                            |
| `logger`                           | `Logger \| "debug" \| "info" \| "warn" \| "error" \| "silent"`                              | Logger instance or log level.                                                                                                                                                                                                                     |
| `streamingUpdateIntervalMs`        | `number`                                                                                    | Throttle interval for fallback streaming (post + edit) in milliseconds.                                                                                                                                                                           |
| `fallbackStreamingPlaceholderText` | `string \| null`                                                                            | Placeholder text posted when fallback streaming (post + edit) starts. Set to \`null\` to wait for the first streamed text before posting.                                                                                                         |
| `concurrency`                      | `"drop" \| "queue" \| "debounce" \| "burst" \| "concurrent" \| ConcurrencyConfig`           | What happens when a message arrives on a thread while a handler is still running. See \[Concurrency]\(/docs/concurrency).                                                                                                                         |
| `lockScope`                        | `"thread" \| "channel" \| ((context: LockScopeContext) => LockScope \| Promise<LockScope>)` | Which messages share a lock: one per thread or one per channel. A function can choose per message. When unset, the adapter's default is used, which is \`"channel"\` for WhatsApp and Telegram. See \[Lock scope]\(/docs/concurrency#lock-scope). |
| `history`                          | `HistoryConfig \| undefined`                                                                | Configuration for the History API's user, thread, and channel scopes. \`history.user\` includes the identity resolver. See \`bot.history\` below.                                                                                                 |

These options are deprecated but still read, so existing bots keep working:

| Option           | Replacement                                                                                                                       |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `onLockConflict` | `concurrency`. It only applies under the `drop` strategy, where `'force'` releases the held lock instead of throwing `LockError`. |
| `identity`       | `history.user.identity`                                                                                                           |
| `transcripts`    | `history.user`                                                                                                                    |
| `threadHistory`  | `history.thread`                                                                                                                  |
| `messageHistory` | `history.thread`. It was renamed to `threadHistory` first, which takes precedence when both are set.                              |

## Event handlers

### onNewMention

Fires when the bot is @-mentioned in a thread it has not subscribed to. Most bots start new conversations from this handler.

```typescript
bot.onNewMention(async (thread, message) => {
  await thread.subscribe();
  await thread.post("Hello!");
});
```

| Property  | Type      | Description                              |
| --------- | --------- | ---------------------------------------- |
| `thread`  | `Thread`  | The thread where the mention occurred.   |
| `message` | `Message` | The message that contains the @-mention. |

### onDirectMessage

Fires for every direct message when registered. Direct message handlers run before `onSubscribedMessage`, `onNewMention`, and pattern handlers. If no direct message handler is registered, unsubscribed DMs fall through to `onNewMention` for backward compatibility.

```typescript
bot.onDirectMessage(async (thread, message, channel) => {
  await thread.post(`Got your DM in ${channel.id}: ${message.text}`);
});
```

| Property  | Type      | Description                               |
| --------- | --------- | ----------------------------------------- |
| `thread`  | `Thread`  | The DM thread where the message occurred. |
| `message` | `Message` | The direct message.                       |
| `channel` | `Channel` | The DM channel.                           |

### onSubscribedMessage

Fires for every new message in a subscribed non-DM thread. Once subscribed, messages (including @-mentions) route here instead of `onNewMention`. DM threads route to `onDirectMessage` first when a direct message handler is registered.

```typescript
bot.onSubscribedMessage(async (thread, message) => {
  if (message.isMention) {
    // User @-mentioned us in a thread we're already watching
  }
  await thread.post(`Got: ${message.text}`);
});
```

### onNewMessage

Fires for messages in unsubscribed threads that aren't DMs and don't mention the bot. Pass a regex to filter by message text, or pass only a handler to receive every such message, including attachment-only messages with empty text. All `onNewMessage` handlers run one after another in registration order.

```typescript
bot.onNewMessage(/^!help/i, async (thread, message) => {
  await thread.post("Available commands: !help, !status");
});
```

```typescript
bot.onNewMessage(async (thread, message) => {
  await thread.post(`Received: ${message.text || "an attachment"}`);
});
```

| Property  | Type                                                                            | Description                                                                                                                                                                   |
| --------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pattern` | `RegExp`                                                                        | Optional regular expression tested against the message text. Omit it to receive every message that reaches pattern routing.                                                   |
| `handler` | `(thread: Thread, message: Message, context?: MessageContext) => Promise<void>` | Handler called for each matching message. \`context\` is set by the \`queue\` and \`burst\` concurrency strategies. See \[MessageContext]\(/docs/concurrency#messagecontext). |

The handler-only form doesn't receive DMs or mentions, even when no `onDirectMessage` or `onNewMention` handler is registered. Passing arguments in the wrong order, a `pattern` that isn't a `RegExp`, or no handler throws a `ChatError` when the handler is registered.

### onReaction

Fires when a user adds or removes an emoji reaction.

```typescript
import { emoji } from "chat";

// Filter to specific emoji
bot.onReaction([emoji.thumbs_up, emoji.heart], async (event) => {
  if (event.added) {
    await event.thread.post(`Thanks for the ${event.emoji}!`);
  }
});

// Handle all reactions
bot.onReaction(async (event) => { /* ... */ });
```

| Property          | Type                   | Description                                          |
| ----------------- | ---------------------- | ---------------------------------------------------- |
| `event.emoji`     | `EmojiValue`           | Normalized emoji value. Supports \`===\` comparison. |
| `event.rawEmoji`  | `string`               | Platform-specific emoji string.                      |
| `event.added`     | `boolean`              | \`true\` if added, \`false\` if removed.             |
| `event.user`      | `Author`               | The user who reacted.                                |
| `event.thread`    | `Thread`               | The thread where the reaction occurred.              |
| `event.message`   | `Message \| undefined` | The message that was reacted to, when available.     |
| `event.messageId` | `string`               | The message ID that was reacted to.                  |

### onAction

Fires when a user clicks a button or selects an option in a card.

```typescript
// Single action
bot.onAction("approve", async (event) => {
  if (event.thread) {
    await event.thread.post("Approved!");
  }
});

// Multiple actions
bot.onAction(["approve", "reject"], async (event) => { /* ... */ });

// All actions
bot.onAction(async (event) => { /* ... */ });
```

| Property          | Type                                                                               | Description                                                                                   |
| ----------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `event.actionId`  | `string`                                                                           | Action ID from the button or select.                                                          |
| `event.value`     | `string \| undefined`                                                              | Optional payload value from the button.                                                       |
| `event.values`    | `Record<string, string> \| undefined`                                              | The card's own input values, keyed by input ID. Absent where the platform has no card inputs. |
| `event.user`      | `Author`                                                                           | User who triggered the action.                                                                |
| `event.thread`    | `Thread \| null`                                                                   | The thread containing the card, or null for view-based actions.                               |
| `event.triggerId` | `string \| undefined`                                                              | Trigger ID for opening modals. Platform-specific and may expire quickly.                      |
| `event.openModal` | `(modal: ModalElement \| ChatElement) => Promise<{ viewId: string } \| undefined>` | Open a modal form in response to this action.                                                 |

### onModalSubmit

Fires when a user submits a modal form.

```typescript
bot.onModalSubmit("feedback", async (event) => {
  const comment = event.values.comment;
  if (event.relatedThread) {
    await event.relatedThread.post(`Feedback: ${comment}`);
  }
});
```

| Property                | Type                       | Description                                                                                      |
| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------ |
| `event.callbackId`      | `string`                   | The callback ID specified when the modal was created.                                            |
| `event.values`          | `Record<string, string>`   | Form field values keyed by input ID.                                                             |
| `event.user`            | `Author`                   | User who submitted the modal.                                                                    |
| `event.relatedThread`   | `Thread \| undefined`      | The thread the modal was opened from, when available.                                            |
| `event.relatedMessage`  | `SentMessage \| undefined` | The message containing the action that opened the modal.                                         |
| `event.relatedChannel`  | `Channel \| undefined`     | The channel the modal was opened from. Available when the modal was opened from a slash command. |
| `event.privateMetadata` | `string \| undefined`      | Arbitrary string passed through the modal lifecycle.                                             |

Returns `ModalResponse | undefined` to control the modal after submission:

| Response                                               | Effect                                                       |
| ------------------------------------------------------ | ------------------------------------------------------------ |
| `{ action: "close" }`                                  | Closes the current view and goes back one level in the stack |
| `{ action: "clear" }`                                  | Closes all views and dismisses the modal                     |
| `{ action: "errors", errors: { fieldId: "message" } }` | Shows validation errors                                      |
| `{ action: "update", modal: ModalElement }`            | Replaces the modal content                                   |
| `{ action: "push", modal: ModalElement }`              | Pushes a new modal view onto the stack                       |

### onOptionsLoad

Fires when an `ExternalSelect` requests options dynamically. Slack only. The handler is keyed on the select's `id` and must return options within Slack's 3-second budget. The adapter caps the loader at about 2.5 seconds and returns an empty result on timeout.

```typescript
bot.onOptionsLoad("assignee", async (event) => {
  const people = await peopleService.search(event.query);
  return people.map((p) => ({ label: p.fullName, value: p.id }));
});
```

Return an array of `OptionsLoadGroup` (`{ label, options }[]`) instead of a flat array to render grouped headers, such as "Recent" and "All". Slack allows at most 100 groups and 100 options per group.

| Property         | Type      | Description                                                                                  |
| ---------------- | --------- | -------------------------------------------------------------------------------------------- |
| `event.actionId` | `string`  | The \`id\` of the select requesting options. Matches the id passed to \`bot.onOptionsLoad\`. |
| `event.query`    | `string`  | The text the user has typed so far.                                                          |
| `event.user`     | `Author`  | The user requesting options.                                                                 |
| `event.adapter`  | `Adapter` | The adapter that received this event.                                                        |
| `event.raw`      | `unknown` | Raw platform-specific payload.                                                               |

### onSlashCommand

Fires when a user invokes a `/command` in the message composer. Supported on Slack and Discord.

```typescript
// Specific command
bot.onSlashCommand("/status", async (event) => {
  await event.channel.post("All systems operational!");
});

// Multiple commands
bot.onSlashCommand(["/help", "/info"], async (event) => {
  await event.channel.post(`You invoked ${event.command}`);
});

// Catch-all
bot.onSlashCommand(async (event) => {
  console.log(`${event.command} ${event.text}`);
});
```

| Property          | Type                                                                               | Description                                                |
| ----------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `event.command`   | `string`                                                                           | The command name, such as "/status".                       |
| `event.text`      | `string`                                                                           | Arguments after the command.                               |
| `event.user`      | `Author`                                                                           | The user who invoked the command.                          |
| `event.channel`   | `Channel`                                                                          | The channel where the command was invoked.                 |
| `event.triggerId` | `string \| undefined`                                                              | Trigger ID for opening modals. Expires after a short time. |
| `event.openModal` | `(modal: ModalElement \| ChatElement) => Promise<{ viewId: string } \| undefined>` | Open a modal form in response to this command.             |
| `event.adapter`   | `Adapter`                                                                          | The platform adapter.                                      |
| `event.raw`       | `unknown`                                                                          | Platform-specific raw payload.                             |

### onModalClose

Fires when a user closes a modal. Requires `notifyOnClose: true` on the modal.

```typescript
bot.onModalClose("feedback", async (event) => { /* ... */ });
```

### onAssistantThreadStarted

Fires when a user opens a new assistant thread through the Slack Assistants API. Use it to set suggested prompts, show a status indicator, or send an initial greeting.

```typescript
bot.onAssistantThreadStarted(async (event) => {
  const slack = bot.getAdapter("slack") as SlackAdapter;
  await slack.setSuggestedPrompts(event.channelId, event.threadTs, [
    { title: "Get started", message: "What can you help me with?" },
  ]);
});
```

| Property          | Type                     | Description                                                              |
| ----------------- | ------------------------ | ------------------------------------------------------------------------ |
| `event.threadId`  | `string`                 | Encoded thread ID.                                                       |
| `event.userId`    | `string`                 | The user who opened the thread.                                          |
| `event.channelId` | `string`                 | The DM channel ID.                                                       |
| `event.threadTs`  | `string`                 | Thread timestamp.                                                        |
| `event.context`   | `AssistantThreadContext` | Where the thread was opened: channel, team, enterprise, and entry point. |
| `event.adapter`   | `Adapter`                | The platform adapter.                                                    |

### onAssistantContextChanged

Fires when a user navigates to a different channel while the Slack Assistants API panel is open. Use it to update suggested prompts or context for the new channel.

```typescript
bot.onAssistantContextChanged(async (event) => {
  const slack = bot.getAdapter("slack") as SlackAdapter;
  await slack.setAssistantStatus(event.channelId, event.threadTs, "Updating context...");
});
```

The event shape is identical to `onAssistantThreadStarted`.

### onAgentSessionStopped

Fires after a user clicks Slack's native agent-session stop button. Chat SDK
aborts the active turn and moves the session out of `processing` before this
handler runs.

```typescript
bot.onAgentSessionStopped(async (event) => {
  await releaseExternalResources(event.threadId);
});
```

The event contains `threadId`, `channelId`, `threadTs`,
`streamingMessageTs`, `userId`, and `adapter`. `streamingMessageTs` lists the
streaming messages Slack stopped and can be empty when no stream was active.

### onAgentSessionTitleChanged

Fires when a user renames a Slack agent session.

```typescript
bot.onAgentSessionTitleChanged(async (event) => {
  await syncTitle(event.threadId, event.title);
});
```

The event contains `title`, `previousTitle`, `threadId`, `channelId`,
`threadTs`, `userId`, and `adapter`. `previousTitle` is omitted when the
session did not have a title before the change.

### onAppHomeOpened

Fires when a user opens the bot's Home tab in Slack. Use it to publish a dynamic Home tab view.

```typescript
bot.onAppHomeOpened(async (event) => {
  const slack = bot.getAdapter("slack") as SlackAdapter;
  await slack.publishHomeView(event.userId, {
    type: "home",
    blocks: [{ type: "section", text: { type: "mrkdwn", text: "Welcome!" } }],
  });
});
```

| Property          | Type      | Description                                  |
| ----------------- | --------- | -------------------------------------------- |
| `event.userId`    | `string`  | The user who opened the Home tab.            |
| `event.channelId` | `string`  | The channel ID associated with the Home tab. |
| `event.adapter`   | `Adapter` | The platform adapter.                        |

### onInstalled

Fires when the bot is installed, including when an app upgrade adds the bot to the manifest. Routine upgrades do not emit this event. Only the Teams adapter emits it, for personal, group chat, and team installs.

```typescript
bot.onInstalled(async (event) => {
  if (!event.channelId) return;
  await bot.channel(event.channelId).post("Thanks for installing!");
});
```

| Property               | Type                     | Description                                                                             |
| ---------------------- | ------------------------ | --------------------------------------------------------------------------------------- |
| `event.action`         | `"add" \| "add-upgrade"` | Install action: "add" or "add-upgrade".                                                 |
| `event.channelId`      | `string \| undefined`    | Normalized destination for the installation, safe to persist for later proactive posts. |
| `event.conversationId` | `string`                 | Platform conversation ID of the installation location.                                  |
| `event.id`             | `string`                 | Platform activity ID, useful for idempotency.                                           |
| `event.userId`         | `string \| undefined`    | The user who installed the bot.                                                         |
| `event.tenantId`       | `string \| undefined`    | Tenant the installation belongs to.                                                     |
| `event.adapter`        | `Adapter`                | The platform adapter.                                                                   |

### onUninstalled

Fires when the bot is removed, including when an app upgrade removes it from the manifest. Same event shape as `onInstalled`, with `action` set to `"remove"` or `"remove-upgrade"`. Clean up durable records for both actions, and do not post to the conversation after removal.

```typescript
bot.onUninstalled(async (event) => {
  if (event.adapter.name === "teams") {
    await removeTeamsInstallation(event);
  } else if (event.adapter.name === "slack") {
    await removeSlackInstallation(event.conversationId);
  }
});
```

`removeTeamsInstallation` and `removeSlackInstallation` are application-owned.
For Teams team installs, associate records with `event.raw.channelData.team.id`
as well as `conversationId`, which can differ between installation and removal.
See the [Teams persistence example](/adapters/official/teams#installation-lifecycle).

The Slack adapter emits `onUninstalled`, with `action` set to `"remove"`, when a
workspace or org uninstalls the app. `conversationId` is the Slack installation
key: the `team_id`, or the `enterprise_id` for org-wide installs. `tenantId` is
the Enterprise Grid `enterprise_id` when the event carries one. See
[Slack uninstalls](/adapters/official/slack#uninstalls).

## Utility methods

### abortTurn

Abort the active handler turn for a thread. Chat SDK signals work in this
process immediately and publishes the cancellation through the configured
state adapter for another serverless instance to observe.

```typescript
await bot.abortTurn(thread.id);
```

Platform adapters normally invoke this for native cancellation events. Model
and tool calls must receive `thread.signal` to stop their own upstream work.

### webhooks

Typed webhook handlers keyed by adapter name. Call them from your HTTP route handler.

```typescript
bot.webhooks.slack(request, { waitUntil });
bot.webhooks.teams(request, { waitUntil });
```

### getAdapter

Get a typed adapter instance by name.

```typescript
const slack = bot.getAdapter("slack");
```

#### Direct client access

Each adapter exposes its platform's typed native API client through a getter named after the SDK: `.webClient` on Slack, `.linearClient` on Linear, and `.octokit` on GitHub.

```typescript
// Slack - full WebClient from @slack/web-api
const slack = bot.getAdapter("slack").webClient;
await slack.pins.add({ channel: "C123ABC", timestamp: "1234567890.123456" });

// Linear - full LinearClient from @linear/sdk
const linear = bot.getAdapter("linear").linearClient;
const issue = await linear.issue("ENG-123");
const project = await issue.project;

// GitHub - full Octokit from @octokit/rest
const github = bot.getAdapter("github").octokit;
const { data: pulls } = await github.rest.pulls.list({
  owner: "vercel",
  repo: "chat",
  state: "open",
});
```

The client uses the credentials from your adapter config. For multi-tenant or multi-workspace adapters (Slack, Linear, GitHub), it returns the client bound to the credentials for the current webhook request context.

> The previous `.client` getter still works on all three adapters as a deprecated alias for `.webClient`, `.linearClient`, and `.octokit`.

> Multi-tenant adapters (GitHub App without a fixed installation ID, Linear with per-org OAuth, Slack in multi-workspace mode) require a webhook handler context to resolve credentials when the native client getter is accessed. Calling it outside a handler throws.
>
> For Slack, you can also bind a token explicitly outside a webhook with `adapter.withBotToken(token, () => adapter.webClient.…)`, for example in cron jobs or workflows. The same pattern is required when `botToken` is configured as an async resolver function, since `.webClient` resolves the token synchronously.
>
> Single-tenant adapters (PAT, API key, static `botToken` string, or a synchronous `botToken` resolver) work anywhere.

| Adapter | Getter          | Type                              |
| ------- | --------------- | --------------------------------- |
| Slack   | `.webClient`    | `WebClient` from `@slack/web-api` |
| Linear  | `.linearClient` | `LinearClient` from `@linear/sdk` |
| GitHub  | `.octokit`      | `Octokit` from `@octokit/rest`    |

### openDM

Open a direct message thread with a user.

```typescript
const dm = await bot.openDM("U123456");
await dm.post("Hello via DM!");

// Or with an Author object
const dm = await bot.openDM(message.author);
```

### getUser

Look up user information by user ID. Returns a `UserInfo` object with name, email, avatar, and bot status, or `null` if the user was not found.

`bot.getUser` picks the adapter from the format of the user ID, so it only works for platforms whose IDs it can recognize: Slack (`U...` or `W...`), Microsoft Teams (`29:...`), Google Chat (`users/...`), Linear (UUID), and Discord, Telegram, and GitHub (numeric). For other adapters that implement `getUser`, such as X, Twilio, and Twitch, call the adapter directly with `bot.getAdapter("x").getUser(userId)`.

```typescript
const user = await bot.getUser("U123456");
console.log(user?.email);    // "alice@company.com"
console.log(user?.fullName); // "Alice Smith"
```

```typescript
// Or with an Author object from a message handler. The adapter is still
// inferred from author.userId.
const user = await bot.getUser(message.author);
```

| Property    | Type                  | Description                                             |
| ----------- | --------------------- | ------------------------------------------------------- |
| `userId`    | `string`              | Platform-specific user ID.                              |
| `userName`  | `string`              | Username or handle.                                     |
| `fullName`  | `string`              | Display name or full name.                              |
| `isBot`     | `boolean`             | Whether the user is a bot.                              |
| `email`     | `string \| undefined` | Email address. Requires extra scopes on some platforms. |
| `avatarUrl` | `string \| undefined` | Profile image URL.                                      |

| Platform        | Constraints                                                                                                                                                                                       |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Slack           | Requires the `users:read` and `users:read.email` scopes. The email scope must be granted at OAuth install time.                                                                                   |
| Discord         | Bot tokens never see email. The `email` OAuth scope only applies to user-context auth.                                                                                                            |
| Telegram        | Bots can only look up users who have previously messaged them.                                                                                                                                    |
| Microsoft Teams | Only works for users who previously interacted with the bot, because profiles are cached from webhook activity. `avatarUrl` is not returned because the Graph API requires a separate photo call. |
| Google Chat     | Same caching constraint as Teams: only users seen in prior webhooks.                                                                                                                              |
| GitHub          | `email` is only returned if the user made it public or you authenticated with the `user:email` scope.                                                                                             |
| Linear          | Returns the full profile, including email and avatar, for any active workspace member.                                                                                                            |
| X               | Returns the name, username, and avatar. `email` is not returned. Call through the adapter, because X's numeric IDs aren't inferred.                                                               |
| Twitch          | Returns the display name, login, and avatar from Get Users. `email` is not returned. Call through the adapter, because Twitch's numeric IDs aren't inferred.                                      |
| Twilio          | Doesn't call Twilio. Returns a profile built from the phone number, with the number as `userId`, `userName`, and `fullName`.                                                                      |

Fields that aren't available return `undefined`.

Numeric user IDs from Discord, Telegram, and GitHub are ambiguous when more than one of those adapters is registered. In that case `bot.getUser` throws a `ChatError` with code `AMBIGUOUS_USER_ID`, even when you pass an `Author`, because the adapter is inferred from the ID alone. Call the adapter directly instead, for example `thread.adapter.getUser?.(message.author.userId)` inside a handler or `bot.getAdapter("telegram").getUser(userId)` elsewhere.

`bot.getUser` throws a `ChatError` in three cases. Handle them if your bot runs on multiple platforms.

| Code                     | When                                                                                              |
| ------------------------ | ------------------------------------------------------------------------------------------------- |
| `NOT_SUPPORTED`          | The inferred adapter doesn't implement `getUser`                                                  |
| `AMBIGUOUS_USER_ID`      | A numeric user ID could belong to more than one registered adapter (Discord, Telegram, or GitHub) |
| `UNKNOWN_USER_ID_FORMAT` | The `userId` string doesn't match any registered platform's ID format                             |

```typescript
import { ChatError } from "chat";

try {
  const user = await bot.getUser(userId);
  if (!user) {
    // User not found on this platform
  }
} catch (error) {
  if (error instanceof ChatError) {
    if (error.code === "NOT_SUPPORTED") {
      // This adapter doesn't support user lookups
    } else if (error.code === "AMBIGUOUS_USER_ID") {
      // Pass message.author or call adapter.getUser(userId) directly
    } else if (error.code === "UNKNOWN_USER_ID_FORMAT") {
      // userId doesn't match any known platform format
    }
  }
}
```

### thread

Get a `Thread` handle by its thread ID. Use it to post to threads outside a webhook, such as from a cron job or an external trigger.

```typescript
const thread = bot.thread("slack:C123ABC:1234567890.123456");
await thread.post("Hello from a cron job!");
```

### channel

Get a `Channel` by its channel ID.

```typescript
const channel = bot.channel("slack:C123ABC");

for await (const msg of channel.messages) {
  console.log(msg.text);
}
```

### initialize / shutdown

Manage the lifecycle manually. Initialization happens automatically on the first webhook. Call `initialize()` yourself when the bot does work outside a webhook.

```typescript
await bot.initialize();
// ... do work ...
await bot.shutdown();
```

During shutdown, the SDK calls the optional `disconnect()` method on each adapter before disconnecting the state adapter. Adapters use it to clean up platform connections, close WebSockets, or tear down subscriptions. If one adapter's `disconnect()` fails, the remaining adapters and the state adapter still disconnect.

### reviver

Get a `JSON.parse` reviver that deserializes `Thread` and `Message` objects from workflow payloads.

```typescript
const data = JSON.parse(payload, bot.reviver());
await data.thread.post("Hello from workflow!");
```

Threads and channels restored by `bot.reviver()` stay bound to that bot's adapters and state, and restored threads use that bot's streaming defaults, even if another Chat instance is registered later. When using multiple bots, parse each payload with the receiving bot's reviver. This does not isolate state keys if the bots share the same state store.

The binding is not serialized. If a restored object crosses a Workflow step boundary, automatic deserialization uses the registered singleton again. For multiple bots, pass the serialized data and explicitly restore it with the receiving bot's reviver inside the step.

There is also a workflow-safe serialization entrypoint that works without importing the `Chat` runtime. Use it in Vercel Workflow files so serializer registration does not load Node-only runtime dependencies:

```typescript
import { Message, reviver, ThreadImpl } from "chat/serialization";

const data = JSON.parse(payload, reviver) as {
  thread: ThreadImpl;
  message: Message;
};
```

`Message`, `ThreadImpl`, and `ChannelImpl` retain their automatic Workflow serialization when imported from either `chat` or `chat/serialization`. The dedicated entrypoint guarantees their serializer module graph does not load the Node-only `Chat` conversation context.

The standalone reviver resolves adapters lazily, looking them up from the Chat singleton on first access. Call `chat.registerSingleton()` before using thread methods like `post()` (typically inside a `"use step"` function). Once a restored thread or channel resolves its runtime, it retains that Chat instance for its adapter, state, and streaming defaults, even if the singleton changes. Registering the correct bot before first use remains the caller's responsibility; use `bot.reviver()` when the owner must be explicit.

### history

Namespaced access to the History API: cross-platform user history, per-thread reads and cache, and per-channel reads.

```typescript
// User scope: cross-platform, keyed by identity resolver result
await bot.history.user.append(thread, message);
const entries = await bot.history.user.list({ userKey, limit: 20 });
await bot.history.user.delete({ userKey });

// Thread scope: adapter.fetchMessages with cache fallback
const { messages } = await bot.history.thread.list(thread.id, { limit: 20 });

// Channel scope: platform APIs
const { messages: channelMessages } = await bot.history.channel.listMessages(
  channel.id,
  { limit: 10 }
);
const { threads } = await bot.history.channel.listThreads(channel.id, {
  limit: 20,
});
```

See [History API reference](/docs/api/history) for full details and the [History guide](/docs/history) for setup and patterns.

> `bot.transcripts` is a deprecated alias for `bot.history.user`. Accessing either when user history is not configured throws.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: History
description: API reference for bot.history, covering the user, thread, and channel scopes.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`bot.history` provides three namespaced scopes for persisting and querying messages. See the [History guide](/docs/history) for setup and usage patterns.

```typescript
import { Chat } from "chat";
```

## Configuration

History scopes are configured under the `history` key on `ChatConfig`.

### ChatConfig.history

| Property | Type                                                    | Description                                                                                                                                                                                                |
| -------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`   | `UserHistoryConfig \| undefined`                        | Cross-platform per-user message persistence. Requires an \`identity\` resolver. Replaces the legacy \`transcripts\` + \`identity\` top-level fields.                                                       |
| `thread` | `{ maxMessages?: number; ttlMs?: number } \| undefined` | Per-thread message history backfill. Used by adapters that set \`persistThreadHistory: true\` (e.g. WhatsApp, and Telegram by default). Replaces the legacy \`threadHistory\` / \`messageHistory\` fields. |

### UserHistoryConfig

Same fields as the deprecated `TranscriptsConfig`, plus an optional `identity` resolver (preferred over the deprecated top-level `ChatConfig.identity`):

| Property         | Type                                                                      | Description                                                                                                                                                                                    |
| ---------------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `identity`       | `(context: IdentityContext) => string \| null \| Promise<string \| null>` | Resolves a stable cross-platform user key from each inbound message. Return \`null\` to skip persistence for that event. May also be set via the deprecated top-level \`ChatConfig.identity\`. |
| `retention`      | `number \| DurationString \| undefined`                                   | List TTL, refreshed on every append. Accepts milliseconds or a duration string ("45s", "30m", "6h", "7d"). Omit for no expiry.                                                                 |
| `maxPerUser`     | `number \| false`                                                         | Hard cap per user key. Older entries are evicted on append. Set \`false\` for no cap.                                                                                                          |
| `storeFormatted` | `boolean`                                                                 | Persist the mdast \`formatted\` field alongside \`text\`. Off by default to keep storage small.                                                                                                |

#### IdentityContext

| Property  | Type      | Description                             |
| --------- | --------- | --------------------------------------- |
| `adapter` | `string`  | Adapter name (e.g. "slack", "discord"). |
| `author`  | `Author`  | Message author info.                    |
| `message` | `Message` | The inbound message.                    |

***

## bot.history.user

Cross-platform per-user message store. Access via `bot.history.user`. Throws when accessed if `history.user` (or the legacy `transcripts` + `identity`) was not configured on the `Chat` instance.

`UserHistoryApi` is identical in shape to the deprecated `TranscriptsApi`.

### append

Persist a `Message` (typically the inbound user message) or an `AppendInput` (typically a bot reply).

```typescript
append(
  thread: Postable,
  message: Message | AppendInput,
  options?: AppendOptions,
): Promise<HistoryEntry | null>;
```

When `message` is a `Message`, `userKey` is read from the instance (set automatically by the SDK from the `identity` resolver). If it's `undefined` (resolver returned `null`), the call is a no-op and returns `null`. When `message` is an `AppendInput`, `options.userKey` is required.

#### AppendInput

| Property            | Type                                | Description                                                                   |
| ------------------- | ----------------------------------- | ----------------------------------------------------------------------------- |
| `role`              | `"user" \| "assistant" \| "system"` | Role tag for the entry.                                                       |
| `text`              | `string`                            | Plain-text body.                                                              |
| `formatted`         | `FormattedContent \| undefined`     | Optional mdast AST. Only stored when \`history.user.storeFormatted\` is true. |
| `platformMessageId` | `string \| undefined`               | Platform-native message ID, when known.                                       |

#### AppendOptions

| Property  | Type                  | Description                                                                                                  |
| --------- | --------------------- | ------------------------------------------------------------------------------------------------------------ |
| `userKey` | `string \| undefined` | Required when appending an \`AppendInput\` (assistant or system role); ignored when appending a \`Message\`. |

### list

Returns entries in chronological order (oldest first). When `limit` is set, returns the newest `N` entries, still in chronological order.

```typescript
list(query: ListQuery): Promise<HistoryEntry[]>;
```

#### ListQuery

| Property    | Type                                                 | Description                          |
| ----------- | ---------------------------------------------------- | ------------------------------------ |
| `userKey`   | `string`                                             | Cross-platform user key.             |
| `limit`     | `number`                                             | Maximum entries returned.            |
| `platforms` | `string[] \| undefined`                              | Filter to a subset of adapter names. |
| `threadId`  | `string \| undefined`                                | Filter to a single thread.           |
| `roles`     | `("user" \| "assistant" \| "system")[] \| undefined` | Filter to specific roles.            |

### count

```typescript
count(query: { userKey: string }): Promise<number>;
```

Returns the total number of entries stored under the user key.

### delete

```typescript
delete(target: { userKey: string }): Promise<{ deleted: number }>;
```

Wipes every entry stored under the user key. Returns the count that was removed.

***

## bot.history.thread

Per-thread message history. Always available, and delegates to the adapter's `fetchMessages`. For adapters that persist history in the SDK-maintained `ThreadHistoryCache` (`persistThreadHistory: true`, e.g. WhatsApp, and Telegram by default), an empty platform response falls back to that cache. Every method throws when the adapter named in the thread ID prefix is not registered, so a typo'd ID fails loudly instead of reading as an empty thread.

### list

```typescript
list(threadId: string, options?: FetchOptions): Promise<FetchResult>;
```

Fetches messages from a thread. Delegates to `adapter.fetchMessages`. On adapters with `persistThreadHistory: true`, an empty first page is served from the SDK-side cache instead. Continuation pages never fall back: when you pass a `cursor`, you get the adapter's response as-is. The cache honors `direction`: the newest `limit` messages by default, the oldest `limit` with `direction: "forward"`.

#### FetchOptions

| Property    | Type                                   | Description                                                     |
| ----------- | -------------------------------------- | --------------------------------------------------------------- |
| `limit`     | `number \| undefined`                  | Maximum number of messages to return.                           |
| `cursor`    | `string \| undefined`                  | Pagination cursor returned by a prior call.                     |
| `direction` | `"backward" \| "forward" \| undefined` | "backward" (newest first, default) or "forward" (oldest first). |

#### FetchResult

| Property     | Type                  | Description                                                   |
| ------------ | --------------------- | ------------------------------------------------------------- |
| `messages`   | `Message[]`           | Normalized messages for the requested page.                   |
| `nextCursor` | `string \| undefined` | Cursor for the next page. \`undefined\` when no more results. |

### collect

Async generator that pages through all messages in a thread (oldest first). Stops when there are no more pages or the optional `limit` is reached.

```typescript
collect(threadId: string, options?: { limit?: number }): AsyncIterable<Message>;
```

```typescript title="lib/bot.ts" lineNumbers
for await (const msg of bot.history.thread.collect(thread.id, { limit: 50 })) {
  console.log(msg.text);
}
```

### append

```typescript
append(threadId: string, message: Message): Promise<void>;
```

Atomically appends a message to the SDK-side thread cache. Called automatically by the SDK on adapters where `persistThreadHistory` is `true`. You can call it manually to warm the cache, but you normally won't need to.

***

## bot.history.channel

Channel-level history. Always available, and delegates every operation to the adapter named in the channel ID prefix. Individual methods throw when the adapter does not implement the underlying capability.

### listMessages

```typescript
listMessages(channelId: string, options?: FetchOptions): Promise<FetchResult>;
```

Fetches top-level messages in a channel (not thread replies). Delegates to `adapter.fetchChannelMessages`. If the adapter doesn't implement it but persists history in the SDK-side store (`persistThreadHistory: true`), messages are served from the channel-keyed cache. Throws when the adapter supports neither.

### listThreads

```typescript
listThreads(channelId: string, options?: ListThreadsOptions): Promise<ListThreadsResult>;
```

Lists threads in a channel. Delegates to `adapter.listThreads`. Throws if the adapter does not implement `listThreads`.

### listThreadsWithMessages

```typescript
listThreadsWithMessages(
  channelId: string,
  options?: { cursor?: string; messagesPerThread?: number; maxThreads?: number },
): Promise<{ threads: Array<{ threadId: string; messages: Message[] }>; nextCursor?: string }>;
```

Convenience helper: lists up to `maxThreads` (default 5) threads, then fetches `messagesPerThread` messages for each through `history.thread.list`, a few threads at a time to stay inside platform rate limits.

#### ListThreadsOptions

| Property | Type                  | Description                          |
| -------- | --------------------- | ------------------------------------ |
| `limit`  | `number \| undefined` | Maximum number of threads to return. |
| `cursor` | `string \| undefined` | Pagination cursor.                   |

#### ListThreadsResult

| Property     | Type                  | Description                                                   |
| ------------ | --------------------- | ------------------------------------------------------------- |
| `threads`    | `ThreadSummary[]`     | Thread summaries.                                             |
| `nextCursor` | `string \| undefined` | Cursor for the next page. \`undefined\` when no more results. |

***

## HistoryEntry

Returned by `bot.history.user.append` and `bot.history.user.list`. Exported from `chat` as `HistoryEntry` (canonical) and `TranscriptEntry` (deprecated alias).

| Property            | Type                                | Description                                                           |
| ------------------- | ----------------------------------- | --------------------------------------------------------------------- |
| `id`                | `string`                            | UUID assigned by the SDK at append time.                              |
| `userKey`           | `string`                            | Cross-platform user key from the identity resolver.                   |
| `role`              | `"user" \| "assistant" \| "system"` | Role tag.                                                             |
| `text`              | `string`                            | Plain-text body. Use this field when building prompts.                |
| `formatted`         | `FormattedContent \| undefined`     | mdast AST. Only present when \`history.user.storeFormatted\` is true. |
| `platform`          | `string`                            | Originating adapter name.                                             |
| `threadId`          | `string`                            | Originating thread ID.                                                |
| `platformMessageId` | `string \| undefined`               | Platform-native message ID, when known.                               |
| `timestamp`         | `number`                            | Milliseconds since epoch, set at append time on the SDK side.         |

## toPromptEntries

```typescript
import { toPromptEntries, type PromptEntry } from "chat";

toPromptEntries(entries: HistoryEntry[]): PromptEntry[];
```

Converts `history.user.list()` results into `{ role, content }` entries ready to pass to an LLM as chat history (for example the AI SDK's `messages` input). Entries with empty text are dropped; order is preserved.

```typescript title="lib/bot.ts" lineNumbers
const entries = await bot.history.user.list({ userKey });
const { text } = await generateText({
  model,
  messages: toPromptEntries(entries),
});
```

#### PromptEntry

| Property  | Type                                | Description                                   |
| --------- | ----------------------------------- | --------------------------------------------- |
| `role`    | `"user" \| "assistant" \| "system"` | Role tag carried over from the history entry. |
| `content` | `string`                            | Plain-text body of the entry.                 |

## Storage

| Scope                        | Storage key pattern          | Notes                                            |
| ---------------------------- | ---------------------------- | ------------------------------------------------ |
| `bot.history.user`           | `transcripts:user:{userKey}` | Backed by `StateAdapter.appendToList`            |
| `bot.history.thread` (cache) | `msg-history:{threadId}`     | Only populated when `persistThreadHistory: true` |

Appends are atomic, so concurrent inbound messages on the same key don't race.

## Deprecated aliases

| Old                                                      | New                                                                                                     |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `bot.transcripts`                                        | `bot.history.user`                                                                                      |
| `ChatConfig.transcripts` + `ChatConfig.identity`         | `ChatConfig.history.user` (with `history.user.identity`, or keep top-level `identity` during migration) |
| `TranscriptEntry`                                        | `HistoryEntry` (also exported as `UserHistoryEntry`)                                                    |
| `TranscriptsConfig`                                      | `UserHistoryConfig`                                                                                     |
| `ChatConfig.threadHistory` / `ChatConfig.messageHistory` | `ChatConfig.history.thread`                                                                             |

All deprecated names continue to work and will not be removed in the current major version. See [Migrating from `bot.transcripts`](/docs/history#migrating-from-bottranscripts).

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Overview
description: API reference for the Chat SDK core package.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: overview
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

API reference for the `chat` package. All exports are available from the top-level import:

```typescript
import { Chat, root, paragraph, text, Card, Button, emoji } from "chat";
```

## Core

| Export                                                  | Description                                                                        |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| [`Chat`](/docs/api/chat)                                | Main class that registers adapters, event handlers, and webhook routing            |
| [`Thread`](/docs/api/thread)                            | Conversation thread with methods for posting, subscribing, and state               |
| [`Channel`](/docs/api/channel)                          | Channel or conversation container that holds threads                               |
| [`Message`](/docs/api/message)                          | Normalized message with text, AST, author, and metadata                            |
| [`ScheduledMessage`](/docs/api/thread#scheduledmessage) | Returned by `thread.schedule()` and `channel.schedule()`, with a `cancel()` method |

## Message formats

| Export                                                      | Description                                                            |
| ----------------------------------------------------------- | ---------------------------------------------------------------------- |
| [`PostableMessage`](/docs/api/postable-message)             | Union type accepted by `thread.post()`                                 |
| [`Plan`](/docs/api/postable-message#plan)                   | Step-by-step task list that mutates after posting                      |
| [`StreamingPlan`](/docs/api/postable-message#streamingplan) | Wraps an async iterable with platform-specific streaming options       |
| [`Cards`](/docs/api/cards)                                  | Rich card components: `Card`, `Text`, `Button`, `Actions`, and more    |
| [`Markdown`](/docs/api/markdown)                            | AST builder functions: `root`, `paragraph`, `text`, `strong`, and more |
| [`Modals`](/docs/api/modals)                                | Modal form components: `Modal`, `TextInput`, `Select`, and more        |

## History

| Export                                                       | Description                                                                       |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| [`bot.history.user`](/docs/api/history#bothistoryuser)       | Cross-platform per-user message store with append, list, count, and delete        |
| [`bot.history.thread`](/docs/api/history#bothistorythread)   | Per-thread message reads from the platform API, with SDK cache fallback           |
| [`bot.history.channel`](/docs/api/history#bothistorychannel) | Per-channel reads through `listMessages`, `listThreads`, and related adapter APIs |
| [`Transcripts`](/docs/api/transcripts)                       | Deprecated alias for `bot.history.user`                                           |

## AI utilities

`toAiMessages`, `createChatTools`, and the supporting types live in the [`chat/ai`](/docs/ai) subpath. See the [AI section](/docs/ai) for the full reference.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Markdown
description: AST builder functions and utilities for programmatic message formatting.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/posting-messages
  - /docs/emoji
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

The SDK uses [mdast](https://github.com/syntax-tree/mdast) (Markdown AST) as the canonical format for message formatting. Each adapter converts the AST to the platform's native format.

```typescript
import {
  root, paragraph, text, strong, emphasis, strikethrough,
  inlineCode, codeBlock, link, blockquote,
  parseMarkdown, stringifyMarkdown, toPlainText, walkAst,
  tableToAscii, tableElementToAscii,
} from "chat";
```

## Type re-exports

The chat package re-exports mdast's union and content types so adapters and downstream code can build exhaustively typed AST walkers without depending on `mdast` directly:

```typescript
import type { Nodes, Root, Content } from "chat";

function render(node: Nodes): string {
  switch (node.type) {
    case "text": return node.value;
    case "strong": return node.children.map(render).join("");
    // ...
    default: throw new Error(`Unhandled: ${node satisfies never}`);
  }
}
```

Adapters use this pattern to make the type checker reject the build when a new mdast node type is introduced upstream.

## Node builders

### root

Root node. Every AST needs one as its top-level wrapper.

```typescript
root([
  paragraph([text("Hello, world!")]),
])
```

| Property   | Type        | Description                                                            |
| ---------- | ----------- | ---------------------------------------------------------------------- |
| `children` | `Content[]` | Top-level content nodes (paragraphs, code blocks, blockquotes, lists). |

### paragraph

A paragraph block.

```typescript
paragraph([text("Hello "), strong([text("world")])])
```

### text

Plain text node.

```typescript
text("Hello, world!")
```

### strong

**Bold** text.

```typescript
strong([text("important")])
```

### emphasis

*Italic* text.

```typescript
emphasis([text("emphasized")])
```

### strikethrough

~~Strikethrough~~ text.

```typescript
strikethrough([text("removed")])
```

### inlineCode

`Inline code` span.

```typescript
inlineCode("const x = 1")
```

### codeBlock

Fenced code block with optional language.

```typescript
codeBlock("const x = 1;", "typescript")
```

| Property | Type                  | Description                                  |
| -------- | --------------------- | -------------------------------------------- |
| `value`  | `string`              | Code content.                                |
| `lang`   | `string \| undefined` | Language identifier for syntax highlighting. |

### link

Hyperlink.

```typescript
link("https://example.com", [text("click here")])
link("https://example.com", [text("click here")], "tooltip title")
```

| Property   | Type                  | Description            |
| ---------- | --------------------- | ---------------------- |
| `url`      | `string`              | Link URL.              |
| `children` | `Content[]`           | Link text content.     |
| `title`    | `string \| undefined` | Optional tooltip text. |

### blockquote

Block quotation.

```typescript
blockquote([paragraph([text("Quoted text")])])
```

## Parsing and stringifying

### parseMarkdown

Parse a markdown string into an mdast AST.

```typescript
const ast = parseMarkdown("**Hello** world");
```

### stringifyMarkdown

Convert an mdast AST back to a markdown string.

```typescript
const md = stringifyMarkdown(ast); // "**Hello** world"
```

Pass `handlers` in the options to customize how individual mdast node types are
serialized, for example when rendering a platform-specific Markdown dialect:

```typescript
const md = stringifyMarkdown(ast, {
  handlers: {
    text: (node) => node.value,
  },
});
```

Custom handlers replace the default serializer for those node types, so they are
responsible for any escaping required by the destination format.

### toPlainText

Strip all formatting and return plain text.

```typescript
const plain = toPlainText(ast); // "Hello world"
```

### markdownToPlainText

Shorthand for parsing markdown and extracting plain text.

```typescript
const plain = markdownToPlainText("**Hello** world"); // "Hello world"
```

## AST utilities

### walkAst

Transform an AST by visiting each node. Return a new value to replace the node, or `undefined` to keep it unchanged.

```typescript
const transformed = walkAst(ast, (node) => {
  if (isStrongNode(node)) {
    return emphasis(getNodeChildren(node));
  }
  return undefined;
});
```

### Type guards

Functions for checking node types:

| Guard                    | Matches       |
| ------------------------ | ------------- |
| `isTextNode(node)`       | Plain text    |
| `isParagraphNode(node)`  | Paragraph     |
| `isStrongNode(node)`     | Bold          |
| `isEmphasisNode(node)`   | Italic        |
| `isDeleteNode(node)`     | Strikethrough |
| `isInlineCodeNode(node)` | Inline code   |
| `isCodeNode(node)`       | Code block    |
| `isLinkNode(node)`       | Link          |
| `isBlockquoteNode(node)` | Blockquote    |
| `isListNode(node)`       | List          |
| `isListItemNode(node)`   | List item     |
| `isTableNode(node)`      | Table         |
| `isTableRowNode(node)`   | Table row     |
| `isTableCellNode(node)`  | Table cell    |

### getNodeChildren / getNodeValue

Safely access node properties without type narrowing.

```typescript
const children = getNodeChildren(node); // Content[] | undefined
const value = getNodeValue(node);       // string | undefined
```

## Table utilities

### tableToAscii

Render an mdast `Table` node as a padded ASCII table string. Used by adapters that lack native table support (Google Chat, Discord, Telegram).

```typescript
import { parseMarkdown, tableToAscii, isTableNode } from "chat";

const ast = parseMarkdown("| Name | Role |\n|------|------|\n| Alice | Engineer |");
const table = ast.children.find(isTableNode);

if (table) {
  console.log(tableToAscii(table));
}
```

Output:

```
Name  | Role
------|---------
Alice | Engineer
```

### tableElementToAscii

Render a table from headers and string row arrays as a padded ASCII table. Used for card `TableElement` fallback rendering.

```typescript
import { tableElementToAscii } from "chat";

const ascii = tableElementToAscii(
  ["Name", "Age", "Role"],
  [
    ["Alice", "30", "Engineer"],
    ["Bob", "25", "Designer"],
  ]
);
```

## Platform formatting

You write standard markdown, and each adapter converts it to the platform's native syntax. This table shows how each platform renders common formatting.

| Feature       | Slack                   | Teams           | Google Chat               |
| ------------- | ----------------------- | --------------- | ------------------------- |
| Bold          | `**text**`              | `**text**`      | `*text*`                  |
| Italic        | `_text_`                | `_text_`        | `_text_`                  |
| Strikethrough | `~~text~~`              | `~~text~~`      | `~text~`                  |
| Code          | `` `code` ``            | `` `code` ``    | `` `code` ``              |
| Code blocks   | ` ``` `                 | ` ``` `         | ` ``` `                   |
| Links         | `[text](url)`           | `[text](url)`   | `[text](url)`             |
| Lists         | Supported               | Supported       | Supported                 |
| Blockquotes   | `>`                     | `>`             | Simulated with `>` prefix |
| Tables        | Native (markdown\_text) | Native GFM      | ASCII fallback            |
| Mentions      | `<@USER>`               | `<at>name</at>` | `<users/{id}>`            |

> Slack accepts standard markdown via the `markdown_text` field on `chat.postMessage` and related methods, so the SDK passes markdown through directly. Incoming Slack messages still arrive as legacy mrkdwn (`*bold*`, `<url|text>`) and are parsed transparently. If you need to send mrkdwn yourself, use `{ raw: "..." }`.

> The AST builders and `parseMarkdown` handle these conversions for you. The table is mainly useful when you work with `raw` platform payloads or debug formatting issues.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Message
description: Normalized message format with text, AST, author, and metadata.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/handling-events
  - /docs/subject
  - /docs/ai/to-ai-messages
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Incoming messages are normalized across all platforms into a consistent `Message` object.

```typescript
import { Message } from "chat";
```

## Properties

| Property      | Type                              | Description                                                                                                                                                                                                         |
| ------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`          | `string`                          | Platform-specific message ID.                                                                                                                                                                                       |
| `threadId`    | `string`                          | Thread ID in adapter:channel:thread format.                                                                                                                                                                         |
| `text`        | `string`                          | Plain text content with all formatting stripped.                                                                                                                                                                    |
| `formatted`   | `Root`                            | mdast AST representation. This is the canonical format for processing.                                                                                                                                              |
| `raw`         | `unknown`                         | Original platform-specific payload (escape hatch).                                                                                                                                                                  |
| `author`      | `Author`                          | Message author info.                                                                                                                                                                                                |
| `metadata`    | `MessageMetadata`                 | Timestamps and edit status.                                                                                                                                                                                         |
| `attachments` | `Attachment[]`                    | File attachments.                                                                                                                                                                                                   |
| `replyTo`     | `Message \| undefined`            | The normalized message this message replies to, when provided by the adapter.                                                                                                                                       |
| `links`       | `LinkPreview[]`                   | Links found in the message, with optional preview metadata.                                                                                                                                                         |
| `isMention`   | `boolean \| undefined`            | The adapter's mention decision. \`true\` and \`false\` are final; \`undefined\` makes Chat SDK match \`@username\` in \`text\`. A direct message with no \`onDirectMessage\` handler registered is always \`true\`. |
| `subject`     | `Promise<MessageSubject \| null>` | Resolves the parent resource (issue, PR, merge request, or Notion page) this message is about. Returns null on chat platforms. See \[Message Subject]\(/docs/subject).                                              |

## Author

| Property   | Type                   | Description                                                                                                                                                                                                            |
| ---------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`   | `string`               | Platform-specific user ID.                                                                                                                                                                                             |
| `userName` | `string`               | Username/handle for @-mentions.                                                                                                                                                                                        |
| `fullName` | `string`               | Display name.                                                                                                                                                                                                          |
| `email`    | `string \| undefined`  | Email address when provided by the platform. Availability may require additional permissions.                                                                                                                          |
| `isBot`    | `boolean \| "unknown"` | Whether the author is a bot.                                                                                                                                                                                           |
| `isMe`     | `boolean`              | Whether the author is this bot.                                                                                                                                                                                        |
| `isSystem` | `boolean \| undefined` | Whether the message was generated by the chat platform itself (e.g. Slack's reserved \`USLACK\` user for notifications like "@user archived the channel"). Absent means \`false\`. Currently set by the Slack adapter. |

### How `isMe` works

Each adapter detects whether a message came from the bot itself. Chat SDK filters `isMe: true` messages before handlers run so bot replies do not loop back into `onNewMessage`, `onNewMention`, or subscribed-thread handlers.

`isMe` means "sent by this bot/runtime", not "sent by the authenticated user or account". For adapters backed by a user-owned account, do not blindly map platform fields like `fromMe` to `isMe`. Only set `isMe: true` for messages the adapter sent itself. If the platform echoes sent messages back through the webhook, track sent message IDs and mark only those echoes as `isMe: true`.

The detection logic varies by platform:

| Platform    | Detection method                                                                                                                                                     |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Slack       | Checks `event.user === botUserId` (primary), then `event.bot_id === botId` (for `bot_message` subtypes). Both IDs are fetched during initialization via `auth.test`. |
| Teams       | Checks `activity.from.id === appId` (exact match), then checks if `activity.from.id` ends with `:{appId}` (handles `28:{appId}` format).                             |
| Google Chat | Checks `message.sender.name === botUserId`. The bot user ID is learned dynamically from message annotations when the bot is first @-mentioned.                       |

> All adapters return `false` if the bot ID isn't known yet, so the bot doesn't ignore messages it should process.

## MessageMetadata

| Property   | Type                | Description                          |
| ---------- | ------------------- | ------------------------------------ |
| `dateSent` | `Date`              | When the message was sent.           |
| `edited`   | `boolean`           | Whether the message has been edited. |
| `editedAt` | `Date \| undefined` | When the message was last edited.    |

## Attachment

| Property        | Type                                                | Description                                                                                                      |
| --------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `type`          | `"image" \| "file" \| "video" \| "audio"`           | Attachment type.                                                                                                 |
| `url`           | `string \| undefined`                               | URL to the file.                                                                                                 |
| `data`          | `Buffer \| Blob \| undefined`                       | Binary data (if already fetched).                                                                                |
| `name`          | `string \| undefined`                               | Filename.                                                                                                        |
| `mimeType`      | `string \| undefined`                               | MIME type.                                                                                                       |
| `size`          | `number \| undefined`                               | File size in bytes.                                                                                              |
| `fetchData()`   | `() => Promise<Buffer \| ArrayBuffer> \| undefined` | Fetch the attachment data. Handles platform auth automatically.                                                  |
| `fetchMetadata` | `Record<string, string> \| undefined`               | Platform-specific IDs for reconstructing fetchData after serialization (e.g. WhatsApp mediaId, Telegram fileId). |

## LinkPreview

Links found in incoming messages are extracted and exposed as `LinkPreview` objects. On platforms that support it (currently Slack), links pointing to other chat messages include a `fetchMessage()` callback to retrieve the full linked message.

| Property         | Type                                  | Description                                                                                                                 |
| ---------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `url`            | `string`                              | The URL.                                                                                                                    |
| `title`          | `string \| undefined`                 | Title from unfurl metadata (if available).                                                                                  |
| `description`    | `string \| undefined`                 | Description from unfurl metadata (if available).                                                                            |
| `imageUrl`       | `string \| undefined`                 | Preview image URL (if available).                                                                                           |
| `siteName`       | `string \| undefined`                 | Site name, e.g. "Vercel" (if available).                                                                                    |
| `fetchMessage()` | `() => Promise<Message> \| undefined` | Fetch the linked chat message. Available when the URL points to a message on the same platform (e.g. a Slack message link). |

> When using [`toAiMessages()`](/docs/ai/to-ai-messages), link metadata is automatically appended to the message content. Embedded message links are labeled as `[Embedded message: ...]` so the AI model understands the context.

### Platform support

| Platform | Link extraction                                       | `fetchMessage()`                                 |
| -------- | ----------------------------------------------------- | ------------------------------------------------ |
| Slack    | URLs from `rich_text` blocks or `<url>` text patterns | Slack message links (`*.slack.com/archives/...`) |
| Others   | Not supported yet; `links` is always `[]`             | —                                                |

## MessageSubject

Returned by `message.subject` on platforms with parent resources. See [Message Subject](/docs/subject) for usage.

| Property      | Type                                        | Description                                                                |
| ------------- | ------------------------------------------- | -------------------------------------------------------------------------- |
| `type`        | `string`                                    | Resource kind, e.g. "issue", "pull\_request", "merge\_request", or "page". |
| `id`          | `string`                                    | Resource identifier (e.g. "ENG-123" or "42").                              |
| `title`       | `string \| undefined`                       | Resource title.                                                            |
| `description` | `string \| undefined`                       | Full description/body in markdown.                                         |
| `status`      | `string \| undefined`                       | Current status (e.g. "In Progress", "open").                               |
| `url`         | `string \| undefined`                       | Web URL to the resource.                                                   |
| `author`      | `{ id: string; name: string } \| undefined` | Resource creator.                                                          |
| `assignee`    | `{ id: string; name: string } \| undefined` | Current assignee.                                                          |
| `labels`      | `string[] \| undefined`                     | Labels/tags.                                                               |
| `raw`         | `unknown`                                   | Full platform API response.                                                |

## Serialization

Messages can be serialized for workflow engines and external systems.

```typescript
// Serialize
const json = message.toJSON();

// Deserialize
const restored = Message.fromJSON(json);
```

The serialized format converts `Date` fields to ISO strings and omits non-serializable fields like `data` buffers and `fetchData` functions. The `fetchMetadata` field is preserved so that adapters can reconstruct `fetchData` when the message is rehydrated from a queue.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Modals
description: Modal form components for collecting user input.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/modals
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Modals display form dialogs that collect structured user input. Modals are currently supported on Slack and Teams.

```typescript
import {
  Modal,
  TextInput,
  DateInput,
  NumberInput,
  Select,
  ExternalSelect,
  RadioSelect,
  SelectOption,
} from "chat";
```

## Modal

Top-level container for a form dialog. Open a modal from an `onAction` or `onSlashCommand` handler using `event.openModal()`.

```typescript
bot.onAction("open-form", async (event) => {
  await event.openModal(
    Modal({
      callbackId: "feedback",
      title: "Submit Feedback",
      submitLabel: "Send",
      children: [
        TextInput({ id: "comment", label: "Comment", multiline: true }),
      ],
    })
  );
});
```

| Property          | Type           | Description                                                               |
| ----------------- | -------------- | ------------------------------------------------------------------------- |
| `callbackId`      | `string`       | Unique ID for routing to onModalSubmit/onModalClose handlers.             |
| `title`           | `string`       | Modal title displayed in the header.                                      |
| `submitLabel`     | `string`       | Label for the submit button.                                              |
| `closeLabel`      | `string`       | Label for the close/cancel button.                                        |
| `notifyOnClose`   | `boolean`      | Whether to fire onModalClose when the user dismisses the modal.           |
| `callbackUrl`     | `string`       | URL to POST form values to when the modal is submitted.                   |
| `privateMetadata` | `string`       | Arbitrary string passed through the modal lifecycle (e.g., JSON context). |
| `children`        | `ModalChild[]` | Form input elements.                                                      |

## TextInput

A text input field.

```typescript
TextInput({
  id: "name",
  label: "Your name",
  placeholder: "Enter your name",
})

TextInput({
  id: "description",
  label: "Description",
  multiline: true,
  maxLength: 500,
  optional: true,
})
```

| Property       | Type      | Description                                |
| -------------- | --------- | ------------------------------------------ |
| `id`           | `string`  | Input ID, used as the key in event.values. |
| `label`        | `string`  | Label displayed above the input.           |
| `placeholder`  | `string`  | Placeholder text.                          |
| `initialValue` | `string`  | Pre-filled value.                          |
| `multiline`    | `boolean` | Render as a textarea.                      |
| `optional`     | `boolean` | Whether the field can be left empty.       |
| `maxLength`    | `number`  | Maximum character length.                  |

## DateInput

A date picker. Renders a Slack `datepicker` and an Adaptive Card `Input.Date` on Teams.

```typescript
DateInput({
  id: "due_date",
  label: "Due date",
  placeholder: "Pick a date",
  initialValue: "2026-08-01",
})
```

| Property       | Type      | Description                                |
| -------------- | --------- | ------------------------------------------ |
| `id`           | `string`  | Input ID, used as the key in event.values. |
| `label`        | `string`  | Label displayed above the input.           |
| `placeholder`  | `string`  | Placeholder text.                          |
| `initialValue` | `string`  | Pre-filled date as YYYY-MM-DD.             |
| `optional`     | `boolean` | Whether the field can be left empty.       |

The submitted value arrives in `event.values` as an ISO `YYYY-MM-DD` string. An `initialValue` that is not a valid `YYYY-MM-DD` date is dropped with a warning rather than forwarded, because Slack rejects a malformed `initial_date` by failing the whole modal.

## NumberInput

A numeric input. Renders a Slack `number_input` and an Adaptive Card `Input.Number` on Teams.

```typescript
NumberInput({
  id: "quantity",
  label: "Quantity",
  min: 1,
  max: 10,
})
```

| Property       | Type      | Description                                                                                                          |
| -------------- | --------- | -------------------------------------------------------------------------------------------------------------------- |
| `id`           | `string`  | Input ID, used as the key in event.values.                                                                           |
| `label`        | `string`  | Label displayed above the input.                                                                                     |
| `placeholder`  | `string`  | Placeholder text.                                                                                                    |
| `initialValue` | `number`  | Pre-filled value.                                                                                                    |
| `min`          | `number`  | Minimum accepted value.                                                                                              |
| `max`          | `number`  | Maximum accepted value.                                                                                              |
| `decimal`      | `boolean` | Allow decimal values. Enforced by Slack; Adaptive Cards has no decimal switch, so Teams accepts decimals either way. |
| `optional`     | `boolean` | Whether the field can be left empty.                                                                                 |

Values in `event.values` are always strings. Parse with `Number(...)` when you need a number.

## Select

Dropdown menu.

```typescript
Select({
  id: "priority",
  label: "Priority",
  placeholder: "Select priority",
  options: [
    SelectOption({ label: "High", value: "high", description: "Urgent tasks" }),
    SelectOption({ label: "Medium", value: "medium" }),
    SelectOption({ label: "Low", value: "low" }),
  ],
})
```

| Property         | Type                    | Description                                                                                      |
| ---------------- | ----------------------- | ------------------------------------------------------------------------------------------------ |
| `id`             | `string`                | Input ID, used as the key in event.values.                                                       |
| `label`          | `string`                | Label displayed above the select.                                                                |
| `placeholder`    | `string`                | Placeholder text.                                                                                |
| `initialOption`  | `string`                | Pre-selected option value.                                                                       |
| `optional`       | `boolean`               | Whether the field can be left empty.                                                             |
| `options`        | `SelectOptionElement[]` | Select options.                                                                                  |
| `dispatchAction` | `boolean`               | Dispatch onAction events when the selection changes in a Slack modal. Ignored by other adapters. |

## ExternalSelect

Dropdown that loads options dynamically from a handler as the user types. Slack-only. Pair with [`bot.onOptionsLoad`](/docs/api/chat#onoptionsload) to supply options. See [Modals → ExternalSelect](/docs/modals#externalselect) for a full example, grouped-options support, and Slack setup notes.

```typescript
ExternalSelect({
  id: "assignee",
  label: "Assignee",
  placeholder: "Search people",
  minQueryLength: 1,
  initialOption: { label: "Alice", value: "U123" },
})
```

| Property         | Type                               | Description                                                                                                                                                                                |
| ---------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`             | `string`                           | Input ID, used as the key in event.values.                                                                                                                                                 |
| `label`          | `string`                           | Label displayed above the select.                                                                                                                                                          |
| `placeholder`    | `string`                           | Placeholder text.                                                                                                                                                                          |
| `minQueryLength` | `number`                           | Minimum characters before the loader fires (Slack default: 3).                                                                                                                             |
| `initialOption`  | `{ label: string, value: string }` | Pre-selected option when the modal opens. Unlike static Select where initialOption is a value string, ExternalSelect needs the full label/value object because the loader has not run yet. |
| `optional`       | `boolean`                          | Whether the field can be left empty.                                                                                                                                                       |

The loader registered via `bot.onOptionsLoad("assignee", handler)` returns either a flat `SelectOptionElement[]` or `OptionsLoadGroup[]` (`{ label, options }[]`) for grouped options.

## RadioSelect

Radio button group for mutually exclusive choices.

```typescript
RadioSelect({
  id: "status",
  label: "Status",
  options: [
    SelectOption({ label: "Open", value: "open" }),
    SelectOption({ label: "Closed", value: "closed" }),
  ],
})
```

Same props as `Select` (except `placeholder`).

## SelectOption

An option used inside `Select` and `RadioSelect`.

```typescript
SelectOption({ label: "High", value: "high", description: "Urgent tasks" })
```

| Property      | Type     | Description                                 |
| ------------- | -------- | ------------------------------------------- |
| `label`       | `string` | Display text.                               |
| `value`       | `string` | Value sent in event.values when selected.   |
| `description` | `string` | Optional description shown below the label. |

## ModalChild types

The `children` array in `Modal` accepts these element types:

| Type                 | Created by                        |
| -------------------- | --------------------------------- |
| `TextInputElement`   | `TextInput()`                     |
| `DateInputElement`   | `DateInput()`                     |
| `NumberInputElement` | `NumberInput()`                   |
| `SelectElement`      | `Select()`                        |
| `RadioSelectElement` | `RadioSelect()`                   |
| `TextElement`        | `Text()`, for static text content |
| `FieldsElement`      | `Fields()`, for key-value display |

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: PostableMessage
description: The union type accepted by thread.post() for sending messages.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/posting-messages
  - /docs/streaming
  - /docs/cards
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`PostableMessage` is the union of all message formats accepted by `thread.post()` and `sent.edit()`.

```typescript
type PostableMessage =
  | AdapterPostableMessage
  | AsyncIterable<string | StreamChunk | StreamEvent>
  | PostableObject;
```

`PostableObject` covers `Plan` (mutable task lists) and `StreamingPlan` (streams with platform-specific options). Both are documented below.

## String

Raw text passed through as-is to the platform.

```typescript
await thread.post("Hello world");
```

## PostableRaw

Explicit raw text. Behaves the same as a plain string.

```typescript
await thread.post({ raw: "Hello world" });
```

| Property      | Type                   | Description                                                                                                    |
| ------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| `raw`         | `string`               | Text passed through as-is to the platform.                                                                     |
| `attachments` | `Attachment[]`         | Typed media attachments for adapters that support outgoing attachments.                                        |
| `files`       | `FileUpload[]`         | Files to upload.                                                                                               |
| `aiGenerated` | `boolean \| undefined` | Mark the message as AI-generated. Adapters with a native AI label (currently Teams) show it; others ignore it. |

## PostableMarkdown

Markdown converted to each platform's native format.

```typescript
await thread.post({ markdown: "**Bold** and _italic_" });
```

| Property      | Type                   | Description                                                                                                    |
| ------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| `markdown`    | `string`               | Markdown text, converted to platform format via mdast.                                                         |
| `attachments` | `Attachment[]`         | Typed media attachments for adapters that support outgoing attachments.                                        |
| `files`       | `FileUpload[]`         | Files to upload.                                                                                               |
| `aiGenerated` | `boolean \| undefined` | Mark the message as AI-generated. Adapters with a native AI label (currently Teams) show it; others ignore it. |

## PostableAst

mdast AST converted to each platform's native format. See [Markdown](/docs/api/markdown) for builder functions.

```typescript
import { root, paragraph, text, strong } from "chat";

await thread.post({
  ast: root([paragraph([strong([text("Hello")])])]),
});
```

| Property      | Type                   | Description                                                                                                    |
| ------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| `ast`         | `Root`                 | mdast AST root node.                                                                                           |
| `attachments` | `Attachment[]`         | Typed media attachments for adapters that support outgoing attachments.                                        |
| `files`       | `FileUpload[]`         | Files to upload.                                                                                               |
| `aiGenerated` | `boolean \| undefined` | Mark the message as AI-generated. Adapters with a native AI label (currently Teams) show it; others ignore it. |

## PostableCard

Rich card with interactive elements. See [Cards](/docs/api/cards) for components.

```typescript
import { Card, Text } from "chat";

await thread.post(Card({ title: "Hello", children: [Text("World")] }));
```

You can also pass a card with explicit fallback text:

```typescript
await thread.post({
  card: Card({ title: "Hello", children: [Text("World")] }),
  fallbackText: "Hello — World",
});
```

| Property       | Type                   | Description                                                                                                    |
| -------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| `card`         | `CardElement`          | Rich card element.                                                                                             |
| `fallbackText` | `string \| undefined`  | Plain text fallback for clients that cannot render cards.                                                      |
| `files`        | `FileUpload[]`         | Files to upload.                                                                                               |
| `aiGenerated`  | `boolean \| undefined` | Mark the message as AI-generated. Adapters with a native AI label (currently Teams) show it; others ignore it. |

## Plan

A `Plan` is a step-by-step task list that mutates after posting. Each `addTask` / `updateTask` / `complete` call re-renders the same message in place. See [Plan API](/docs/streaming#plan-api) for full usage.

```typescript
import { Plan } from "chat";

const plan = new Plan({ initialMessage: "Researching options..." });
await thread.post(plan);
await plan.addTask({ title: "Look up records" });
await plan.complete({ completeMessage: "Done!" });
```

Adapters that don't support `PostableObject` editing render the plan as fallback text and ignore subsequent mutations.

## StreamingPlan

Wraps an async iterable with platform-specific streaming options. Use this when you need to pass options like task grouping or stop blocks through `thread.post()`. See [Streaming with options](/docs/streaming#streaming-with-options).

```typescript
import { StreamingPlan } from "chat";

const planned = new StreamingPlan(stream, {
  groupTasks: "plan",
  endWith: [feedbackBlock],
  updateIntervalMs: 750,
});

await thread.post(planned);
```

| Property           | Type                                | Description                                                                                                       |
| ------------------ | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `groupTasks`       | `"plan" \| "timeline" \| undefined` | Slack: render task\_update chunks as \`"plan"\` (single grouped block) or \`"timeline"\` (inline cards, default). |
| `endWith`          | `unknown[] \| undefined`            | Slack: Block Kit elements appended when the stream stops (e.g. retry / feedback buttons).                         |
| `updateIntervalMs` | `number \| undefined`               | Post+edit adapters: minimum interval between update cycles in ms.                                                 |

## AsyncIterable (streaming)

An async iterable of strings, `StreamChunk` objects, or stream events. The SDK streams the message in real time using platform-native APIs where available.

You can yield structured `StreamChunk` objects for rich content like task progress cards on platforms that support it (Slack). See [Streaming](/docs/streaming#structured-streaming-chunks) for details.

Both AI SDK stream types and TanStack AI streams are supported:

```typescript
// fullStream (recommended): preserves step boundaries in multi-step agents
const result = await agent.stream({ prompt: message.text });
await thread.post(result.fullStream);

// textStream: plain string chunks
await thread.post(result.textStream);

// TanStack AI: the stream returned by chat()
await thread.post(chat({ adapter, messages }));
```

When using `fullStream`, the SDK auto-detects `text-delta` and `finish-step` events, extracting text and inserting paragraph breaks between agent steps. AG-UI `TEXT_MESSAGE_CONTENT` and `TEXT_MESSAGE_END` events from TanStack AI are handled the same way: deltas become text and each message end becomes a paragraph break between tool-loop turns.

## FileUpload

Used in the `files` field of any structured message format.

| Property   | Type                            | Description                                         |
| ---------- | ------------------------------- | --------------------------------------------------- |
| `data`     | `Buffer \| Blob \| ArrayBuffer` | Binary file data.                                   |
| `filename` | `string`                        | Filename.                                           |
| `mimeType` | `string \| undefined`           | MIME type (inferred from filename if not provided). |

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Thread
description: Represents a conversation thread with methods for posting, subscribing, and state management.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/threads-messages-channels
  - /docs/posting-messages
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

A `Thread` represents a conversation thread on any platform. Event handlers receive one, and you can also create thread handles with `chat.thread()` or `chat.openDM()`.

## Properties

| Property         | Type        | Description                                          |
| ---------------- | ----------- | ---------------------------------------------------- |
| `id`             | `string`    | Full thread ID in \`adapter:channel:thread\` format. |
| `channelId`      | `string`    | Channel or conversation ID.                          |
| `adapter`        | `Adapter`   | The platform adapter this thread belongs to.         |
| `isDM`           | `boolean`   | Whether this is a direct message conversation.       |
| `channel`        | `Channel`   | The \`Channel\` containing this thread.              |
| `recentMessages` | `Message[]` | Cached messages from the webhook payload.            |

## post

Post a message to the thread. Accepts strings, structured messages, cards, streams, and `PostableObject` instances (`Plan`, `StreamingPlan`).

```typescript
// Plain text
await thread.post("Hello!");

// Markdown
await thread.post({ markdown: "**Bold** text" });

// AST
await thread.post({ ast: root([paragraph([text("Hello")])]) });

// Card
await thread.post(Card({ title: "Hi", children: [Text("Hello")] }));

// Stream (AI SDK fullStream recommended for multi-step agents)
// TanStack AI chat() streams are also accepted
await thread.post(result.fullStream);

// Plan (mutable task list)
const plan = new Plan({ initialMessage: "Working..." });
await thread.post(plan);
await plan.addTask({ title: "Step 1" });

// Streaming with platform options
await thread.post(new StreamingPlan(stream, { groupTasks: "plan" }));
```

**Parameters:** `message: string | PostableMessage | ChatElement`

`ChatElement` covers card and modal elements, whether you write them in JSX or build them with functions such as `Card()`.

**Returns:** `Promise<SentMessage | PostableObject>`. Plain messages and streams return a `SentMessage` with `edit()`, `delete()`, `addReaction()`, and `removeReaction()` methods. `Plan` and `StreamingPlan` inputs return the same object so you can keep mutating it.

See [Posting Messages](/docs/posting-messages) for details on each format.

## reply

Post a message with a native reference to another message.

```typescript
await thread.reply(message, {
  markdown: "Thanks, I can help with that.",
});
```

**Parameters:** `target: string | Message`, `message: string | AdapterPostableMessage | AsyncIterable<string | StreamChunk | StreamEvent> | ChatElement`

**Returns:** `Promise<SentMessage>`

The target `Message` must belong to the same thread. Streams are buffered before sending. Unlike `post()`, `reply()` does not accept `Plan` or `StreamingPlan`. Adapters without native message reply support throw `NotImplementedError`.

Prefer passing the `Message` over its ID. The `Message` is checked against this thread and carried through to `SentMessage.replyTo` and cached thread history. A bare ID is only resolved to a `Message` when the thread already holds it in `recentMessages`; otherwise the reply is still sent, but `replyTo` is left undefined.

## postEphemeral

Post a message visible only to a specific user.

```typescript
await thread.postEphemeral(userId, "Only you can see this", {
  fallbackToDM: true,
});
```

| Property               | Type                                    | Description                                                                               |
| ---------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------- |
| `user`                 | `string \| Author`                      | User ID string or Author object.                                                          |
| `message`              | `AdapterPostableMessage \| ChatElement` | Message content. Streams are not supported.                                               |
| `options.fallbackToDM` | `boolean`                               | If true, falls back to DM when native ephemeral is not supported. If false, returns null. |

**Returns:** `Promise<EphemeralMessage | null>`

## schedule

Schedule a message for future delivery. Only the Slack adapter supports this. Other adapters throw `NotImplementedError`.

```typescript
const scheduled = await thread.schedule("Reminder: standup in 5 minutes!", {
  postAt: new Date("2026-03-09T09:00:00Z"),
});

// Cancel before it's sent
await scheduled.cancel();
```

**Parameters:** `message: AdapterPostableMessage | ChatElement`, `options: { postAt: Date }`

**Returns:** `Promise<ScheduledMessage>`

> Streaming and file uploads are not supported in scheduled messages.

## getParticipants

Get the unique human participants in a thread. Returns deduplicated authors and excludes all bots. Use it to subscribe only to 1:1 conversations and unsubscribe when others join.

```typescript
const participants = await thread.getParticipants();

// Subscribe only when one person is talking to the bot
if (participants.length === 1) {
  await thread.subscribe();
}

// Unsubscribe when the thread becomes a group conversation
if (participants.length > 1) {
  await thread.unsubscribe();
}
```

> Each call fetches the full message history to find all participants, which takes multiple platform API calls on threads with long history. Consider checking `message.author` against a known set before calling `getParticipants()` on every incoming message.

## subscribe / unsubscribe

Manage thread subscriptions. Subscribed non-DM threads route all messages to `onSubscribedMessage` handlers. DM threads route to `onDirectMessage` first when a direct message handler is registered.

```typescript
await thread.subscribe();
await thread.unsubscribe();
const subscribed = await thread.isSubscribed();
```

Subscriptions persist across restarts through your state adapter.

## state

Store typed, per-thread state that persists across requests. State has a 30-day TTL.

```typescript
// Read state
const state = await thread.state; // TState | null

// Merge into existing state
await thread.setState({ aiMode: true });

// Replace state entirely
await thread.setState({ aiMode: false }, { replace: true });
```

## startTyping

Show a typing indicator in the thread. No-op on platforms that don't support
it. With Slack Agent messaging, calling this without a custom status sets the
session to `processing` and identifies the initiating user. Slack's native stop
button also requires the `agent_session_stopped` event subscription.

A custom status uses the legacy `assistant.threads.setStatus` compatibility
bridge for loading labels instead. That endpoint cannot receive the initiating
user, and an existing native processing indicator can take precedence over the
label. Use the default indicator when you need native session behavior.

```typescript
await thread.startTyping();

// With custom status (Slack only)
await thread.startTyping("Searching documents...");
```

## signal

An `AbortSignal` for the active turn. Slack aborts it when the user clicks the
native agent-session stop button, including when the stop webhook reaches a
different serverless instance sharing the same state adapter.

Pass it to model and tool APIs so cancellation stops upstream work:

```typescript
const result = await agent.stream({
  prompt: message.text,
  abortSignal: thread.signal,
});
await thread.post(result.fullStream);
```

Threads created outside an incoming handler expose a signal that remains
unaborted.

## markAsRead

Mark an inbound message as read. WhatsApp, Messenger, and XChat support this capability. Other adapters throw `NotImplementedError`.

Inside a message handler, omit the argument to mark the current message:

```typescript
bot.onDirectMessage(async (thread) => {
  await thread.markAsRead();
});
```

Pass a `Message` or message ID when targeting a message explicitly:

```typescript
await thread.markAsRead(message);
await thread.markAsRead(message.id);
```

A `Message` must belong to the thread, and passing one from another thread throws. A bare message ID is sent to the adapter as given, since there is nothing to check it against. Calling `markAsRead()` without an argument outside a message handler throws because there is no current message.

Platforms may advance the conversation's read state through the target message, which also marks earlier messages as read.

## messages / allMessages

Iterate through message history.

```typescript
// Newest first (auto-paginates)
for await (const msg of thread.messages) {
  console.log(msg.text);
}

// Oldest first (auto-paginates)
for await (const msg of thread.allMessages) {
  console.log(msg.text);
}
```

## refresh

Re-fetch messages from the API and update `recentMessages`.

```typescript
await thread.refresh();
```

## mentionUser

Get a platform-specific @-mention string for a user.

```typescript
await thread.post(`Hey ${thread.mentionUser(userId)}, check this out!`);
```

## Serialization

Threads can be serialized for workflow engines and external systems. The serialized thread includes the current message if one is available.

```typescript
// Serialize
const json = thread.toJSON();

// Pass to a workflow
await workflow.start("my-workflow", {
  thread: thread.toJSON(),
});
```

The serialized format includes the thread ID, channel ID, adapter name, DM status, and the current message when present.

### Deserialization

Use `bot.reviver()` as a `JSON.parse` reviver to automatically restore `Thread` and `Message` objects from serialized payloads:

```typescript
const data = JSON.parse(payload, bot.reviver());
await data.thread.post("Hello from workflow!");
```

The reviver calls `ThreadImpl.fromJSON()` and `Message.fromJSON()` for any serialized objects it encounters.

When a restored thread starts streaming, it uses its Chat instance's `fallbackStreamingPlaceholderText` and `streamingUpdateIntervalMs` defaults. `bot.reviver()` binds restored threads to that bot; standalone and Workflow deserialization bind to the registered singleton on first runtime access. These settings are not stored in the serialized payload, so resumed work uses the receiving bot's configuration. An explicit `StreamingPlan` update interval still takes precedence.

If you pass an adapter directly to `ThreadImpl.fromJSON(data, adapter)`, streaming can work without a registered Chat instance, using the default settings. Streaming defaults come only from a Chat instance that has that exact adapter registered, under any key. If the registered instance doesn't own the adapter, state still comes from the registered singleton, as in earlier versions. Prefer `bot.reviver()` to bind ownership explicitly.

## ScheduledMessage

Returned by `thread.schedule()` and `channel.schedule()`.

| Property             | Type                  | Description                                     |
| -------------------- | --------------------- | ----------------------------------------------- |
| `scheduledMessageId` | `string`              | Platform-specific scheduled message ID.         |
| `channelId`          | `string`              | Channel ID where the message will be posted.    |
| `postAt`             | `Date`                | When the message will be sent.                  |
| `raw`                | `unknown`             | Platform-specific raw response.                 |
| `cancel()`           | `() => Promise<void>` | Cancel the scheduled message before it is sent. |

## SentMessage

Returned by `thread.post()`. Extends `Message` with mutation methods.

| Property                | Type                                                                          | Description                          |
| ----------------------- | ----------------------------------------------------------------------------- | ------------------------------------ |
| `edit(newContent)`      | `(content: string \| PostableMessage \| ChatElement) => Promise<SentMessage>` | Edit this message.                   |
| `delete()`              | `() => Promise<void>`                                                         | Delete this message.                 |
| `addReaction(emoji)`    | `(emoji: EmojiValue \| string) => Promise<void>`                              | Add a reaction to this message.      |
| `removeReaction(emoji)` | `(emoji: EmojiValue \| string) => Promise<void>`                              | Remove a reaction from this message. |

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Transcripts (deprecated)
description: Configuration, methods, and entry shape for the deprecated cross-platform per-user transcript API.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: reference
related:
  - /docs/history
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

> `bot.transcripts` and the `transcripts` config key are deprecated. Use [`bot.history.user`](/docs/api/history#bothistoryuser) and the `history.user` config key instead. The API surface is identical. `bot.transcripts` will continue to work in the current major version.

`bot.transcripts` provides per-user message persistence keyed by a stable cross-platform identifier. See the [History guide](/docs/history) for setup, usage patterns, and migration steps.

```typescript
import { Chat } from "chat";
```

## Configuration

`history.user` (or the deprecated `transcripts`) requires an identity resolver. Set `history.user.identity` or the deprecated top-level `identity` field. Passing `history.user` without either throws at construction.

### ChatConfig.transcripts (deprecated → history.user)

| Property         | Type                                    | Description                                                                                                                    |
| ---------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `retention`      | `number \| DurationString \| undefined` | List TTL, refreshed on every append. Accepts milliseconds or a duration string ("45s", "30m", "6h", "7d"). Omit for no expiry. |
| `maxPerUser`     | `number \| false`                       | Hard cap per user. Older entries are evicted on append. Set \`false\` for no cap.                                              |
| `storeFormatted` | `boolean`                               | Persist the mdast \`formatted\` field alongside \`text\`. Off by default to keep storage small.                                |

### ChatConfig.identity

```typescript
identity: (context: IdentityContext) => string | null | Promise<string | null>;
```

Called once per inbound message during dispatch. The result is attached to the `Message` instance as `message.userKey`. Return `null` to skip persistence for an event.

#### IdentityContext

| Property  | Type      | Description                             |
| --------- | --------- | --------------------------------------- |
| `adapter` | `string`  | Adapter name (e.g. "slack", "discord"). |
| `author`  | `Author`  | Message author info.                    |
| `message` | `Message` | The inbound message.                    |

## Methods

Access via `bot.history.user` (preferred) or `bot.transcripts` (deprecated alias). Throws if neither `history.user` nor `transcripts` was configured on the `Chat` instance.

### append

Persist a `Message` (typically the inbound user message) or an `AppendInput` (typically a bot reply you just posted).

```typescript
append(
  thread: Postable,
  message: Message | AppendInput,
  options?: AppendOptions,
): Promise<TranscriptEntry | null>;
```

When `message` is a `Message`, `userKey` is read from the instance. If it's `undefined` (the resolver returned `null`), the call is a no-op and returns `null`. When `message` is an `AppendInput`, `options.userKey` is required.

#### AppendInput

| Property            | Type                                | Description                                                                  |
| ------------------- | ----------------------------------- | ---------------------------------------------------------------------------- |
| `role`              | `"user" \| "assistant" \| "system"` | Role tag for the entry.                                                      |
| `text`              | `string`                            | Plain-text body.                                                             |
| `formatted`         | `FormattedContent \| undefined`     | Optional mdast AST. Only stored when \`transcripts.storeFormatted\` is true. |
| `platformMessageId` | `string \| undefined`               | Platform-native message ID, when known.                                      |

#### AppendOptions

| Property  | Type                  | Description                                                                                                  |
| --------- | --------------------- | ------------------------------------------------------------------------------------------------------------ |
| `userKey` | `string \| undefined` | Required when appending an \`AppendInput\` (assistant or system role); ignored when appending a \`Message\`. |

### list

Returns entries in chronological order (oldest first). When `limit` is set, returns the newest `N` entries, still in chronological order.

```typescript
list(query: ListQuery): Promise<TranscriptEntry[]>;
```

#### ListQuery

| Property    | Type                                                 | Description                                                                                                            |
| ----------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `userKey`   | `string`                                             | Cross-platform user key.                                                                                               |
| `limit`     | `number`                                             | Maximum entries returned. Cannot exceed the stored entry count. \`maxPerUser\` limits storage unless set to \`false\`. |
| `platforms` | `string[] \| undefined`                              | Filter to a subset of adapter names.                                                                                   |
| `threadId`  | `string \| undefined`                                | Filter to a single thread.                                                                                             |
| `roles`     | `("user" \| "assistant" \| "system")[] \| undefined` | Filter to specific roles.                                                                                              |

### count

```typescript
count(query: CountQuery): Promise<number>;
```

Returns the total number of entries stored under the user key. `CountQuery` has a single field, `userKey: string`.

### delete

```typescript
delete(target: { userKey: string }): Promise<{ deleted: number }>;
```

Wipes every entry stored under the user key. Returns the count that was removed. Single-entry and time-range deletes are not supported, because the underlying `appendToList` primitive can't support them safely under concurrent writes.

## TranscriptEntry

Returned by `append` and `list`.

| Property            | Type                                | Description                                                          |
| ------------------- | ----------------------------------- | -------------------------------------------------------------------- |
| `id`                | `string`                            | UUID assigned by the SDK at append time.                             |
| `userKey`           | `string`                            | Cross-platform user key from the IdentityResolver.                   |
| `role`              | `"user" \| "assistant" \| "system"` | Role tag.                                                            |
| `text`              | `string`                            | Plain-text body. Use this field when building prompts.               |
| `formatted`         | `FormattedContent \| undefined`     | mdast AST. Only present when \`transcripts.storeFormatted\` is true. |
| `platform`          | `string`                            | Originating adapter name.                                            |
| `threadId`          | `string`                            | Originating thread ID.                                               |
| `platformMessageId` | `string \| undefined`               | Platform-native message ID, when known.                              |
| `timestamp`         | `number`                            | Milliseconds since epoch, set at append time on the SDK side.        |

## Storage

Backed by `StateAdapter.appendToList` / `getList` / `delete`. Every built-in state adapter (`memory`, `redis`, `ioredis`, `pg`) supports these primitives.

Entries are stored under `transcripts:user:{userKey}` as a capped list. `appendToList` is atomic, so concurrent inbound messages don't race.

The `retention` value is applied as the list TTL and refreshed on every append. With `retention: "30d"`, a user who hasn't talked to the bot in 30 days has their transcript expire automatically.

## See also

- [History API reference](/docs/api/history): the current API (`bot.history.user`, `bot.history.thread`, `bot.history.channel`)
- [History guide](/docs/history): setup, patterns, and migration

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Building an adapter
description: Learn how to build your own Chat SDK adapter for any messaging platform.
docs_index: /llms.txt
lastUpdated: 2026-10-30
type: guide
prerequisites:
  - /docs/getting-started
  - /docs/adapters
related:
  - /docs/contributing/testing
  - /docs/contributing/publishing
  - /docs/contributing/vendor-official
  - /docs/cards
  - /docs/actions
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Build your adapter as its own npm package. It implements the `Adapter` interface for your platform, converts messages between Chat SDK's Markdown AST and the platform's format, and exports a factory function such as `createMatrixAdapter`.

## What adapters are

An adapter connects Chat SDK to one messaging platform. It handles webhook verification, message parsing, and API calls for that platform so your handler code stays platform-agnostic.

Chat SDK ships with Vercel-maintained [official adapters](/adapters). Anyone can build an adapter for another platform with the same `Adapter` interface and publish it as a [community](/docs/contributing/publishing#listing-on-chat-sdkdev) or [vendor-official](/docs/contributing/vendor-official) adapter.

### Adapter tiers

| Tier            | Description                                  | Examples                   |
| --------------- | -------------------------------------------- | -------------------------- |
| Official        | Published under `@chat-adapter/*` by Vercel  | Slack, Teams, Discord      |
| Vendor-official | Built and maintained by the platform company | Resend, Liveblocks, Photon |
| Community       | Built by third-party developers              | Any open-source adapter    |

This guide covers the implementation. After you publish, [list a community adapter on chat-sdk.dev](/docs/contributing/publishing#listing-on-chat-sdkdev), or follow the [vendor-official guide](/docs/contributing/vendor-official) if you represent the platform vendor.

> The `@chat-adapter/` npm scope is reserved for official adapters. Publish your adapter under your own scope or as an unscoped package.

## Project setup

This guide uses a hypothetical Matrix adapter as a running example. Replace "matrix" with your platform name throughout. `YOUR_PUBLISHED_ADAPTER_PACKAGE` is a placeholder, not an npm package to install. Replace it with a valid package name you own before publishing.

### package.json

```json title="package.json" lineNumbers
{
  "name": "YOUR_PUBLISHED_ADAPTER_PACKAGE",
  "version": "0.1.0",
  "description": "Matrix adapter for Chat SDK",
  "type": "module",
  "main": "./dist/index.js",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    }
  },
  "files": ["dist"],
  "scripts": {
    "build": "tsup",
    "dev": "tsup --watch",
    "test": "vitest run --coverage",
    "test:watch": "vitest",
    "typecheck": "tsc --noEmit",
    "clean": "rm -rf dist"
  },
  "peerDependencies": {
    "chat": "^4.0.0"
  },
  "dependencies": {
    "@chat-adapter/shared": "^4.0.0"
  },
  "devDependencies": {
    "@types/node": "^22.0.0",
    "chat": "^4.0.0",
    "tsup": "^8.3.0",
    "typescript": "^5.7.0",
    "vitest": "^4.0.0"
  },
  "publishConfig": {
    "access": "public"
  },
  "keywords": ["chat-sdk", "chat-adapter", "matrix"],
  "license": "MIT"
}
```

Key points:

- The package is ESM-only (`"type": "module"`).
- `chat` is a peer dependency because your adapter runs inside the consumer's `Chat` instance.
- `@chat-adapter/shared` provides error classes and utility functions.

### tsup.config.ts

```typescript title="tsup.config.ts" lineNumbers
import { defineConfig } from "tsup";

export default defineConfig({
  entry: ["src/index.ts"],
  format: ["esm"],
  dts: true,
  clean: true,
  sourcemap: true,
});
```

### tsconfig.json

```json title="tsconfig.json" lineNumbers
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "declaration": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "strictNullChecks": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "**/*.test.ts"]
}
```

### vitest.config.ts

```typescript title="vitest.config.ts" lineNumbers
import { defineProject } from "vitest/config";

export default defineProject({
  test: {
    globals: true,
    environment: "node",
    coverage: {
      provider: "v8",
      reporter: ["text", "json-summary"],
      include: ["src/**/*.ts"],
      exclude: ["src/**/*.test.ts"],
    },
  },
});
```

## Define your types

Start by defining the platform-specific types your adapter needs.

```typescript title="src/types.ts" lineNumbers
/** Decoded thread ID components for Matrix */
export interface MatrixThreadId {
  /** Matrix room ID (e.g., "!abc123:matrix.org") */
  roomId: string;
  /** Matrix event ID for the thread root (e.g., "$event123") */
  eventId?: string;
}

/** Configuration for the Matrix adapter */
export interface MatrixAdapterConfig {
  /** Matrix homeserver URL */
  homeserverUrl: string;
  /** Access token for the bot account */
  accessToken: string;
  /** Optional bot display name override */
  userName?: string;
}
```

Every adapter needs two interfaces:

- A thread ID interface that describes the decoded components of your `{adapter}:{segment1}:{segment2}` thread ID.
- A config interface for the credentials and options needed to connect to the platform.

## Implement the Adapter interface

Create an adapter class that implements the `Adapter` interface from `chat`. Start with the class skeleton and constructor, then add each group of methods below.

```typescript title="src/adapter.ts" lineNumbers
import {
  extractCard,
  extractFiles,
  toBuffer,
  ValidationError,
} from "@chat-adapter/shared";
import type {
  Adapter,
  AdapterPostableMessage,
  ChatInstance,
  EmojiValue,
  FetchOptions,
  FetchResult,
  FormattedContent,
  Logger,
  RawMessage,
  ThreadInfo,
  WebhookOptions,
} from "chat";
import { ConsoleLogger, Message } from "chat";
import { MatrixFormatConverter } from "./format-converter";
import type { MatrixAdapterConfig, MatrixThreadId } from "./types";

export class MatrixAdapter implements Adapter<MatrixThreadId, unknown> {
  readonly name = "matrix";
  readonly userName: string;
  readonly botUserId?: string;

  private chat: ChatInstance | null = null;
  private logger: Logger;
  private config: MatrixAdapterConfig;
  private converter = new MatrixFormatConverter();

  constructor(config: MatrixAdapterConfig & { logger?: Logger }) {
    this.config = config;
    this.userName = config.userName ?? "matrix-bot";
    this.logger = config.logger ?? new ConsoleLogger();
  }

  // Methods shown in sections below...
}
```

The `Adapter` interface takes two generics: `TThreadId` (your decoded thread ID shape) and `TRawMessage` (the platform's raw message type).

### Initialization

The SDK calls `initialize` once when the `Chat` instance is created. Use it to store the `ChatInstance` reference, set up your logger, validate credentials, and fetch bot info.

```typescript title="src/adapter.ts"
async initialize(chat: ChatInstance): Promise<void> {
  this.chat = chat;
  this.logger = chat.getLogger("matrix");

  // Validate credentials, fetch bot user info, etc.
  // Example: const me = await this.apiCall("/account/whoami");
  // this.botUserId = me.user_id;
}
```

### Disconnect

The optional `disconnect()` method is called during `chat.shutdown()` to clean up resources. Use it to close persistent connections, tear down subscriptions, or release any platform-specific resources.

```typescript title="src/adapter.ts"
async disconnect(): Promise<void> {
  // Close WebSocket connections, clean up subscriptions, etc.
  // Example: await this.matrixClient.stop();
}
```

Adapters that don't hold persistent connections can skip this method entirely.

### Thread ID encode/decode

Thread IDs typically follow the pattern `{adapter}:{segment1}:{segment2}`, though some adapters use more or fewer segments. The `encodeThreadId` and `decodeThreadId` methods must roundtrip consistently. Use `base64url` encoding for segments that contain special characters. `channelIdFromThreadId` returns the channel portion of a thread ID, which the SDK uses for channel-level operations such as `thread.channel`.

```typescript title="src/adapter.ts" lineNumbers
encodeThreadId(data: MatrixThreadId): string {
  const roomSegment = Buffer.from(data.roomId).toString("base64url");
  if (data.eventId) {
    const eventSegment = Buffer.from(data.eventId).toString("base64url");
    return `matrix:${roomSegment}:${eventSegment}`;
  }
  return `matrix:${roomSegment}`;
}

decodeThreadId(threadId: string): MatrixThreadId {
  const parts = threadId.split(":");
  if (parts.length < 2 || parts[0] !== "matrix") {
    throw new ValidationError(`Invalid Matrix thread ID: ${threadId}`);
  }
  const roomId = Buffer.from(parts[1], "base64url").toString();
  const eventId = parts[2]
    ? Buffer.from(parts[2], "base64url").toString()
    : undefined;
  return { roomId, eventId };
}

channelIdFromThreadId(threadId: string): string {
  const [adapter, roomSegment] = threadId.split(":");
  return `${adapter}:${roomSegment}`;
}
```

### Webhook handling

`handleWebhook` is the entry point for all incoming platform events. Always:

1. Verify the request signature first, and return 401 if it's invalid.
2. Parse the platform payload.
3. Call `this.chat.processMessage()` with positional args. It handles `waitUntil` internally.
4. Return a 200 response immediately.

Polling transports should await the promises returned by `processMessage`, `processAction`, `processSlashCommand` and `processReaction` before acknowledging input. These promises reject on handler failure; the default `waitUntil` task still logs and absorbs errors for webhook responses. A transport that owns deduplication and recovery, such as Telegram polling, can pass `{ deduplicate: false }` to `processMessage` to bypass the core message deduplication cache. Leave deduplication enabled for ordinary webhook delivery.

```typescript title="src/adapter.ts" lineNumbers
async handleWebhook(
  request: Request,
  options?: WebhookOptions
): Promise<Response> {
  // 1. Verify request signature
  const signature = request.headers.get("x-matrix-signature");
  if (!signature) {
    return new Response("Missing signature", { status: 401 });
  }

  const body = await request.text();
  const isValid = this.verifySignature(body, signature);
  if (!isValid) {
    return new Response("Invalid signature", { status: 401 });
  }

  // 2. Parse the webhook payload
  const payload = JSON.parse(body);

  // 3. Process the message asynchronously
  if (this.chat && payload.type === "m.room.message") {
    const threadId = this.encodeThreadId({
      roomId: payload.room_id,
      eventId: payload.thread_root_id,
    });

    // Use a factory function for lazy async parsing
    const isMention = this.checkMention(payload);
    const factory = async (): Promise<Message<unknown>> => {
      const msg = this.parseMessage(payload);
      if (isMention) {
        msg.isMention = true;
      }
      return msg;
    };

    // processMessage handles waitUntil registration internally
    this.chat.processMessage(this, threadId, factory, options);
  }

  // 4. Return a fast 200 to acknowledge receipt
  return new Response("OK", { status: 200 });
}
```

### Message parsing

Convert the raw platform message into a normalized `Message` instance. The `author` fields use `userId` and `userName`, and `isBot` accepts `boolean | "unknown"`. Include a `metadata` object with `dateSent` and `edited` instead of a top-level `createdAt`.

Set `author.isMe` only when the message was sent by this adapter runtime and should be ignored by Chat SDK's handler dispatch. Do not map a platform "sent from my account" flag directly to `isMe` unless that account is the bot identity. For user-owned account adapters, keep user-authored messages as `isMe: false` and track message IDs returned by `postMessage`; if the platform echoes one of those IDs through the webhook, mark that echo as `isMe: true` and `isBot: true`.

Set `isMention` only when the adapter can decide it from the platform's own metadata. Chat SDK uses the value as the mention decision: `true` and `false` are final, and only `undefined` makes it fall back to matching `@username` in `text`. Leave the field unset when the adapter has no mention information instead of reporting `false`. The one exception is direct messages: when no `onDirectMessage` handler is registered, Chat SDK marks every DM as a mention regardless of what the adapter reported.

```typescript title="src/adapter.ts" lineNumbers
parseMessage(raw: unknown): Message<unknown> {
  const payload = raw as Record<string, unknown>;

  return new Message({
    id: payload.event_id as string,
    threadId: this.encodeThreadId({
      roomId: payload.room_id as string,
      eventId: payload.thread_root_id as string | undefined,
    }),
    ...this.converter.parseIncoming(payload.body as string),
    raw,
    author: {
      userId: payload.sender as string,
      userName: payload.sender as string,
      fullName: payload.sender_display_name as string ?? "",
      isBot: (payload.sender as string).startsWith("@bot"),
      isMe: false,
    },
    metadata: {
      dateSent: new Date(payload.origin_server_ts as number),
      edited: false,
    },
    attachments: [],
  });
}
```

#### `isBotMention`

Apps that route, acknowledge, or forward webhook events before a Chat SDK bot handles them need the same mention decision without an adapter instance. When a platform can notify the bot for a reference that is not an invocation, such as a bot token inside code, export `isBotMention` so those apps do not reimplement it:

```typescript
export function isBotMention(event: PlatformEvent, botUserId: string): boolean;
```

- **Same decision as `isMention`.** It returns `true` exactly when `parseMessage` would set `isMention: true` for that event. Implement both from one function so they cannot diverge.
- **Raw inbound event.** `event` is the platform's own event object, the same value as the `raw` field of a payload from the adapter's webhook parser. `botUserId` is the bot's own platform user ID.
- **Runtime-free entry point.** Export it from the adapter's low-level webhook subpath, such as `@chat-adapter/slack/webhook`, so routers can import it without loading the adapter. The package root may re-export it.

The [Slack adapter](https://github.com/vercel/chat/blob/main/packages/adapter-slack/src/mention.ts) implements this contract.

### Sending messages

Use `extractCard()` and `extractFiles()` from `@chat-adapter/shared` to check for rich content. Use `extractPostableAttachments()` if your adapter maps normalized `Attachment` objects to platform-native media uploads. Use your format converter's `renderPostable()` to convert the message to platform format.

```typescript title="src/adapter.ts" lineNumbers
async postMessage(
  threadId: string,
  message: AdapterPostableMessage
): Promise<RawMessage<unknown>> {
  const { roomId, eventId } = this.decodeThreadId(threadId);

  const card = extractCard(message);
  const files = extractFiles(message);

  // Upload files if present
  for (const file of files) {
    const buffer = await toBuffer(file.data);
    // Upload to Matrix media repo...
  }

  // Render text content
  const text = card
    ? this.converter.renderPostable({ card: message.card })
    : this.converter.renderPostable(message);

  const response = await this.sendMatrixMessage(roomId, text, eventId);
  return { raw: response, id: response.event_id };
}

async editMessage(
  threadId: string,
  messageId: string,
  message: AdapterPostableMessage
): Promise<RawMessage<unknown>> {
  const { roomId } = this.decodeThreadId(threadId);
  const text = this.converter.renderPostable(message);
  const response = await this.editMatrixMessage(roomId, messageId, text);
  return { raw: response, id: response.event_id };
}

async deleteMessage(threadId: string, messageId: string): Promise<void> {
  const { roomId } = this.decodeThreadId(threadId);
  await this.redactMatrixEvent(roomId, messageId);
}
```

### Buttons and callback URLs

When the host app passes a `Card` with `<Button callbackUrl={...}>`, the SDK rewrites each of those buttons before your adapter sees the postable. It stores the `callbackUrl` in the state adapter under a short token and replaces the button's `value` with `__cb:<16-hex-chars>`, which is 21 characters in total. Your adapter doesn't need to handle this case separately. It only has to round-trip `button.value` through your platform's button payload.

In practice, that means two things:

1. On the send side, when you render a `ButtonElement` to your platform's button payload, encode both `button.id` (the action ID) and `button.value` (which may be `undefined`, a user-supplied value, or a callback token). Pick a delimiter that cannot appear in either, and validate the encoded string fits the platform's limit.
2. On the receive side, when the user clicks a button, decode the platform payload back into `actionId` and `value`, and pass them to `chat.processAction({ actionId, value, ... })`. The SDK detects the `__cb:` prefix, looks up the stored callback URL, POSTs to it, and passes the original value, if there is one, to your `onAction` handlers.

The Discord adapter is a good reference. It joins the action ID and value with `\n` and validates the result against Discord's 100-character `custom_id` limit:

```typescript title="src/cards.ts (discord)" lineNumbers
const DISCORD_CUSTOM_ID_DELIMITER = "\n";
const DISCORD_CUSTOM_ID_MAX_LENGTH = 100;

export function encodeDiscordCustomId(
  actionId: string,
  value?: string
): string {
  if (value == null || value === "") {
    validateLength(actionId);
    return actionId;
  }
  const encoded = `${actionId}${DISCORD_CUSTOM_ID_DELIMITER}${value}`;
  validateLength(encoded);
  return encoded;
}

export function decodeDiscordCustomId(customId: string): {
  actionId: string;
  value: string | undefined;
} {
  const idx = customId.indexOf(DISCORD_CUSTOM_ID_DELIMITER);
  if (idx === -1) {
    return { actionId: customId, value: undefined };
  }
  // Use the FIRST delimiter only, because values may legitimately contain "\n".
  return {
    actionId: customId.slice(0, idx),
    value: customId.slice(idx + 1),
  };
}
```

> Platform button-data limits are the main constraint to plan for. Discord's
> `custom_id` is 100 chars; Telegram's `callback_data` is 64 bytes. The SDK's
> callback token is fixed at 21 chars (`__cb:` + 16 hex), so the worst-case
> payload your encoding must fit is `actionId + delimiter + 21`. If the
> encoded string exceeds the platform limit, throw a `ValidationError` from
> `@chat-adapter/shared` so the host app fails fast at post time rather than
> silently truncating.

The SDK handles modals with `callbackUrl` entirely through stored modal context, so your adapter needs no special handling. Call `chat.processModalSubmit(event, contextId, { waitUntil })` from your webhook handler, and the SDK POSTs to the modal's `callbackUrl`. If you provide `waitUntil`, the SDK uses it so the POST doesn't block the response.

### Reactions

Handle both `EmojiValue` objects and plain strings. `EmojiValue` has a `name` property and a `toString()` method, but no `unicode` field.

```typescript title="src/adapter.ts" lineNumbers
async addReaction(
  threadId: string,
  messageId: string,
  emoji: EmojiValue | string
): Promise<void> {
  const { roomId } = this.decodeThreadId(threadId);
  const emojiStr = typeof emoji === "string" ? emoji : emoji.name;
  await this.sendReaction(roomId, messageId, emojiStr);
}

async removeReaction(
  threadId: string,
  messageId: string,
  emoji: EmojiValue | string
): Promise<void> {
  const { roomId } = this.decodeThreadId(threadId);
  const emojiStr = typeof emoji === "string" ? emoji : emoji.name;
  await this.removeMatrixReaction(roomId, messageId, emojiStr);
}
```

### Fetching and typing

`fetchMessages` should return messages in chronological order (oldest first). The `nextCursor` enables pagination.

```typescript title="src/adapter.ts" lineNumbers
async fetchMessages(
  threadId: string,
  options?: FetchOptions
): Promise<FetchResult<unknown>> {
  const { roomId } = this.decodeThreadId(threadId);
  // Fetch from platform API with pagination
  return { messages: [], nextCursor: undefined };
}

async fetchThread(threadId: string): Promise<ThreadInfo> {
  const { roomId } = this.decodeThreadId(threadId);
  return {
    id: threadId,
    title: undefined,
    createdAt: new Date(),
  };
}

async startTyping(threadId: string): Promise<void> {
  const { roomId } = this.decodeThreadId(threadId);
  // Send typing notification via platform API
}
```

### Formatting

Delegate to your format converter (covered in the next section).

```typescript title="src/adapter.ts"
renderFormatted(content: FormattedContent): string {
  return this.converter.fromAst(content.ast);
}
```

## Build a format converter

Each adapter needs a format converter that translates between the platform's text format and mdast (Markdown AST), the canonical format used by Chat SDK.

```typescript title="src/format-converter.ts" lineNumbers
import {
  BaseFormatConverter,
  type Root,
  parseMarkdown,
  stringifyMarkdown,
  text,
  strong,
  emphasis,
  inlineCode,
  codeBlock,
  link,
  paragraph,
  root,
} from "chat";
import type { AdapterPostableMessage } from "chat";

export class MatrixFormatConverter extends BaseFormatConverter {
  /**
   * Convert platform text to mdast AST.
   * If your platform uses standard markdown, just use parseMarkdown().
   */
  toAst(platformText: string): Root {
    // Matrix supports standard markdown, so we can parse directly
    return parseMarkdown(platformText);
  }

  /**
   * Convert mdast AST to platform text format.
   * Walk the AST and produce platform-specific markup.
   */
  fromAst(ast: Root): string {
    // Matrix supports standard markdown, so we can stringify directly
    return stringifyMarkdown(ast);
  }

  /**
   * Override renderPostable only if your platform needs custom rendering
   * (e.g., converting @mentions to platform-specific syntax).
   * The base class already handles text/formatted/card fallback logic.
   */
  renderPostable(message: AdapterPostableMessage): string {
    // Example: convert @mention syntax to Matrix pill format
    const rendered = super.renderPostable(message);
    return rendered.replace(
      /@(\w+)/g,
      (_, name) => `<a href="https://matrix.to/#/@${name}:matrix.org">@${name}</a>`
    );
  }
}
```

For platforms with non-standard formatting, implement custom parsing in `toAst()` and rendering in `fromAst()`. See the [Discord adapter](https://github.com/vercel/chat/blob/main/packages/adapter-discord/src/markdown.ts) for an example of handling platform-specific mention syntax.

Use `parseIncoming()` to build a message's `text` and `formatted` fields from incoming platform text, including messages fetched from history. It calls `toAst()` once and derives the plain text from that AST. Some inputs are slow to parse or produce trees too deep to serialize, so before parsing, `parseIncoming()` checks the text against these limits in linear time. Characters inside top-level fenced code blocks don't count toward the limits, since markdown isn't parsed there.

| Limit                                                                                                    | Default           | Protected field               |
| -------------------------------------------------------------------------------------------------------- | ----------------- | ----------------------------- |
| Text length                                                                                              | 16,384 characters | `maxIncomingParseLength`      |
| `*`, `_`, and `~` characters                                                                             | 2,048             | `maxIncomingEmphasisMarkers`  |
| `]` characters                                                                                           | 128               | `maxIncomingClosingBrackets`  |
| `<` characters                                                                                           | 512               | `maxIncomingAngleBrackets`    |
| `www.` links in one word                                                                                 | 8                 | `maxIncomingWwwAutolinks`     |
| Nesting on one line: blockquote, list, and footnote markers plus half the columns of leading indentation | 32                | `maxIncomingContainerMarkers` |

When text exceeds a limit, `parseIncoming()` skips `toAst()` and keeps the text verbatim in a single unformatted text node. It does the same after parsing when the tree is deeper than `maxIncomingAstDepth` (128 levels), or when `toAst()` throws a `RangeError`, such as a stack overflow. Other errors from `toAst()` propagate. Override these fields in your converter if your platform needs different limits, and call `parseIncoming()` rather than `toAst()` for any text that users write.

The checks run on the text passed to `parseIncoming()`. If your `toAst()` rewrites platform text before parsing it, for example by decoding HTML entities, override `exceedsIncomingBudget()` to check the rewritten text instead. If your platform text carries markup that shouldn't reach users unparsed, such as entities or mention tokens, override `incomingFallbackText()` to clean up the text kept on fallback. Both run on input that may be too costly to parse, so keep them linear. When one message arrives as several parts that you parse separately, check the parts together with `exceedsIncomingBudget()` so their combined size stays within the limits.

## Optional methods

These methods are optional. Implement them to support more Chat SDK features:

| Method                                        | Purpose                                                                                                      |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `disconnect()`                                | Clean up connections and resources during shutdown                                                           |
| `getConcurrencyScope()`                       | Scope message deduplication, locks, queues, concurrency limits, and cancellation to the authenticated tenant |
| `openDM(userId)`                              | Open a direct message conversation                                                                           |
| `isDM(threadId)`                              | Check if a thread is a DM                                                                                    |
| `stream(threadId, textStream)`                | Stream AI responses in real-time                                                                             |
| `openModal(triggerId, modal)`                 | Open a modal/dialog form                                                                                     |
| `postEphemeral(threadId, userId, message)`    | Post a message visible to one user                                                                           |
| `postChannelMessage(channelId, message)`      | Post a top-level message (not in a thread)                                                                   |
| `onThreadSubscribe(threadId)`                 | Hook for platform-specific subscription setup                                                                |
| `fetchChannelInfo(channelId)`                 | Fetch channel metadata                                                                                       |
| `listThreads(channelId)`                      | List threads in a channel                                                                                    |
| `fetchMessage(threadId, messageId)`           | Fetch a single message by ID                                                                                 |
| `fetchChannelMessages(channelId)`             | Fetch top-level channel messages                                                                             |
| `scheduleMessage(threadId, message, options)` | Schedule a message for future delivery; return a `ScheduledMessage` with `cancel()`                          |

Implement only the methods your platform supports. The SDK handles adapters that leave optional methods out.

For multi-tenant adapters whose conversation IDs can overlap, implement `getConcurrencyScope(): string | undefined`. Return a stable, non-secret scope from the authenticated installation context. Base it on the credential boundary: if one installation serves several workspaces with the same credentials, use one scope for all of them, since each entry point may report a different workspace for the same conversation. The same scope must be available during message handling and `abortTurn()` calls, including across processes. Never derive it from the message author's workspace or store credentials in it.

Returning `undefined` preserves unscoped keys for single-tenant adapters. If tenant context is required but unavailable, throw rather than silently using unscoped keys. This hook does not change public conversation IDs or scope subscriptions, thread state, or history.

## Factory function

Export a factory function that creates your adapter with environment variable fallbacks:

```typescript title="src/factory.ts" lineNumbers
import { ConsoleLogger } from "chat";
import type { Logger } from "chat";
import { ValidationError } from "@chat-adapter/shared";
import { MatrixAdapter } from "./adapter";
import type { MatrixAdapterConfig } from "./types";

export function createMatrixAdapter(
  config?: Partial<MatrixAdapterConfig> & { logger?: Logger }
): MatrixAdapter {
  const homeserverUrl =
    config?.homeserverUrl ?? process.env.MATRIX_HOMESERVER_URL;
  const accessToken =
    config?.accessToken ?? process.env.MATRIX_ACCESS_TOKEN;

  if (!homeserverUrl) {
    throw new ValidationError(
      "Matrix homeserver URL is required. Pass it in config or set MATRIX_HOMESERVER_URL."
    );
  }
  if (!accessToken) {
    throw new ValidationError(
      "Matrix access token is required. Pass it in config or set MATRIX_ACCESS_TOKEN."
    );
  }

  return new MatrixAdapter({
    homeserverUrl,
    accessToken,
    userName: config?.userName,
    logger: config?.logger,
  });
}
```

Then export both the class and factory from your entry point:

```typescript title="src/index.ts" lineNumbers
export { MatrixAdapter } from "./adapter";
export { MatrixFormatConverter } from "./format-converter";
export { createMatrixAdapter } from "./factory";
export type { MatrixAdapterConfig, MatrixThreadId } from "./types";
```

## Shared utilities

Use the utilities in `@chat-adapter/shared` instead of reimplementing them:

### Error classes

```typescript
import {
  AdapterError,          // Base error class
  AdapterRateLimitError, // Platform rate limit hit
  AuthenticationError,   // Invalid credentials
  ResourceNotFoundError, // Thread/message not found
  PermissionError,       // Insufficient permissions
  ValidationError,       // Invalid input
  NetworkError,          // HTTP/connection failure
} from "@chat-adapter/shared";
```

Throw these errors from your adapter methods. The SDK catches and logs them with appropriate context.

### Message utilities

```typescript
import {
  extractCard,   // Extract CardElement from AdapterPostableMessage
  extractFiles,  // Extract FileUpload[] from AdapterPostableMessage
  toBuffer,      // Convert FileDataInput to Buffer (async)
  toBufferSync,  // Convert FileDataInput to Buffer (sync)
  cardToFallbackText, // Convert card to plain text
} from "@chat-adapter/shared";
```

### Token encryption

If your adapter persists OAuth tokens to a `StateAdapter`, encrypt them at rest with the shared AES-256-GCM helpers instead of rolling your own:

```typescript
import {
  encryptToken,         // Encrypt a string into an EncryptedTokenData envelope
  decryptToken,         // Decrypt an envelope back to the original string
  decodeKey,            // Decode a hex-64 or base64-44 32-byte key (throws on wrong length)
  isEncryptedTokenData, // Type guard for tolerating legacy plaintext records
  type EncryptedTokenData,
} from "@chat-adapter/shared";
```

Accept the key as an optional `encryptionKey` config field (auto-detected from a `*_ENCRYPTION_KEY` env var), encrypt on `setInstallation()`, decrypt on `getInstallation()`, and use `isEncryptedTokenData` to keep accepting plaintext records so operators can roll the key in without flushing existing installs. See `@chat-adapter/slack` and `@chat-adapter/linear` for reference implementations.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Documenting your adapter
description: Write a README, configuration reference, and usage examples for your adapter.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/contributing/building
  - /docs/contributing/testing
related:
  - /docs/contributing/publishing
  - /docs/contributing/vendor-official
  - /docs/adapters
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Your README is what developers see on npm and GitHub before they install your adapter. Vercel-maintained adapters all use the structure below, so following it lets developers find install steps, credentials, and limitations where they expect them. Community adapters should meet the same bar.

> The examples below describe a fictional Matrix adapter. `YOUR_PUBLISHED_ADAPTER_PACKAGE` is a placeholder, not a package to install. Replace it everywhere, including badges and imports, with the exact npm name of the adapter you own and have published. Verify the installation command and npm links before publishing your README.

## README structure

Your `README.md` should include these sections in order:

### Title and badges

Start with the package name as an H1, followed by npm badges and a one-line description.

```markdown title="README.md"
# YOUR_PUBLISHED_ADAPTER_PACKAGE

[![npm version](https://img.shields.io/npm/v/YOUR_PUBLISHED_ADAPTER_PACKAGE)](https://www.npmjs.com/package/YOUR_PUBLISHED_ADAPTER_PACKAGE)
[![npm downloads](https://img.shields.io/npm/dm/YOUR_PUBLISHED_ADAPTER_PACKAGE)](https://www.npmjs.com/package/YOUR_PUBLISHED_ADAPTER_PACKAGE)

Matrix adapter for [Chat SDK](https://chat-sdk.dev/docs).
```

### Installation

Show the install command with `chat` as a co-dependency.

````markdown title="README.md"
## Installation

```bash
npm install chat YOUR_PUBLISHED_ADAPTER_PACKAGE
```
````

### Quick start

Give a minimal working example that developers can copy. Call the factory function with explicit config so readers can see which credentials they need.

````markdown title="README.md"
## Usage

```typescript
import { Chat } from "chat";
import { createMatrixAdapter } from "YOUR_PUBLISHED_ADAPTER_PACKAGE";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    matrix: createMatrixAdapter({
      homeserverUrl: process.env.MATRIX_HOMESERVER_URL!,
      accessToken: process.env.MATRIX_ACCESS_TOKEN!,
    }),
  },
});

bot.onNewMention(async (thread, message) => {
  await thread.post("Hello from Matrix!");
});
```
````

### Environment variables

List every environment variable your adapter reads, with a description and example value.

```markdown title="README.md"
## Environment variables

| Variable | Required | Description |
|----------|----------|-------------|
| `MATRIX_HOMESERVER_URL` | Yes | Matrix homeserver URL (e.g., `https://matrix.example.com`) |
| `MATRIX_ACCESS_TOKEN` | Yes | Bot account access token |
| `MATRIX_BOT_USERNAME` | No | Override the bot display name |
```

### Configuration reference

Document every field in your config interface, including defaults.

```markdown title="README.md"
## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `homeserverUrl` | `string` | `MATRIX_HOMESERVER_URL` | Matrix homeserver URL |
| `accessToken` | `string` | `MATRIX_ACCESS_TOKEN` | Bot account access token |
| `userName` | `string` | `"matrix-bot"` | Bot display name |
| `logger` | `Logger` | `ConsoleLogger` | Custom logger instance |
```

### Platform setup

Walk through creating the bot account on the platform. Use numbered steps, link to the platform's developer portal, and call out where to find each credential.

```markdown title="README.md"
## Platform setup

1. Create a bot account on your Matrix homeserver
2. Generate an access token for the bot
3. Set the webhook URL to `https://your-domain.com/api/webhooks/matrix`
```

### Features

List what your adapter supports. Use a feature table if it helps. Call out any limitations.

```markdown title="README.md"
## Features

- Mentions and DMs
- Rich text (bold, italic, code, links)
- Reactions (add and remove)
- File uploads
- Typing indicators
- Thread support
```

### License

```markdown title="README.md"
## License

MIT
```

## Code-level documentation

### Exported types

Export your config and thread ID interfaces so consumers can use them in their own type annotations. The TypeScript declarations that `tsup` generates are the main API reference for your adapter, so write interface field comments that are useful in editor hover docs.

```typescript title="src/types.ts" lineNumbers
/** Configuration for the Matrix adapter */
export interface MatrixAdapterConfig {
  /** Matrix homeserver URL (e.g., "https://matrix.example.com") */
  homeserverUrl: string;
  /** Access token for the bot account */
  accessToken: string;
  /** Override the bot display name (default: "matrix-bot") */
  userName?: string;
}
```

> TSDoc comments on exported interfaces and functions appear in IDE tooltips and generated `.d.ts` files. Keep them concise and factual.

### What not to document

- Internal or private methods. They're implementation details.
- Types re-exported from `chat` or `@chat-adapter/shared`. Link to the upstream docs instead.
- Obvious behavior. `postMessage` posts a message and needs no further explanation.

## Sample messages file

Include a `sample-messages.md` file in your package root with real webhook payloads from the platform. Contributors use these payloads to reproduce and debug parser edge cases.

````markdown title="sample-messages.md"
# Matrix sample messages

## Text message

```json
{
  "type": "m.room.message",
  "room_id": "!abc123:matrix.org",
  "event_id": "$evt456",
  "sender": "@alice:matrix.org",
  "content": {
    "msgtype": "m.text",
    "body": "Hello world"
  },
  "origin_server_ts": 1700000000000
}
```

## Bot mention

```json
{
  "type": "m.room.message",
  "room_id": "!abc123:matrix.org",
  "event_id": "$evt789",
  "sender": "@alice:matrix.org",
  "content": {
    "msgtype": "m.text",
    "body": "@bot help me",
    "format": "org.matrix.custom.html",
    "formatted_body": "<a href=\"https://matrix.to/#/@bot:matrix.org\">bot</a> help me"
  },
  "origin_server_ts": 1700000001000
}
```
````

Vercel-maintained adapters include a `sample-messages.md` file in their package roots. Use those as a format reference.

## Checklist

Before publishing, verify your documentation covers:

- [ ] README with badges, install, quick start, env vars, config reference, platform setup
- [ ] TSDoc comments on all exported interfaces and factory functions
- [ ] `sample-messages.md` with real platform webhook payloads
- [ ] Links to Chat SDK docs (`chat-sdk.dev`) where relevant

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Publishing your adapter
description: Package, version, and publish your community Chat SDK adapter to npm.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/contributing/building
  - /docs/contributing/testing
  - /docs/contributing/documenting
related:
  - /docs/adapters
  - /docs/contributing/vendor-official
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Community adapters are published to npm under your own package name. After publishing, you can list your adapter on the chat-sdk.dev Adapters page.

## Package checklist

Before publishing, verify your `package.json` meets these requirements:

`YOUR_PUBLISHED_ADAPTER_PACKAGE` is a placeholder for your adapter's npm package name. Replace it with a valid name you own before publishing, and use that exact name in the post-publish verification commands. Do not install the placeholder or an unrelated package with a similar name.

```json title="package.json" lineNumbers
{
  "name": "YOUR_PUBLISHED_ADAPTER_PACKAGE",
  "version": "1.0.0",
  "type": "module",
  "main": "./dist/index.js",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    }
  },
  "files": ["dist"],
  "peerDependencies": {
    "chat": "^4.0.0"
  },
  "publishConfig": {
    "access": "public"
  },
  "keywords": ["chat-sdk", "chat-adapter", "matrix"],
  "license": "MIT"
}
```

| Field                | Why it matters                                                |
| -------------------- | ------------------------------------------------------------- |
| `"type": "module"`   | Publishes ESM only, matching the Chat SDK packages            |
| `"files": ["dist"]`  | Publishes only compiled output, which keeps the package small |
| `"exports"`          | Declares explicit entry points for bundlers and Node.js       |
| `"peerDependencies"` | Lets consumers provide their own `chat` instance              |
| `"publishConfig"`    | Required for scoped packages (`@your-scope/chat-adapter-*`)   |
| `"keywords"`         | Include `chat-sdk` and `chat-adapter` for npm discoverability |

## Naming conventions

| Convention | Pattern                             | When to use                                    |
| ---------- | ----------------------------------- | ---------------------------------------------- |
| Unscoped   | `chat-adapter-PLATFORM`             | A unique, available name for your adapter      |
| Scoped     | `@YOUR_SCOPE/chat-adapter-PLATFORM` | An adapter published under a scope you control |

Replace `PLATFORM` and `YOUR_SCOPE` with your own values. These are naming patterns, not packages to install. New npm package names must be lowercase; see [npm's package name rules](https://docs.npmjs.com/cli/v11/configuring-npm/package-json#name).

> The `@chat-adapter/` npm scope is reserved for Vercel-maintained adapters. Do not publish under this scope.

## Build and verify

Before publishing, build the package, type-check it, and run the tests.

```sh title="Terminal"
# Build
npm run build

# Type-check
npm run typecheck

# Run tests
npm test
```

Inspect the package contents to confirm that only `dist/` is included:

```sh title="Terminal"
npm pack --dry-run
```

You should see output like:

```
dist/index.js
dist/index.d.ts
dist/index.js.map
package.json
README.md
LICENSE
```

If you see `src/`, `node_modules/`, or test files in the output, update your `"files"` field or add a `.npmignore`.

## Versioning

Follow [semver](https://semver.org):

| Change                                              | Bump    | Example           |
| --------------------------------------------------- | ------- | ----------------- |
| Bug fix, internal refactor                          | `patch` | `1.0.0` → `1.0.1` |
| New feature, new export, new config option          | `minor` | `1.0.0` → `1.1.0` |
| Breaking change (removed export, changed signature) | `major` | `1.0.0` → `2.0.0` |

If a new Chat SDK major version changes your adapter's peer dependency range, bump your adapter's major version too.

## Publish to npm

```sh title="Terminal"
npm publish
```

For scoped packages published for the first time:

```sh title="Terminal"
npm publish --access public
```

## Peer dependency compatibility

Your adapter should declare `chat` as a peer dependency with a caret range:

```json
{
  "peerDependencies": {
    "chat": "^4.0.0"
  }
}
```

This means your adapter works with any `4.x` release. When the Chat SDK ships a new major version:

1. Test your adapter against the new version
2. Update the peer dependency range
3. Publish a new major version of your adapter

## Post-publish verification

After publishing, verify the package works for consumers:

```sh title="Terminal"
# Create a temp directory
mkdir /tmp/test-adapter && cd /tmp/test-adapter
npm init -y

# Install your adapter
npm install chat YOUR_PUBLISHED_ADAPTER_PACKAGE

# Verify the import works
node -e "import('YOUR_PUBLISHED_ADAPTER_PACKAGE').then(m => console.log(Object.keys(m)))"
```

You should see your exported symbols (`createMatrixAdapter`, `MatrixAdapter`, etc.).

## Keeping your adapter up to date

- Watch the [Chat SDK changelog](https://github.com/vercel/chat/releases) for new features and breaking changes.
- Run your test suite against new Chat SDK releases before they ship to catch compatibility issues early.
- When the `Adapter` interface adds new optional methods, consider implementing them to keep your adapter feature-complete.

## Listing on chat-sdk.dev

Community adapters can be listed on the [Adapters](https://chat-sdk.dev/adapters) page by opening a PR against the [Chat SDK repo](https://github.com/vercel/chat) that adds a docs page under `apps/docs/content/adapters/community/` and an entry in [`@chat-adapter/catalog`](/docs/adapter-catalog). Add the entry as `packages/catalog/src/adapters/community/my-adapter.ts` and register it in `COMMUNITY_ADAPTERS` in `packages/catalog/src/adapters/index.ts`. Your adapter's README is fetched from GitHub at build time and rendered on its dedicated page.

> Platform vendors should follow the [vendor-official guide](/docs/contributing/vendor-official) instead.

### Pin your README to a commit or tag

> The `readme` field must reference a specific commit SHA or tag, not a branch name like `main`.

The docs site re-renders on every deploy, so an unpinned `readme` would serve whatever is on your default branch at that moment, including edits made after the listing PR was reviewed. Pinning keeps the rendered content at the version we approved. To publish new README content, open a follow-up PR that bumps the ref.

```typescript title="packages/catalog/src/adapters/community/my-adapter.ts"
import type { CommunityAdapter } from "../../types";

export const myAdapter = {
  author: "your-github-org",
  description: "One-line summary of what the adapter connects to.",
  features: {
    postMessage: "yes",
    editMessage: "yes",
    streaming: { status: "partial", label: "Post+Edit" },
  },
  group: "community",
  name: "My Adapter",
  packageName: "YOUR_PUBLISHED_ADAPTER_PACKAGE",
  readme: "https://github.com/your-org/chat-adapter-my-thing/tree/v1.2.0",
  slug: "my-adapter",
  type: "platform",
} as const satisfies CommunityAdapter;
```

The `features` keys are listed in `PLATFORM_FEATURE_CATEGORIES` and `STATE_FEATURE_CATEGORIES` in `packages/catalog/src/features.ts`. Omitted keys render as unsupported.

Accepted `readme` formats:

| Format                | Example                                                     |
| --------------------- | ----------------------------------------------------------- |
| Repo root at a tag    | `https://github.com/owner/repo/tree/v1.0.0`                 |
| Repo root at a commit | `https://github.com/owner/repo/tree/abc1234...`             |
| Subpath in a monorepo | `https://github.com/owner/repo/tree/<ref>/packages/adapter` |

Unpinned refs, such as `tree/main` or a URL without `/tree/<ref>`, emit a build warning and are rejected during PR review.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Testing adapters
description: Write unit tests, integration tests, and replay tests for community Chat SDK adapters.
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/contributing/building
related:
  - /docs/adapters
  - /docs/testing
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Chat SDK adapters are the trust boundary between your application and a platform. High test coverage is expected: unit tests for every public method, and integration tests that wire up the full `Chat` → `Adapter` → handler pipeline.

All adapters in this repo use [vitest](https://vitest.dev) with `@vitest/coverage-v8`. Community adapters should follow the same convention.

> This page covers the hand-rolled patterns used inside this repo's `packages/`. If you're testing a bot or a custom adapter as a consumer of Chat SDK, use [`@chat-adapter/tests`](/docs/testing). It ships factories and Vitest matchers that cover most of these patterns in a few lines.

## Unit tests

### Factory function

Verify that the factory validates config, reads environment variables, and sets defaults.

```typescript title="src/factory.test.ts" lineNumbers
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { createMatrixAdapter } from "./factory";

describe("createMatrixAdapter", () => {
  const originalEnv = process.env;

  beforeEach(() => {
    process.env = { ...originalEnv };
  });

  afterEach(() => {
    process.env = originalEnv;
  });

  it("creates adapter from explicit config", () => {
    const adapter = createMatrixAdapter({
      homeserverUrl: "https://matrix.example.com",
      accessToken: "syt_test_token",
    });

    expect(adapter.name).toBe("matrix");
  });

  it("reads environment variables as fallback", () => {
    process.env.MATRIX_HOMESERVER_URL = "https://matrix.example.com";
    process.env.MATRIX_ACCESS_TOKEN = "syt_test_token";

    const adapter = createMatrixAdapter();
    expect(adapter.name).toBe("matrix");
  });

  it("throws when homeserver URL is missing", () => {
    expect(() => createMatrixAdapter({ accessToken: "tok" } as never))
      .toThrow("homeserver URL");
  });

  it("throws when access token is missing", () => {
    expect(() =>
      createMatrixAdapter({
        homeserverUrl: "https://matrix.example.com",
      } as never)
    ).toThrow("access token");
  });
});
```

### Thread ID encode/decode

Verify that `encodeThreadId` and `decodeThreadId` roundtrip consistently and reject invalid formats.

```typescript title="src/thread-id.test.ts" lineNumbers
import { describe, it, expect } from "vitest";
import { MatrixAdapter } from "./adapter";

const adapter = new MatrixAdapter({
  homeserverUrl: "https://matrix.example.com",
  accessToken: "syt_test_token",
});

describe("thread ID encoding", () => {
  it("roundtrips room-only thread ID", () => {
    const data = { roomId: "!abc123:matrix.org" };
    const encoded = adapter.encodeThreadId(data);
    const decoded = adapter.decodeThreadId(encoded);

    expect(decoded.roomId).toBe(data.roomId);
    expect(encoded).toMatch(/^matrix:/);
  });

  it("roundtrips thread ID with event", () => {
    const data = {
      roomId: "!abc123:matrix.org",
      eventId: "$event456",
    };
    const encoded = adapter.encodeThreadId(data);
    const decoded = adapter.decodeThreadId(encoded);

    expect(decoded.roomId).toBe(data.roomId);
    expect(decoded.eventId).toBe(data.eventId);
  });

  it("throws on invalid format", () => {
    expect(() => adapter.decodeThreadId("invalid")).toThrow();
    expect(() => adapter.decodeThreadId("slack:C123:ts")).toThrow();
  });
});
```

### Webhook signature verification

Test a missing signature header, an invalid signature, and a valid signature.

```typescript title="src/webhook.test.ts" lineNumbers
import { describe, it, expect } from "vitest";
import { MatrixAdapter } from "./adapter";

const adapter = new MatrixAdapter({
  homeserverUrl: "https://matrix.example.com",
  accessToken: "syt_test_token",
});

describe("handleWebhook", () => {
  it("returns 401 when signature header is missing", async () => {
    const request = new Request("https://example.com/webhook", {
      method: "POST",
      body: "{}",
    });

    const response = await adapter.handleWebhook(request);
    expect(response.status).toBe(401);
  });

  it("returns 401 when signature is invalid", async () => {
    const request = new Request("https://example.com/webhook", {
      method: "POST",
      headers: { "x-matrix-signature": "invalid" },
      body: "{}",
    });

    const response = await adapter.handleWebhook(request);
    expect(response.status).toBe(401);
  });

  it("returns 200 for valid signed request", async () => {
    const body = JSON.stringify({ type: "m.room.message" });
    const request = createSignedRequest(body); // Your signing helper

    const response = await adapter.handleWebhook(request);
    expect(response.status).toBe(200);
  });
});
```

### Message parsing

Cover the main message types: plain text, bot messages, DMs, edited messages, attachments, and formatted text.

```typescript title="src/parse-message.test.ts" lineNumbers
import { describe, it, expect } from "vitest";
import { MatrixAdapter } from "./adapter";

const adapter = new MatrixAdapter({
  homeserverUrl: "https://matrix.example.com",
  accessToken: "syt_test_token",
});

describe("parseMessage", () => {
  it("parses a plain text message", () => {
    const raw = {
      event_id: "$evt1",
      room_id: "!room1:matrix.org",
      body: "Hello world",
      sender: "@alice:matrix.org",
      sender_display_name: "Alice",
      origin_server_ts: 1700000000000,
    };

    const message = adapter.parseMessage(raw);
    expect(message.text).toBe("Hello world");
    expect(message.author.userId).toBe("@alice:matrix.org");
    expect(message.author.isBot).toBe(false);
  });

  it("detects bot messages", () => {
    const raw = {
      event_id: "$evt2",
      room_id: "!room1:matrix.org",
      body: "Automated response",
      sender: "@bot:matrix.org",
      origin_server_ts: 1700000000000,
    };

    const message = adapter.parseMessage(raw);
    expect(message.author.isBot).toBe(true);
  });
});
```

### Format converter

Test `toAst()` and `fromAst()` for each node type your platform supports, plus `renderPostable()` for all message variants.

```typescript title="src/format-converter.test.ts" lineNumbers
import { describe, it, expect } from "vitest";
import { MatrixFormatConverter } from "./format-converter";

const converter = new MatrixFormatConverter();

describe("MatrixFormatConverter", () => {
  describe("toAst", () => {
    it("parses plain text", () => {
      const ast = converter.toAst("Hello world");
      expect(ast.type).toBe("root");
    });

    it("parses bold text", () => {
      const ast = converter.toAst("**bold**");
      // Verify the AST contains a strong node
      const paragraph = ast.children[0];
      expect(paragraph.children[0].type).toBe("strong");
    });
  });

  describe("fromAst", () => {
    it("renders bold text", () => {
      const ast = converter.toAst("**bold**");
      const result = converter.fromAst(ast);
      expect(result).toContain("**bold**");
    });
  });

  describe("renderPostable", () => {
    it("renders plain text", () => {
      const result = converter.renderPostable({ text: "Hello" });
      expect(result).toBe("Hello");
    });

    it("renders card fallback", () => {
      const result = converter.renderPostable({
        card: {
          type: "card",
          title: "Test Card",
          children: [],
        },
      });
      expect(result).toContain("Test Card");
    });
  });
});
```

## Integration testing

Integration tests wire your adapter into a full `Chat` instance and verify end-to-end message handling.

### Test context factory

Create a factory that sets up the full test environment:

```typescript title="src/test-utils.ts" lineNumbers
import { Chat, type Message, type Thread, type ActionEvent, type ReactionEvent } from "chat";
import { createMemoryState } from "@chat-adapter/state-memory";
import { createMatrixAdapter } from "./factory";

interface CapturedMessages {
  mentionMessage: Message | null;
  mentionThread: Thread | null;
  followUpMessage: Message | null;
  followUpThread: Thread | null;
}

interface WaitUntilTracker {
  waitUntil: (task: Promise<unknown>) => void;
  waitForAll: () => Promise<void>;
}

function createWaitUntilTracker(): WaitUntilTracker {
  const tasks: Promise<unknown>[] = [];

  return {
    waitUntil: (task) => {
      tasks.push(task);
    },
    waitForAll: async () => {
      await Promise.all(tasks);
      tasks.length = 0;
    },
  };
}

export function createMatrixTestContext(handlers: {
  onMention?: (thread: Thread, message: Message) => void | Promise<void>;
  onSubscribed?: (thread: Thread, message: Message) => void | Promise<void>;
  onAction?: (event: ActionEvent) => void | Promise<void>;
  onReaction?: (event: ReactionEvent) => void | Promise<void>;
}) {
  const adapter = createMatrixAdapter({
    homeserverUrl: "https://matrix.example.com",
    accessToken: "syt_test_token",
  });

  const state = createMemoryState();
  const chat = new Chat({
    userName: "matrix-bot",
    adapters: { matrix: adapter },
    state,
    logger: "error",
  });

  const captured: CapturedMessages = {
    mentionMessage: null,
    mentionThread: null,
    followUpMessage: null,
    followUpThread: null,
  };

  if (handlers.onMention) {
    const handler = handlers.onMention;
    chat.onNewMention(async (thread, message) => {
      captured.mentionMessage = message;
      captured.mentionThread = thread;
      await handler(thread, message);
    });
  }

  if (handlers.onSubscribed) {
    const handler = handlers.onSubscribed;
    chat.onSubscribedMessage(async (thread, message) => {
      captured.followUpMessage = message;
      captured.followUpThread = thread;
      await handler(thread, message);
    });
  }

  if (handlers.onAction) {
    chat.onAction(handlers.onAction);
  }

  if (handlers.onReaction) {
    chat.onReaction(handlers.onReaction);
  }

  const tracker = createWaitUntilTracker();

  return {
    chat,
    adapter,
    state,
    tracker,
    captured,
    sendWebhook: async (fixture: unknown) => {
      const request = createSignedMatrixRequest(fixture); // Your signing helper
      await chat.webhooks.matrix(request, {
        waitUntil: tracker.waitUntil,
      });
      await tracker.waitForAll();
    },
  };
}

function createSignedMatrixRequest(payload: unknown): Request {
  const body = JSON.stringify(payload);
  // Add platform-specific signature headers
  return new Request("https://example.com/webhook/matrix", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-matrix-signature": computeSignature(body),
    },
    body,
  });
}

function computeSignature(body: string): string {
  // Platform-specific signature computation
  return "valid-signature";
}
```

### Writing integration tests

Use the test context to verify the full message flow:

```typescript title="src/integration.test.ts" lineNumbers
import { describe, it, expect } from "vitest";
import { createMatrixTestContext } from "./test-utils";

describe("Matrix adapter integration", () => {
  it("handles mention → subscribe → follow-up flow", async () => {
    const ctx = createMatrixTestContext({
      onMention: async (thread) => {
        await thread.subscribe();
        await thread.post("Got it!");
      },
      onSubscribed: async (thread, message) => {
        await thread.post(`Echo: ${message.text}`);
      },
    });

    // Send a mention
    await ctx.sendWebhook({
      type: "m.room.message",
      room_id: "!room1:matrix.org",
      event_id: "$evt1",
      body: "@bot hello",
      sender: "@alice:matrix.org",
      origin_server_ts: Date.now(),
    });

    expect(ctx.captured.mentionMessage).not.toBeNull();
    expect(ctx.captured.mentionMessage?.text).toBe("@bot hello");

    // Send a follow-up in the same thread
    await ctx.sendWebhook({
      type: "m.room.message",
      room_id: "!room1:matrix.org",
      thread_root_id: "$evt1",
      event_id: "$evt2",
      body: "follow up",
      sender: "@alice:matrix.org",
      origin_server_ts: Date.now(),
    });

    expect(ctx.captured.followUpMessage).not.toBeNull();
    expect(ctx.captured.followUpMessage?.text).toBe("follow up");
  });
});
```

## What to test end-to-end

Cover these flows in your integration tests:

| Flow                   | What to verify                                                                |
| ---------------------- | ----------------------------------------------------------------------------- |
| Mention                | Bot detects @mention, handler fires, `mentionMessage` is captured             |
| Subscribe + follow-up  | After `thread.subscribe()`, subsequent messages trigger `onSubscribedMessage` |
| Actions                | Button clicks fire `onAction` with correct action ID and user info            |
| Reactions              | Emoji reactions fire `onReaction` with correct emoji and message ID           |
| Self-message filtering | Messages from the bot itself are ignored                                      |
| DM flow                | Direct messages are detected and routed correctly                             |

## Recording and replay tests (advanced)

To debug production issues, you can record webhook interactions and replay them as test fixtures. The recording tooling lives in the Chat SDK repo's `examples/nextjs-chat` app, and the `pnpm recording:*` commands run from there.

1. Enable recording by setting `RECORDING_ENABLED=true` in your deployed environment. Recordings are tagged with the current git SHA.

2. Interact with the bot. Each message you send, button you click, and reaction you add is recorded.

3. Export the recordings:

```sh title="Terminal"
pnpm recording:list
pnpm recording:export session-<id>
```

4. Create test fixtures by extracting webhook payloads from the exported recording and saving them as JSON:

```json title="fixtures/replay/matrix-mention.json"
{
  "botName": "matrix-bot",
  "botUserId": "@bot:matrix.org",
  "mention": { "type": "m.room.message", "body": "@bot help", "..." : "..." },
  "followUp": { "type": "m.room.message", "body": "thanks", "..." : "..." }
}
```

5. Write replay tests that use the fixtures in your test context:

```typescript title="src/replay.test.ts" lineNumbers
import { describe, it, expect } from "vitest";
import fixture from "../fixtures/replay/matrix-mention.json";
import { createMatrixTestContext } from "./test-utils";

describe("replay: mention flow", () => {
  it("handles recorded mention interaction", async () => {
    const ctx = createMatrixTestContext({
      onMention: async (thread) => {
        await thread.subscribe();
      },
    });

    await ctx.sendWebhook(fixture.mention);
    expect(ctx.captured.mentionMessage).not.toBeNull();

    await ctx.sendWebhook(fixture.followUp);
    expect(ctx.captured.followUpMessage).not.toBeNull();
  });
});
```

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: List a vendor-official adapter
description: "Qualify for the vendor-official tier and add your adapter to the Chat SDK docs, @chat-adapter/catalog, create-chat-sdk, and eve.dev/integrations."
docs_index: /llms.txt
lastUpdated: 2026-10-27
type: guide
prerequisites:
  - /docs/contributing/building
  - /docs/contributing/publishing
related:
  - /docs/adapters
  - /docs/create-chat-sdk
  - /docs/contributing/documenting
  - /docs/vercel-connect
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

A vendor-official adapter is built and maintained by the company behind the platform or by the primary maintainer of that platform's API. You implement the same `Adapter` interface as a [community adapter](/docs/contributing/building). After Vercel accepts your listing, your adapter appears in:

- The [Adapters](/adapters) page under **Vendor Official**
- The [`@chat-adapter/catalog`](/docs/adapter-catalog) setup metadata
- [`create-chat-sdk`](/docs/create-chat-sdk)
- [eve.dev/integrations](https://eve.dev/integrations)

Browse current listings on the [Adapters](/adapters) page.

## Compare adapter tiers

|                                                      | Official               | Vendor-official               | Community                  |
| ---------------------------------------------------- | ---------------------- | ----------------------------- | -------------------------- |
| Maintainer                                           | Vercel                 | Platform vendor               | Third-party developers     |
| npm package                                          | `@chat-adapter/*`      | Your org scope or unscoped    | Your org scope or unscoped |
| Docs listing                                         | `/adapters/official/…` | `/adapters/vendor-official/…` | `/adapters/community/…`    |
| [eve.dev/integrations](https://eve.dev/integrations) | Yes                    | Yes                           | No                         |
| `@chat-adapter/catalog` setup metadata               | Yes                    | Yes                           | No                         |
| `create-chat-sdk`                                    | Yes                    | Yes                           | No                         |

All three tiers share the same interface. Developers install and register your adapter the same way they use any other adapter. Vendor-official adds stronger discoverability and a higher maintenance bar.

> The `@chat-adapter/` npm scope is reserved for Vercel-maintained official adapters. Publish under your own org scope or as an unscoped package.

## Check qualifications

Before you open a listing PR, confirm that you can meet all of these:

- You will continue to maintain the adapter
- The repo lives in an official vendor-owned GitHub organization
- Your primary product docs cover the adapter
- You have announced the adapter in a blog post, changelog, or on social media
- The adapter does not depend on platform APIs that are in private or closed beta
- The adapter accepts credentials as resolver functions, not only static strings

### Support non-static credentials

Credential fields in your adapter config must accept a function alongside a plain string, and the adapter must resolve it on each outbound API call rather than caching the result:

```typescript
accessToken: string | (() => string | Promise<string>);
```

This lets developers supply rotating, short-lived tokens from tools like [Vercel Connect](/docs/vercel-connect) instead of long-lived secrets. The official adapters that work with Vercel Connect follow this pattern; see the outbound fields in the [Vercel Connect adapter table](/docs/vercel-connect#adapter-support) for examples.

If you don't represent the platform vendor, [list as community](/docs/contributing/publishing#listing-on-chat-sdkdev) instead.

## Review listing terms

Meeting the qualifications does not guarantee acceptance. Vercel reviews each request and may decline a listing for any reason.

If Vercel lists your adapter, you own ongoing support:

- Keep the adapter compatible with current Chat SDK APIs and your platform's APIs
- Address bug reports promptly
- Support developers who use your adapter

Vercel may remove a vendor-official adapter from the docs, catalog, eve integrations, and `create-chat-sdk` at any time, without notice. Removal can follow lack of maintenance, security or support risk, or failure to meet the tier bar.

## Build and publish your package

Ship a published npm package before you ask for a listing. Follow the same guides as community adapters:

1. [Build an adapter](/docs/contributing/building)
2. [Test it](/docs/contributing/testing)
3. [Document it](/docs/contributing/documenting)
4. [Publish it](/docs/contributing/publishing)

Your listing PR must point at that published package and a GitHub README pinned to a commit or tag.

## Submit a listing PR

Open a pull request against [vercel/chat](https://github.com/vercel/chat). Copy an existing page from [`apps/docs/content/adapters/vendor-official/`](https://github.com/vercel/chat/tree/main/apps/docs/content/adapters/vendor-official) and replace the details with yours. Choose a short kebab-case slug that is not already taken.

Include all of the following in the PR:

1. **Docs page.** Add an MDX page under `apps/docs/content/adapters/vendor-official/` and register the slug in that folder's `meta.json`. Mark the page as vendor-official, set your company as the author, render the feature matrix with `<FeatureSupport />`, and add install and quick-start examples that match your published package and README.
2. **Catalog entry.** Add `packages/catalog/src/adapters/vendor-official/your-slug.ts` and register it in `ADAPTERS` in `packages/catalog/src/adapters/index.ts`. The entry drives the [Adapters](/adapters) listing, the feature matrix on your docs page, and setup UIs that read [`@chat-adapter/catalog`](/docs/adapter-catalog) without importing your package. Copy a similar vendor-official entry and fill in the package name, author, factory export, peer dependencies, environment variables, and `features` from your docs. Point `readme` at a pinned commit or tag, not a branch. See [Pin your README to a commit or tag](/docs/contributing/publishing#pin-your-readme-to-a-commit-or-tag).
3. **CLI scaffold.** Add a matching entry in `packages/create-chat-sdk/src/catalog/scaffold-spec.ts` so `create-chat-sdk` can generate a bot that uses your adapter. Match the factory call shape of a similar adapter. After merge, developers can pass `--adapter your_slug` or browse vendor-official adapters with `--vendor`.
4. **Test allowlists.** Update the lists in `packages/integration-tests` so CI recognizes the new docs page and package imports.
5. **Changeset.** Add a changeset that bumps `@chat-adapter/catalog` and `create-chat-sdk` (patch), with one line describing the addition.

## Prepare for review

Reviewers check that:

- You meet the qualifications above
- Install snippets, factory exports, and env vars match the published package and README
- The README link is pinned to a commit or tag
- Catalog peer dependencies match what the docs tell people to install
- Credential fields accept function-form values and are resolved per call
- The catalog entry matches the docs page, including the package name, author, and capabilities

## Keep the listing current

After merge, your adapter appears under **Vendor Official** on the [Adapters](/adapters) page, in the static catalog, on [eve.dev/integrations](https://eve.dev/integrations), and in `create-chat-sdk` when it fits the webhook-only scaffold.

When you change env vars, peer dependencies, or the factory API, open a follow-up PR that updates the docs page, catalog entry, and pinned README ref together.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)