mirror of
https://github.com/vercel/chat.git
synced 2026-09-14 18:32:29 +08:00
@chat-adapter/linear@4.29.0
192 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6581d31507 |
chore(release): version packages (#469)
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.29.0 ### Minor Changes - |
||
|
|
9d7891b2f5 |
fix(release): prevent accidental major bumps (#520)
## summary fixes the release plan so peer-dependent packages only trigger major bumps when the next dependency version falls outside their supported range this keeps the current release on `4.29.0` instead of accidentally bumping the fixed `chat` and `@chat-adapter/*` group to `5.0.0` also changes `@chat-adapter/tests` to use a real `chat` peer range while keeping `workspace:*` for local development |
||
|
|
ac8a20779c |
feat(chat): add chat/ai subpath for AI SDK utilities (#492)
## Summary
Introduces a dedicated `chat/ai` subpath as the home for every Vercel AI
SDK helper that ships with Chat SDK. Importing from this subpath keeps
the optional `ai` and `zod` peer dependencies out of bundles that don't
use them.
### What's new
- **`createChatTools`** — exposes Chat SDK operations as ready-to-use AI
SDK tools so an agent can read, post, react, edit, delete, and manage
thread subscriptions across every adapter the supplied `Chat` instance
has registered.
- Write operations require user approval by default (`requireApproval:
true`); toggle globally or per-tool.
- Three presets — `reader`, `messenger`, `moderator` — scope the
toolset.
- Individual tools can also be cherry-picked (`import { postMessage,
addReaction } from "chat/ai"`).
- **`toAiMessages`** (and the `Ai*` / `ToAiMessagesOptions` types) now
live alongside the tools at `chat/ai`. The previous `chat` re-exports
continue to work, but are flagged `@deprecated` with an editor hint
pointing to the new home — migration is a one-line import change.
- **Docs** — new `/docs/ai` section between Usage and Adapters in the
sidebar:
- `/docs/ai` — Overview
- `/docs/ai/ai-sdk-tools` — `createChatTools` guide
- `/docs/ai/to-ai-messages` — `toAiMessages` reference
- `/docs/ai/types` — Reference for every type exported from `chat/ai`
- **Example app** — `examples/nextjs-chat` now demos the new surface via
a "Run Agent Demo" button on the welcome card and a free-form `/agent
<prompt>` slash command (streaming, with a placeholder so users get
immediate feedback in channel contexts where Slack's typing-status API
is a no-op).
### Future plans
`createChatTools` currently exposes the cross-adapter Chat SDK surface
only. A natural follow-up is to also support **platform-specific tools**
— e.g. expose Slack-only `pin`/`unpin`, Discord-only thread archiving,
GitHub-only issue commenting, etc., so users can further extend what
their agent can do without dropping back to raw adapter calls. The shape
would likely be additional opt-in factories under `chat/ai` (or
per-adapter subpaths like `@chat-adapter/slack/ai`) that return tools
layered on top of the platform-specific adapter clients, while keeping
the cross-platform `createChatTools` API as the lowest common
denominator.
### Coverage
- `createChatTools` orchestrator: 100% statements / 94.7% branches.
- Every tool factory's `execute()` is exercised end-to-end (29 tests in
`index.test.ts`).
- `toAiMessages` keeps its existing 35-test suite covering role mapping,
attachment handling, links, transforms, and unsupported-attachment
fallbacks.
- Tools folder overall: 99.0% statements / 86.1% branches / 97.4%
functions / 98.9% lines.
---------
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
|
||
|
|
b75eedbb5f |
feat(chat): add queue-debounce concurrency strategy (#495)
## summary adds an opt-in `burst` concurrency strategy for #414 when a thread is idle, the first message waits for `debounceMs`, messages that arrive during that window are queued, and the handler runs once with the latest message plus earlier burst messages in `context.skipped` after the handler finishes, messages that arrived while it was running are drained like `queue`, so the latest queued message is processed with earlier queued messages in `context.skipped` keeps existing `drop`, `queue`, `debounce`, and `concurrent` behavior unchanged updates docs to cover `burst`, explain when to choose it over `debounce`, and document the related `MessageContext` behavior |
||
|
|
716e934aa2 |
feat(web-adapter): first class support for Vue and Svelte (#498)
## Summary <!-- What does this PR do? --> ## Test plan <!-- How did you verify the changes? --> ## Checklist - [ ] All commits are signed and verified - [ ] `pnpm validate` passes - [ ] Changeset added (or N/A — see [CONTRIBUTING.md](./CONTRIBUTING.md)) - [ ] Documentation updated (or N/A) --------- Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
2f108bd4b3 |
feat: rename adapter.client to adapter.octokit / adapter.linearClient / adapter.webClient (#478)
## Summary
Rename the public native client getter on the GitHub, Linear, and Slack
adapters so it matches the underlying SDK class instead of the generic
`.client`. The previous `.client` getter is preserved as a `@deprecated`
alias on all three adapters, so existing code keeps working without
changes.
- `bot.getAdapter("github").client` is now
`bot.getAdapter("github").octokit` (returns `Octokit`)
- `bot.getAdapter("linear").client` is now
`bot.getAdapter("linear").linearClient` (returns `LinearClient` from
`@linear/sdk`)
- `bot.getAdapter("slack").client` is now
`bot.getAdapter("slack").webClient` (returns `WebClient` from
`@slack/web-api`)
Each new getter has TSDoc covering single- vs multi-tenant resolution
rules and when calling outside a webhook handler throws. Focused unit
tests assert that the new getter returns the underlying SDK instance,
that single-tenant calls return the same instance, that the deprecated
`.client` alias points at the new getter, that multi-tenant mode without
webhook context throws on both getters, and that inside a webhook
context the getter resolves to the per-tenant client.
Commits are split for review:
1. `feat(adapter-github): rename adapter.client to adapter.octokit`
2. `feat(adapter-linear): rename adapter.client to adapter.linearClient`
3. `docs: use .octokit / .linearClient in chat-sdk.dev examples`
4. `chore: changeset for adapter native client getter rename`
5. `fix: hoist regex literals in new client-getter tests to module
scope`
6. `feat(adapter-slack): rename adapter.client to adapter.webClient`
7. `docs: include slack .webClient in chat-sdk.dev examples`
8. `chore: include adapter-slack in native client getter rename
changeset`
9. `test(adapter-github,adapter-linear): cover with-context resolution
on the new client getters`
---------
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
|
||
|
|
b9b17cd37d |
fix(discord): handle interactions in gateway-only mode (#490)
## summary fixes #343 fix Discord gateway-only mode so `InteractionCreate` events are handled directly when no interactions endpoint is configured slash commands now defer the gateway interaction and route through the existing slash command handler path, and button interactions defer updates before routing through the existing action handler path also clarifies in the Discord README that Discord sends interactions through either the Gateway or an Interactions Endpoint URL, not both |
||
|
|
add27309fb | feat(telegram): support typed attachment uploads (#485) | ||
|
|
fdebde7988 |
Reapply "feat(slack): expose direct WebClient access via adapter.client" (#472) (#476)
This reverts commit
|
||
|
|
711babe06d |
fix(adapter-telegram): handle video_note (round video messages) in extractAttachments (#457)
* fix(adapter-telegram): handle video_note in extractAttachments Round video messages (video_note) were silently dropped because extractAttachments had no branch for them. Adds the video_note field to TelegramMessage and extracts it as a "video" attachment with width/height set to the clip's length. Fixes #456 * test(adapter-telegram): add video_note attachment extraction test |
||
|
|
06fb8e59ef |
chore: set up konsistent with basic initial config for package, adapter, and state adapter conventions (#466)
* set up konsistent with basic initial config * add konsistent to CI * fix konsistent.json formatting * fix(gchat): move GoogleChatAdapterConfig to ./types for konsistent * fix(slack): move SlackAdapterConfig to ./types and drop Partial wrapper from createSlackAdapter * fix(messenger): name createMessengerAdapter parameter MessengerAdapterConfig * fix(web): rename WebAdapterOptions to WebAdapterConfig and import Adapter type in index.ts * fix(whatsapp): align WhatsAppAdapterConfig and creator with konsistent + map kebab to PascalCase * fix(state-memory): add MemoryStateAdapterOptions type for konsistent * fix(state-ioredis): unify URL and client options under IoRedisStateAdapterOptions * fix(state-redis): unify URL and client options under RedisStateAdapterOptions * fix(state-pg): unify URL and client options under PostgresStateAdapterOptions * chore: changeset for konsistent convention alignment * chore: drop CHANGELOG.md from konsistent's required files list CHANGELOG.md is generated automatically by changesets on each release — it's never hand-authored and doesn't exist for a package until its first release lands. Requiring it as a convention check makes CI fail indefinitely for any newly added package, with no honest fix available (an empty placeholder is just noise that gets overwritten on first release). * docs: document konsistent and package shape conventions * fix(web): use WebAdapterConfig in WebAdapter field types after main merge The merge of main into konsistent brought in PR #475's `protected` field modifiers on top of the WebAdapterOptions → WebAdapterConfig rename, leaving two stale references to the (un-imported) old name. Switch them to WebAdapterConfig and update a stale JSDoc reference in als.ts to match. --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> Co-authored-by: Ben Sabic <27636870+bensabic@users.noreply.github.com> |
||
|
|
e60bc8c408 |
chore: add .nvmrc file, formally specify Node version range support, and cover more versions in CI (#465)
* add .nvmrc file * follow up * make support of Node >= 20 explicit * update default Node version for contributing to the repo to 24 * run build-and-test CI job for both Node 20 and 24 * add changeset for package.json change |
||
|
|
3347bfbcda |
chore: remove .vercel.approvers files (#483)
Code ownership is already governed by .github/CODEOWNERS. Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
2ffed48bea |
feat: make adapter internals protected to enable subclassing (#475)
* chore: changed class function access to protected * chore: format * chore: added changeset * chore(changeset): drop unchanged shared package, expand description * refactor(adapters): keep internal state private, only protected for extension surface Narrow scope of #475: caches, polling/runtime state, and one-shot warning flags stay private. Methods and shared helpers (logger, formatConverter, chat, config) remain protected as the documented extension surface. Also fixes a typecheck failure where gchat's oauth2Client (now private) no longer requires a portable type for the emitted .d.ts. * test(adapters): add subclass extensibility tests Each adapter now has a compile-time test that subclasses can access the documented protected surface. If any of these members revert to private, the test file fails to type-check. * style: apply ultracite formatting to subclass tests * style(slack): mark static cache TTL constants as readonly These three protected static cache TTLs are configuration constants, not mutable state. Marking them readonly prevents subclasses (the new extension surface from this PR) from mutating values shared across every instance in-process. * test(adapters): document intent of subclass extensibility tests Mirrors the inline comment from the Telegram subclass test across the other nine adapter tests so future readers immediately understand these blocks are type-only sentinels — they fail at typecheck (not vitest) if a member reverts to private. * docs(adapters): document subclassing for adapter customization Adds a "Customizing an adapter via subclassing" section to the Adapters page that walks through extending an official adapter to override a protected hook (using the issue #433 Telegram processUpdate scenario as the canonical example) and clarifies that private members are intentionally off-limits. * refactor(linear): expose accessTokenExpiry to subclasses The surrounding refreshClientCredentialsToken and ensureValidToken methods are now protected, but accessTokenExpiry was kept private — meaning a subclass overriding either method couldn't read or update the expiry without calling super. Flipping it to protected lets subclasses fully reimplement the token-refresh flow. * chore(changeset): bump adapters from patch to minor This PR adds a new, additive capability — subclassing official adapters to override protected hooks. Per CONTRIBUTING.md, additive backward-compatible features warrant a minor bump rather than a patch. * docs(adapters): clarify subclassing surface stability Correct the parenthetical describing what stays `private` (credentials are now `protected`) and add a callout warning that the `protected` extension surface is intentionally broader than the public API but not yet fully stable, so subclass authors know to pin versions and prefer overriding the smallest hook. --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
2279f1db70 |
Revert "feat(slack): expose direct WebClient access via adapter.client" (#472)
* Revert "feat(slack): expose direct WebClient access via adapter.client (#471)"
This reverts commit
|
||
|
|
8366b8b0fb |
feat(slack): expose direct WebClient access via adapter.client (#471)
* feat(slack): expose direct WebClient access via adapter.client
Mirror the Linear and GitHub adapter pattern by exposing the underlying
@slack/web-api WebClient as `adapter.client` for any Web API call not
covered by the SDK's high-level methods.
Resolution order:
1. Token from the current request context (multi-workspace webhooks,
`withBotToken()`).
2. The default `botToken` when configured as a static string or a
synchronous resolver function.
Throws AuthenticationError outside of any context in multi-workspace
mode, or when `botToken` is configured as an async resolver. For both,
bind the token explicitly with `adapter.withBotToken(token, () => ...)`.
Internally, the existing private `client` field is renamed to `_client`
so the public getter can return per-token cached `WebClient` instances.
All internal API calls continue to route through `_client.foo(await
this.withToken(...))` unchanged. Also fixes `createSlackAdapter()`
silently dropping the `apiUrl` config field, surfaced by the new
apiUrl-propagation test.
* docs(slack): document direct WebClient access
Add Slack to the "Direct client access" section of the chat-sdk.dev
docs (api/chat.mdx, usage.mdx) alongside Linear and GitHub. Update the
multi-tenant Callout to spell out both Slack constraints — request
context required in multi-workspace mode, and `withBotToken()` required
when `botToken` is an async resolver.
Add a parallel "Direct WebClient access" section to the Slack adapter
README with a usage example, the token resolution order, and the
async-resolver workaround.
* feat(example): add Channel Info button using slack.client
Demonstrate the new direct WebClient access pattern in the nextjs-chat
demo with a "Channel Info (Slack)" button. The handler resolves the
Slack adapter from the action event, reaches into
`adapter.client.conversations.info` (channels:read scope, already in
the example manifest), and renders the result as a Card with channel
name, member count, topic, purpose, and the standard flags. Falls back
to a friendly message on non-Slack platforms.
* feat(example): add Pin Message button using slack.client.pins.add
Pin the welcome card itself via `adapter.client.pins.add({ channel,
timestamp: event.messageId })` to demonstrate calling a Slack Web API
endpoint not wrapped by the SDK. Adds the required `pins:write` scope
to the example Slack manifest.
* chore(example): render channel info as a table and include num_members
Replace the Fields/Section layout in the Channel Info card with a
two-column Table for a tidier presentation, and pass
`include_num_members: true` so the Members row is actually populated
(Slack's `conversations.info` omits it by default).
* test(slack): expand coverage for adapter.client
Adds three tests:
- Cache differentiation: distinct tokens produce distinct WebClient
instances so per-workspace credentials never bleed across calls.
- apiUrl env var resolution: SLACK_API_URL is honored by the WebClient
the new getter returns (covers GovSlack-style deployments).
- End-to-end multi-workspace token routing: a real block_actions
webhook drives `processAction`, and the handler-side
`event.adapter.client.token` matches the installation's bot token —
proving the request-context-bound client works inside webhook
dispatch.
---------
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
|
||
|
|
0adf3adef6 |
feat(tests): add @chat-adapter/tests test kit (#470)
* feat(tests): add @chat-adapter/tests test kit
New package providing Vitest factories, custom matchers, and a setup file for
people building Chat SDK adapters and bots.
Factories: createMockAdapter, createMockChatInstance, createMockState (with
working in-memory subscriptions/locks/KV/queues), createTestMessage,
mockLogger / createMockLogger.
Matchers: toHavePosted(threadId, textPattern?), toHaveDispatched(handler),
toBeSubscribedTo(threadId). Auto-register via the
'@chat-adapter/tests/setup' subpath in vitest setupFiles.
chat and vitest are peer dependencies. Adapter-specific helpers (e.g. signed
Slack webhook builders) belong in each adapter's own /testing subpath, not
in this kit.
* test(integration-tests): allow @chat-adapter/tests imports in README check
* docs: add Testing page covering @chat-adapter/tests
New content/docs/testing.mdx walks bot authors and custom-adapter authors
through the kit's factories, custom matchers, and setup file. Added under
the Usage section in the sidebar, after error-handling.
Cross-link from contributing/testing.mdx clarifying that the hand-rolled
patterns there are for repo contributors building first-party adapters,
while consumers of Chat SDK should use @chat-adapter/tests.
* test(integration-tests): allow @chat-adapter/tests imports in docs check
* fix(tests): match real Adapter.postMessage signature in toHavePosted
Adapter.postMessage is (threadId: string, message: AdapterPostableMessage)
— previously the matcher read args[0] as { id: string } and args[1] as
{ text: string }, neither of which match the actual SDK shape. The matcher's
own tests fed the same wrong shape into the mock so they passed locally
while the matcher silently failed against any real bot or adapter.
Now compares args[0] as a string threadId, and extracts a comparable string
from AdapterPostableMessage's union — strings directly, PostableMarkdown
.markdown, PostableRaw.raw, and PostableCard.fallbackText. PostableAst and
fallback-less cards aren't text-matchable; documented in the JSDoc.
Tests updated to call postMessage with the real signature and to cover
each comparable AdapterPostableMessage shape.
* test(tests): add smoke tests driving matchers against a real Chat
Construct a real `Chat` with a `createMockAdapter` + `createMockState` and
exercise `Chat.thread().post()` and `.subscribe()` end-to-end. The matchers
(toHavePosted, toBeSubscribedTo) then assert against the actual call shape
the SDK uses, so a future signature drift breaks here instead of silently
agreeing with whatever wrong shape lives in the unit tests.
This is the regression guard for the postMessage-shape bug fixed in the
prior commit: each new matcher in subsequent PRs should be paired with a
smoke case here.
* feat(tests): round out adapter mutation matchers
Adds toHaveEdited, toHaveDeleted, toHaveReactedWith, toHaveStartedTyping,
and toHavePostedToChannel — covering the common Adapter mutation surface
that bot authors assert on. Each matcher's signature was checked against
packages/chat/src/types.ts, and each is paired with a smoke case that
drives a real Chat through the corresponding Thread/Channel API so
signature drift breaks the smoke test instead of silently agreeing with
the unit tests.
Emoji matching accepts both plain strings and EmojiValue ({ name }).
Text matching reuses the same extraction rules as toHavePosted —
strings, PostableMarkdown.markdown, PostableRaw.raw, and
PostableCard.fallbackText. Documented in matcher JSDoc, README, and
the Testing docs page.
---------
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
|
||
|
|
c46fdb6b34 |
[slack] add support for external installation providers for bot token management (#467)
* [slack] add support for external installation providers for bot token management * changeset * fix(slack): correct stale 'Connex' comment to 'Vercel Connect' * docs(slack): expand changeset with provider details and Enterprise Grid notes * docs(slack): document installationProvider and Enterprise Grid lookup keys * test(slack): cover installationProvider for interactive payloads on both install types * fix(slack): route rehydrateAttachment through installationProvider --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
0f0c203165 |
fix(slack): prefer webhookVerifier over signingSecret (#468)
* fix(slack): prefer webhookVerifier over signingSecret and SLACK_SIGNING_SECRET
When `webhookVerifier` is configured, ignore both `config.signingSecret`
and the `SLACK_SIGNING_SECRET` env var. Previously a configured
`signingSecret` (or env var) would shadow the verifier the caller wired
up, which is the opposite of the intended override behavior.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* docs(slack): update README to match new webhookVerifier precedence
Mirror the JSDoc/changeset wording: webhookVerifier wins over both
signingSecret and SLACK_SIGNING_SECRET. The previous note still claimed
signingSecret won, contradicting the behavior fixed in
|
||
|
|
5edcbbf7ef |
chore(release): version packages (#464)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
b3fc64d34e |
chore(release): version packages (#442)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
0cc3d06fd4 |
docs: fix stale API examples, adapter matrix, and broken links (#463)
* 1 * 2 * cs * 3 |
||
|
|
c1cd9b5da1 |
feat(chat): add callbackUrl to buttons and modals (#454)
* 1 * wfw * 4224 * dfe * wip * f * 22 * tsts * more * ch * dc * t * tm * docs * ex * k * cs * lock * test(chat): expand callbackUrl coverage * docs: document callbackUrl handling for adapter authors * docs: expand changeset for callbackUrl feature * docs(skill): mention callbackUrl on Button and Modal * feat(example): add modal callbackUrl workflow demo * test(integration): add replay tests for callbackUrl flows --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
68025ca965 |
[messenger] add messenger (meta) platform adapter to chat sdk (#461)
* [messenger] add messenger (meta) platform adapter to chat sdk - Webhook handling with HMAC-SHA256 signature verification - Generic and Button template support for cards - Postback, reaction, delivery/read confirmation handling - Message caching for fetchMessages (Messenger has no history API) - Replay tests and ~98% code coverage Co-authored-by: Dimitar K. Nikolov <mitkodkn@users.noreply.github.com> Co-authored-by: Ben Sabic <27636870+bensabic@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> * Fix: The `@chat-adapter/messenger` package version is `4.15.0` while all other packages in the Changesets fixed version group are at `4.27.0`, breaking the fixed versioning contract. This commit fixes the issue reported at packages/adapter-messenger/package.json:3 **Bug explanation:** The repository uses Changesets with a `"fixed"` configuration: `[["chat", "@chat-adapter/*"]]`. This means all packages matching these patterns must always share the same version number. Every package in the group (`chat`, `@chat-adapter/discord`, `@chat-adapter/gchat`, `@chat-adapter/github`, `@chat-adapter/linear`, `@chat-adapter/shared`, `@chat-adapter/slack`, `@chat-adapter/teams`, `@chat-adapter/telegram`, `@chat-adapter/web`, `@chat-adapter/whatsapp`, and the state packages) is at version `4.27.0`, except `@chat-adapter/messenger` which is at `4.15.0`. This is likely because the messenger adapter was newly added to the monorepo (copied from a template or created fresh) and its version was never aligned with the rest of the fixed group. This mismatch will cause problems with the Changesets release workflow — when Changesets tries to bump versions for the fixed group, it may produce inconsistent or errored releases because one package is 12 minor versions behind the others. **Fix explanation:** Changed `"version": "4.15.0"` to `"version": "4.27.0"` in `packages/adapter-messenger/package.json` to align it with all other packages in the fixed version group. Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com> Co-authored-by: visyat <vishal.yathish@gmail.com> * Fix: Messenger adapter env var guard only checks `FACEBOOK_APP_SECRET` but `createMessengerAdapter` requires all three env vars, causing a `ValidationError` crash at Next.js build time when only `FACEBOOK_APP_SECRET` is set. This commit fixes the issue reported at examples/nextjs-chat/src/lib/adapters.ts:154 **Bug Analysis:** The build failure is confirmed in the Vercel build log with: ``` Error [ValidationError]: pageAccessToken is required. Set FACEBOOK_PAGE_ACCESS_TOKEN or provide it in config. ``` The root cause is in `examples/nextjs-chat/src/lib/adapters.ts` at line ~154. The messenger adapter guard only checks for `FACEBOOK_APP_SECRET`: ```typescript if (process.env.FACEBOOK_APP_SECRET) { ``` However, `createMessengerAdapter` (in `packages/adapter-messenger/src/index.ts`) validates and throws `ValidationError` for each of three required env vars: `FACEBOOK_APP_SECRET`, `FACEBOOK_PAGE_ACCESS_TOKEN`, and `FACEBOOK_VERIFY_TOKEN`. When only `FACEBOOK_APP_SECRET` is set in the Vercel project environment, the guard passes, `createMessengerAdapter` is called, and it throws a `ValidationError` for the missing `FACEBOOK_PAGE_ACCESS_TOKEN`. Since this code runs at module evaluation time during the Next.js build's "Collecting page data" phase, the uncaught error crashes the entire build. This is inconsistent with other adapters in the same file. For example, the WhatsApp adapter checks both `WHATSAPP_ACCESS_TOKEN` and `WHATSAPP_PHONE_NUMBER_ID`, and the gchat/github/linear/whatsapp adapters all wrap creation in try-catch blocks. **Fix:** 1. Updated the env var guard to check all three required environment variables (`FACEBOOK_APP_SECRET`, `FACEBOOK_PAGE_ACCESS_TOKEN`, and `FACEBOOK_VERIFY_TOKEN`) before attempting to create the adapter. 2. Wrapped the `createMessengerAdapter` call in a try-catch block (matching the pattern used by gchat, github, linear, and whatsapp adapters) so that any unexpected validation errors are caught and logged as warnings instead of crashing the build. Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com> Co-authored-by: visyat <vishal.yathish@gmail.com> --------- Co-authored-by: Dimitar K. Nikolov <mitkodkn@users.noreply.github.com> Co-authored-by: Ben Sabic <27636870+bensabic@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com> Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com> |
||
|
|
eb5f94a8ee |
feat(chat): add message.subject and adapter client access (#459)
* 1 * w * 3f * x * ln * gh * sl * t1 * u * t2 * t3 * t4 * t5 * d * d2 * cs * fx * cl * docs: clean up subject + .client docs and restructure nav - subject.mdx: simplify prose, drop redundant platform lists, link to MessageSubject API and getAdapter - api/message.mdx: add MessageSubject TypeTable - api/chat.mdx: expand getAdapter with Direct client access content - adapters.mdx: add Parent subject and Native client rows to feature matrix - usage.mdx: mention .client under Accessing adapters - adapter-github/-linear READMEs: add Direct API client section - meta.json: split Features into Messaging + Interactivity, move error-handling to Usage - title case across messaging-cluster page titles --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
3490a8c84c |
feat: add @chat-adapter/web — browser chat UI for chat-sdk bots (#444)
* feat(chat): expose awaitable Promise from processMessage
Return the inner task as Promise<void> instead of void so streaming
adapters can await full handler completion and surface user-handler
rejections at the wire level. waitUntil semantics for existing webhook
adapters are unchanged — the SDK still tracks the work with errors
swallowed (and logged) so platforms don't retry on handler bugs.
Required by @chat-adapter/web, whose response body is the user
handler's stream.
* feat(adapter-web): add @chat-adapter/web package
A new platform adapter that lets a chat-sdk bot serve a browser chat
UI alongside Slack/Teams/Discord/etc. without writing any client-side
glue. Speaks the AI SDK UI message stream protocol, so @ai-sdk/react's
useChat and the ai-elements component library work out of the box.
- `@chat-adapter/web` — server: createWebAdapter({ userName, getUser })
- `@chat-adapter/web/react` — client: useChat() preconfigured with
DefaultChatTransport against /api/chat (override via `api`)
Defaults that matter for v1:
- `isDM: true` — every web message routes through onDirectMessage
- `persistMessageHistory: true` — chat-sdk caches each turn in the
configured state adapter so handlers can read prior context via
thread.messages / channel.messages (no platform history API exists)
- channelId === threadId — web has no separate channel concept; this
prevents cross-conversation bleed when a single user has multiple
useChat sessions
- Native `adapter.stream` implementation pumps text-deltas straight
onto the SSE response — no post+edit fallback
Out of scope for v1: cards/JSX rendering, reactions, modals, file
uploads, edit/delete, multi-tab proactive push.
* feat(example-nextjs-chat): wire up web adapter and add /chat page
- Register the web adapter in lib/adapters.ts with a demo getUser
(single shared identity — replace with NextAuth/Clerk/cookie auth
in production)
- Expose POST /api/chat backed by bot.webhooks.web (using next/after
for waitUntil)
- Add a minimal /chat page using @chat-adapter/web/react's useChat —
same bot.onDirectMessage handler that powers Slack now powers the
browser too
Bumps `ai` to ^6.0.174 to align with @ai-sdk/react@^3 (avoids dual
provider-utils versions in the workspace).
* docs: list @chat-adapter/web in registry
- Add an entry to adapters.json so the package shows up on /adapters
- Add a globe SVG to lib/logos.tsx and wire it into the icon map
- Mention the new adapter in docs/adapters.mdx
* feat(adapter-web): tighten request handling and message construction
- Reject user ids containing ':' with HTTP 400 — the character would
corrupt the thread-id round-trip through decodeThreadId
- Skip emitting text-start/text-end in postMessage when the resolved
text is empty so useChat doesn't render blank assistant bubbles
- Derive the parseMessage author from raw.role so rehydrated assistant
messages report the bot identity instead of "unknown"
- Drop the duplicate handler-error log; chat.processMessage already
logs at ERROR level
- Document the actual persistMessageHistory default (true) and the
state-cache rationale; promote the fetchMessages no-op rationale
into its JSDoc
* test(adapter-web): add direct coverage for stream()
- Aborting request.signal mid-stream short-circuits the iterator and
still writes text-end via the finally block
- Non-text StreamChunks (task_update, plan_update) are dropped without
emitting any delta
- The SentMessage returned from thread.post matches the id used in
text-start / text-end events
* docs(adapter-web): expand README into the full adapter docs page
The docs site renders each adapter's README, so flesh out
@chat-adapter/web to match the depth of @chat-adapter/slack:
authentication boundary, threading semantics, streaming,
persistence, React hook reference, configuration table,
feature matrix, and troubleshooting.
* docs(adapter-web): drop unsupported provider import from streaming example
* fix(adapter-web): validate conversationId for reserved colon character
* fix(example): show error state in web chat demo
* fix(example): add thinking indicator to web chat demo
* feat(example): redesign web chat demo with tailwind
* chore: remove redundant changeset
---------
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
Co-authored-by: dancer <josh@afterima.ge>
|
||
|
|
d7999aba26 |
chore: add Vercel Code Approvers files mirroring CODEOWNERS (#450)
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
46d183bdab |
feat(chat): add Transcripts API + rename per-thread cache to threadHistory (#448)
* feat(chat): add Transcripts API and rename per-thread cache to threadHistory
Introduce `bot.transcripts` for cross-platform per-user message persistence.
When `ChatConfig.transcripts` and `ChatConfig.identity` are configured, every
inbound message has its `userKey` resolved during dispatch and the API exposes
`append` / `list` / `count` / `delete` keyed by that user. Backed by the
existing `StateAdapter.appendToList` primitive — every built-in state adapter
supports it with no contract changes.
Rename the existing per-thread history cache from `messageHistory` to
`threadHistory` (with backwards compat for `ChatConfig.messageHistory` and
`Adapter.persistMessageHistory`) so the two persistence layers don't share a
"messages" name. The state-adapter storage key prefix is unchanged so existing
data isn't orphaned.
`delete()` writes a tombstone via `appendToList(key, _, { maxLength: 1 })`
rather than `state.delete(key)`, because `state.delete` only addresses the
k/v namespace on every non-memory state adapter — `list()` and `count()`
filter the tombstone out so the API contract is preserved.
* docs(chat): cover Transcripts API and Conversation history
Add a Features-style "Conversation history" guide (`/docs/conversation-history`)
walking through identity resolution, the LLM-context append/list pattern,
filtering, and per-user deletion for DSR flows.
Add an API reference page at `/docs/api/transcripts` with `<TypeTable>` blocks
for `ChatConfig.transcripts`, `ChatConfig.identity`, every method on
`bot.transcripts`, and the `TranscriptEntry` shape.
Wire both into the corresponding `meta.json` files.
* example(nextjs-chat): wire Transcripts API into the AI mode handler
Replace the brittle `threadState.history` shim with `bot.transcripts.list({ ..., threadId, limit })` as the fallback context source for platforms without
`fetchMessages` (Telegram, WhatsApp). Drop the `history` field from
`ThreadState` accordingly.
Add a hardcoded `TEST_USER_KEY = "test-user"` so the API can be exercised
without juggling real user identities, plus "Show Transcripts" and
"Clear Transcripts" buttons in the welcome card so the store can be
inspected and reset from chat.
* fix(chat): tighten Transcripts API public surface and wiring
Polish on top of the Transcripts API + threadHistory rename, addressing
review concerns before merge.
Public surface (`types.ts`, `index.ts`):
- Expose `transcripts` on the `ChatInstance` interface so callers typed
against the public interface can reach `bot.transcripts`.
- Promote the `count` argument to a named `CountQuery` interface,
matching `DeleteTarget` / `ListQuery`. Exported from `index.ts`.
- Document on `TranscriptsApi.list()` that pagination is intentionally
out-of-scope — the store keeps at most `maxPerUser` entries per user.
- Reconcile the `TranscriptEntry.id` JSDoc with the implementation:
UUID assigned at append time, returned in append order, not
lexicographically sortable; use `timestamp` for cross-store ordering.
Wiring (`chat.ts`):
- Include `threadId` in the identity-resolver failure log context so
operators can correlate failures with the source thread.
Stale-reference sweep:
- Replace lingering "Messages API" / `chat.messages` /
`messages.storeFormatted` strings in shipped JSDoc with the new
`transcripts` names (these ride into `.d.ts` and are user-visible).
- Fix the dead `[Messages API](./messages.ts)` link in the existing
thread-history-rename changeset.
* test(chat): cover dual-read precedence, resolver edges, concurrent ops
Fill gaps in the Transcripts API + threadHistory rename test suite:
`chat.test.ts` (persistThreadHistory block):
- top-level `config.messageHistory` (deprecated alias) flows through
to the per-thread cache when `threadHistory` is unset
- `threadHistory` takes precedence over `messageHistory` when both are
set — pinned by asserting `appendToList` receives the new config's
`maxLength` / `ttlMs`
- both `persistThreadHistory` and `persistMessageHistory` set on the
adapter still triggers persistence
`transcripts-wiring.test.ts`:
- sync resolver returning a plain string populates `message.userKey`
- resolver returning `""` is treated as no userKey (truthy check at
the dispatch hook would silently flip if a future change moved to
`!== undefined`)
`transcripts.test.ts`:
- concurrent append/delete/append interleave preserves invariants:
`count()` and `list()` agree (no tombstone leak), no pre-delete
entry survives, and the post-delete result is bounded by the two
concurrent appends
* docs(chat): use named types in Transcripts API reference
- `formatted` rows in the AppendInput / TranscriptEntry TypeTables
now render `FormattedContent | undefined` (the alias actually
exported from `chat`), instead of `Root | undefined` which would
force readers to pull the type from `mdast` directly.
- `count` signature uses the new `CountQuery` named type, with a
one-liner describing its single field.
* example(nextjs-chat): fix stale comment on transcripts demo handler
The action handler was relabelled to `transcripts` when it was wired
to `bot.transcripts.list`, but the leading comment still read
"Demonstrate fetchMessages and allMessages" from the previous
iteration. Update it to describe the transcripts demo.
---------
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com>
|
||
|
|
3546b3fddb |
feat(slack): use native markdown_text for outgoing messages (#440)
* feat(slack): use native markdown_text field for outgoing messages
Slack now natively renders markdown via the `markdown_text` parameter on
chat.postMessage / postEphemeral / update / scheduleMessage and via
response_url payloads. The adapter passes markdown through directly instead
of converting to mrkdwn.
- Tables, headings, code fences, blockquotes, and nested lists render
natively in Slack instead of falling back to ASCII / mrkdwn.
- `string` and `{ raw }` messages still go to `text` (preserves literal `*`).
- `{ markdown }` and `{ ast }` messages go to `markdown_text` (12k char limit).
- `renderWithTableBlocks`, `toBlocksWithTable`, `mdastTableToSlackBlock`,
and the AST→mrkdwn renderer (`fromAst` / `nodeToMrkdwn`) are removed.
- `SlackMarkdownConverter` alias is removed; use `SlackFormatConverter`.
- `renderFormatted(ast)` now returns standard markdown (was mrkdwn).
- Incoming `message` events still arrive as mrkdwn and are parsed unchanged.
Net -473 lines across markdown.ts and the five sender call sites.
* fix(slack): use mrkdwn fallback for response_url edits
|
||
|
|
f46a6fb0bc | fix(telegram): apply MarkdownV2 entity safety trim to streaming chunks (#446) | ||
|
|
9824d3335e |
Adapter hardening pass (#441)
* Adapter hardening pass * chore: remove redundant changeset --------- Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
f55378a3d8 |
chore(release): version packages (#378)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> |
||
|
|
ded6f78088 |
fix(slack): enrich link previews with unfurl metadata from attachments (#395)
* fix(slack): enrich link previews with unfurl metadata from attachments * fix(slack): add trailing slash normalization for unfurl URL matching * fix(slack): store unfurl metadata from message_changed and enrich subsequent messages * fix(slack): poll for unfurls so link metadata survives the message_changed race |
||
|
|
8a0c7b308d |
[chat] fix Slack streaming team ID for interactive payloads (#330)
* [chat] fix Slack streaming team ID for interactive payloads * chore: downgrade changeset to patch --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
ed46bae52e |
feat(adapter-teams): native streaming for DMs via emit (#416)
* feat(adapter-teams): use native Teams SDK streaming for DMs Use ctx.stream.emit() from the Teams SDK for DM streaming instead of manual post+edit. This sends proper typing activities with streamType channelData, giving the native streaming UI in Teams. - Capture IStreamer from activity context in handleMessageActivity - Block handler with deferred promise so stream stays alive during processing - streamViaEmit() for DMs: uses stream.emit() with incremental text deltas - Group chats: accumulate full response and post as single message (no flicker) - Handle StreamCancelledError and stream.canceled for graceful cancellation Co-Authored-By: Claude <noreply@anthropic.com> * fix(tests): update Teams streaming assertions for accumulate-and-post Group chats now accumulate streamed chunks and post as a single message instead of post+edit, so assertions should check sentActivities not updatedActivities. * style: format replay-streaming test * chore: add changeset for teams native streaming --------- |
||
|
|
a520797922 |
feat: add chat.getUser() for cross-platform user lookups (#391)
* feat: add chat.getUser() for cross-platform user lookups Add UserInfo type and optional getUser() method to the Adapter interface. Implement on Slack (extends existing lookupUser with email/avatar), Discord, Google Chat, GitHub, Linear, and Telegram adapters. Add "Who Am I" button to the example app demonstrating the feature. Update docs with getUser API reference and usage examples. * fix(chat): improve getUser across slack and gchat adapters - slack: return null from lookupUser on failure instead of fallback object, removing the isBot === undefined sentinel in getUser - slack: use image_192 instead of image_72 for better avatar quality - gchat: cache avatarUrl from webhook sender payload - gchat: return avatarUrl in getUser response - gchat: fix tests to use current cache format with isBot field - docs: document null return, fix example to use message.author * chore: fix lint * docs(chat): include Microsoft Teams in getUser supported adapters list * feat(adapter-teams): add getUser() support (#404) * feat(adapter-teams): add getUser() via Microsoft Graph API - Cache aadObjectId from activity.from during webhook handling - Implement getUser() using Graph GET /users/{user-id} endpoint - Requires User.Read.All application permission - Returns null gracefully when user hasn't interacted or Graph call fails * docs: add getUser() section to Teams adapter README * chore: apply ultracite formatting to adapter-teams getUser * fix(chat): cover all 7 adapters in getUser inference and document per-platform constraints --------- Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
70281dc58f |
feat(chat): add initialOption and option_groups to ExternalSelect (#410)
* feat(chat): add initialOption and option_groups to ExternalSelect * docs(modals): document ExternalSelect initialOption and option_groups, truncate group label to 75 chars |
||
|
|
b0ab804f18 |
- Bundle guide markdown and a templates manifest with the chat package at resources/guides/*.md and resources/templates.json so AI agents can discover Chat SDK resources offline (#423)
- Add scripts/sync-resources.ts (run via pnpm sync-resources) that reads apps/docs/resources-edge-config.json, fetches each guide's .md version over https with a timeout and size cap, writes templates.json, and regenerates the Available resources block in skills/chat/SKILL.md - Migrate the Slack Next.js, Discord Nuxt, and Hono code-review guides from on-site MDX to Vercel KB and register them in the resources edge-config JSON alongside the existing external guides - Remove /docs/guides MDX content, sidebar entries, top-level Guides nav entry, getting-started cards, and the dead /guides/ branch in the sitemap route now that all guides live externally and are surfaced on /resources - Replace the homepage Guides/Templates section and the standalone Adapters pill section with a single two-column Resources + Adapters section (icons, headings, descriptions, outline buttons, divider), and drop the URL footer from ResourceCard on the Resources page - Update skills/chat/SKILL.md to point at resources/guides and resources/templates.json and list the available guides and templates between marker comments that sync-resources rewrites - Add tsx to knip's ignoreBinaries so npx tsx in the new script does not fail lint Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
2531e9cff5 |
feat(slack): dynamic botToken resolver and custom webhookVerifier (#421)
* feat(slack): dynamic botToken resolver and custom webhookVerifier Allow `botToken` to be a function returning `string | Promise<string>` so apps can rotate or lazily fetch tokens; the resolver is invoked per API call. Add `webhookVerifier: (request) => string | Promise<string>` as an alternative to `signingSecret` for custom request verification — returns the verified body text or throws to produce a 401. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * change verifier signature to make it compatible with function * make scheduleMessage cancel() rotation-safe and honor verifier body - scheduleMessage cancel(): re-resolve token in single-workspace mode so rotation works. Slack rotated tokens have a 12h TTL and scheduled messages can outlive their schedule-time token, leaving cancel() with stale auth. Multi-workspace still snapshots ctx.token since cancel() runs outside the AsyncLocalStorage frame. - webhookVerifier: when it returns a string, use it as the verified body for downstream parsing. JSDoc previously implied this contract; the code only checked truthiness. - webhookVerifier JSDoc: explicit SECURITY note that timestamp/replay protection is the implementer's responsibility when bypassing signingSecret. - Tests: cover Attachment.fetchData snapshot semantics — multi-workspace uses the ctx token captured at attachment creation; single-workspace re-resolves the default provider per fetch (rotation-safe). * docs(slack): document botToken resolver and webhookVerifier in README * opt out of SLACK_SIGNING_SECRET env fallback when webhookVerifier is set A webhookVerifier passed in config was being silently shadowed by SLACK_SIGNING_SECRET in the env (read by both createSlackAdapter and the SlackAdapter constructor). An explicit verifier now opts out of that fallback in both code paths. Added a regression test that stubs the env var via vi.stubEnv. * register handleReactionEvent's outer promise via waitUntil handleReactionEvent does async work (conversations.replies, users.info) before delegating to chat.processReaction, which is the only point that registers a waitUntil task. The outer prep work was untracked, so callers that drained waitUntil tasks could complete before the reaction handler finished — flaky in CI under tight microtask scheduling. Track the outer promise too so the full handler is awaited. * fix(integration-tests): drain waitUntil cascade in test tracker --------- Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
d630e6c8a7 |
fix(chat): honor concurrency.maxConcurrent in the concurrent strategy (#419)
Closes #417. - handleConcurrent now acquires a per-thread semaphore slot when maxConcurrent is finite; fast path preserved for the default Infinity. - Constructor throws on maxConcurrent < 1 (would deadlock) and warns when maxConcurrent is paired with a non-concurrent strategy (was previously ignored silently). Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
d440b0f920 |
chore: add changeset for #415 (Teams SDK 2.0.8) (#418)
Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
a179b29141 |
Implement external_select block kit for Slack (#397)
* feat(slack): external_select's block kit implementation - block_suggestion handler for slack webgook - new <ExternalSelect/> to chat modal jsx - new .onOptionsLoad() * feat: add tests for new external_selec implementation * feat(docs): Slack externa_select docs * chore: changeset * chore: remove docs from changeset --------- Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
b9a1961aa5 |
fix(telegram): MarkdownV2 rendering + telegram-chat reference example (#407)
* fix(telegram): switch parse_mode from legacy Markdown to MarkdownV2
The Telegram adapter hardcoded `parse_mode: "Markdown"` (legacy) but
rendered messages via the SDK's generic `stringifyMarkdown()`, which
emits standard markdown. Two incompatible dialects glued together:
- Standard markdown uses `**bold**`, Telegram legacy uses `*bold*`
- Legacy Markdown has no escape rules — any message with `.`, `!`,
`(`, `)`, `-`, `_` in unexpected positions was rejected with
`can't parse entities`, which is virtually every LLM-generated
response
- Legacy Markdown is deprecated by Telegram and lacks support for
underline, strikethrough, spoiler, and blockquote
This commit:
- Switches TELEGRAM_MARKDOWN_PARSE_MODE to "MarkdownV2"
- Replaces fromAst() with a proper AST → MarkdownV2 renderer:
- Single `*bold*`, `_italic_`, `~strike~` markers
- Context-aware escaping: 20-char matrix for normal text, only
`` ` `` and `\` inside code blocks, only `)` and `\` inside link
URLs
- Headings rendered as bold (MarkdownV2 has no heading syntax)
- Ordered/unordered lists with escaped dashes and periods
- Blockquotes with per-line `>` prefix
- Tables pre-empted and rendered as ASCII code blocks
- Explicit handlers for reference-style links, images, HTML, and
definitions so nothing is silently dropped
- Routes card fallback text through `fromMarkdown` (not raw escape)
with `boldFormat: "**"` — @chat-adapter/shared's cardToFallbackText
defaults `boldFormat` to "*" (Slack mrkdwn), which would render as
italic on Telegram. Explicit "**" keeps the card title rendered as
real MarkdownV2 bold.
- Fixes resolveParseMode so every message routed through the format
converter (`{markdown}`, `{ast}`, cards, JSX) gets
`parse_mode: "MarkdownV2"`. Previously only `{markdown}` and cards
were covered, so `{ast}` messages shipped without parse_mode and
rendered asterisks literally.
- Documents inbound vs outbound dialects on applyTelegramEntities /
escapeMarkdownInEntity (inbound entities → standard markdown)
versus the new outbound MarkdownV2 renderer, so future
contributors don't confuse the two.
Tests: full 20-char MarkdownV2 escape matrix, context-escape tests
for code blocks and link URLs, nested-formatting tests, edge cases
(empty, whitespace-only, raw HTML), and an end-to-end LLM-output
corpus test that asserts MarkdownV2 validity (no unescaped special
chars outside entities or code blocks). Regression guards added in
index.test.ts for the AST / plain-string / raw parse_mode paths and
for card-title MarkdownV2 bold rendering.
Fixes #226
* feat(examples): add telegram-chat reference bot
Polling-mode Telegram bot that exercises the adapter end-to-end:
MarkdownV2 rendering, interactive cards with inline keyboards,
reactions, file uploads, and streaming edits. Runs with a single
`pnpm --filter example-telegram-chat start`; no webhook, no public
URL, no external API keys.
Menu structure — three categorized sub-menus reached from any DM text:
- Text & Markdown: plain, inline emphasis, code block, links, list+table,
20-char torture string, LLM-style corpus, streaming editMessage loop
- Cards & Actions: interactive approval card (edits in-place on press),
callback_data size probe demonstrating the 64-byte limit, LinkButton
- Media & Reactions: on-demand reaction one-shot (briefly subscribes),
generated 1×1 PNG upload, generated minimal PDF upload
Zero new runtime deps. PNG/PDF are hand-rolled in memory
(lib/png.ts, lib/pdf.ts) rather than pulled from a binary-processing
library. Failure handling is consistent: every demo runner is
try/catch-wrapped and posts an inline ❌ line with the error message.
Excluded from npm release via .changeset/config.json.
* fix(telegram): produce valid MarkdownV2 when truncating long messages
The MarkdownV2 migration widened a latent truncation bug into a reliable
400. The previous truncator sliced at 4096/1024 chars and appended
literal "..." — but in MarkdownV2 `.` is a reserved character, the slice
can leave an orphan trailing `\`, and it can cut through a paired
entity (`*bold*`, `` `code` ``) leaving it unclosed.
Unify the two truncate methods into one `truncateForTelegram(text,
limit, parseMode)` that appends `\.\.\.` for MarkdownV2 and walks back
past unbalanced entity delimiters or orphan backslashes. Plain text
keeps literal `...`. Adds 8 length-limit tests.
Related cleanup:
- Move MarkdownV2 string utilities and Bot API limits to markdown.ts.
- Type renderMarkdownV2 exhaustively on mdast's `Nodes` union with a
`never` assertion so new node kinds fail the build. Replaces the
hand-rolled `AstNode` interface. Adds explicit cases for table /
tableRow / tableCell (throw — preprocessed by fromAst),
footnoteDefinition, footnoteReference, yaml.
- Introduce `TelegramParseMode = "MarkdownV2" | "plain"` replacing
`string | undefined`. `toBotApiParseMode` handles the wire mapping.
- Re-export `Nodes` from the chat package; re-export
`TelegramReactionType` from the adapter entry.
* feat(examples): add length-limit demos to telegram-chat reference bot
Three new menu entries exercise the MarkdownV2 truncation path that the
prior commit fixed:
- Long (5000 plain) — basic truncation, verifies escaped `\.\.\.` ellipsis
- Long (bold crosses 4096) — entity-balancing heuristic for unclosed `*`
- Long (code crosses 4096) — entity-balancing heuristic for unclosed `` ` ``
Each button posts a message whose rendered length exceeds Telegram's
4096-char limit and would have produced `can't parse entities` 400s
against the previous truncator. Serves as an interactive smoke test
alongside the unit tests in packages/adapter-telegram.
* test(telegram): add unit tests for truncation helpers and MarkdownV2 boundary trimming
* docs(telegram): update README to reflect MarkdownV2 parse mode
* chore: unexport trimToMarkdownV2SafeBoundary to fix knip
---------
Co-authored-by: dancer <josh@afterima.ge>
|
||
|
|
4c24c94832 |
fix(adapter-teams): resolve DM conversation IDs for Graph API (#403)
* fix(adapter-teams): resolve DM conversation IDs for Graph API fetchMessages
DM conversation IDs from Bot Framework are opaque and don't work with
Graph's /chats/{chat-id}/messages endpoint. Cache the user's AAD object
ID from incoming activities and construct the correct Graph chat ID
(19:{aadId}_{botId}@unq.gbl.spaces) via a new TeamsGraphContext union.
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(adapter-teams): simplify graph context branching
Remove redundant type checks — DMs never have threadMessageId so the
channel guard doesn't need an explicit DM exclusion.
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
7e90d9c8fa |
Add Slack Socket Mode support (#162)
* Add slack/socket mode dependency
* Update config types and SlackAdapter class
* Add socket mode methods, extract interactive dispatch
* Update createSlackAdapter factory function
* Write tests for socket mode
* Create slack-socket-mode.md
* Run fix
* Fix polynomial regex issues
* Fix: Floating promises in `routeSocketEvent` for slash commands and interactive payloads can cause unhandled promise rejections that crash the Node.js process.
This commit fixes the issue reported at packages/adapter-slack/src/index.ts:1152
**Bug Analysis:**
In `routeSocketEvent` (line 1150), which is a synchronous `void` method, two async operations produce floating promises:
1. `this.handleSlashCommand(params)` (line 1165) - `handleSlashCommand` is `async` and always returns a `Promise<Response>`. It calls `await this.lookupUser(userId)` which internally calls `await this.chat.getState().get()` (before the try/catch around the API call), and `this.chat.processSlashCommand()`. Any of these could throw.
2. `this.dispatchInteractivePayload(payload)` (line 1172) - Returns `Response | Promise<Response>`. When the payload type is `view_submission`, it delegates to `async handleViewSubmission()`, which calls `await this.chat.processModalSubmit()` and accesses `payload.view.state.values` (which could throw on malformed payloads).
Since `routeSocketEvent` is synchronous (`void` return type) and called from a sync context within the socket mode event handler (after `await ack()` has already completed), these returned promises are fire-and-forget. If any reject, it triggers an unhandled promise rejection, which in Node.js 15+ terminates the process by default.
In contrast, in the webhook code path (`handleWebhook`), these same methods are always `return`-ed from async functions, so their promises are properly chained to the caller.
**Fix:**
Added `.catch()` handlers to both floating promises:
1. For `handleSlashCommand`: Added `.catch()` that logs the error via `this.logger.error`.
2. For `dispatchInteractivePayload`: Since it returns `Response | Promise<Response>` (only a Promise for `view_submission`), used `instanceof Promise` to conditionally attach a `.catch()` handler only when the result is a Promise.
This approach was chosen over making `routeSocketEvent` async because: (a) it doesn't change the method signature, (b) the caller doesn't need to await it (the ack has already been sent), and (c) errors are logged rather than silently swallowed.
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: haydenbleasel <hello@haydenbleasel.com>
* Add socket mode forwarding support to Slack adapter
- Export SlackForwardedSocketEvent type
- Add x-slack-socket-token check at top of handleWebhook() for forwarded events
- Update routeSocketEvent() to accept WebhookOptions and use waitUntil
- Add startSocketModeListener(), runSocketModeListener(), forwardSocketEvent()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add tests for socket mode forwarding
- Forwarded event accepted/rejected based on appToken
- Bypasses signature verification for forwarded events
- Options passthrough to handlers
- startSocketModeListener returns 200/500 appropriately
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add socket mode cron route and vercel config
- New /api/slack/socket-mode route using createPersistentListener
- Mirrors Discord gateway pattern (CRON_SECRET auth, Redis coordination)
- Cron runs every 9 min, listener duration 10 min
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Fix signingSecret defaulting to empty string in socket mode
Make signingSecret optional (string | undefined) instead of falling
back to "". verifySignature now returns false when no secret is
configured, preventing HMAC with an empty key from silently passing.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Wrap event_callback in try-catch in routeSocketEvent
Sync errors from processEventPayload were silently dropped in
socket mode. Wrap with try-catch for parity with slash_commands
and interactive cases.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Use dedicated socketForwardingSecret for forwarding auth
Stop using the Slack app-level token (xapp-...) as the bearer token
for HTTP forwarding. Adds socketForwardingSecret config option
(auto-detected from SLACK_SOCKET_FORWARDING_SECRET) with fallback
to appToken for backwards compatibility.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Replace double cast with type guard for socket event body
Validate body.event exists and construct a properly typed
SlackWebhookPayload instead of using `as unknown as`.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Internalize SlackForwardedSocketEvent type
Remove export — only used internally by the forwarding mechanism.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Fix formatting in socketForwardingSecret check
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add socket mode documentation to Slack adapter README
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(slack): use SDK envelope type for socket mode event routing
* fix(slack): pass interactive response through ack in socket mode
* feat(chat): add clear modal response action to close entire view stack
* chore: update changeset for clear modal action
---------
Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: dancer <josh@afterima.ge>
|
||
|
|
7e5b447e1d |
fix(discord): remove duplicate text when posting card messages (#256)
* Resolves #246 * Add card test coverage for postMessage/editMessage and changeset * fix(discord): clear content on edit to prevent text persisting alongside card * test(discord): add card content edge case tests --------- Co-authored-by: dancer <josh@afterima.ge> |
||
|
|
53c6b688ed |
fix(slack): guard Slack API calls against empty threadTs to fix invalid_thread_ts (#292)
* fix(slack): guard Slack API calls against empty threadTs to fix invalid_thread_ts Preserve the intentional empty threadTs for top-level DMs (added in #39 for openDM() subscription matching) while preventing Slack API errors. Instead of changing the threadTs logic, normalize empty threadTs to undefined at the entry of each method that calls Slack APIs (postMessage, postEphemeral, scheduleMessage, stream). This way: - openDM() subscription matching continues to work (empty threadTs) - Slack API calls receive undefined instead of "" (no invalid_thread_ts) The stream method throws ValidationError on empty threadTs (matching startTyping's early-return pattern) so TypeScript narrows correctly without any `as string` casts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Add tests for empty threadTs normalization in stream, scheduleMessage, and postEphemeral --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
c26ee6c721 |
fix(slack): preserve email addresses in @mention regex (#394)
The mention rewrite regex only excluded `<` before `@`, so `user@example.com` was converted to `user<@example>.com`, breaking plain emails and `<mailto:…>` links. Extend the lookbehind to also exclude word characters so emails pass through unchanged. Fixes #392 |
||
|
|
9093292ef4 |
feat(chat): add streaming options to thread.post() (#388)
* feat(chat): add streaming options to thread.post() * test(chat): add comprehensive tests for PostStreamOptions * feat(chat): add StreamMessage PostableObject for streaming with options * refactor(chat): remove PostStreamOptions second param, keep only StreamMessage PostableObject * refactor(chat): rename StreamMessage to StreamingPlan, fix post() return type Rename per Malte's feedback - StreamingPlan better describes what the options control (task grouping, stop blocks for streamed plans). Fix type safety issue where post<T extends PostableObject>() returned SentMessage at runtime instead of T. Now awaits handleStream() for side effects and returns the original StreamingPlan instance. * test(chat): cover updateIntervalMs-only and fallback paths for StreamingPlan Remove a duplicated test block, drop a duplicate JSDoc line on Thread.post, and add tests for posting a StreamingPlan with only updateIntervalMs and for routing StreamingPlan through the fallback post+edit path when the adapter has no native streaming. --------- Co-authored-by: Ben Sabic <bensabic@users.noreply.github.com> |
||
|
|
1c12d33629 | wip (#383) |