Commit Graph

31 Commits

Author SHA1 Message Date
mdnanocom 270b1c2592 fix(gchat): accept endpointUrl as a direct-webhook JWT audience (#518)
## Summary

When a Google Chat app's connection setting **Authentication audience**
is set to **HTTP endpoint URL** (Google's recommended option for
HTTP-hosted apps that aren't behind Cloud Run IAM, see [Verify requests
from Google Chat][1]),
the bearer token Google sends is an OIDC ID token whose `aud` is the
endpoint URL — not the GCP project number.
The adapter previously only verified against `googleChatProjectNumber`,
so URL-audience tokens always failed with
`401 Unauthorized` and direct webhooks silently broke for any app
configured this way.

This change makes the adapter verify direct-webhook JWTs against
`googleChatProjectNumber` and/or `endpointUrl`, accepting either when
both are configured (handy for multi-env setups that mix the two modes).
The constructor's fail-closed check accepts an explicit `endpointUrl` as
a valid direct-webhook verifier alongside `googleChatProjectNumber`,
`pubsubAudience`, and `disableSignatureVerification`.

[1]:
https://developers.google.com/workspace/chat/verify-requests-from-chat

## Behavior

| Config | Direct-webhook `aud` accepted |
| ----------------------------------------------------------- |
--------------------------------- |
| `googleChatProjectNumber` only (current behavior) | project number |
| `endpointUrl` only (**new**) | endpoint URL |
| Both `googleChatProjectNumber` and `endpointUrl` (**new**) | either |
| Neither, no `pubsubAudience`, no `disableSignatureVerification` |
constructor throws (unchanged) |

### Security note

Auto-detected endpoint URLs (the value `handleWebhook` falls back to
from the incoming `request.url` when `endpointUrl` is not configured)
are intentionally **not** promoted to verifier status. Treating an
auto-detected URL as a valid audience would let any caller bypass
verification by hitting the bot at a URL of their choice.
A new `endpointUrlIsAudience` flag captures whether the caller
explicitly configured `endpointUrl`, and only that case enables
URL-based verification. A regression test guards this.

## Implementation

- `verifyBearerToken` accepts `string | string[]`
(`OAuth2Client.verifyIdToken`
  already supports both).
- `handleWebhook` builds `directAudiences = [projectNumber,
explicitEndpointUrl].filter(Boolean)` and passes a single string when
only one verifier is configured (to preserve the prior call shape) or an
array when both are.
- Docs updated in `apps/docs/content/adapters/official/google-chat.mdx`:
describe both authentication-audience modes and document `endpointUrl`
as an accepted verifier.
- Changeset: `@chat-adapter/gchat: patch`.

## Test plan

- [x] `pnpm --filter @chat-adapter/gchat test` — 250/250 pass (5 new
tests).
- [x] `pnpm typecheck` — 33/33 tasks pass.
- [x] `pnpm check` (Ultracite/Biome) clean.
- [x] `pnpm konsistent` clean.
- [x] Validated end-to-end against a real Google Chat app configured
with
"HTTP endpoint URL" as authentication audience: webhooks that previously
      401'd now verify and process correctly.

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-15 14:41:15 +10:00
Shkumbin Hasani 2338a66544 feat(whatsapp): add sendTemplate for pre-approved template messages (#588)
Closes #585

## Summary

Adds `sendTemplate()` to the WhatsApp adapter for sending pre-approved
[Message
Templates](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates)
— the only message type the Cloud API accepts outside the 24-hour
customer service window, and therefore required for business-initiated
conversations (notifications, reminders, re-engagement).

The inbound half already existed (`handleButtonResponse` dispatches
template quick-reply taps to `onAction` handlers); this completes the
outbound side. Notably, the package's `AGENTS.md` already documented
`sendTemplate` and `WhatsAppTemplateMessage` as part of the public
surface — this PR implements exactly that documented API.

## Changes

- **`sendTemplate(threadId, template)`** on `WhatsAppAdapter` — posts a
`type: "template"` payload through the existing `graphApiRequest` path
and returns a `RawMessage`, mirroring
`sendInteractiveMessage`/`sendSingleTextMessage`
- **Types**: `WhatsAppTemplateMessage`, `WhatsAppTemplateComponent`,
`WhatsAppTemplateParameter`, `WhatsAppTemplateButtonParameter` in
`types.ts`, modeled on the Cloud API template object (header/body/button
components; text, currency, date_time, and media parameters),
re-exported from the package entry point
- Templates are kept out of the `PostableMessage`/mdast pipeline —
they're sent by name + variable components, not free-form markdown, and
the adapter intentionally does not auto-substitute templates for
outbound text posts (per AGENTS.md)
- `openDM()` JSDoc now links to `sendTemplate` for the
business-initiated path

## Docs

- New "Template messages" section in the adapter README and
`apps/docs/content/adapters/official/whatsapp.mdx` with a usage example
- Added "Template messages" row to the README feature table
- Corrected the feature-matrix frontmatter labels: `cardFormat`
"WhatsApp templates" → "Interactive messages" and `fields` "Template
variables" → "Formatted text" — cards render as Cloud API interactive
messages (as the page body already states), and the old labels would now
wrongly imply cards go through the new template API

## Usage

```typescript
const threadId = await adapter.openDM("15551234567");

await adapter.sendTemplate(threadId, {
  name: "appointment_reminder",
  language: "en",
  components: [
    {
      type: "body",
      parameters: [{ type: "text", text: "Tomorrow at 2pm" }],
    },
  ],
});
```

## Testing

- 5 new tests in `index.test.ts` following the existing `fetch`-spy
pattern: payload shape (name/language/`to`), component pass-through
(body + URL button), empty-components omission, missing-message-ID
error, and invalid thread ID rejection
- `pnpm validate` (knip, check, typecheck, test, build) passes — 117/117
adapter tests green

Includes a `minor` changeset for `@chat-adapter/whatsapp`.

---------

Signed-off-by: dancer <josh@afterima.ge>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-13 21:50:06 +10:00
Ben Sabic 0f743c9b33 feat(slack): support native Slack agents (#698)
Builds on the Agent messaging experience support from #684 with a
declarative config layer for building Slack agents, plus hardening for
native streaming.

Everything is configured on `createSlackAdapter()` — no per-event wiring
required.

## Slack adapter (`@chat-adapter/slack`)

### `suggestedPrompts`

Static payload or per-thread resolver, applied automatically when an
assistant/agent thread opens:

- `assistant_thread_started` (legacy `assistant_view`), with the
thread's `thread_ts`
- Messages-tab `app_home_opened` (with `agentView` enabled), without
`thread_ts` so prompts pin atop the agent conversation

The resolver receives the thread context (`channelId`, `userId`, legacy
`threadTs`/`teamId`/`enterpriseId`, and normalized active-view
`entities` under `agentView`); returning `null`/`undefined` skips the
thread. Prompts beyond Slack's 4-prompt limit are dropped with a
warning. Resolver/API failures are logged, never a webhook 500. Applied
via `waitUntil` inside the request scope so multi-workspace token
context propagates.

### `loadingMessages`

Default rotating status strings for the assistant thinking indicator,
used by `startTyping` and `setAssistantStatus` when no explicit
status/messages are passed.

### `nativeStreaming` + automatic post-and-edit fallback

- New `nativeStreaming` config (default `true`). Set `false` on Slack
flavours without the `chat.startStream` family (e.g., GovSlack) to
always stream via post-and-edit.
- If the workspace rejects the **first** native streaming call,
`stream()` falls back to throttled post-and-edit mid-stream instead of
failing the reply; already-consumed text is preserved (it lives in the
renderer). Permanent platform errors (`unknown_method`,
`method_deprecated`, `feature_not_enabled`) latch native streaming off
for subsequent streams on the adapter instance; transient errors don't
latch.
- Structured chunks (`task_update`/`plan_update`) are skipped in
fallback mode; failures after native content has rendered still
propagate (mixing surfaces would duplicate output).
- Also updates the stale streaming description in the package AGENTS.md
(the adapter now streams via
`chat.startStream`/`appendStream`/`stopStream`, not `chat.update`).

### `feedbackButtons`

Appends Slack's native thumbs up/down (a `context_actions` block with a
`feedback_buttons` element) to every streamed reply on
`chat.stopStream`, after any `StreamingPlan` `endWith` blocks. Pass
`true` for defaults or an options object (`actionId`, labels, values).
Clicks dispatch through the regular `block_actions` flow to
`bot.onAction` with a positive/negative value — no new plumbing. Exports
`buildFeedbackButtonsBlock(options?)` for attaching the same block to
non-streamed messages.

New exported types: `SlackFeedbackButtonsOptions`,
`SlackSuggestedPrompt`, `SlackSuggestedPrompts`,
`SlackSuggestedPromptsContext`, `SlackSuggestedPromptsOptions`.

## Docs

- Configuration table rows for `agentView`, `suggestedPrompts`,
`loadingMessages`, `nativeStreaming`, `feedbackButtons`.
- New "Native streaming" and "Feedback buttons" sections plus
declarative suggested-prompts examples.
- All agent content grouped under a new **Advanced → Agents** subsection
(Agent messaging experience → Assistants API → Native streaming →
Feedback buttons). Heading titles unchanged, so existing anchors keep
resolving.
- TypeTable descriptions rewritten as plain text (they don't render
markdown).

## Example app (`examples/nextjs-chat`)

- `SLACK_AGENT_OPTIONS` shared across both Slack adapter branches:
active-view-aware `suggestedPrompts` resolver, `loadingMessages`,
`feedbackButtons` with an `ai_feedback` acknowledgment handler.
- Env toggles: `SLACK_AGENT_VIEW` (agent_view mode) and
`SLACK_NATIVE_STREAMING` (compare native vs post-and-edit).
- Commented `agent_view` blocks in `slack-manifest.yml` (feature block,
`assistant:write` scope, agent events) with a note that the switch is
irreversible.
- AI flows call `startTyping()` without an explicit status so configured
loading messages rotate.

## Test plan

- `pnpm validate` and `pnpm konsistent` pass.
- 26 new unit tests: suggested prompts
(static/resolver/agent_view/truncation/error paths), loading message
defaults, native streaming fallback (opt-out, mid-stream fallback,
permanent-error latching, transient non-latching, propagation after
native render, structured-chunk skipping), feedback buttons (block
shape, custom options, ordering after `endWith`, webhook round-trip of a
click).
- Each adapter commit was built and verified independently (typecheck +
full suite green at every step) for bisectability.
- Verified manually against a live `agent_view` workspace: prompts
pinned on thread open, loading messages rotating in the thinking
indicator, native token-by-token streaming in DMs and channel threads,
post-and-edit fallback via the opt-out flag, and feedback clicks
dispatching to `onAction`.

## Notes

- One changeset covers the three adapter features (`minor` for
`@chat-adapter/slack`).
- Known follow-up (not in this PR): under `agentView`, a subscribed
conversation-scoped DM thread (the #684 openDM bridge) routes DM
messages to a thread without `thread_ts`, which silently pins DMs to
post-and-edit. Worth deciding whether the bridge should keep per-message
threading for replies or log loudly when it redirects.

## Screenshots

| Suggested Prompts | Feedback Buttons |
| --- | --- |
| <img width="647" height="347" alt="CleanShot 2026-07-13 at 13 26 27"
src="https://github.com/user-attachments/assets/4c89932b-ed19-4b4a-83ae-d3d022d0c120"
/> | <img width="825" height="276" alt="CleanShot 2026-07-13 at 13 28
23"
src="https://github.com/user-attachments/assets/6bdf6979-5209-4bed-b0bc-dfbee7165455"
/> |

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-13 12:27:25 +01:00
Dima Grossman 8bd8a57518 feat(whatsapp): send outbound files and attachments via Cloud API (#537)
Implement media upload, MIME mapping, caption fallbacks, and card+file
sequencing.

## Summary

The WhatsApp adapter previously ignored `files` and `attachments` on
outbound `post()` calls (only text and interactive cards were sent).
This PR implements full outbound media support via the [WhatsApp Cloud
API](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media):

1. **Binary upload** — `POST /{phoneNumberId}/media` → `media_id` →
typed media message
2. **Link passthrough** — HTTPS `Attachment.url` sent directly (no
upload)
3. **Multi-file** — one WhatsApp message per file/attachment, sent
sequentially
4. **Captions** — markdown or card fallback text on the first media
message when supported
5. **Card + files** — media first, then interactive buttons (when
applicable)

**Packages:** `@chat-adapter/whatsapp` (minor)

---

## Supported inputs

| Input | Description |
|-------|-------------|
| `files: FileUpload[]` | Binary buffers/blobs with `filename` and
optional `mimeType`. Always uploaded via `/media`. |
| `attachments: Attachment[]` | Typed media (`image` \| `file` \|
`video` \| `audio`). Binary via `data` / `fetchData`, or HTTPS URL-only
via `url`. |

Both can be combined on `{ markdown }`, `{ raw }`, `{ ast }`, or `{ card
}` postables. `files` are processed first, then `attachments`.

### Examples

```typescript
// PDF with caption
await thread.post({
  markdown: "Here's the report",
  files: [{ data: pdfBuffer, filename: "report.pdf", mimeType: "application/pdf" }],
});

// Multiple files (N sequential messages)
await thread.post({
  markdown: "Two files attached",
  files: [
    { data: buf1, filename: "a.pdf", mimeType: "application/pdf" },
    { data: buf2, filename: "b.png", mimeType: "image/png" },
  ],
});

// Card with buttons + image file
await thread.post({
  card: approvalCard,
  files: [{ data: proofBuffer, filename: "proof.png", mimeType: "image/png" }],
});

// Files only (no text)
await thread.post({
  markdown: "",
  files: [{ data: buffer, filename: "data.xlsx" }],
});
```

---

## Behavior reference

### Message flow (with media)

```
postMessage()
  ├─ files or attachments present?
  │    YES → postMessageWithMedia()
  │         ├─ Resolve text (card fallback OR markdown/raw/ast)
  │         ├─ Caption strategy (see below)
  │         ├─ For each file/attachment: upload (if binary) → sendMediaMessage()
  │         └─ Card present?
  │              ├─ interactive buttons → sendInteractiveMessage()
  │              └─ text-only card fallback → sendTextMessage() (if caption didn't already send text)
  │
  └─ NO → existing text / card-only path (unchanged)
```

### Multi-file

WhatsApp allows **one media object per API message**. Multiple `files`
or `attachments` in a single `post()` produce **N sequential messages**.
The returned `RawMessage` is the **last** one sent (same convention as
long-text chunking).

| File index | Caption |
|------------|---------|
| First | Markdown / card fallback text (when caption rules allow) |
| 2…N | No caption |

### Caption placement

| Condition | Behavior |
|-----------|----------|
| Text ≤ 1024 chars, first media is not `audio`, media supports captions
| Text sent as **caption** on first media message |
| Text > 1024 chars | **Separate text message first**, then media with
no captions |
| First media is `audio` | **Separate text message first** (audio does
not support captions), then audio |
| No text (`markdown: ""`, files only) | Media only, no caption |

### MIME type → WhatsApp message type

| MIME | WhatsApp `type` |
|------|-----------------|
| `image/jpeg`, `image/png` | `image` |
| Other `image/*` (e.g. GIF, WebP, SVG) | `document` |
| `video/mp4`, `video/3gpp` | `video` |
| `audio/*` | `audio` |
| Everything else (PDF, XLSX, etc.) | `document` |

For `Attachment` without `mimeType`, the adapter uses `attachment.type`
(`image` → image, `file` → document, etc.), then applies MIME rules when
`mimeType` is set.

### Size limits (pre-flight)

Throws `ValidationError` when binary size is known (before upload):

| Type | Limit |
|------|-------|
| `image` | 5 MB |
| `audio` | 16 MB |
| `video` | 16 MB |
| `document` | 100 MB |

URL-only attachments skip size validation unless `attachment.size` is
provided.

### Card + files

When both a **card** and **files/attachments** are present:

1. **Media message(s)** first — caption uses `cardToFallbackText(card)`
on the first media item
2. **Card message** second:
   - Valid reply buttons (1–3) → interactive button message
- Otherwise → text fallback message (skipped if text was already sent as
a leading message)

### Card image vs `files` (important)

| How image is provided | Result |
|-----------------------|--------|
| `<Image>` child or `card.imageUrl` only (no `files`) | **No real image
media.** Card becomes interactive text or text fallback; image URL may
appear as plain text in fallback. |
| `files` / `attachments` + card with buttons | **Real image message** +
separate interactive button message |

To send a photo with buttons, pass the image via `files` or
`attachments`, not only as a card image child.

### Link passthrough

- `Attachment` with **only** `url` (no `data` / `fetchData`) → `{ link:
url }` in the media payload
- URL **must** be `https://`
- No `/media` upload call

### Binary resolution

| Source | Path |
|--------|------|
| `FileUpload.data` | `toBuffer()` → `uploadMedia()` → `{ id }` |
| `Attachment.data` / `fetchData` | Same |
| `Attachment.url` only | `{ link }` passthrough |

---

## Out of scope (follow-ups)

- Stickers (WebP encoding requirements)
- Voice notes (`voice` vs `audio` distinction)
- Media ID caching across posts (30-day expiry)
- Interactive message **image headers** (card-embedded images without
`files`)
- Replay integration test mock extensions for `/media`
- Edit/replace flows that include files

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-13 21:03:07 +10:00
josh 4bca64f058 feat(x): support image uploads on posts and DMs (#700)
## summary

the X adapter previously rejected every attachment (`File uploads are
not supported by the X adapter yet`). this adds image upload support:
images passed as `files` or `attachments` are uploaded through X's v2
chunked media endpoints and attached to the resulting post or DM

- uploads via X's current path-based flow: `POST
/2/media/upload/initialize` (JSON) then `/{id}/append` (multipart) then
`/{id}/finalize`, reusing the adapter's managed OAuth token
- attaches `media_ids` on `POST /2/tweets` for posts, and `attachments`
for DMs
- supports png, jpeg, and webp, up to 4 per post, with or without text
- requires the `media.write` OAuth 2.0 scope on the user token

### before / after

- before: posting a message with `files`/`attachments` throws a
`ValidationError`
- after: images upload and attach, and a post can be media-only or media
plus text

<details>
<summary>usage</summary>

```typescript
await thread.post({
  markdown: "France lead the title race",
  files: [{ data: pngBuffer, filename: "odds.png", mimeType: "image/png" }],
});
```

</details>

## test plan

- added unit tests covering the initialize JSON body, the multipart
append path, finalize, `media_ids` on the tweet, DM `attachments`,
media-only posts, MIME inference from filename, the over-limit
rejection, and unsupported-type rejection
- verified live against the X API end to end: uploaded an image and
posted then deleted it through the adapter (the initial command-param
implementation 400'd against the live API, which is what surfaced the
path-based endpoints as required)
- `pnpm --filter @chat-adapter/x build`, tests, `pnpm exec biome check`,
and `pnpm konsistent` all pass

---------

Signed-off-by: dancer <josh@afterima.ge>
2026-07-13 18:57:29 +10:00
ishaksebsib 8d7ccdb11b feat(telegram): support multiple file and attachment uploads (#605)
## Summary

Adds Telegram media group support for posting multiple files and
compatible typed attachments. Multiple `files` are sent as document
media groups, while `attachments` preserve image, video, audio, or file
media types and use Telegram’s native `sendMediaGroup`.

---------

Signed-off-by: dancer <josh@afterima.ge>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-13 08:59:49 +01:00
Dean Mauro 0fdb902980 feat(discord): Components support (#678)
## Summary

#### What

Adds opt-in support for Discord
[Components](https://docs.discord.com/developers/components/reference).

#### Why

Discord Components allows developers more control over the layout of bot
messages by treating text, images, files, and buttons as flexible
components. Instead of the rigid text-above-embeds layout, elements can
be arranged in any order or column.

An extreme example of what's possible with Components:

<img width="728" height="1117" alt="image"
src="https://github.com/user-attachments/assets/fde6ab9c-f635-45fb-b64f-9ddf4c26580f"
/>

#### How

Embeds remain the default behavior. The Discord adapter now supports a
`componentsV2` flag to
When enabled, card messages render with Discord Components v2
containers, sections, text displays, media galleries, separators,
buttons, and string selects, and include the `IS_COMPONENTS_V2` message
flag.

## Test plan

Create a Chat with the Discord adapter. Set `contentFormat:
DiscordContentFormat.ComponentsV2` and create a post that uses sections,
markdown, buttons, etc. Note that
1. All elements should render correctly.
2. Individual sections can contain their own actions.
3. Markdown formatting gets rendered correctly.

```
import { Actions, Button, Card, CardText, Image, LinkButton, Section } from "chat";
import { createDiscordAdapter } from "@chat-adapter/discord";

const discord = createDiscordAdapter({
  contentFormat: DiscordContentFormat.ComponentsV2,
});

await thread.post(
  <Card title="Deployment ready" subtitle="Production build completed">
    <Section>
      <CardText>
        **Version 2.4.0** is ready to promote.

        Review the release notes, then choose an action below.
      </CardText>
      <Image url="https://example.com/deploy-preview.png" alt="Preview" />
    </Section>

    <Actions>
      <Button id="promote" style="primary">
        Promote
      </Button>
      <Button id="rollback" style="danger">
        Roll back
      </Button>
      <LinkButton url="https://example.com/deployments/123">
        View deployment
      </LinkButton>
    </Actions>
  </Card>
);
```

---------

Signed-off-by: dancer <josh@afterima.ge>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-13 08:48:48 +01:00
Max 6c2a3918d5 feat(discord): rename thread channels (#693)
## Summary

Add `DiscordAdapter#setThreadTitle()` to rename native Discord thread
channels and document the required **Manage Threads** permission.

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
Signed-off-by: dancer <josh@afterima.ge>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-13 08:17:21 +01:00
Faraz Patankar 5341f909a4 feat(discord): ignore @everyone/@here pings unless respondToGlobalMentions is set (#701)
## Summary

Fixes #699.

In gateway mode, the bot responded to `@everyone`/`@here` announcements.
The legacy gateway listener used discord.js
`message.mentions.has(botId)`, which counts global pings as a mention of
the bot by default.

Global pings are now ignored on both gateway paths by default, and a new
`respondToGlobalMentions` config option (default `false`, per the
issue's suggestion) lets users opt back in:

- **Legacy gateway mode**: mention detection passes `{ ignoreEveryone:
true }` to `mentions.has()`; `@everyone`/`@here` only count via
`message.mentions.everyone` when the option is enabled. Direct mentions,
`mentionRoleIds` role mentions, and replies to the bot are unaffected.
- **Forwarded gateway mode**: added the `mention_everyone` field to
`DiscordGatewayMessageData` and wired it into the same gate (this path
previously ignored global pings silently, with no way to opt in).

## Changes

- `respondToGlobalMentions?: boolean` on `DiscordAdapterConfig` (default
`false`)
- Mention detection updated in both `setupLegacyGatewayHandlers` and
`handleForwardedMessage`
- 5 new tests covering both transports: global pings ignored by default,
honored when opted in, and direct mentions still detected while global
pings are ignored
- Docs: config tables in
`apps/docs/content/adapters/official/discord.mdx` and the adapter README
- Changeset (minor, `@chat-adapter/discord`)

## Testing

- `pnpm validate` passes (knip + check + typecheck + test + build)
- All 249 `@chat-adapter/discord` tests pass, including the 5 new ones

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Faraz Patankar <farazpatankar@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 08:12:43 +01:00
Ben Sabic 4717a38407 feat(slack): support data table and data visualization blocks (#696)
Adds support for Slack's [data
table](https://docs.slack.dev/reference/block-kit/blocks/data-table-block)
and [data
visualization](https://docs.slack.dev/reference/block-kit/blocks/data-visualization-block)
Block Kit blocks.

- **`chat`**: new cross-platform `ChartElement` + `Chart()` builder (JSX
supported) mirroring Slack's model — pie `segments`, or bar/area/line
`series` against shared `categories`. `Table()` gains optional `caption`
and `pageSize`. Charts degrade to a text table on other platforms via
the shared card fallback (`chartElementToFallbackText`).
- **`@chat-adapter/slack`**: card tables now render as paginated,
sortable `data_table` blocks by default (header-only tables keep the
plain `table` block; oversized tables still fall back to ASCII). Charts
render as `data_visualization` blocks; charts violating Slack
constraints — including the undocumented **max 2 charts per message** —
fall back to a text rendering instead of an API rejection. Same
treatment in the `@chat-adapter/slack/blocks` subpath.
- **`postMessage`** now surfaces Slack's per-block validation messages
on `invalid_blocks` errors (this is how the 2-chart limit was found).
- Example app gets a **Show Charts** button and table pagination on
**Show Table**; docs, feature matrices, and changeset updated.

Verified live against Slack: data table pagination/sorting and both
chart types render natively.

<table>
  <tr>
    <th>Data Table</th>
    <th>Data Charts</th>
  </tr>
  <tr>
<td><img width="979" height="896" alt="CleanShot 2026-07-12 at 23 28 32"
src="https://github.com/user-attachments/assets/3307bd90-9322-452f-86fb-07d46446822d"
/></td>
<td><img width="955" height="879" alt="CleanShot 2026-07-12 at 23 29 02"
src="https://github.com/user-attachments/assets/ddb31a1b-e3fd-457c-a2e6-bde4934afebe"
/></td>
  </tr>
</table>

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-13 07:57:40 +01:00
damianborowy-nexos 1721fa01e7 feat(slack): add Slack Agent messaging experience (agent_view) support (#684)
## Summary

Add support for Slack's Agent messaging experience (`agent_view`), the
2026 replacement for `assistant_view`.

## Core (`chat`)

- New `onAppContextChanged` event carrying the active-view context as a
normalized `AppContextEntity[]` (`channel` / `canvas` / `list` /
`message` / `unknown`) describing what the user is currently viewing.
- `AppHomeOpenedEvent` now carries:
  - the same folded active-view context as optional `entities`
- the opened `tab` (`"home"` / `"messages"`), so handlers can
distinguish a Home-tab open from the DM-open signal under `agent_view`

## Slack adapter (`@chat-adapter/slack`)

- **`agentView` config flag.** Under `agent_view`:
- `app_home_opened` is the DM-open signal and fires regardless of tab
(branch on `event.tab` if you also publish a Home view)
- DM messages are threaded per Slack's new model — each user message is
a thread root (`thread_ts ?? ts`)
- conversation-scoped threads returned by `openDM()` keep working: when
that thread is subscribed, incoming top-level DM messages route to it,
so `onSubscribedMessage` and per-thread state behave the same as in
legacy mode
- **`app_context_changed` routing** with normalized entities. Malformed
payloads degrade gracefully: a missing `context` yields `entities: []`,
and entities with a null/malformed `value` normalize to `kind:
"unknown"` — never a webhook 500.
- **`getAppContext(message)`** helper to read the folded active-view
context off a DM message.
- **`setSuggestedPrompts`** accepts an optional thread reference
(`agent_view` lets prompts sit at the top of the agent conversation).
- **Env auth fallback now keys off auth fields**: `SLACK_BOT_TOKEN` /
`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` fallback is disabled only when
an auth-related field (`botToken`, `clientId`, `clientSecret`,
`installationProvider`) is passed explicitly, rather than by the
presence of any config object. This lets non-auth options compose with
env auth — e.g. `createSlackAdapter({ agentView: true })` picks up env
credentials — and matches the semantics documented in the adapter's
AGENTS.md. *(Behavior change for callers passing non-auth-only configs
while relying on env vars being ignored.)*
- Bumped `@slack/web-api` to `^7.18.0` (adds the optional `thread_ts`
typing for `setSuggestedPrompts`).

## Docs

- New "Agent messaging experience" section on the Slack adapter page
(config, manifest snippet, threading model, openDM bridge).
- "Handling active-view context" section in handling-events, plus
`tab`/`entities` rows on the app-home event table.
- Callout: under `agent_view`, bot replies are threaded per user
message, so `conversations.history` only returns the user's side of a DM
— build AI conversation history from transcripts instead of channel
history.

## Example app (`examples/nextjs-chat`)

- Plain `SLACK_BOT_TOKEN` adapter branch (previously Slack was only
wired via Vercel Connect).
- DM AI history built from transcripts instead of channel history (see
docs callout above); assistant turns persisted.
- The `dm me` trigger regex now matches mention text, which carries the
`@bot` prefix on Slack.

## Test plan

- `pnpm validate` and `pnpm konsistent` pass.
- Unit tests cover the new events, entity normalization (including
malformed payloads), `agent_view` DM threading, the openDM subscription
bridge, `tab` passthrough, `setSuggestedPrompts` thread handling, and
env-fallback behavior; an integration replay test exercises the full
webhook flow.
- Verified manually against a live `agent_view` workspace:
`onAppContextChanged` entities, folded context on `app_home_opened` and
DM messages, `tab` values for both tabs, per-message DM threading, the
openDM subscription bridge, and signed malformed-payload replays (all
return 200).
- Legacy regression pass with `agentView` off: conversation-scoped DM
threading, Home-tab-only `app_home_opened`, mention flow unchanged.

### Slack references

- Agent messaging experience:
https://docs.slack.dev/changelog/2026/06/30/agent-messages-tab/
- Active-view context:
https://docs.slack.dev/changelog/2026/07/02/app-context/

## Checklist

- [x] All commits are signed and verified
- [x] All commits are signed off for the DCO (`git commit -s`)
- [x] `pnpm validate` passes
- [x] Changeset added
- [x] Documentation updated

---------

Signed-off-by: Damian Borowy <301205838+damianborowy-nexos@users.noreply.github.com>
Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-12 19:35:28 +10:00
josh ef2542c5fd feat(x): add X (Twitter) adapter (#682)
## summary

new `@chat-adapter/x` adapter for X (Twitter), built on the X API v2 and
the X Activity API. write bot logic once and reply to mentions, hold DM
conversations, post from the account, and like posts, like the other
Chat SDK adapters

what it supports:
- reply to public mentions (`post.mention.create`) and top-level posts
via `channel.post`
- send and receive direct messages (`dm.received` / `dm.sent`)
- edit and delete owned posts, delete own DM events
- likes as the only reaction (`emoji.heart` or `"like"`)
- buffered streaming: accumulates an LLM stream and posts once instead
of post+edit churn on a public timeline
- OAuth 2.0 user context with managed token refresh (rotating refresh
token persisted in the state adapter, optional AES-256-GCM encryption)
- webhook CRC and `x-twitter-webhooks-signature` verification

key design decisions:
- DMs are threaded by the other participant's user id (`x:dm:{userId}`)
because X DM webhooks carry no conversation id, only participants
- OAuth 2.0 only at runtime: DM send and read are verified to work on
OAuth 2.0 user tokens, so no OAuth 1.0a in the adapter (subscription and
webhook setup is one-time and handled in the X developer console)
- parsers were written against real captured payloads: mentions use the
v2 shape (author hydrated in `includes.users`), DMs use the legacy
Account Activity shape (`direct_message_events`,
`message_create.message_data`, a `users` map, and no conversation id)

also includes the `chat/adapters` catalog entry, docs page, CLI scaffold
spec, and `sample-messages.md` with real captured payloads

<details><summary>usage</summary>

```typescript
import { Chat } from "chat";
import { createXAdapter } from "@chat-adapter/x";

const bot = new Chat({
  userName: "mybot",
  adapters: { x: createXAdapter() },
});

bot.onNewMention(async (thread, message) => {
  await thread.post(`hi @${message.author.userName}!`);
});

bot.onDirectMessage(async (thread) => {
  await thread.post("hello from X");
});
```
</details>

## test plan

- adapter unit tests pass against the real captured payload shapes, with
regression tests for author-from-`includes` (mentions) and the legacy
`direct_message_events` shape (DMs)
- real captured `post.mention.create` and `dm.received` payloads
verified end-to-end through `handleWebhook`: signature verification,
routing, author resolution, and participant threading, plus
bad-signature rejection returns 401
- every write and read path fired live against the X API through the
adapter: top-level post, reply to a mention, like and unlike, edit,
delete, DM send, DM read, DM delete
- OAuth 2.0 managed token refresh exercised live (access and refresh
token rotation)

---------

Signed-off-by: dancer <josh@afterima.ge>
2026-07-07 23:07:36 +01:00
Ben Sabic 6750d59e72 feat(github): add Vercel Connect support (#650)
Adds Vercel Connect support to the GitHub adapter:

- A new `installationToken` config option (string or resolver) supplies
installation access tokens directly, skipping the GitHub App private-key
JWT exchange.
- A new optional `webhookVerifier` verifies inbound webhooks (Connect
trigger-forwarded requests via a Vercel OIDC token) in place of the
GitHub webhook secret.

Pair with `connectGitHubAdapter()` from `@vercel/connect/chat`. Includes
a changeset (`@chat-adapter/github` minor).

Stacked on #647 (base `vercel-connect/base`).

## Companion

`@vercel/connect/chat` subpath: vercel/vercel#16826.

<img width="933" height="755" alt="CleanShot 2026-06-30 at 12 02 18"
src="https://github.com/user-attachments/assets/cc834560-0486-4f09-b8d5-8264be360544"
/>

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-03 01:38:51 +10:00
Ben Sabic 4115c9431e feat(linear): add Vercel Connect support (#649)
Adds Vercel Connect support to the Linear adapter:

- `accessToken` now accepts a `() => string | Promise<string>` resolver
in addition to a string, so tokens can be sourced from Vercel Connect at
runtime.
- A new optional `webhookVerifier` verifies inbound webhooks (Connect
trigger-forwarded requests via a Vercel OIDC token) in place of the
Linear webhook secret.
- Connect-mode outbound calls outside webhook handling are supported via
`withInstallation(organizationId, fn)`.

Pair with `connectLinearAdapter()` from `@vercel/connect/chat`. Includes
a changeset (`@chat-adapter/linear` minor).

Stacked on #647 (base `vercel-connect/base`).

## Companion

`@vercel/connect/chat` subpath: vercel/vercel#16826.

<img width="929" height="664" alt="CleanShot 2026-06-30 at 12 35 30"
src="https://github.com/user-attachments/assets/c5861cb9-d66b-42c6-b838-5b4983f48646"
/>

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-03 01:23:21 +10:00
Ben Sabic ba687cb13c docs(slack): document Vercel Connect support (#648)
Documents authenticating the Slack adapter with Vercel Connect via
`connectSlackAdapter()` from `@vercel/connect/chat`. The Slack adapter
already supports a `botToken` resolver and a `webhookVerifier`, so this
is a documentation-only change (no changeset).

Stacked on #647 (base `vercel-connect/base`).

## Companion

`@vercel/connect/chat` subpath: vercel/vercel#16826.

<img width="824" height="527" alt="CleanShot 2026-06-30 at 12 03 26"
src="https://github.com/user-attachments/assets/cbced069-8913-4848-9cf1-df0e5f614353"
/>

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-03 01:01:51 +10:00
Dean Mauro 022a502726 feat(discord): add ephemeral slash command responses (#514)
## summary

resolves #515

adds Discord slash-command interaction response flags so selected
commands can defer as ephemeral

Discord locks ephemerality on the initial
`DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE` response, so the adapter now
exposes `interactionFlags` on `createDiscordAdapter` for that initial
acknowledgement

```ts
import {
  createDiscordAdapter,
  DiscordInteractionResponseFlag,
} from "@chat-adapter/discord";

const discord = createDiscordAdapter({
  interactionFlags: ({ command }) => {
    if (command === "/admin") {
      return DiscordInteractionResponseFlag.Ephemeral;
    }
  },
});
```

handlers still use the normal `event.channel.post(...)` flow, and
`event.channel.postEphemeral(...)` keeps the normal Chat SDK fallback
behavior outside Discord's slash-command interaction response path


Co-authored-by: dancer <josh@afterima.ge>
2026-07-01 04:16:52 +01:00
OSS Polar Bear 8c7141174a feat(teams): add low-level primitives (#593)
Add Teams subpath exports for custom runtimes, including Bot Connector
API helpers, Graph reads, parse-only webhooks, format helpers, Adaptive
Cards, and Task Module primitives.

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-06-16 18:54:07 +10:00
Ben Sabic 8f3af76565 feat: add create-chat-sdk CLI (#603)
Adds `create-chat-sdk`, a CLI that scaffolds a Next.js Chat SDK bot
project:

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

# non-interactive
npm create chat-sdk@latest -- my-bot --adapter slack redis -y
```

The user picks platform and state adapters interactively or via
`--adapter`, and the CLI generates a webhook-only project with
`src/lib/bot.ts`, `.env.example`, `next.config.ts`, `package.json`, and
a README, then optionally runs `git init` and installs dependencies.
There are no pages or client UI in the template.

Adapter choices come straight from the `chat/adapters` catalog, so the
CLI has no adapter registry of its own. When a coding agent such as
Cursor or Claude Code runs the CLI, it uses non-interactive defaults and
requires an explicit platform adapter. `--interactive` forces prompts.

## also in this pr

- `google-chat` is renamed to `gchat` everywhere, including docs pages,
the OG image, and adapter catalog. Old URLs redirect permanently,
including language-prefixed and `/og` paths
- a new docs page is available at `chat-sdk.dev/docs/create-chat-sdk`,
and the CLI is promoted on the homepage, package READMEs, and agent
skill
- `create-chat-sdk` releases independently with a minor changeset for
its initial `0.1.0` release

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-06-16 08:48:38 +01:00
josh 4662309fe3 feat(telegram): support native rich messages (#616)
## summary

adds native rich message support for Telegram Bot API 10.1

explicit markdown and AST messages now use `sendRichMessage`, edits use
rich message payloads, and private chat streams use
`sendRichMessageDraft` before persisting the completed response

preserves existing behavior for plain strings, raw messages, cards,
media captions, and older or custom Bot API servers through automatic
fallback

adds typed inbound rich message parsing, rich message limits, regression
coverage, and updated adapter documentation
2026-06-15 19:44:32 +01:00
aqt 8336a3e818 feat(slack): expose webClientOptions to configure the underlying WebClient (#602)
## summary

adds `webClientOptions` to `SlackAdapterConfig` so users can configure
the underlying Slack `WebClient` instances

the options apply to both the default client and per-token clients used
for multi-workspace requests, including settings such as `retryConfig`,
per-request `timeout`, custom headers, and `rejectRateLimitedCalls`

`slackApiUrl` is intentionally excluded from `webClientOptions` because
the existing `apiUrl` option remains the single configuration path for
overriding the Slack Web API base URL

custom headers are cloned for each client because the Slack SDK adds
authorization to the provided headers object, preventing credentials
from leaking between token-bound clients

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-06-14 23:46:22 +01:00
ishaksebsib 9c936f8796 feat(telegram): support slash commands (#586)
## Summary

Adds Telegram bot command support for Chat SDK slash command handlers.

- Routes Telegram `/command` and `/command@botusername` messages to
`bot.onSlashCommand`
   - Ignores commands addressed to another bot
   - Keeps non-command messages on the existing normal message path

   ## Test plan

   - `pnpm validate`
   - Tested locally against a real Telegram bot

   ## Checklist

   - [x] All commits are signed and verified
   - [x] `pnpm validate` passes
   - [x] Changeset added
   - [x] Documentation updated

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-06-09 22:36:36 +10:00
Ben Sabic 7ecb9730e3 chore(docs): add missing Twilio logo and add official platform adapter OG images (#589)
Adds official platform adapter branding across the docs site, npm
READMEs, and social previews.

- **Homepage**: add Twilio to the supported-platforms logo grid
- **OG images**: add custom artwork for all 11 official platform
adapters under content/adapters/official/og/; serve static-first from
the existing /adapters/official/{slug}/og route with dynamic fallback
for state adapters
- **READMEs**: add linked hero banners to every official platform
adapter package README, using the live OG URL as the single image source
- **Tests**: integration-test guardrails for OG image coverage, README
banner discoverability, and knip-clean helpers
- **Changeset**: empty changeset for CI

<img width="2400" height="1256" alt="Chat SDK - Slack"
src="https://github.com/user-attachments/assets/4d186a1c-5651-44b8-8698-091ee23b44da"
/>

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-06-06 14:51:30 +10:00
Ben Sabic 9921dcd1c4 docs(seo): improve npm metadata, README discoverability, and structured data (#587)
Improves Chat SDK discoverability across npm, READMEs, and the docs site
for search engines and AI coding agents.

- **npm metadata**: point every published package `homepage` at
chat-sdk.dev deep links; expand `chat` keywords/description; fix
`repository.directory` (`packages/chat-sdk` → `packages/chat`); align
state adapter keywords
- **READMEs**: add npm callouts, Documentation/Guides links, and AI
Coding Agents sections (skill install, optional Vercel Plugin,
`llms.txt` / `llms-full.txt`) across all published packages and the repo
root
- **docs JSON-LD**: `HowTo` / `TechArticle` on getting-started,
streaming, and cards; `CollectionPage` + official-only `ItemList` on
`/adapters` (with split human vs JSON-LD descriptions)
- **UTMs**: add `chat-sdk_site` / `chat-sdk_repo` tracking params to
Resources links in selected MDX pages and adapter READMEs (discord,
github, slack, liveblocks, getting-started, ai index)
- **contract tests**: integration-tests guardrails for npm metadata and
README discoverability so future package additions don't drift

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-06-05 14:00:18 +10:00
Aamir Jawaid 6750dda955 docs: use stable Teams CLI package (#568)
## Summary
- Updates Teams setup docs to install `@microsoft/teams.cli` instead of
the old `@preview` tag.

## Why
- Teams CLI is stable now, so the docs should point folks at the stable
package. Nice and tidy.

## Interesting bits
- This touches both the public docs page and the adapter README so they
don't disagree.

## Test plan
- Not run; docs-only change.
2026-06-01 12:10:16 -07:00
Ben Sabic 9b8d8c4518 Discoverability lift: link KB guides, broaden npm keywords, mirror to AGENTS.md (#560)
Broad SEO/AEO pass across the docs site, adapter READMEs and AGENTS.md
files, and npm package metadata so Chat SDK content shows up better in
search engines, in LLM-driven package recommendations, and in
IDE/coding-agent context.

**Docs site**

- Adds a `## Resources` section to the Getting Started and AI overview
pages and to the Slack, Discord, GitHub, Liveblocks, and Sendblue
adapter pages, each linking to applicable guides/templates with
descriptions sourced from `resources-edge-config.json` and a cross-link
back to the central `/resources` hub.

**Adapter packages**

- Mirrors the same Resources sections into the Slack, Discord, and
GitHub READMEs (so they surface on npm) and into their AGENTS.md files
(so coding agents see them alongside the API notes).
- Expands `keywords` on every published adapter and state package — adds
`chat-sdk`, `chatbot`, `ai-agent`, `ai-sdk`, `vercel`, plus
platform-specific terms like `slack-bot`, `block-kit`, `slash-commands`,
`github-app`, `whatsapp-business`, `state-adapter`.

**Resources registry**

- Registers four new entries in `resources-edge-config.json`
(Human-in-the-Loop guide, Liveblocks AI agent guide, Slack + Vercel Blob
guide, Durable iMessage Agent template) and runs `pnpm sync-resources`
so the bundled `chat` package guides, `templates.json`, and
`skills/chat/SKILL.md` all pick them up.
- Fixes the synced Slack AI agent guide to import `toAiMessages` from
`chat/ai` instead of the deprecated `chat` re-export path (the upstream
KB source has also been updated, so future syncs will preserve this).

**Drive-by fixes**

- Resend adapter doc quick start: corrects `MemoryStateAdapter` class
import to the `createMemoryState()` factory (matching every other
adapter doc).
- Zalo adapter doc: drops the "community adapter" callout that
duplicated frontmatter.

**Tooling / CI**

- Adds `tsx` as a root devDependency so `pnpm sync-resources` works out
of the box (it previously relied on `npx tsx`, which hung when not
pre-cached).
- Loosens the CI changeset gate to also skip `packages/chat/resources/`
(generated data), matching the existing `*.md` carve-out.

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-05-29 11:41:23 +10:00
luren 5461ea982b feat(telegram): add native DM draft streaming with segmented stream results (#340)
## Summary

Add native Telegram DM streaming via `sendMessageDraft` while preserving
Chat SDK's existing post+edit fallback for non-DM threads.

This PR:
- adds native private-chat draft streaming to the Telegram adapter
- splits long streamed markdown into Telegram-safe persisted segments
- retries without `parse_mode` when Telegram rejects markdown entity
parsing
- exposes segmented native stream results in the chat core
- updates docs and feature matrices to reflect Telegram DM draft
streaming

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-05-28 15:17:10 -07:00
josh 25ebc3b925 feat(twilio): add sms, mms, and voice helpers (#558)
## summary

adds a first-class Twilio adapter for SMS and MMS bots, plus low-level
voice helpers for custom Twilio voice routes

this includes webhook parsing and signature verification, outbound
Messages API helpers, phone-number and Messaging Service sending,
inbound MMS attachments with authenticated `fetchData`, plain text card
fallback rendering, markdown conversion, and runtime-light `api`,
`webhook`, `voice`, and `format` subpaths

the adapter intentionally avoids the `twilio` npm runtime dependency so
apps can use the low-level helpers without pulling in the full SDK
2026-05-27 15:39:23 -07:00
josh 0488a6613c docs(slack): document low-level api subpaths (#557)
## summary

documents the low-level Slack subpaths for custom runtimes that own
routing, state, sessions, or workflow execution

covers `@chat-adapter/slack/webhook`, `@chat-adapter/slack/format`,
`@chat-adapter/slack/api`, and `@chat-adapter/slack/blocks`, including
when to use them instead of the full `createSlackAdapter` runtime

also links the new guide from the Slack adapter page
2026-05-27 09:16:47 -07:00
Hugo 716e934aa2 feat(web-adapter): first class support for Vue and Svelte (#498)
## Summary

<!-- What does this PR do? -->

## Test plan

<!-- How did you verify the changes? -->

## Checklist

- [ ] All commits are signed and verified
- [ ] `pnpm validate` passes
- [ ] Changeset added (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [ ] Documentation updated (or N/A)

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-05-14 19:18:24 -07:00
Ben Sabic 2f108bd4b3 feat: rename adapter.client to adapter.octokit / adapter.linearClient / adapter.webClient (#478)
## Summary

Rename the public native client getter on the GitHub, Linear, and Slack
adapters so it matches the underlying SDK class instead of the generic
`.client`. The previous `.client` getter is preserved as a `@deprecated`
alias on all three adapters, so existing code keeps working without
changes.

- `bot.getAdapter("github").client` is now
`bot.getAdapter("github").octokit` (returns `Octokit`)
- `bot.getAdapter("linear").client` is now
`bot.getAdapter("linear").linearClient` (returns `LinearClient` from
`@linear/sdk`)
- `bot.getAdapter("slack").client` is now
`bot.getAdapter("slack").webClient` (returns `WebClient` from
`@slack/web-api`)

Each new getter has TSDoc covering single- vs multi-tenant resolution
rules and when calling outside a webhook handler throws. Focused unit
tests assert that the new getter returns the underlying SDK instance,
that single-tenant calls return the same instance, that the deprecated
`.client` alias points at the new getter, that multi-tenant mode without
webhook context throws on both getters, and that inside a webhook
context the getter resolves to the per-tenant client.

Commits are split for review:

1. `feat(adapter-github): rename adapter.client to adapter.octokit`
2. `feat(adapter-linear): rename adapter.client to adapter.linearClient`
3. `docs: use .octokit / .linearClient in chat-sdk.dev examples`
4. `chore: changeset for adapter native client getter rename`
5. `fix: hoist regex literals in new client-getter tests to module
scope`
6. `feat(adapter-slack): rename adapter.client to adapter.webClient`
7. `docs: include slack .webClient in chat-sdk.dev examples`
8. `chore: include adapter-slack in native client getter rename
changeset`
9. `test(adapter-github,adapter-linear): cover with-context resolution
on the new client getters`

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-05-13 08:35:31 +10:00
Ben Sabic 79227ae991 docs: refresh adapter pages with hand-authored MDX (#474)
## Summary

Refreshes the adapter docs end-to-end so every adapter — official,
vendor-official, and community — now ships hand-authored MDX, lives
under a clean URL structure, and renders on a polished
sidebar/right-rail layout dedicated to `/adapters` (the shared `/docs`
chrome is untouched).

```mermaid
flowchart LR
  subgraph Before
    direction TB
    OB[official] --> CB[community<br/>incl. 5 vendor pages]
  end
  subgraph After
    direction TB
    OA[official] --> VA[vendor-official<br/>5 pages] --> CA[community]
  end
  Before -.-> After
```

### Content & routing

- **New `/adapters/vendor-official/<slug>` route** for vendor-maintained
adapters (Beeper Matrix, Photon iMessage, Liveblocks, Resend, Zernio).
Sidebar gets a third labelled group ("Vendor-Official Adapters") between
Official and Community, with a top divider matching the existing
Community treatment.
- **All 13 vendor-official + community adapters migrated** from runtime
README fetching to hand-authored MDX with rich `features:` matrices and
full body content (install, quick start, configuration, auth,
gateway/streaming, troubleshooting). README fetch stays as a fallback
for any future community adapter that hasn't been migrated yet, gated by
a new `mdxBody: true` frontmatter flag.
- **Messenger filter pages removed** (`/adapters/for/<messenger>` + the
"Browse by messenger" chip row on `/adapters`). Existing URLs
308-redirect to `/adapters`.
- **Permanent redirects** from
`/adapters/community/{matrix,imessage,resend,zernio,liveblocks}` to
their new `/adapters/vendor-official/...` paths.
- **Fixed** `/docs/adapters` and `/docs/state` so the bare pages are
accessible again — the previous catch-all redirect (`:slug*`) was
swallowing them. Switched to `:slug+` so subpath URLs still 308 while
the bare pages render.

### Visual polish

- **Adapter-only sidebar variant** (`AdaptersDocsLayout` +
`AdaptersSidebar`) with uppercase eyebrow separators, tighter rows, and
a thin themed scrollbar utility class. The shared `/docs` sidebar is
untouched.
- **Restyled `AdapterHero`**: drops the badges row + packageName, sits
the title inline with the logo, larger 17 px tagline, horizontal divider
beneath the block.
- **Restyled `PackageInstall`** as a tabbed dark single-line snippet
with a `$` prompt prefix and a copy button — replaces the previous
multi-line `CodeBlock` layout.
- **New "Deploy your chat app on Vercel" upsell card** (`<Upsell />`)
replaces the old `EditSource / ScrollTop / Feedback / CopyPage` footer
cluster on every adapter detail page.
- **Listing & messenger pages**: align the H1 to a tighter `text-4xl
sm:text-[44px]`, and the section headers to `text-base font-medium
tracking-tight` with a one-line muted lede.

### Tooling & tests

- Added `mdxBody: true` opt-in to the adapter frontmatter schema
(`source.config.ts`), and updated both detail-page handlers
(`community/[slug]` and the new `vendor-official/[slug]`) to render the
MDX body when present, falling back to README fetch otherwise.
- Refactored both detail-page handlers to flatten the body-render
branches into a `renderBody()` helper, removing the nested ternaries
that were tripping `lint/style/noNestedTernary`.
- New test file
[`packages/integration-tests/src/docs-adapters.test.ts`](https://github.com/vercel/chat/blob/docs/refresh-adapters/packages/integration-tests/src/docs-adapters.test.ts)
— **220 new assertions** covering:
- Adapter MDX frontmatter completeness, slug ↔ filename consistency, and
`type ∈ {platform, state}`.
- Vendor-official invariants: exactly the expected slugs,
`vendorOfficial: true`, `community: true`, `author`, `mdxBody: true`,
`<FeatureSupport />` rendered.
- Community invariants: `community: true` (never vendor-official),
`mdxBody: true`, `<FeatureSupport />`.
- Official invariants: never flagged, `packageName` always under
`@chat-adapter/*`.
- `adapters.json` ↔ MDX sync on `packageName` / `type` / `community` /
`vendorOfficial`.
- Extended `VALID_DOC_PACKAGES` so `docs-content.test.ts` accepts the
new vendor-official + community packages, plus `@chat-adapter/web`,
`@chat-adapter/web/react`, and `@chat-adapter/messenger`.

### Per-package AGENTS.md

- Added `AGENTS.md` to every official adapter and state adapter (14
packages), each tailored to that adapter's surface — overview, directory
layout, build/test commands, public exports, thread ID format, webhook
flow, authentication, format conversion, cards/streaming, platform
quirks, testing approach, coding conventions, and release rules.
- Added a one-line `CLAUDE.md` (`@AGENTS.md`) beside each so Claude Code
picks up the same instructions through its built-in resolver — same
convention as the root.

### Web adapter copy

- Cleaned up the Web adapter tagline (removed inline backticks) and
dropped the now-redundant "v1 scope" section from the body.

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-05-12 16:01:19 +10:00