Commit Graph

307 Commits

Author SHA1 Message Date
github-actions[bot] 3468cdfe0b chore(release): version packages (#767)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @chat-adapter/gchat@4.37.0

### Minor Changes

- c3b5a08: Bind Pub/Sub push verification to a specific identity with
the new pubsubServiceAccountEmail option, alongside the existing
audience check. Pushes are rejected unless the token email matches it.
Direct webhooks are unaffected.
- 7a19223: Bind Workspace Add-on webhook verification to a specific
identity with the new `workspaceAddOnServiceAccountEmail` option,
replacing a pattern match on the add-on service account email. Workspace
Add-on Chat apps must set it; standalone Chat apps are unaffected.

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/instagram@4.37.0

### Minor Changes

- 2a2b2c5: Add a native Instagram Direct Messages adapter with signed
webhooks, media, quick replies, story context, reactions, and typed Meta
API errors.

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/notion@4.37.0

### Minor Changes

- 0ec6a73: Add `@chat-adapter/notion` for Notion page and block comment
discussions: webhook HMAC verification, Post+Edit streaming,
conversation history, `message.subject` page metadata, plain-text
`@userName`/`@botUserId` mention detection, and File Uploads (up to 3
native attachments). Registers the adapter in the `chat/adapters`
catalog and `create-chat-sdk` CLI scaffold, and adds Notion emoji
platform support.

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/slack@4.37.0

### Minor Changes

- 4ac0455: Add message update and delete lifecycle callbacks, with Slack
message_changed and message_deleted dispatch support.

### Patch Changes

- 6f0d2f0: Resolve outgoing @name mentions on the Slack native streaming
path so streamed responses mention users consistently with the
post-and-edit fallback. Committed renderer text is resolved
incrementally, keeping fenced code literal and preserving the existing
ambiguity semantics.
- 4cc3445: Bound the length of bracketed URLs parsed from message text
in the link-unfurl fallback, avoiding a quadratic scan on adversarial
input. Valid links are unaffected.
- c311827: Preserve the Slack channel ID when converting labeled channel
tokens (`<#C123|general>` now becomes `#general (C123)`) so agents can
pass the ID to channel tools, and normalize the commonly hallucinated
`<label|url>` link order before Markdown conversion
- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/whatsapp@4.37.0

### Minor Changes

- 6abf480: Add native WhatsApp LinkButton support

- A card whose only interactive element is a single `LinkButton` with a
non-empty label and an `http://` or `https://` URL is now sent as a
native `cta_url` interactive message, as long as the card has no header
image or image, table, chart, or inline link children and the post
carries no files or attachments.
- Link button URLs are now appended as `Label: url` lines to interactive
button message bodies and to media captions, instead of being dropped.
- Everything else is unchanged: non-matching cards keep the formatted
text fallback, and card + media posts keep the single captioned media
send.

- 16879fd: Fix the `WhatsAppInboundMessage.context` type to model all
documented webhook variants. The type previously declared `context?: {
from: string; id: string }`, but Meta's Cloud API sends mutually
exclusive context shapes: quoted replies carry `from`/`id`, forwarded
messages carry only `forwarded` or `frequently_forwarded` (no `id`), and
catalog product inquiries add `referred_product`. Code narrowed by the
old type could dereference `context.id` and crash at runtime on
forwarded messages. All context fields are now optional and the
forwarded/product-inquiry fields are included. Consumers that
dereference `context.from` or `context.id` without a guard will now see
a type error, surfacing what was already a latent crash on forwarded
messages.

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## chat@4.37.0

### Minor Changes

- 2a2b2c5: Add a native Instagram Direct Messages adapter with signed
webhooks, media, quick replies, story context, reactions, and typed Meta
API errors.
- 4ac0455: Add message update and delete lifecycle callbacks, with Slack
message_changed and message_deleted dispatch support.
- 0ec6a73: Add `@chat-adapter/notion` for Notion page and block comment
discussions: webhook HMAC verification, Post+Edit streaming,
conversation history, `message.subject` page metadata, plain-text
`@userName`/`@botUserId` mention detection, and File Uploads (up to 3
native attachments). Registers the adapter in the `chat/adapters`
catalog and `create-chat-sdk` CLI scaffold, and adds Notion emoji
platform support.
- 85e3d22: Close residual gaps in agent read-tool scoping.
`createChatTools`'s read guard now wraps modal, assistant-thread,
assistant-context, app-home, app-context, and member-joined dispatch so
tools built in those handlers inherit the active conversation, and it
logs a warning (instead of failing open silently) when a read runs with
no resolvable scope. Scoping stays channel-level by default, so a thread
scope still permits sibling threads in its channel. Pass the new
`strictScope: true` to confine a thread scope to that thread alone,
rejecting both sibling threads and the parent channel, which matters on
platforms where a channel is the widest read available (a GitHub channel
is an entire repo).

Note that reads inside those newly wrapped handlers were previously
unscoped. An agent built in an `onModalSubmit`, `onAppHomeOpened`, or
`onMemberJoinedChannel` handler that reads another channel will now be
rejected. Pass an explicit `scope`, or `scope: false` for intentionally
workspace-wide reads.
## create-chat-sdk@0.3.0

### Minor Changes

- 2a2b2c5: Add a native Instagram Direct Messages adapter with signed
webhooks, media, quick replies, story context, reactions, and typed Meta
API errors.
- 0ec6a73: Add `@chat-adapter/notion` for Notion page and block comment
discussions: webhook HMAC verification, Post+Edit streaming,
conversation history, `message.subject` page metadata, plain-text
`@userName`/`@botUserId` mention detection, and File Uploads (up to 3
native attachments). Registers the adapter in the `chat/adapters`
catalog and `create-chat-sdk` CLI scaffold, and adds Notion emoji
platform support.
## @chat-adapter/discord@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/github@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/linear@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/messenger@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/shared@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
## @chat-adapter/teams@4.37.0

### Patch Changes

- 4cc3445: Harden Teams HTML-to-text conversion to strip tags until the
output is stable, so nested or malformed markup can't leave a partial
tag behind. `stripHtmlTags` is now shared across the format and Graph
message converters.
- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/telegram@4.37.0

### Patch Changes

- 629e655: Combine incoming Telegram media groups into one message with
ordered attachments and the shared caption.
- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/twilio@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/web@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/x@4.37.0

### Patch Changes

- b674923: Restrict the X CRC challenge to the opaque token shape X
sends before signing it. The endpoint previously returned an HMAC over
any `crc_token`, which let a caller have an arbitrary webhook body
signed and replay that as `x-twitter-webhooks-signature` on a forged
POST. A webhook body is JSON and can no longer pass the token check, so
a CRC response can't double as a POST event signature.
- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
  - @chat-adapter/shared@4.37.0
## @chat-adapter/state-ioredis@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
## @chat-adapter/state-memory@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
## @chat-adapter/state-pg@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
## @chat-adapter/state-redis@4.37.0

### Patch Changes

- Updated dependencies [2a2b2c5]
- Updated dependencies [4ac0455]
- Updated dependencies [0ec6a73]
- Updated dependencies [85e3d22]
  - chat@4.37.0
## @chat-adapter/tests@4.37.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-07 18:30:01 +01:00
josh c3b5a08e7e fix(gchat): bind Pub/Sub push verification to a configured identity (#797)
## summary

Pub/Sub push verification checked the token's `aud` and nothing else.
[Google's
guidance](https://docs.cloud.google.com/pubsub/docs/authenticate-push-subscriptions)
is explicit that signature and audience verification are not sufficient
on their own, and that the `email` and `email_verified` claims must be
checked alongside them

adds `pubsubServiceAccountEmail` (env
`GOOGLE_CHAT_PUBSUB_SERVICE_ACCOUNT_EMAIL`), the identity in the
subscription's push auth settings. a push is accepted only when
`email_verified` is true and `email` matches exactly. when the option is
unset, pushes are rejected rather than trusted on their audience alone

direct webhooks are untouched, and the project-number path already bound
to an exact issuer

### how it happened

`verifyBearerToken` took the claim validator as an optional parameter,
so a call site could simply omit it, and the Pub/Sub one did while the
direct-webhook one did not. that is now required:

```diff
-    validatePayload?: (payload: {
+    validatePayload: (payload: {
```

both call sites pass one and the type system enforces it, so the
omission cannot recur

## test plan

- a token from a different service account is rejected
- a token is rejected when no identity is configured
- a token is rejected when `email_verified` is not true
- a token with no `email` claim is rejected
- a matching identity with a verified email is accepted
- direct-webhook and project-number verification are unchanged

docs cover the new option in the README and adapter page, including the
push-subscription authentication step that produces the token
2026-08-07 17:54:40 +01:00
Ben Sabic 2a2b2c5500 feat(instagram): add native DM adapter (#770)
Adds a first-party Instagram Direct Messages adapter backed by Meta's
Instagram API with Instagram Login.

- Verifies webhook challenges and HMAC signatures, then normalizes DMs,
story replies, media, quick replies, postbacks, and reactions.
- Sends plain text, cards, quick replies, typing indicators, URL
attachments, and uploaded media through `graph.instagram.com`.
- Maps authentication, rate-limit, and 24-hour messaging-window failures
to typed adapter errors.
- Registers Instagram in the adapter catalog, CLI scaffold, official
docs, replay suite, and Next.js example.

## Usage

```ts
import { createInstagramAdapter } from "@chat-adapter/instagram";
import { Chat } from "chat";

const bot = new Chat({
  userName: "mystore",
  adapters: { instagram: createInstagramAdapter() },
});
```

## Webhook

```ts
export async function POST(request: Request) {
  return bot.webhooks.instagram(request);
}
```

## Verification

- `pnpm --filter @chat-adapter/instagram test`
- `pnpm --filter @chat-adapter/instagram typecheck`
- `pnpm --filter example-nextjs-chat typecheck`
- `pnpm --filter example-nextjs-chat build`
- `pnpm check`
- `pnpm konsistent`

## Live Testing

<table>
  <tr>
<td><img width="1440" height="2109" alt="1000000502"
src="https://github.com/user-attachments/assets/9fdb8c3b-4e41-4c81-9426-08756a5e4201"
/></td>
<td><img width="1440" height="1995" alt="1000000503"
src="https://github.com/user-attachments/assets/8a572493-c57a-4412-9049-5737aaa9dfd0"
/></td>
  </tr>
</table>

Closes #729 / Co-Authored by @ivandujaut

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-08-07 17:38:15 +01:00
Aradhya C P 6abf4807db feat(whatsapp): Add native LinkButton support for WhatsApp CTA URL messages (#781)
Adds native `LinkButton` support to the WhatsApp adapter by
mapping Chat SDK `LinkButton` actions to WhatsApp Cloud API CTA URL
interactive messages.

Previously, WhatsApp cards containing only `LinkButton` actions were
rendered as plain text with the URL exposed. WhatsApp supports native
CTA URL buttons through `interactive.type: "cta_url"`, so this change
enables the adapter to use that native capability.

Closes #780

## Changes Made

- Added support for converting a single `LinkButton` action into a
WhatsApp CTA URL interactive message.
- Added the `cta_url` interactive message shape to the WhatsApp adapter
types.
- Preserved existing reply button behavior and fallback handling for
unsupported card configurations.
- Added test coverage for:
  - Single `LinkButton` → native CTA URL message conversion.
  - Existing reply button behavior remaining unchanged.
  - Multiple `LinkButton` fallback behavior.

### Test Coverage

Added tests covering the new CTA URL conversion path and verified the
generated WhatsApp payload contains:

- `interactive.type: "cta_url"`
- `action.name: "cta_url"`
- `action.parameters.display_text`
- `action.parameters.url`

## Screenshots/Demos

<img width="864" height="338" alt="image"
src="https://github.com/user-attachments/assets/cc58a76b-5a96-406a-9f79-ca7a2725836b"
/>

## Additional Notes

WhatsApp CTA URL messages only support a single URL button per
interactive message. The implementation intentionally only promotes
cards with exactly one `LinkButton` into a CTA URL message and keeps
existing fallback behavior for unsupported combinations.

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-08-07 15:17:47 +10:00
Ben Sabic 0ec6a7361b feat(notion): add Notion comments adapter (#689)
Adds `@chat-adapter/notion`, an official adapter that lets a Chat SDK
bot take part in **Notion comment discussions** (page-level and
block/discussion threads) with the same handler code used for Slack,
Linear, GitHub, etc. Inbound events arrive via Notion webhooks
(`comment.created`) with HMAC signature verification; outbound actions
use the Comments REST API. Because Notion lets a connection edit its own
comments, the adapter supports **Post+Edit streaming**.

### Highlights

- **Webhooks** — `comment.created` verified with `X-Notion-Signature`
HMAC over the raw body (timing-safe), plus the one-time
`verification_token` handshake. Returns a fast 200 with idempotent,
state-backed dedupe.
- **Post+Edit streaming** — posts the first chunk, then `PATCH`es the
comment as tokens arrive, throttled to Notion's ~3 req/s limit (global
token bucket, `Retry-After` aware). Long bodies are split into
sequential comments to stay under the 2000-char rich-text cap.
- **Mentions** — three modes: `mention` (default; plain-text `@userName`
/ `@botUserId`), `all-comments`, and `keyword`.
- **`message.subject`** — resolves the parent page via the Pages API
(title, url, archived status, author).
- **File uploads** — up to 3 native attachments via the File Uploads API
(binary `single_part`; public URLs via `external_url` with bounded
polling); overflow and failures fall back to markdown links.
- **History** — `fetchMessages` over list-comments (open comments only),
direction-aware.
- Cards render as markdown fallback; reactions / typing / DMs are typed
no-ops or errors. Registered in the `chat/adapters` catalog and the
`create-chat-sdk` scaffold; pinned to `Notion-Version: 2026-03-11`.

### Usage

```ts
// lib/bot.ts
import { Chat } from "chat";
import { createNotionAdapter } from "@chat-adapter/notion";
import { createRedisState } from "@chat-adapter/state-redis";

export const bot = new Chat({
  userName: "notion-bot",
  adapters: { notion: createNotionAdapter() }, // reads NOTION_TOKEN + NOTION_VERIFICATION_TOKEN
  state: createRedisState(),
});

bot.onNewMention(async (thread, message) => {
  const subject = await message.subject; // parent page metadata (title, url, …)
  await thread.post(`Thanks for the mention on **${subject?.title ?? "this page"}**!`);
});
```

```ts
// app/api/webhooks/notion/route.ts
import { bot } from "@/lib/bot";

export const POST = (request: Request): Promise<Response> => bot.webhooks.notion(request);
```

### Configuration

Auto-detects `NOTION_TOKEN` and `NOTION_VERIFICATION_TOKEN`, plus
optional `NOTION_BOT_USERNAME`, `NOTION_MENTION_MODE`,
`NOTION_KEYWORDS`, and `NOTION_VERSION`; everything is overridable via
`createNotionAdapter({ … })`. The docs page covers the full connection +
webhook setup (capabilities, content access, and the webhook-URL-lock
warning).

Changeset bumps `@chat-adapter/notion`, `chat`, and `create-chat-sdk`
(minor). Layered as four commits: `feat` (adapter +
catalog/scaffold/emoji), `docs`, `test`, `chore(example)`.

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-08-05 14:15:44 +01:00
josh 4ac0455134 feat(chat): add message update and delete lifecycle callbacks (#788)
## summary

adds `onMessageUpdated` and `onMessageDeleted`, so a bot can react when
a message is edited or removed. Slack dispatches both today; other
adapters can opt in later

supersedes #549, which was verified there against real Slack webhooks.
reopened from a branch in this repo with the original commits preserved
and signed

```typescript
bot.onMessageUpdated(async (thread, message, previousMessage) => {
  await mirror.update(message.id, message.text);
});

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

both are lifecycle events: they never route through `onNewMessage`,
`onNewMention`, or `onSubscribedMessage`, and the concurrency strategies
do not apply

### notes

- **the bot's own edits are filtered.** slack sends a `message_changed`
for every `chat.update`, and post-and-edit streaming calls it once per
delta, so without this a single streamed reply would call the handler
back repeatedly on its own message
- **`previousMessage` is forwarded on edits.** slack sends the pre-edit
message and it was being dropped. an edit handler usually needs the
before to know what changed, so it is the optional third argument
- **the two shapes differ deliberately.** an edit carries a full
replacement message, so it gets `(thread, message, previousMessage?)`. a
delete has no message, only the id of what was removed, so it gets an
event. use `chat.thread(event.threadId)` when a delete handler needs one
- **one thread id helper** now serves message, edit, and delete, so an
edit cannot resolve to a different thread than the message it edits

## test plan

core:

- an edit dispatches to `onMessageUpdated` and not to the normal message
handlers
- the handler receives the pre-edit message as its third argument
- the bot's own edits are skipped
- a delete dispatches with normalized event data
- both run inside the active conversation, so read tools built in these
handlers stay scoped

slack:

- `message_changed` dispatches as an update, `message_deleted` as a
delete
- `previous_message` is forwarded, and left undefined when slack omits
it
- hidden unfurl updates stay ignored, hidden real edits still dispatch
- message, edit, and delete resolve to one thread id in a flat DM and in
a threaded `agent_view` DM

verified against a real slack workspace over socket mode: editing and
deleting a DM both routed to the same thread id as the original message

---------

Co-authored-by: Miłosz Lenczewski <m.lenczewski@tidio.net>
2026-08-05 13:22:54 +01:00
josh 7a1922357c fix(gchat): bind add-on webhook verification to a configured identity (#787)
## summary

endpoint-URL webhook verification accepted any `email` claim matching
the generic Workspace Add-on shape:

```ts
/^service-\d+@gcp-sa-gsuiteaddons\.iam\.gserviceaccount\.com$/
```

the `\d+` is a GCP project number, and service agents are
`service-{PROJECT_NUMBER}@gcp-sa-{SERVICE}...` for the project that owns
them. so that shape identifies "some Workspace Add-on", not *this* app's
add-on, and it was the only thing standing between a public endpoint URL
and a verified request. the method's own doc comment already stated the
correct invariant, that the token is only trustworthy if it was issued
to Google Chat itself

adds `workspaceAddOnServiceAccountEmail` (env
`GOOGLE_CHAT_WORKSPACE_ADDON_SERVICE_ACCOUNT_EMAIL`) and compares add-on
identities exactly. when it is unset, add-on-shaped tokens are rejected
rather than trusted by shape, with a log naming the option to set

`chat@system.gserviceaccount.com` is untouched, so standalone Chat apps
behave exactly as before. the project-number and Pub/Sub paths were
already bound to exact identities and are unchanged

### behavior

| token `email` | before | after |
| --- | --- | --- |
| `chat@system.gserviceaccount.com` | accept | accept |
| add-on shape, matches configured identity | accept | accept |
| add-on shape, different project | accept | **reject** |
| add-on shape, option unset | accept | **reject** |

<details>
<summary>why not reject at construction</summary>

refusing to initialize when the option is absent would be the
stricter-looking choice, but the adapter cannot tell Workspace Add-on
mode from config alone, it only sees `endpointUrl`. throwing there would
break every ordinary endpoint-URL Chat app. rejecting add-on-shaped
tokens at verification is the precise equivalent without the collateral

</details>

## test plan

- an add-on token matching the configured identity is accepted
- an add-on token from a different project is rejected, the case the
generic shape allowed
- an add-on token is rejected when no identity is configured
- `chat@system.gserviceaccount.com` is still accepted with no add-on
config
- suffixed and prefixed lookalike domains, an uppercase variant, and
trailing whitespace are all rejected
- a matching identity with `email_verified: false` is rejected

the two rejection cases above returned 200 before this change and 401
after
2026-08-05 13:16:07 +01:00
Mukund Sarma 4cc3445c6f fix(teams,slack): follow-up hardening for html and url parsing (#779)
Follow-up and hardening for two inbound parsers.

- **Teams** — HTML-to-text conversion now strips tags until the output
is stable, so nested or malformed markup can't leave a partial tag
behind. A shared `stripHtmlTags` helper backs both the format converter
and the Graph message converter (was three inline single-pass regexes).
- **Slack** — the link-unfurl fallback bounds the length of bracketed
URLs parsed from message text, avoiding a quadratic scan on adversarial
input. Valid links are unaffected.

Two changesets (`@chat-adapter/teams`, `@chat-adapter/slack`); no
public-type change. Independent of #774/#775.
2026-08-04 11:29:50 +10:00
Mohith Gajjela 6f0d2f020a fix(slack): resolve outgoing mentions on the native streaming path (#755)
Fixes #754, reported by @alvarosevilla95.

Slack's native streaming path appended renderer deltas as raw
`markdown_text`, skipping the outgoing @name mention resolution that the
post-and-edit fallback gets via postMessage/editMessage, so cached names
rendered as plain text in the default mode.

The fix runs committed `StreamingMarkdownRenderer` text through the
existing `resolveOutgoingMentions` incrementally (line by line, tracking
code-fence state) before each `streamer.append` delta is computed. Chunk
safety falls out of the renderer's own semantics: incomplete lines are
only committed inside fences (where mentions stay literal, matching the
full-text resolver) or at inline-marker cuts, which cannot split a bare
`@name`, so a mention spanning source chunks still reaches the resolver
whole. The fallback path is untouched.

Patch changeset included; both commits are DCO signed off. Six
regression tests cover unique resolution, chunk-spanning mentions,
mid-stream line commits, ambiguity, participant disambiguation, and
code-fence literalness; 5 of the 6 fail without the fix (the sixth
passes either way by design, since the broken path also leaves ambiguous
mentions plain). Package suite: 626 passed (baseline 620, zero new
failures); biome and typecheck clean.

---------

Signed-off-by: Mohith Gajjela <109003762+Mohith26@users.noreply.github.com>
2026-08-03 14:33:33 +01:00
Mukund Sarma 85e3d22ba1 fix(chat): follow-up hardening and docs for agent read-tool scoping (#774)
Follow-up hardening and updated docs for the agent read-tool scoping in
`createChatTools`.

## What changed

- Wrap the remaining dispatch paths (modal submit/close,
assistant-thread, assistant-context, app-home, app-context,
member-joined) in `runInConversation` so read tools built inside those
handlers inherit the active conversation.
- Log a warning when a read runs with no resolvable scope, instead of
failing open silently.
- Keep scoping channel-level by default; add opt-in `strictScope: true`
to confine a thread scope to that thread alone (rejects sibling threads
on per-thread-ACL platforms like Discord and GitHub).
- Update the AI SDK tools docs to cover the channel-level default, what
`scope` does and does not do, and the `strictScope` opt-in.

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-08-03 13:50:05 +01:00
Ricardo Rivero 16879fdc7a fix(whatsapp): model forwarded and product-inquiry context variants in WhatsAppInboundMessage (#723)
## Problem

`WhatsAppInboundMessage.context` is typed as:

```ts
/** Context for quoted replies */
context?: {
  from: string;
  id: string;
};
```

But Meta's Cloud API webhook sends **mutually exclusive context shapes**
depending on message origin ([text messages webhook
reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)):

- **Quoted replies** (and interactions with a business message): `from`
+ `id`
- **Forwarded messages**: only `forwarded` ("only included if forwarded
5 times or less") or `frequently_forwarded` ("only included if forwarded
more than 5 times") — **no `id`, no `from`**
- **Catalog product inquiries**: `from` + `id` + `referred_product`

Because the type declares `id` required whenever `context` is present,
downstream code like `message.raw.message.context?.id.trim()`
type-checks cleanly and then throws a `TypeError` at runtime the first
time a user forwards a message to the bot — `context` exists, `id`
doesn't. We hit exactly this in production code building reply-to
handling on top of the adapter.

## Change

- All `context` fields are optional, and the forwarded/product-inquiry
fields (`forwarded`, `frequently_forwarded`, `referred_product`) are
added, with doc comments noting which variant each field belongs to.
- Changeset included (`@chat-adapter/whatsapp`: patch).

The adapter itself never reads `context` at runtime, so this is a
type-only change. Consumers who currently dereference `context.id`
unguarded will get a compile error after upgrading — intentionally,
since that code is a latent runtime crash on forwarded messages.

---------

Signed-off-by: Ricardo Rivero <ricardo@enzadon.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-08-03 13:43:08 +01:00
Mukund Sarma b674923849 fix(x): harden CRC challenge token validation (#775)
Follow-up hardening for the X webhook CRC challenge.

The CRC challenge endpoint returned an HMAC over any caller-supplied
`crc_token`, using the same construction and secret as POST webhook
signature verification. That let a caller have an arbitrary body signed
via the public GET challenge and replay the response as
`x-twitter-webhooks-signature` on a forged POST.

`crc_token` is now restricted to X's opaque token shape before signing.
A webhook event body is JSON and can never match, so a CRC response can
no longer double as a POST event signature. Both base64 and base64url
alphabets are accepted so a legitimate token is never rejected.
`verifySignature` is unchanged.

Regression tests: a webhook-shaped `crc_token` is rejected with 400 and
no `response_token`; a signature the challenge can produce (for a valid
token) verifies only against a body equal to that token, which is not
event JSON, so no handler is dispatched. 216 adapter-x tests pass.

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-08-03 13:06:06 +01:00
Sergey Bekrin c311827945 fix(slack): preserve channel id and normalize frequently hallucinated link format (#756)
This change fixes two conversion issues in `slackMrkdwnToMarkdown`,
which runs on every incoming Slack message.

**1. Preserve channel IDs in labeled channel tokens**

Previously the channel ID was dropped during conversion, so agents
reading `message.text` had no ID to pass to channel tools. Labeled
tokens now keep both the readable name and the ID:

```
<#C042BLND6R6|general>   →   #general (C042BLND6R6)
<#C042BLND6R6>           →   #C042BLND6R6            (unchanged)
```

Bare channel mentions are still enriched with the channel name via
`conversations.info`, so incoming messages end up with both the name and
the ID either way.

**2. Normalize the commonly hallucinated link order**

AI models frequently emit Slack links with the label and URL swapped.
These are now normalized before Markdown conversion:

```
<docs|https://example.com>   →   [docs](https://example.com)
```

Valid links whose display label is itself a URL (common with Slack's
truncated link displays) are detected and left in the correct order:

```
<https://a.com|https://b.com>   →   [https://b.com](https://a.com)
```

---------

Signed-off-by: Sergey Bekrin <sergey@bekrin.me>
Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-08-03 09:14:53 +10:00
Max 629e655578 fix(telegram): combine incoming media groups (#760)
- buffer incoming Telegram updates that share a `media_group_id` and
dispatch them once the album settles
- coordinate through the configured `StateAdapter` so separate
serverless instances still produce one message
- preserve the shared caption and order attachments by Telegram message
ID

---------

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-08-01 11:52:04 +10:00
github-actions[bot] 470b6af94b chore(release): version packages (#748)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @chat-adapter/slack@4.36.0

### Minor Changes

- 0153a39: Add `DateInput` and `NumberInput` modal children. The Slack
adapter renders them as a `datepicker` and a `number_input`, the Teams
adapter as `Input.Date` and `Input.Number`, and both submitted values
arrive in `event.values` as strings.

Teams submit values that arrive as JSON numbers are now stringified into
`event.values` instead of being dropped. This fixes `Input.Number`, but
applies to any numeric value a Teams dialog submits — a key that was
previously absent from `event.values` will now be present as a string.

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/teams@4.36.0

### Minor Changes

- 0153a39: Add `DateInput` and `NumberInput` modal children. The Slack
adapter renders them as a `datepicker` and a `number_input`, the Teams
adapter as `Input.Date` and `Input.Number`, and both submitted values
arrive in `event.values` as strings.

Teams submit values that arrive as JSON numbers are now stringified into
`event.values` instead of being dropped. This fixes `Input.Number`, but
applies to any numeric value a Teams dialog submits — a key that was
previously absent from `event.values` will now be present as a string.

### Patch Changes

- 257a32d: Route Teams personal and group conversations using their
explicit conversation type so group chats use buffered fallback even
when their IDs resemble direct messages.
- 3c37cfb: Authenticate connector-hosted inline attachments and parse
Teams file download cards.
- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/x@4.36.0

### Minor Changes

- caa6325: Add XChat support to `@chat-adapter/x`, shipped from the new
`@chat-adapter/x/chat` subpath so it sits alongside the existing X
adapter. The XChat crypto stack (`@xdevplatform/chat-xdk`,
`@xdevplatform/xdk`, `juicebox-sdk`) is an optional peer dependency, so
existing `@chat-adapter/x` users are unaffected. All cryptography is
handled inside the adapter via `@xdevplatform/chat-xdk` (wasm) and all
REST goes through the typed `@xdevplatform/xdk` client. Only a bot token
and a Juicebox PIN are required: the bot's identity (user id and
@handle) is resolved from `GET /2/users/me` at startup.

- Encrypted send/receive in DMs and groups (webhook push + polling),
signature verification on by default; undecryptable or unverified events
are dropped
- Webhook POSTs must carry a valid `x-twitter-webhooks-signature`, which
X sends on every delivery. Set `consumerSecret` (or `X_CONSUMER_SECRET`)
to receive webhooks, or `disableWebhookVerification` when an upstream
layer already verifies them. Polling deployments are unaffected
- Mention detection from structured mention entities, swipe-replies to
the bot, and a plain-text `@handle` fallback; group replies sent as
quoted replies
- `openDM(userId)` starts (or reuses) an encrypted 1:1, running a full
key exchange when needed so the bot can message first
- Media both ways: inbound attachments with lazy download+decrypt,
outbound encrypted uploads
- Edit and delete of the bot's own messages; the first edit of a fresh
message is age-gated by `editSafetyDelayMs` (default 5000ms) so
receiving clients have stored the original
- Reactions in and out, read receipts (`sendReadReceipts`, default on),
typing keep-alive, configurable group welcome message
- Cards degrade to text with tappable URL/mention entities plus a URL
preview attachment
- Requests carry a `chat-sdk-xchat/<version>` User-Agent product token
so Chat SDK traffic is identifiable in X API request logs (a User-Agent
set via `apiHeaders` takes precedence)
- Registered in the `chat/adapters` catalog and the `create-chat-sdk`
CLI scaffold, with a new optional `importPath` catalog field for
adapters that ship on a subpath

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## chat@4.36.0

### Minor Changes

- c5d86b1: confine built-in agent read tools to the conversation being
handled, with an optional scope override
- 0153a39: Add `DateInput` and `NumberInput` modal children. The Slack
adapter renders them as a `datepicker` and a `number_input`, the Teams
adapter as `Input.Date` and `Input.Number`, and both submitted values
arrive in `event.values` as strings.

Teams submit values that arrive as JSON numbers are now stringified into
`event.values` instead of being dropped. This fixes `Input.Number`, but
applies to any numeric value a Teams dialog submits — a key that was
previously absent from `event.values` will now be present as a string.

### Patch Changes

- 257a32d: Route Teams personal and group conversations using their
explicit conversation type so group chats use buffered fallback even
when their IDs resemble direct messages.
- b547f45: Stop treating email addresses as bot mentions. A message
containing `jane@acme.com` no longer triggers a bot named `acme`,
because the `@` in `detectMention` must not follow a word character.
Real mentions are unaffected, including at the start of a message, after
punctuation, and suffixed names such as GitHub's `mybot[bot]`.
- caa6325: Add XChat support to `@chat-adapter/x`, shipped from the new
`@chat-adapter/x/chat` subpath so it sits alongside the existing X
adapter. The XChat crypto stack (`@xdevplatform/chat-xdk`,
`@xdevplatform/xdk`, `juicebox-sdk`) is an optional peer dependency, so
existing `@chat-adapter/x` users are unaffected. All cryptography is
handled inside the adapter via `@xdevplatform/chat-xdk` (wasm) and all
REST goes through the typed `@xdevplatform/xdk` client. Only a bot token
and a Juicebox PIN are required: the bot's identity (user id and
@handle) is resolved from `GET /2/users/me` at startup.

- Encrypted send/receive in DMs and groups (webhook push + polling),
signature verification on by default; undecryptable or unverified events
are dropped
- Webhook POSTs must carry a valid `x-twitter-webhooks-signature`, which
X sends on every delivery. Set `consumerSecret` (or `X_CONSUMER_SECRET`)
to receive webhooks, or `disableWebhookVerification` when an upstream
layer already verifies them. Polling deployments are unaffected
- Mention detection from structured mention entities, swipe-replies to
the bot, and a plain-text `@handle` fallback; group replies sent as
quoted replies
- `openDM(userId)` starts (or reuses) an encrypted 1:1, running a full
key exchange when needed so the bot can message first
- Media both ways: inbound attachments with lazy download+decrypt,
outbound encrypted uploads
- Edit and delete of the bot's own messages; the first edit of a fresh
message is age-gated by `editSafetyDelayMs` (default 5000ms) so
receiving clients have stored the original
- Reactions in and out, read receipts (`sendReadReceipts`, default on),
typing keep-alive, configurable group welcome message
- Cards degrade to text with tappable URL/mention entities plus a URL
preview attachment
- Requests carry a `chat-sdk-xchat/<version>` User-Agent product token
so Chat SDK traffic is identifiable in X API request logs (a User-Agent
set via `apiHeaders` takes precedence)
- Registered in the `chat/adapters` catalog and the `create-chat-sdk`
CLI scaffold, with a new optional `importPath` catalog field for
adapters that ship on a subpath
## @chat-adapter/discord@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/gchat@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/github@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/linear@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/messenger@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/shared@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
## @chat-adapter/telegram@4.36.0

### Patch Changes

- 53bf73d: Preserve Telegram stable media identifiers in normalized
attachment metadata and report photo attachments as JPEG.
- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/twilio@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/web@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## @chat-adapter/whatsapp@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
  - @chat-adapter/shared@4.36.0
## create-chat-sdk@0.2.1

### Patch Changes

- caa6325: Add XChat support to `@chat-adapter/x`, shipped from the new
`@chat-adapter/x/chat` subpath so it sits alongside the existing X
adapter. The XChat crypto stack (`@xdevplatform/chat-xdk`,
`@xdevplatform/xdk`, `juicebox-sdk`) is an optional peer dependency, so
existing `@chat-adapter/x` users are unaffected. All cryptography is
handled inside the adapter via `@xdevplatform/chat-xdk` (wasm) and all
REST goes through the typed `@xdevplatform/xdk` client. Only a bot token
and a Juicebox PIN are required: the bot's identity (user id and
@handle) is resolved from `GET /2/users/me` at startup.

- Encrypted send/receive in DMs and groups (webhook push + polling),
signature verification on by default; undecryptable or unverified events
are dropped
- Webhook POSTs must carry a valid `x-twitter-webhooks-signature`, which
X sends on every delivery. Set `consumerSecret` (or `X_CONSUMER_SECRET`)
to receive webhooks, or `disableWebhookVerification` when an upstream
layer already verifies them. Polling deployments are unaffected
- Mention detection from structured mention entities, swipe-replies to
the bot, and a plain-text `@handle` fallback; group replies sent as
quoted replies
- `openDM(userId)` starts (or reuses) an encrypted 1:1, running a full
key exchange when needed so the bot can message first
- Media both ways: inbound attachments with lazy download+decrypt,
outbound encrypted uploads
- Edit and delete of the bot's own messages; the first edit of a fresh
message is age-gated by `editSafetyDelayMs` (default 5000ms) so
receiving clients have stored the original
- Reactions in and out, read receipts (`sendReadReceipts`, default on),
typing keep-alive, configurable group welcome message
- Cards degrade to text with tappable URL/mention entities plus a URL
preview attachment
- Requests carry a `chat-sdk-xchat/<version>` User-Agent product token
so Chat SDK traffic is identifiable in X API request logs (a User-Agent
set via `apiHeaders` takes precedence)
- Registered in the `chat/adapters` catalog and the `create-chat-sdk`
CLI scaffold, with a new optional `importPath` catalog field for
adapters that ship on a subpath
## @chat-adapter/state-ioredis@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
## @chat-adapter/state-memory@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
## @chat-adapter/state-pg@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
## @chat-adapter/state-redis@4.36.0

### Patch Changes

- Updated dependencies [257a32d]
- Updated dependencies [c5d86b1]
- Updated dependencies [0153a39]
- Updated dependencies [b547f45]
- Updated dependencies [caa6325]
  - chat@4.36.0
## @chat-adapter/tests@4.36.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-01 01:19:44 +01:00
Santiago Medina caa63253c5 feat(x): add XChat encrypted messaging support (#745)
## summary

new `@chat-adapter/xchat` adapter for XChat, X's encrypted messaging.
write bot logic once and hold encrypted 1:1 and group conversations like
the other Chat SDK adapters — all crypto handled inside the adapter via
`@xdevplatform/chat-xdk` (wasm), all REST via the typed
`@xdevplatform/xdk` client.

## background: chat-xdk


[`@xdevplatform/chat-xdk`](https://www.npmjs.com/package/@xdevplatform/chat-xdk)
is the official XChat cryptography SDK — a Rust core compiled to
WebAssembly that implements the XChat encryption protocol. it handles
per-conversation symmetric keys and key exchange, message
encryption/decryption, event signing and signature verification, and
encrypted media (secretstream). the bot's private keys live in a
PIN-protected [Juicebox](https://juicebox.xyz) store (secret-shared
across independent realms), so no key material sits in env vars or on
disk — the adapter unlocks with a PIN at startup. this adapter is the
glue: chat-xdk produces and consumes the encrypted envelopes, the typed
`@xdevplatform/xdk` client moves them over the X API, and everything is
normalized to the Chat SDK's `Thread`/`Message` model.

what it supports:
- encrypted send/receive in DMs and groups (webhook push + polling),
signature verification on by default
- mention detection from structured mention entities, swipe-replies to
the bot, and a plain-text `@handle` fallback; group replies go out as
quoted replies with TTL propagated
- `openDM(userId)`: starts (or reuses) an encrypted 1:1 —
cached/history-recovered conversation key, else a full key exchange so
the bot can message first
- media both ways: inbound attachments with lazy download+decrypt,
outbound encrypted (secretstream) via the 3-step upload flow
- edit and delete of the bot's own messages: edits are encrypted events
targeting the original's sequence id; deletes are locally signed
delete-for-all actions recipients verify
- reactions in and out, typing keep-alive while handlers run,
configurable group welcome message
- read receipts sent per delivered inbound message (`sendReadReceipts`,
default on)
- cards by degradation: text + tappable entities, link buttons as
`label: url` lines, primary link as a URL preview attachment with
optional encrypted banner

key design decisions:
- mdast stays the canonical format; markdown passes through as raw text
(XChat clients render plain text — no markdown), with URLs and @mentions
made tappable via entity spans and tables degraded to ASCII code blocks
- thread ids are `xchat:{conversationId}` (groups `g…`, 1:1s the sorted
participant pair)
- the first edit of a fresh message is age-gated (`editSafetyDelayMs`,
default 5000ms): receiving clients park an edit whose original hasn't
arrived, leaving the message permanently invisible — the gate prevents
that race
- undecryptable or unverified events are dropped, never delivered as
empty messages
- no core changes: the adapter implements the standard `Adapter`
interface only

also includes the `chat/adapters` catalog entry, docs page (with OG
image), `adapters.json` registry entry, and `create-chat-sdk` scaffold
spec, modeled on the `x` adapter's registration.

<details><summary>usage</summary>

```bash
XCHAT_BOT_TOKEN=...    # OAuth2 user access token (identity resolved from GET /2/users/me)
XCHAT_PIN=...          # Juicebox PIN that unlocks the bot's keys
X_CONSUMER_SECRET=...  # optional: verifies webhook signatures
```

```typescript
import { Chat } from "chat";
import { createXchatAdapter } from "@chat-adapter/xchat";
import { createMemoryState } from "@chat-adapter/state-memory";

const bot = new Chat({
  userName: "mybot",
  adapters: { xchat: createXchatAdapter() }, // credentials from env
  state: createMemoryState(),
});

// DMs always
bot.onDirectMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});

// group chats when the bot is @mentioned
bot.onNewMention(async (thread, message) => {
  await thread.post("You rang?");
});

// wire the webhook (e.g. a Next.js route)
export async function POST(request: Request) {
  return bot.webhooks.xchat(request);
}
```

</details>

testing: 109 unit tests, including real-wasm-crypto round trips against
vendored fixture vectors (decrypt + signature verification, webhook
delivery, read receipts, edit age-gating, signed deletes). verified live
against production XChat: DMs, group mentions, media, reactions, edits,
deletes, openDM, cards.

note on the lockfile: `@xdevplatform/xdk@0.6.6` was published <48h ago,
so it was resolved with a one-shot `--config.minimumReleaseAge=0`
override; the locked integrity hash was verified against the npm
registry. the repo policy file is untouched.

---------

Co-authored-by: dancer <josh@afterima.ge>
2026-07-31 23:52:18 +01:00
Max 53bf73db22 fix(telegram): preserve media identity and MIME metadata (#752)
## Summary

Preserve Telegram's stable `file_unique_id` alongside the current
downloadable `file_id` in normalized attachment metadata. Telegram photo
attachments now report `image/jpeg`, including rich-message photos.

This keeps adapter normalization in `@chat-adapter/telegram`;
deduplication remains consumer-owned. After upgrading to the release
containing this patch, Calories can remove
`patches/@chat-adapter__telegram@4.35.0.patch` while retaining its
perceptual-hash fallback for recompressed images.

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-07-31 17:49:26 +01:00
Max 3c37cfbc15 fix(teams): authenticate protected inline attachments (#749)
## Summary

Authenticates connector-hosted Teams inline attachments through the
configured Bot Framework client, so `message.attachments[].fetchData()`
can retrieve protected content. Teams file download cards use their
direct `content.downloadUrl` anonymously, and serialized attachments
reconstruct the same routing during rehydration.

Bot credentials are limited to non-redirecting HTTPS requests whose
origin exactly matches the Activity connector origin. Cross-origin URLs,
HTTP URLs, and file-card download URLs never enter the authenticated
client path.

File-card MIME inference covers common image and text formats plus PDF,
XLS, and XLSX attachments.

The implementation follows [Microsoft's inline-image access-token
sample](https://learn.microsoft.com/en-us/samples/officedev/microsoft-teams-samples/officedev-microsoft-teams-samples-bot-file-upload-nodejs/)
and [Teams file-card
contract](https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/bots-filesv4).


Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-07-31 17:36:36 +01:00
josh b547f45842 fix(chat): stop treating email addresses as bot mentions (#761)
## summary

a message containing an email address like `jane@acme.com` was treated
as a mention of a bot named `acme`, so the bot engaged on every pasted
colleague email

`detectMention` now requires the `@` not to follow a word character:

```ts
`(?<!\\w)@${escapeRegex(botUserName)}(?![\\w-])`
```

- applies to both the username and the user id pattern
- an email local part always ends in a word character, so
`jane@acme.com`, `foo.bar@acme.com`, `foo-bar@acme.com` and url userinfo
are all excluded
- real mentions are unaffected: start of a message, after a space, after
punctuation like `(` or `:`, and after an ellipsis

fixes #759
2026-07-31 17:31:42 +01:00
CamdenA21 0153a39f7b feat(modals): add DateInput and NumberInput modal children (#757)
`ModalChild` is `TextInput | Select | ExternalSelect | RadioSelect |
Text | Fields` — there is no date or number primitive. A bot collecting
a renewal date or a quantity has to render a text input with a
`YYYY-MM-DD` hint and validate the string on submit, on every platform,
even though neither platform is the constraint:

- Slack Block Kit has a native
[`datepicker`](https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element)
and
[`number_input`](https://docs.slack.dev/reference/block-kit/block-elements/number-input-element).
- Adaptive Cards has `Input.Date` and `Input.Number`, both already
exported by `@microsoft/teams.cards`.

One addition to the union lifts both surfaces. `ModalSubmitEvent.values`
stays `Record<string, string>`, so this is additive for existing
handlers.

## Changes

- `DateInput` / `NumberInput` element types, builders, and options in
`packages/chat/src/modals.ts`, added to `ModalChild` +
`VALID_MODAL_CHILD_TYPES`.
- JSX/React support: props, component overloads, `modalComponentMap`,
and `fromReactModalElement` branches.
- Slack renderer: `datepicker` (`initial_date`, `placeholder`) and
`number_input` (`is_decimal_allowed`, `initial_value`, `min_value`,
`max_value` — Slack takes these as strings).
- Teams renderer: `Input.Date` / `Input.Number`, in both `modals.ts`
(`@microsoft/teams.cards`) and the dependency-free `modals-primitives`.
- Docs: `docs/modals.mdx` component tables and `docs/api/modals.mdx`
reference + `ModalChild` table.
- Changeset (`chat`, `@chat-adapter/slack`, `@chat-adapter/teams`:
minor).

### Two runtime decode gaps this had to close

- Slack reports a datepicker as `selected_date`, not `value`, so
view-submission flattening now reads `value ?? selected_date ??
selected_option?.value`. `number_input` already arrives as `value`.
- Teams' `Input.Number` submits a JSON **number**, which the previous
`typeof val === "string"` filter dropped silently. Numbers are now
stringified in both `parseDialogSubmitValues` and
`parseTeamsDialogSubmitValues`. This applies to any numeric value a
Teams dialog submits, not only `Input.Number` — a key that used to be
absent from `event.values` is now present as a string. Called out in the
changeset; one existing test updated. Non-scalar values are still
dropped.

### Deliberate asymmetries

- `DateInput` has no `min`/`max` — Slack's `datepicker` has no bounds,
and a prop that silently does nothing on one platform is worse than its
absence.
- `NumberInput.decimal` maps to Slack's required `is_decimal_allowed`.
Adaptive Cards has no decimal switch, so Teams accepts decimals either
way; this is called out in the docs.
- A `DateInput` `initialValue` that is not a real `YYYY-MM-DD` date is
dropped with a warning instead of forwarded. Slack rejects a malformed
`initial_date` by failing the entire `views.open` with
`invalid_arguments` — the modal never opens, and the error surfaces as a
JSON pointer rather than anything actionable. Adaptive Cards just
renders the field empty, so forwarding verbatim would make the same
modal work on Teams and die on Slack. The drop matches how
`filterModalChildren` handles unsupported children. Validation
round-trips through `Date` because it rolls impossible dates over
(`2026-02-31` → Mar 3) instead of rejecting them.

Signed-off-by: CamdenA21 <camden@sandstone.com>
2026-07-31 15:00:44 +10:00
josh c5d86b103e feat(chat): scope agent read tools to the active conversation (#751)
built-in agent read tools now stay inside the conversation they are
handling, so a thread or channel id the model supplies that resolves
elsewhere is rejected before the adapter is called

- `Chat` tracks the conversation being handled across message, action,
slash command and reaction dispatch, using `AsyncLocalStorage`
- read tools (`fetchMessages`, `fetchChannelMessages`, `fetchThread`,
`listThreads`, `getThreadParticipants`, `getChannelInfo`) inherit that
conversation, so existing handlers get this with no code change
- scoping is per channel, so an agent can still follow other threads in
its own conversation
- pass `scope` to set it explicitly, or `scope: false` for
workspace-wide reads

this brings read tools in line with the least-privilege defaults write
tools already have, where `needsApproval` is on unless you opt out

**not breaking:** `scope` is optional and every existing call site keeps
working. agents that run outside a handler, such as a queued job or a
resumed workflow step, have no conversation to inherit and should pass
`scope`

## test plan

- read tools reject out-of-conversation ids and still serve
in-conversation ones, per tool
- the conversation is inherited correctly through message, action, slash
command and reaction dispatch
- concurrent conversations stay isolated, so one agent cannot inherit
another's scope
- an explicit `scope` overrides the handled conversation, and `scope:
false` restores workspace-wide reads
- ids resolve through `adapter.channelIdFromThreadId`, verified against
the slack, teams, google chat, discord, telegram and whatsapp id shapes
- `pnpm validate` clean: workspace tests, typecheck, lint, knip and
build all pass
2026-07-29 09:41:58 +10:00
Max 257a32d01c fix(teams): classify group chats by conversation type (#746)
Fixes `a:`-prefixed Teams group chats being treated as DMs, so they use
non-DM routing and buffered responses.

[Microsoft defines conversation IDs as opaque strings and
`conversationType` as the channel-provided conversation
discriminator](https://github.com/Microsoft/botframework-sdk/blob/main/specs/botframework-activity/botframework-activity.md#conversation-account).
The adapter therefore stores a classification override only when
`conversationType` disagrees with the legacy ID-prefix heuristic.
Existing subscription and history keys remain stable when the heuristic
was already correct. Explicit group chats also bypass stale DM Graph
context, and Graph-listed child threads retain the override.

---------

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-07-28 00:34:29 +10:00
github-actions[bot] e3c136b6dc chore(release): version packages (#710)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @chat-adapter/discord@4.35.0

### Minor Changes

- 26c0522: Add an opt-in channel allowlist for treating non-bot Discord
messages as directed to the bot without requiring a mention. Configure
via `respondToChannelIds` or the `DISCORD_RESPOND_TO_CHANNEL_IDS` env
var (comma-separated).

### Patch Changes

- b605cf6: Preserve Discord's angle-bracket syntax for suppressing link
previews when rendering markdown.
- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/slack@4.35.0

### Minor Changes

- bb7cd12: Expose sender email addresses on normalized incoming Slack
message authors. `message.author.email` is populated from the same
cached `users.info` lookup used for display names and requires the
`users:read.email` scope; without it the field stays undefined.
- 907450d: Enterprise Grid fixes:

- `handleOAuthCallback` now handles org-wide installs
(`is_enterprise_install`): Slack returns `team: null` for these, and the
installation is now keyed by the enterprise ID — the same key webhook
token resolution looks up — instead of failing. The result includes
`enterpriseId` and `isEnterpriseInstall`, and `SlackInstallation`
records both.
- Socket mode now resolves per-installation tokens for events, slash
commands, and interactive payloads in multi-workspace deployments
(matching the HTTP webhook path), and no longer drops `enterprise_id` /
`is_enterprise_install` / `is_ext_shared_channel` from event payloads.
- The user profile cache and display-name mention reverse index are now
scoped by installation in multi-workspace deployments, so profiles
fetched with one workspace's token no longer bleed into another and
mentions can no longer resolve to a same-named user from a different
workspace. Existing cache entries repopulate on first lookup
(single-workspace keys are unchanged). `withBotToken` accepts an
optional `{ installationId }` so proactive/cron posts outside webhook
handling scope these caches too.
- API calls made while handling an event from an org-wide install now
pass the event's `team_id` explicitly, as Slack requires for
workspace-scoped methods (`conversations.list`, `usergroups.*`, …) on
org tokens. When an event carries a `context_team_id` (shared channels
hosted on an "away" workspace), channel-addressed calls echo it back as
`client_context_team_id`.
- Retried event deliveries (`x-slack-retry-num`, socket `retry_num`) are
dropped when the original delivery was already dispatched, using an
`event_id` marker in the state adapter (24-hour TTL). Events whose first
delivery never arrived are still recovered via the retry.
- Bare `@W…` mentions in outgoing messages are now recognized as raw
Enterprise Grid user IDs (previously only `@U…` was), so they render as
real mentions instead of being treated as display names.
- Event token resolution now prefers the envelope's `authorizations[0]`
— Slack's documented location for the event's installation identity —
over the top-level `team_id`/`enterprise_id`, which can name a different
workspace for Slack Connect shared-channel events. Top-level fields
remain as a fallback.

### Patch Changes

- 80def3a: Add optional `isSystem` field to the normalized message
`Author` type to distinguish platform-generated messages from humans and
bots. The Slack adapter now sets `isSystem: true` for messages authored
by Slack's reserved `USLACK` user (e.g. "@user archived the channel"
notifications in DMs), so consumers no longer need to hard-code
Slack-specific user IDs.
- 92530dd: Return a replyable Slack thread ID from `channel.post()` by
using the posted top-level message's timestamp as the thread root.
- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/teams@4.35.0

### Minor Changes

- 5eb8b84: Add support for adding and removing reactions from Microsoft
Teams messages.
- 46681f5: Expose Microsoft Graph email addresses on normalized incoming
Teams message authors. Resolved user profiles are cached in the state
adapter (1 hour, failed lookups 5 minutes) so the lookup doesn't add a
Graph call per message.
- 160140e: Add native Microsoft Teams targeted message support via
`thread.postEphemeral()` and `channel.postEphemeral()`.
- e06b4b6: Add a `token` config option to `TeamsAdapterConfig` for
supplying a custom token factory, forwarded to the Teams SDK's
`AppOptions.token`. This lets bots authenticate on runtimes that can't
reach Azure IMDS (so `federated` managed identity isn't reachable) but
can still mint access tokens through an external mechanism, without
needing a static client secret.

### Patch Changes

- 3895ab3: Fall back to Microsoft Graph's user principal name when a
Teams user has no mail address.
- 93a58af: Show explicitly configured progress as a native Teams DM
status while preserving native streaming.
- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/telegram@4.35.0

### Minor Changes

- 54eea71: Add an optional Telegram user allowlist via `allowedUserIds`
or the comma-separated `TELEGRAM_ALLOWED_USER_IDS` environment variable.

### Patch Changes

- 0701679: Cache the compiled bot-mention regex in `isBotMentioned`
instead of recompiling it per message, and make the protected `sleep`
helper accept an optional `AbortSignal` so `stopPolling()` interrupts
the polling backoff delay immediately.
- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## chat@4.35.0

### Minor Changes

- 4cb7e5d: Add a `chat/workflow` subpath with `requestApproval()`:
durable human-in-the-loop approvals built on Workflow SDK. It posts an
approval card with Approve/Deny buttons, suspends the workflow until a
user decides (or an optional timeout elapses), validates approvers,
finalizes the card with the outcome, and returns `{ approved, timedOut,
user }`. Also exports the `buildApprovalCard` and `buildResolvedCard`
builders. Requires the new optional `workflow` peer dependency.
- 46681f5: Expose Microsoft Graph email addresses on normalized incoming
Teams message authors. Resolved user profiles are cached in the state
adapter (1 hour, failed lookups 5 minutes) so the lookup doesn't add a
Graph call per message.

### Patch Changes

- 80def3a: Add optional `isSystem` field to the normalized message
`Author` type to distinguish platform-generated messages from humans and
bots. The Slack adapter now sets `isSystem: true` for messages authored
by Slack's reserved `USLACK` user (e.g. "@user archived the channel"
notifications in DMs), so consumers no longer need to hard-code
Slack-specific user IDs.
- 93a58af: Show explicitly configured progress as a native Teams DM
status while preserving native streaming.
- 25f3099: `toAiMessages` no longer drops messages that have no text. A
message with an empty text body is now kept when it has links or
attachments the converter can include: images and text files (`text/*`,
JSON, XML, YAML, etc.) with a working `fetchData()`. Messages whose only
attachments are unsupported (video, audio, other file types, or
attachments without `fetchData()`) are still skipped, and
`onUnsupportedAttachment` now fires for video/audio attachments on these
previously filtered messages.

Note: multipart `content` no longer always starts with a text part. When
a kept message had no text, its `content` array contains only attachment
parts.
## @chat-adapter/gchat@4.35.0

### Patch Changes

- 270b1c2: fix(gchat): accept `endpointUrl` as a direct-webhook verifier
and verify each token type correctly

When a Google Chat app's connection setting **Authentication audience**
is set
to **HTTP endpoint URL** — Google's recommended option for HTTP-hosted
apps
not behind Cloud Run IAM, and the only mode available for Workspace
Add-on
Chat apps — incoming tokens are Google OIDC ID tokens whose `aud` is the
endpoint URL rather than the GCP project number. Previously the adapter
only
verified against `googleChatProjectNumber`, so URL-audience tokens
always
failed with 401 Unauthorized. The adapter now accepts `endpointUrl` as a
direct-webhook verifier (including in the constructor's fail-closed
check),
validating the OIDC token's audience plus the Google Chat issuer email
claims
  (`chat@system.gserviceaccount.com`, or the
`service-{projectNumber}@gcp-sa-gsuiteaddons.iam.gserviceaccount.com`
service
identity for Workspace Add-on Chat apps) with `email_verified: true` — a
public endpoint URL audience alone is not sufficient to forge a request.

  Project-number-audience tokens are now verified per Google's reference
  implementation: they are JWTs self-signed by
`chat@system.gserviceaccount.com`, so the adapter checks them against
that
  service account's X.509 certificates with issuer
`chat@system.gserviceaccount.com` (previously it used `verifyIdToken`,
which
only accepts Google OIDC issuers and certs and therefore rejected every
real
project-number token). When both verifiers are configured, either token
type
  is accepted.

  The adapter still infers an endpoint URL from incoming requests for
button-click action routing only — that inferred value is never used as
a
JWT verification audience, and inference now only happens after a
request
has passed verification (or verification was explicitly disabled),
because
  `request.url` derives from the attacker-controllable `Host` header in
  serverless runtimes.

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/github@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/linear@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/messenger@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/shared@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
## @chat-adapter/twilio@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/web@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/whatsapp@4.35.0

### Patch Changes

- 09b72e9: fix whatsapp card media duplication

- Prevent card titles and body content from appearing twice when sending
cards with files on WhatsApp.
- Avoid adding the full card fallback text as an image caption when an
interactive message follows.
- Keep interactive WhatsApp messages responsible for rendering card
titles, bodies, and actions.

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/x@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
  - @chat-adapter/shared@4.35.0
## @chat-adapter/state-ioredis@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
## @chat-adapter/state-memory@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
## @chat-adapter/state-pg@4.35.0

### Patch Changes

- d88789c: Fix `setIfNotExists()` so it can claim a cache key whose
existing row has expired. Previously the query used `ON CONFLICT DO
NOTHING`, so an expired row in `chat_state_cache` still blocked
acquisition until opportunistic cleanup deleted it — diverging from the
memory and Redis adapters, which treat expired entries as absent. Keys
stored without a TTL remain permanent and are never overwritten.
- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
## @chat-adapter/state-redis@4.35.0

### Patch Changes

- Updated dependencies [80def3a]
- Updated dependencies [4cb7e5d]
- Updated dependencies [46681f5]
- Updated dependencies [93a58af]
- Updated dependencies [25f3099]
  - chat@4.35.0
## @chat-adapter/tests@4.35.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-24 22:21:13 +01:00
Max 54eea71501 feat(telegram): add user allowlist (#742)
## Summary

Add an opt-in `allowedUserIds` Telegram adapter option, with
`TELEGRAM_ALLOWED_USER_IDS` as a comma-separated environment fallback.
Updates from other or unidentified users are ignored before dispatch.

This follows the adapter-level targeting pattern from [the Discord
channel response allowlist](https://github.com/vercel/chat/pull/715),
while enforcing an ingress allowlist instead of expanding mention
routing.

## Test plan

- `pnpm --filter @chat-adapter/telegram test`
- `pnpm --filter @chat-adapter/telegram typecheck`
- `pnpm check`
- `pnpm konsistent`
- `TURBO_CONCURRENCY=2 pnpm validate`

## 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 (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (or N/A)

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-07-24 21:06:44 +01:00
Aamir Jawaid 160140e32b feat(teams): add targeted ephemeral messages (#737)
## Summary

Microsoft Teams supports targeted messages that are visible only to a
selected conversation member, but the Teams adapter did not expose that
native behavior through the SDK's ephemeral-message API. This PR wires
`postEphemeral` for Teams to send native targeted messages while
preserving normal `postMessage` behavior by default.

The adapter now creates explicit targeted outbound activities with
`MessageActivity.withRecipient(recipient, true)` for text and
adaptive-card messages, returns `usedFallback: false`, and keeps the
feature gated behind `thread.postEphemeral()` /
`channel.postEphemeral()`. It also bumps the Teams SDK packages to
`^2.0.13`, adds targeted coverage, updates public docs/matrices, and
includes a changeset.

Live verification found that Teams targeted messages require the app to
be installed in the shared conversation. Group chats and channels both
worked after using the Teams install picker with `Open -> select
placement -> Go`; personal bot chat targeted sends returned a Teams
`BadArgument` response.

## Test plan

Previously validated with:

- `corepack pnpm --filter @chat-adapter/teams exec vitest run
src/index.test.ts --coverage.enabled=false`
- `corepack pnpm --filter @chat-adapter/teams exec tsc --noEmit`
- `corepack pnpm --filter example-nextjs-chat exec tsc --noEmit`
- `corepack pnpm --filter chat exec vitest run src/emoji.test.ts
--coverage.enabled=false`
- `corepack pnpm --filter @chat-adapter/teams exec tsup`
- Targeted `ultracite check` on changed files

Live verified `TeamsAdapter.postEphemeral(...)` in:

- Group chat `Demo Test 2`: Teams UI showed `Only you can see this
message`.
- Channel `General / Teams SDK`: Teams returned message ID
`1784749118197`, and the UI showed `Only you can see this message`.

<img width="884" height="299" alt="Screenshot 2026-07-22 at 12 41 41 PM"
src="https://github.com/user-attachments/assets/cd350ac8-c158-4779-8028-3450eb8670f2"
/>
<img width="1098" height="559" alt="Screenshot 2026-07-22 at 12 41
33 PM"
src="https://github.com/user-attachments/assets/bf6ea12b-ab11-46ee-a3a8-ff5e9583066d"
/>


## Checklist

- [ ] All commits are signed and verified - unsigned commit created
after local GPG/SSH signing was unavailable and user approved continuing
- [ ] `pnpm validate` passes - full validate not run; targeted
validation listed above
- [x] Changeset added (or N/A - see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (or N/A)

---------

Co-authored-by: dancer <josh@afterima.ge>
Copilot-Session: 601a7414-48f0-4e6d-ba03-28fa4d2d5c0a
2026-07-23 19:53:13 +01:00
Aradhya C P 09b72e9dd3 fix(whatsapp): stop duplicating card title when posting Card with files (#736)
## Description

Fixes a WhatsApp adapter bug where posting a **Card together with
files** caused the card title (and other card text) to appear twice:
once in the media caption (from `cardToFallbackText`) and again in the
interactive message header/body (from `cardToWhatsApp`).

`postMessageWithMedia` now checks whether the card will be sent as an
interactive message first. If so, it skips using the full card fallback
as the media caption and lets the interactive message own the title,
body, and buttons. Text-fallback cards + files keep the previous caption
behavior (single message, no duplicate text).

## Type of Change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Refactoring (no functional changes)

## Related Issues

Fixes #735
Closes #735
Related to #735

<!-- Replace # with the issue number after opening the bug report -->

## Changes Made

- In `postMessageWithMedia`, compute `cardToWhatsApp(card)` first and
reuse that result.
- When the card is **interactive**, do not set media caption from
`cardToFallbackText` (empty caption text) so title/body are not
duplicated on the image.
- When the card is **text fallback**, keep captioning media with
`cardToFallbackText` and avoid sending a second text message (existing
behavior).
- Expand unit coverage in `index.test.ts` for interactive + files (title
once, no caption duplication for text/fields, multi-file, audio, HTTPS
attachment) and text-fallback caption behavior.

## Testing

- [x] All existing tests pass
- [x] Added new tests for the changes
- [x] Manually tested the changes

### Test Coverage

- Built the package, then used `pnpm link` to link the built `dist` into
a separate test project.
- Exercised `thread.post({ card, files })` against the reported bug
scenario and confirmed the title no longer appears twice (caption empty
for interactive cards; title only on the interactive message).
- Added / updated unit tests in
`packages/adapter-whatsapp/src/index.test.ts`; all related tests pass
locally (`pnpm --filter @chat-adapter/whatsapp test`).

## Screenshots/Demos

<!-- Paste before/after WhatsApp screenshots here -->

**Before (title duplicated on caption + interactive header):**

<img width="433" height="428" alt="image"
src="https://github.com/user-attachments/assets/37c776fd-b4f6-48f3-a365-6e2073316576"
/>



**After (title only on interactive message; media uncaptioned):**

<img width="428" height="390" alt="image"
src="https://github.com/user-attachments/assets/fb1f43d9-623a-4e22-83ea-dd96cd6d3877"
/>

<img width="408" height="405" alt="image"
src="https://github.com/user-attachments/assets/3959eb04-e722-43f4-8b85-91b724faebcb"
/>


## Checklist

- [x] My code follows the project's code style
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings or errors
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I have created a changeset (`pnpm changeset`)
- [x] All commits are signed and verified
- [ ] All commits are signed off for the DCO (`git commit -s`)
- [x] `pnpm validate` passes
- [x] Changeset added (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [ ] Documentation updated (or N/A)

## Changeset

- [x] I have created a changeset for these changes

<!-- Reminder: behavioural package changes need `pnpm changeset` for
`@chat-adapter/whatsapp` -->

## Additional Notes

- No change to `@chat-adapter/shared`’s `cardToFallbackText` — it
remains correct as a full text fallback. The bug was reusing that full
fallback as a caption while also sending a full interactive card.
- Card-only posts (no files) are unchanged.

---------
2026-07-23 19:18:25 +01:00
Akazawa Daisuke 92530dd352 fix(slack): return replyable thread ID from channel posts (#720)
## summary

fixes #719

updates Slack channel posts to return a replyable thread ID rooted at
the newly posted top-level message

`postChannelMessage` still omits `thread_ts` for the initial channel
post, then uses Slack's returned message `ts` to construct
`slack:<channel>:<ts>` for the `SentMessage`

this allows `chat.thread(sent.threadId).post(...)` to reply to a message
returned by `channel.post(...)` instead of creating another top-level
channel message

file-only uploads without a Slack message `ts` keep their existing
channel-scoped thread ID

## test plan

- added a Slack adapter regression assertion that `postChannelMessage`
returns `slack:C123:<message ts>`
2026-07-23 19:05:34 +01:00
Utopia 5eb8b846a7 feat(teams): support outbound reactions (#734)
Outbound Teams reactions were originally implemented as part of #302,
then removed because the Teams feature was not fully rolled out. In [the
follow-up
discussion](https://github.com/vercel/chat/pull/302#issuecomment-4147056867),
the Teams SDK maintainer said they were happy to add the support back
once the rollout was ready. Microsoft now documents agent reaction
support without a preview caveat.

This PR restores that support against the current Teams SDK API:

- implement `addReaction` and `removeReaction` with
`conversations.addReaction` / `conversations.deleteReaction`
- pass native Teams reaction IDs through unchanged and map common
normalized Chat SDK emoji names to their Teams IDs
- upgrade the aligned `@microsoft/teams.*` dependencies to 2.0.14
- update the Teams feature matrices and add a minor changeset

The implementation stays within the existing adapter methods and does
not add another abstraction or affect streaming behavior.

---------

Signed-off-by: Utopia <154325211+Utopi-a@users.noreply.github.com>
2026-07-23 10:52:00 +10:00
Cole 25f30998ce fix(chat): keep attachment/link-only messages in toAiMessages (#713)
- `toAiMessages` previously filtered out any message with empty or
whitespace-only text (`sorted.filter((msg) => msg.text.trim())`). This
discarded messages that carry meaningful content without text — e.g. an
image uploaded with no caption, a file-only upload, or a link-only
message.
- Now messages are kept as long as they have usable content (text,
image/file attachments, or links). Only messages with *none* of those
are skipped.
- When an attachment-only message is included, no empty `text` part is
prepended (an empty text part would be rejected by the AI SDK).
Link-only messages render a standalone `Links:\n...` block.

## Changes

- `packages/chat/src/ai/messages.ts` — drop the text-only pre-filter;
build text conditionally; skip only truly empty messages.
- `packages/chat/src/ai/messages.test.ts` — add tests for image-only,
link-only, interleaved, whitespace-with-attachment, and fully-empty
cases.
- `apps/docs/content/docs/ai/to-ai-messages.mdx` — update the documented
filtering behavior.
- Changeset added (`chat`: patch).

---------

Co-authored-by: Cole Corrente <cole.corrente@snowflake.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-22 14:40:41 +10:00
CamdenA21 e06b4b606b feat(teams): forward a custom token factory to the Teams SDK (#732)
`TeamsAdapterConfig` never forwards a `token` field through to the
underlying `@microsoft/teams.apps` `AppOptions.token`, even though the
Teams SDK already supports it as a genuine "bring your own credentials"
escape hatch (`TokenCredentials['token']`).

The only non-secret auth path currently exposed is `federated`, which
maps to `managedIdentityClientId` and only resolves via Azure-native
managed-identity sources (IMDS, AppService, CloudShell, MachineLearning,
ServiceFabric). That's unreachable from serverless/edge runtimes (e.g.
Vercel) that can't hit Azure IMDS but still need to mint access tokens
through an external mechanism (e.g. a workload-identity federation
bridge exchanging a platform-native OIDC token for an Azure AD token).

We've been carrying a local patch on `@chat-adapter/teams` doing exactly
this forwarding to unblock a production Teams bot running on Vercel with
a user-assigned managed identity. Opening this as a proper PR instead of
staying on the patch indefinitely.

## Changes

- `TeamsAdapterConfig.token?: (scope: string | string[], tenantId?:
string) => string | Promise<string>` — matches
`TokenCredentials['token']`'s real signature.
- `toAppOptions` forwards `config.token` straight through.
- `clientSecret` resolution now also short-circuits when `token` is
provided (alongside the existing `federated` check) —
`TokenManager.initializeCredentials` checks `clientId && clientSecret`
before `clientId && token`, so a stray
`appPassword`/`TEAMS_APP_PASSWORD` would otherwise silently win over an
explicitly configured token factory.
- Unit tests in `config.test.ts` and a `createTeamsAdapter` factory test
in `index.test.ts`.
- Docs: added the `token` config option and a third "Authentication
methods" example in `apps/docs/content/adapters/official/teams.mdx`.
- Changeset (`@chat-adapter/teams`: minor).

---------

Signed-off-by: CamdenA21 <camden@sandstone.ai>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-22 13:18:59 +10:00
Ben Sabic 4cb7e5d58e feat(chat): durable human-in-the-loop approvals via chat/workflow (#728)
Adds a `chat/workflow` subpath export with `requestApproval()`. This is
the DX from #284, rebuilt on Workflow SDK so the approval survives
deploys, restarts, and arbitrarily long waits. No in-memory promises, no
approvals registry, no restart-recovery machinery: the workflow suspends
on a webhook and resumes when a button is clicked.

`requestApproval()` posts a card with Approve/Deny buttons whose
`callbackUrl` targets a `createWebhook()` URL, suspends the workflow
until a decision (or optional durable-sleep timeout), validates
approvers, finalizes the card in place with the outcome (removing the
buttons, leaving an audit trail), and returns the decision.

```typescript
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",
    approvers: ["U_ALICE", "U_BOB"],
  });
  if (approved) {
    await deploy(opts.version);
  }
}
```

Starting it from a handler is one line. `Thread` instances serialize
across the workflow boundary automatically via the existing
`@workflow/serde` hooks on `ThreadImpl` (requires
`chat.registerSingleton()`):

```typescript
import { start } from "workflow/api";
bot.onNewMention(async (thread, message) => {
  await start(deployApproval, [{ thread, version: parseVersion(message.text) }]);
});
```

**Details**

- `workflow` is a new **optional** peer dependency (same pattern as
`ai`); the subpath is the only code that imports it
- Unauthorized clicks (when `approvers` is set) and unrecognizable
payloads post a notice / are ignored, and the workflow keeps waiting
- On timeout the card is finalized as timed out and the result has
`timedOut: true`
- Card builders (`buildApprovalCard`, `buildResolvedCard`) are exported
for custom flows
- Verified the published `dist` preserves the `"use step"` directives
and down-levels `using` correctly, so the app-side Workflow SDK compiler
handles the library code
- Docs page under Interactivity; changeset (`chat` minor); 8 unit tests
mocking the `workflow` primitives

**Deliberate deviation from #284:** no `thread.requestApproval()`
method. The function must suspend at workflow level, so hanging it off
`ThreadImpl` would make `workflow` a hard dependency of core (or require
prototype patching). The standalone `requestApproval(thread, options)`
keeps the dependency optional.

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-22 10:18:38 +10:00
Ben Sabic 907450d73f fix(slack): Enterprise Grid support (#724)
## Slack Enterprise Grid Support

Fixes a set of Enterprise Grid gaps in the Slack adapter, found by
auditing the adapter against Slack's current Enterprise documentation
([Developing for Enterprise
orgs](https://docs.slack.dev/enterprise/developing-for-enterprise-orgs/),
[Events API](https://docs.slack.dev/apis/events-api/),
[oauth.v2.access](https://docs.slack.dev/reference/methods/oauth.v2.access/)).

The headline bug: org-wide installs completing OAuth through
`handleOAuthCallback` were stored under a key that webhook token
resolution never looks up, so every subsequent event failed with "no
installation found."

### Org-wide OAuth installs

`oauth.v2.access` returns `team: null` and a populated `enterprise`
object for org-wide installs (`is_enterprise_install: true`). The
callback previously keyed every installation by `result.team.id`. It now
keys org-wide installs by `enterprise.id` — the same key incoming
webhooks resolve tokens by — and records `enterpriseId` /
`isEnterpriseInstall` on `SlackInstallation`. The returned `teamId` is
always the storage key, so it keeps round-tripping with
`getInstallation` / `deleteInstallation` for both install types.

### Socket mode token resolution

Socket-mode events (live and forwarded from a serverless listener)
bypassed the multi-workspace token-resolution block in `handleWebhook`
entirely and dropped `enterprise_id` / `is_enterprise_install` when
rebuilding the payload. The resolution logic is now factored into
helpers (`resolveEventRequestContext`, `runSlashCommand`,
`extractInstallationFromInteractivePayload`) shared by both paths, so
events, slash commands, and interactive payloads resolve
per-installation tokens identically over HTTP and socket. Socket JSON
delivers `is_enterprise_install` as a boolean where form-encoded
webhooks deliver `"true"`; both shapes are handled.

### Event routing via `authorizations[0]`

Slack documents the envelope's `authorizations[0]` — not the top-level
fields — as the authoritative installation identity for an event. The
top-level `team_id` / `enterprise_id` can name a different workspace for
Slack Connect shared-channel events (slackapi/bolt-js#935), and org-wide
envelopes may omit the top-level flags. Token resolution now prefers
`authorizations[0]` with top-level fallback, matching Bolt's behavior.

### Installation-scoped user caches

The user profile cache (`slack:user:*`) and display-name mention reverse
index (`slack:user-by-name:*`) were global across installations. In
multi-workspace deployments, one tenant's cached profile bled into
another, and mention resolution could pick a same-named user from a
different workspace. Both are now prefixed with the current installation
ID (enterprise ID for org-wide installs — correct on Grid, where users
are org-global). Single-workspace keys are unchanged; scoped entries
repopulate on first lookup.

### `team_id` on org-token API calls

Org-wide tokens span every workspace in the org, so workspace-scoped Web
API methods (`conversations.list`, `usergroups.list`, …) require an
explicit `team_id`. `withToken` now injects the event's `team_id` on
calls made under an org-wide install when the caller didn't set one —
Slack documents always passing it as safe ("accepted, but ignored"
elsewhere). When an event arrives from a shared channel hosted on an
"away" workspace, its `context_team_id` is echoed back as
`client_context_team_id`, scoped to calls targeting the originating
channel.

### Event retry deduplication

Retried deliveries (`x-slack-retry-num` header, socket `retry_num`) are
dropped when the original delivery was already dispatched, using an
`event_id` marker in the state adapter (24 h TTL, covering Slack's
opt-in Delayed Events redeliveries). First deliveries pay no state read,
and events whose first delivery never arrived are still recovered via
the retry — preserving the existing missed-event recovery semantics.

### W-prefixed user IDs

Grid users can have `W…` IDs anywhere `U…` appears. The outgoing
bare-mention scanner only recognized `@U…` as a raw user ID; it now
accepts both. This was the only `^U` assumption in the package —
incoming mention parsing was already prefix-agnostic.

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-21 09:10:52 +10:00
Ben Sabic bb7cd1241d feat(slack): expose author email on incoming messages (#716)
Slack counterpart to #711: populates `message.author.email` on
normalized incoming Slack messages.

Unlike Teams, no new lookup was needed — `parseSlackMessage` already
resolves the sender via the state-cached `users.info` call
(`lookupUser`), and the cached profile already carried `email`. This
change threads that value onto the author, so there is no additional API
call per message. The email is only present when the app has the
`users:read.email` scope; otherwise (or when the lookup is skipped, e.g.
webhook posts with a `username`) the field stays `undefined`.

Also documents the optional scope in the adapter README and the docs
site manifest section. The core `Author.email` field and serialization
already landed in #711, so this is a Slack-only changeset.

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-21 07:44:08 +10:00
Max 26c052258c feat(discord): add channel response allowlist (#715)
## Summary

Adds an opt-in `respondToChannelIds` Discord adapter option. Non-bot
messages in configured parent channels and their child threads are
routed through mention handlers without requiring an @mention; top-level
messages keep the adapter's existing automatic thread creation, and
forwarded Gateway packets preserve the parent channel for thread
replies.

I understand this might be something you want to keep out but I find it
very useful for my own "Hermes-like" agent :)

## Test plan

- `pnpm --filter @chat-adapter/discord test`
- `pnpm --filter @chat-adapter/discord typecheck`
- `pnpm check`
- `pnpm konsistent`
- `pnpm typecheck`
- `pnpm validate`

## 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 (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (or N/A)

---------

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-18 22:29:56 +10:00
Dean Mauro b605cf63a2 fix(discord): Suppress link previews in markdown (#726)
## Summary

Fixes #692 

When bracketed `<link>` or `[text](<link>)` notations are used in
Discord markdown, embedded link previews should be suppressed.

We have to identify this notation in the markdown parser and decorate
the resulting AST so the `[text](<link>)` notation can be handled as
well. Otherwise, this information gets lost along the way.

## Test plan

```
await event.channel.post({ markdown: '<https://google.com>'});
```

<img width="172" height="27" alt="image"
src="https://github.com/user-attachments/assets/386ea82d-d00c-4ebd-a29b-b2cd495e973e"
/>


```
await event.channel.post({ markdown: '[Google](<https://google.com>)'});
```

<img width="199" height="29" alt="image"
src="https://github.com/user-attachments/assets/0faea900-1742-482e-b477-0b5e5ac87316"
/>


## 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 (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (or N/A)
2026-07-18 22:10:35 +10:00
Ben Sabic 80def3ab17 feat: add author.isSystem to distinguish platform-generated messages (#707)
Closes #653

Chat SDK's normalized author only distinguished the current bot from
other bots (`isBot`/`isMe`), so Slack system notifications authored by
the reserved `USLACK` user — which carry no `bot_id` and no system
subtype — were dispatched to handlers as if human-authored. Consumers
had to hard-code `message.author.userId === "USLACK"`, leaking
Slack-specific identifiers into adapter-independent code.

This adds an optional `isSystem?: boolean` to the normalized `Author`
type, documented so that an absent value means `false`. Keeping it
optional avoids breaking existing custom adapters and serialized
messages, as proposed in the issue. The Slack adapter now sets it in
both parse paths (`parseSlackMessage` and the sync `parseMessage` path)
via a `SLACK_SYSTEM_USER_ID` constant, so applications can write:

```ts
bot.onNewMention(async (thread, message) => {
  if (message.author.isSystem) {
    return;
  }
  await generateAssistantResponse(thread, message);
});
```

Other adapters can adopt the same field when their platforms expose
equivalent system-generated messages.

Also included:

- Regression tests covering the issue's exact case (`USLACK` DM, no
`bot_id`, no subtype) across all three layers: async parse, sync
`parseMessage`, and end-to-end `handleWebhook` dispatch — plus the
negative case for human authors.
- A `USLACK` webhook fixture in `sample-messages.md`.
- `isSystem` documented in the Author type table on the Message API docs
page.
- Changesets for `chat` and `@chat-adapter/slack`.

---------

Co-authored-by: mdnanocom <arnaud@massive-dynamic.ai>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-16 00:46:05 +10:00
Jörmungandrk 0701679e40 fix: Enhance mention regex and sleep method with abort support (#706)
Refactor mention regex handling and sleep method to support abort
signal. a new `RegExp` is compiled on every call to `isBotMentioned`,
which is invoked for every incoming message. Since `username` is stable
after initialization, this regex can be compiled once (e.g. cached in a
private field and updated when `_userName` changes) and reused across
calls.


## Checklist

- [x] All commits are signed and verified
- [x] All commits are signed off for the DCO (`git commit -s`)
- [x] `pnpm validate` passes
- [ ] Changeset added (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [ ] Documentation updated (or N/A)

---------

Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-15 14:58:53 +10:00
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
zhygis d88789c982 fix(state-pg): setIfNotExists TTL expiry (#636)
## Summary

Fixes the Postgres state adapter so `setIfNotExists()` can claim a cache
key whose existing row has expired.

Previously the method used `ON CONFLICT DO NOTHING`, so an expired row
in `chat_state_cache` still blocked acquisition until a separate cleanup
deleted it. That diverged from the memory adapter behavior and from the
expected lease semantics for cache-backed coordination.

The new query keeps active rows protected, but replaces rows whose
`expires_at` is in the past.

## Validation

- `pnpm --filter @chat-adapter/state-pg test`
- `pnpm --filter @chat-adapter/state-pg typecheck`
- `pnpm exec ultracite check packages/state-pg/src/index.ts
packages/state-pg/src/index.test.ts`

---------

Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-15 14:39:32 +10:00
Max 46681f50cb fix(teams): hydrate incoming author email (#711)
## Summary

Adds optional email to normalized message authors and preserves it
through message serialization.

For incoming Teams messages, resolves the sender with the activity's
Entra object ID before dispatch, falling back to the cached ID when the
activity omits it. The lookup reuses the existing `mail ??
userPrincipalName` mapping from #708, and missing permissions or Graph
failures leave email undefined without blocking message delivery.

This deliberately revisits the author-profile boundary discussed in
#239: the core field is optional, and Teams populates it only when
Microsoft Graph can resolve the sender.

## Test plan

- [x] `pnpm --filter chat exec vitest run src/message.test.ts`
- [x] `pnpm --filter @chat-adapter/teams exec vitest run
src/index.test.ts`
- [x] Chat and Teams package typechecks and builds
- [x] `TURBO_CONCURRENCY=2 pnpm validate`

## 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 (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (or N/A)

---------

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
Signed-off-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-15 14:37:56 +10:00
Max 93a58af563 fix(teams): preserve native streaming with placeholders (#709)
## Summary

Preserves Teams native DM streaming when
`fallbackStreamingPlaceholderText` is explicitly configured. Direct
messages show the text through the Teams SDK native informative status
before streaming the answer, group chats use the core post-and-edit
fallback, `null` disables progress, and omitted configuration keeps the
existing native-DM/buffered-group behavior.

## Test plan

- [x] `pnpm --filter @chat-adapter/teams exec vitest run
src/index.test.ts`
- [x] `pnpm --filter chat exec vitest run src/chat.test.ts
src/thread.test.ts`
- [x] Teams and Chat package typechecks and builds
- [x] `TURBO_CONCURRENCY=2 pnpm validate`

## 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 (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (or N/A)

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-07-15 01:15:15 +10:00
Max 3895ab3fa9 fix(teams): fall back to user principal name for email (#708)
## Summary

Use Microsoft Graph's `userPrincipalName` as the Teams user's email when
`mail` is missing, while preserving `mail` precedence when both fields
are present.

## Test plan

- [x] `pnpm --filter @chat-adapter/teams test`
- [x] `pnpm --filter @chat-adapter/teams typecheck`
- [x] `pnpm --filter @chat-adapter/teams build`
- [x] `TURBO_CONCURRENCY=2 pnpm validate`

## 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 (or N/A — see
[CONTRIBUTING.md](./CONTRIBUTING.md))
- [x] Documentation updated (N/A — no public API change)

Signed-off-by: onmax <maximogarciamtnez@gmail.com>
2026-07-15 01:10:10 +10:00
github-actions[bot] f84b5911e7 chore(release): version packages (#695)
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @chat-adapter/discord@4.34.0

### Minor Changes

- 0fdb902: Add opt-in Discord Components v2 rendering for Chat SDK cards
via `contentFormat: DiscordContentFormat.ComponentsV2`.
- 5341f90: Ignore `@everyone`/`@here` pings by default in gateway mode.
Previously the legacy gateway listener treated global pings as bot
mentions, so the bot responded to announcements. A new
`respondToGlobalMentions` config option (default `false`) restores the
old behavior when enabled, and also lets forwarded gateway messages opt
in via the `mention_everyone` field.
- 6c2a391: Add support for renaming native Discord thread channels.

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/slack@4.34.0

### Minor Changes

- 1721fa0: Add support for Slack's Agent messaging experience
(`agent_view`).

- New core event `onAppContextChanged` with a normalized
`AppContextEntity[]` describing the user's active view (channel / canvas
/ list / message / unknown).
- `AppHomeOpenedEvent` now carries the folded active-view context as
`entities` and the opened `tab` (Slack: `"home"` / `"messages"`), so
handlers can tell a Home-tab open from the DM-open signal under
`agent_view`.
- Slack adapter: new `agentView` config flag (under `agent_view`,
`app_home_opened` is the DM-open signal regardless of tab and folded
context is surfaced), routing for the `app_context_changed` event, and a
`getAppContext(message)` helper to read the folded context on DM
messages.
- `setSuggestedPrompts` now accepts an optional thread reference
(agent_view lets prompts sit at the top of the agent conversation).
- Under `agentView`, DM (Messages-tab) messages are threaded per new
Slack's 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.
- `createSlackAdapter` env auth fallback (`SLACK_BOT_TOKEN` /
`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`) is now disabled only when an
auth or verification field (`botToken`, `clientId`, `clientSecret`,
`installationProvider`, `signingSecret`, `webhookVerifier`) is passed
explicitly, instead of by any config object — so `createSlackAdapter({
agentView: true })` still picks up env credentials, while
explicit-secret configs stay immune to ambient env vars.
- Bumped `@slack/web-api` to `^7.18.0` (adds the optional `thread_ts`
typing for `setSuggestedPrompts`).

- 4717a38: Add chart support and richer table rendering, with native
Slack data table and data visualization blocks.

- New core `ChartElement` and `Chart()` builder (JSX supported) with
pie, bar, area, and line charts, mirroring Slack's data visualization
model: pie charts take `segments`, series charts take named `series`
plotted against shared `categories` with optional `xLabel`/`yLabel`.
- `TableElement` / `Table()` gain optional `caption` (accessible table
description) and `pageSize` (rows per page) fields.
- Charts degrade gracefully on platforms without native chart support:
the underlying data renders as a text table via the shared card fallback
(new `chartElementToFallbackText` helper).
- Slack adapter: card tables now render as [data table
blocks](https://docs.slack.dev/reference/block-kit/blocks/data-table-block)
by default — paginated and sortable — instead of plain table blocks.
Header-only tables keep the plain table block; tables exceeding Slack
limits (100 data rows, 20 columns, 10,000 characters) fall back to ASCII
as before.
- Slack adapter: card charts render as [data visualization
blocks](https://docs.slack.dev/reference/block-kit/blocks/data-visualization-block).
Charts violating Slack constraints (50-character title, 12
segments/series, 20 categories, 20-character labels, one data point per
category, max 2 charts per message) fall back to a text rendering
instead of being rejected by the API.
- The `@chat-adapter/slack/blocks` subpath gets the same treatment:
`SlackChartElement` types, `chart` card children, data table rendering,
and matching limits.
- `postMessage` now surfaces Slack's per-block validation details when
the API rejects blocks (`invalid_blocks`), instead of the bare "An API
error occurred" message.

- 0f743c9: Add declarative agent-experience config and harden native
streaming:

- `suggestedPrompts` — a static payload or per-thread resolver, applied
automatically when an assistant/agent thread opens
(`assistant_thread_started` in legacy `assistant_view`, or a
Messages-tab `app_home_opened` under `agentView`, where prompts pin at
the top of the agent conversation without a `thread_ts`). The resolver
receives the thread context (`channelId`, `userId`, legacy
`threadTs`/`teamId`/`enterpriseId`, and active-view `entities` under
`agentView`); returning `null`/`undefined` skips the thread. Prompts
beyond Slack's 4-prompt limit are dropped with a warning, and
resolver/API failures are logged without failing the webhook.
- `loadingMessages` — default rotating status strings for the assistant
thinking indicator, used by `startTyping` and `setAssistantStatus` when
no explicit status/messages are passed.
- `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()`
now falls back to throttled post-and-edit mid-stream instead of failing
the reply; already-consumed text is preserved. Permanent platform errors
(`unknown_method`, `method_deprecated`, `feature_not_enabled`) latch
native streaming off for subsequent streams on the adapter instance.
Structured chunks (`task_update` / `plan_update`) are skipped in
fallback mode.

- `feedbackButtons` — append Slack's native thumbs up/down
(`context_actions` + `feedback_buttons` block) to every streamed reply.
Pass `true` for defaults or an options object (`actionId`, labels,
values); clicks dispatch through `bot.onAction` with a positive/negative
value. A `buildFeedbackButtonsBlock(options?)` helper is exported for
attaching the block to non-streamed messages.

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

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/telegram@4.34.0

### Minor Changes

- 8d7ccdb: Add Telegram media group uploads for multiple files and
attachments.

### Patch Changes

- 2531a42: Fix `detectMention` (and the Telegram adapter's
`isBotMentioned`) falsely matching `@bot` when `@bot-dev` is mentioned.
`\b` (word boundary) matches between a word character and a hyphen, so
`/@bot\b/` incorrectly matches `@bot-dev`. Replaced with `(?![\w-])` to
exclude hyphens.
- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/web@4.34.0

### Minor Changes

- 6714efc: Support AI SDK v7 as a peer dependency.

- `chat` now accepts `ai@^6.0.182 || ^7.0.0` (`chat/ai` tools work with
both majors).
- `@chat-adapter/web` now accepts `ai@^6 || ^7`, `@ai-sdk/react@^3 ||
^4`, `@ai-sdk/svelte@^4 || ^5`, and `@ai-sdk/vue@^3 || ^4`.
- The `chat/ai` tool factories now declare explicit `Tool<Input,
Output>` return types instead of relying on inference, so the published
declarations no longer depend on `ai` internals that changed in v7. The
public type surface is unchanged.

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/whatsapp@4.34.0

### Minor Changes

- 2338a66: Add `sendTemplate()` for sending pre-approved template
messages, enabling business-initiated conversations outside the 24-hour
customer service window
- 8bd8a57: Implement outbound file and attachment sending for the
WhatsApp adapter.

Supports binary `FileUpload` uploads, typed `Attachment` payloads
(binary or HTTPS link passthrough), multi-file sequential sends, smart
MIME-to-message-type mapping, caption placement with audio/long-text
fallbacks, and card+file sequencing.

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/x@4.34.0

### Minor Changes

- 4bca64f: add image upload support to X posts and DMs via the chunked
media upload endpoints

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## chat@4.34.0

### Minor Changes

- 1721fa0: Add support for Slack's Agent messaging experience
(`agent_view`).

- New core event `onAppContextChanged` with a normalized
`AppContextEntity[]` describing the user's active view (channel / canvas
/ list / message / unknown).
- `AppHomeOpenedEvent` now carries the folded active-view context as
`entities` and the opened `tab` (Slack: `"home"` / `"messages"`), so
handlers can tell a Home-tab open from the DM-open signal under
`agent_view`.
- Slack adapter: new `agentView` config flag (under `agent_view`,
`app_home_opened` is the DM-open signal regardless of tab and folded
context is surfaced), routing for the `app_context_changed` event, and a
`getAppContext(message)` helper to read the folded context on DM
messages.
- `setSuggestedPrompts` now accepts an optional thread reference
(agent_view lets prompts sit at the top of the agent conversation).
- Under `agentView`, DM (Messages-tab) messages are threaded per new
Slack's 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.
- `createSlackAdapter` env auth fallback (`SLACK_BOT_TOKEN` /
`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`) is now disabled only when an
auth or verification field (`botToken`, `clientId`, `clientSecret`,
`installationProvider`, `signingSecret`, `webhookVerifier`) is passed
explicitly, instead of by any config object — so `createSlackAdapter({
agentView: true })` still picks up env credentials, while
explicit-secret configs stay immune to ambient env vars.
- Bumped `@slack/web-api` to `^7.18.0` (adds the optional `thread_ts`
typing for `setSuggestedPrompts`).

- 4717a38: Add chart support and richer table rendering, with native
Slack data table and data visualization blocks.

- New core `ChartElement` and `Chart()` builder (JSX supported) with
pie, bar, area, and line charts, mirroring Slack's data visualization
model: pie charts take `segments`, series charts take named `series`
plotted against shared `categories` with optional `xLabel`/`yLabel`.
- `TableElement` / `Table()` gain optional `caption` (accessible table
description) and `pageSize` (rows per page) fields.
- Charts degrade gracefully on platforms without native chart support:
the underlying data renders as a text table via the shared card fallback
(new `chartElementToFallbackText` helper).
- Slack adapter: card tables now render as [data table
blocks](https://docs.slack.dev/reference/block-kit/blocks/data-table-block)
by default — paginated and sortable — instead of plain table blocks.
Header-only tables keep the plain table block; tables exceeding Slack
limits (100 data rows, 20 columns, 10,000 characters) fall back to ASCII
as before.
- Slack adapter: card charts render as [data visualization
blocks](https://docs.slack.dev/reference/block-kit/blocks/data-visualization-block).
Charts violating Slack constraints (50-character title, 12
segments/series, 20 categories, 20-character labels, one data point per
category, max 2 charts per message) fall back to a text rendering
instead of being rejected by the API.
- The `@chat-adapter/slack/blocks` subpath gets the same treatment:
`SlackChartElement` types, `chart` card children, data table rendering,
and matching limits.
- `postMessage` now surfaces Slack's per-block validation details when
the API rejects blocks (`invalid_blocks`), instead of the bare "An API
error occurred" message.

- 6714efc: Support AI SDK v7 as a peer dependency.

- `chat` now accepts `ai@^6.0.182 || ^7.0.0` (`chat/ai` tools work with
both majors).
- `@chat-adapter/web` now accepts `ai@^6 || ^7`, `@ai-sdk/react@^3 ||
^4`, `@ai-sdk/svelte@^4 || ^5`, and `@ai-sdk/vue@^3 || ^4`.
- The `chat/ai` tool factories now declare explicit `Tool<Input,
Output>` return types instead of relying on inference, so the published
declarations no longer depend on `ai` internals that changed in v7. The
public type surface is unchanged.

### Patch Changes

- 5c926f1: Preserve markdown structural whitespace when extracting
normalized message text.
- 2531a42: Fix `detectMention` (and the Telegram adapter's
`isBotMentioned`) falsely matching `@bot` when `@bot-dev` is mentioned.
`\b` (word boundary) matches between a word character and a hyphen, so
`/@bot\b/` incorrectly matches `@bot-dev`. Replaced with `(?![\w-])` to
exclude hyphens.
## @chat-adapter/gchat@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/github@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/linear@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/messenger@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/shared@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
## @chat-adapter/teams@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/twilio@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
  - @chat-adapter/shared@4.34.0
## @chat-adapter/state-ioredis@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
## @chat-adapter/state-memory@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
## @chat-adapter/state-pg@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
## @chat-adapter/state-redis@4.34.0

### Patch Changes

- Updated dependencies [5c926f1]
- Updated dependencies [2531a42]
- Updated dependencies [1721fa0]
- Updated dependencies [4717a38]
- Updated dependencies [6714efc]
  - chat@4.34.0
## @chat-adapter/tests@4.34.0

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-13 16:41:59 +01:00
Remon Oldenbeuving 5c926f1987 fix(chat): preserve markdown whitespace in plain text (#604)
## Problem
When I mention a Chat SDK-powered bot on GitHub like this:

```
@bot
hi there!
```

The mention doesn't trigger any handling, because the `mdastToString`
helper replaces all newlines with an empty string, so the logs look like
this:

```
[chat-sdk] Checking message patterns { patternCount: 0, patterns: [], messageText: '@bothi there' }
[chat-sdk] No handlers matched message {
  threadId: 'github:RSO/chat:issue:29',
  text: '@bothi there'
}
```

## Summary
- Preserve structural markdown whitespace when extracting normalized
plain text from mdast.
- Add regression coverage for newline-separated bot mentions in core
markdown extraction, GitHub issue/review comments, and Chat mention
routing.
- Add a patch changeset for the behavior fix.

## Testing
- `pnpm check`
- `pnpm knip`
- `pnpm test:workspace`
- `pnpm --filter chat test`
- `pnpm --filter @chat-adapter/github test`
- `pnpm --filter chat typecheck`
- `pnpm --filter @chat-adapter/github typecheck`

## Notes
- `pnpm validate` was attempted and reached the full Turbo test graph,
but failed on `packages/integration-tests/src/replay-discord.test.ts`
(`should skip bot's own messages in subscribed threads`). Rerunning
`pnpm --filter @chat-adapter/integration-tests test --
src/replay-discord.test.ts` passed, so this appears unrelated to the
markdown whitespace change.
- `.github/CONTRIBUTING.md` requires signed commits. This environment
has no `gpg` binary and no SSH signing identities loaded, so the commit
in this PR is currently unsigned and may need to be re-signed before
merge.

---------

Signed-off-by: dancer <josh@afterima.ge>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-13 13:40:17 +01:00
C. T. Lin 6714efc3a1 feat: support AI SDK v7 (ai@7) as a peer dependency (#691)
Closes #690

## What

Widens the AI SDK peer dependency ranges so the Chat SDK installs
cleanly next to `ai@7`:

- `chat`: `ai@^6.0.182 || ^7.0.0`
- `@chat-adapter/web`: `ai@^6 || ^7`, `@ai-sdk/react@^3 || ^4`,
`@ai-sdk/svelte@^4 || ^5`, `@ai-sdk/vue@^3 || ^4`

This also unbreaks `create-chat-sdk` scaffolds, which install
`ai@latest` (now v7) next to `chat` and currently hit a peer conflict
out of the box.

## The one real v6 → v7 break

In v7, `tool()` with an `execute` function returns
`ExecutableTool<Tool<...>>` — an internal type from
`@ai-sdk/provider-utils` that `ai` does not re-export. The `chat/ai`
tool factories relied on inference, so declaration emit failed with
TS2742 (17 errors). The factories now declare explicit `Tool<Input,
Output>` return types, which is exactly the shape the previously
published `.d.ts` already had — the public type surface is unchanged,
and the emitted declarations only reference types from `ai` (portable
for consumers on either major).

Everything else checked out compatible:

- v7 stream parts keep `text-delta` / `finish-step` shapes, so
`fromFullStream` duck-typing works unchanged; `fullStream` remains as a
deprecated alias
- tool-level `needsApproval` is deprecated in v7 but still typed and
honored
- `createUIMessageStream`, `createUIMessageStreamResponse`,
`isTextUIPart`, `UIMessage`, `UIMessageStreamWriter`, `ChatInit`,
`DefaultChatTransport` all still exported — `@chat-adapter/web` needed
zero source changes

## Other changes

- devDependencies move to v7 so the workspace develops/tests against the
latest major
- `examples/nextjs-chat` and `examples/nuxt-chat` move to `ai@^7`
(required — mixing majors across the workspace fails typecheck, since
`chat`'s d.ts resolves `ai` types from its own devDependency)
- Test-only: the `ToolExecutionOptions` stub type is now derived from
`Tool["execute"]` because v7 made the generic parameter required
- Changeset included (minor for `chat` and `@chat-adapter/web`)

## Verification

The same source was verified against **both majors** (`ai@6.0.182` and
`ai@7.0.17`): `tsc --noEmit` and the full test suites (`chat`: 1035
tests, `@chat-adapter/web`: 21 tests) pass on each. `pnpm validate`
(knip + check + typecheck + test + build, including both examples) is
green on v7.

Note for adopters: `ai@7` itself requires Node.js ≥ 22 and is ESM-only;
`chat` keeps `engines.node >= 20` since `ai` is an optional peer.

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

Signed-off-by: chentsulin <chentsulin@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: dancer <josh@afterima.ge>
2026-07-13 21:50:27 +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
Takuma Shibuya 2531a4227e fix username regexp (#621)
## Summary

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

Fix `detectMention` falsely matching `@bot` when `@bot-dev` is
mentioned. `\b` (word boundary) matches between a word character and a
hyphen, so `/@bot\b/` incorrectly matches `@bot-dev`. Replaced with
`(?![\w-])` to exclude hyphens.

## Test plan

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

## Checklist

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

---------

Signed-off-by: sivchari <shibuuuu5@gmail.com>
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
2026-07-13 20:39:20 +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