packages/ai exposes the Vercel Chat SDK through
@tuturuuu/ai/chat-sdk. Use it when a Tuturuuu agent needs to operate across
external channels and internal product surfaces with one normalized thread and
message contract.
The target workflow is:
Package Boundary
Import the Chat SDK boundary from:chat/ai tool helpers, then
adds Tuturuuu registry helpers for platform and state adapters.
Adapter Coverage
The adapter registry mirrors the Chat SDK adapter directory. Official platform adapters:- Slack:
@chat-adapter/slack - Microsoft Teams:
@chat-adapter/teams - Google Chat:
@chat-adapter/gchat - Discord:
@chat-adapter/discord - GitHub:
@chat-adapter/github - Linear:
@chat-adapter/linear - Telegram:
@chat-adapter/telegram - WhatsApp Business Cloud:
@chat-adapter/whatsapp - Messenger:
@chat-adapter/messenger - Web:
@chat-adapter/web
- Beeper Matrix:
@beeper/chat-adapter-matrix - Photon iMessage:
chat-adapter-imessage - Resend:
@resend/chat-sdk-adapter - Zernio:
@zernio/chat-sdk-adapter - Liveblocks:
@liveblocks/chat-sdk-adapter
- Webex:
@bitbasti/chat-adapter-webex - Baileys WhatsApp:
chat-adapter-baileys - Sendblue iMessage:
chat-adapter-sendblue - Blooio iMessage/RCS/SMS:
chat-adapter-blooio - Zalo:
chat-adapter-zalo - Mattermost:
chat-adapter-mattermost
- Memory:
@chat-adapter/state-memory - Redis:
@chat-adapter/state-redis - ioredis:
@chat-adapter/state-ioredis - PostgreSQL:
@chat-adapter/state-pg - Cloudflare Durable Objects:
chat-state-cloudflare-do - MySQL:
chat-state-mysql
Runtime Construction
Create a runtime by selecting only the adapters a route or worker owns. Passingtrue means the adapter should read credentials from its documented
environment variables. Passing an object forwards that object to the adapter
factory.
cloudflare:workers; load it only in a Cloudflare Workers runtime.
Agent Tools
Expose the selected chat runtime to AI SDK calls with Chat SDK tools:reader preset for analysis-only agents, messenger for normal
posting and DM workflows, and moderator for destructive operations such as
editing and deleting messages. Keep approval gates enabled by default for
visible writes unless the workflow has an explicit unattended execution policy.
External Chat Mirror
Apps/web AI agents mirror inbound and outbound Discord/Zalo messages through server-owned private RPCs. Runtime handlers persist webhook events as soon as they arrive, then persist any automatic or manual outbound response after the Chat SDK adapter accepts the post. When an operator clicks sync in Infrastructure > AI Agents, apps/web creates the configured Chat SDK runtime, opens the external thread handle, and consumes recentthread.messages when the adapter supports history fetch. Discord can
return recent messages with the right bot scopes. Official Zalo behaves as a
webhook-first adapter, so the mirror is populated by received events. Personal
Zalo channels use the experimental zca-js listener and can fetch group chat
history when the personal account session supports it. The personal adapter
also normalizes supported media messages into Chat SDK attachments. The mirror
stores those binaries in the workspace Drive provider, records only private
attachment metadata, and serves authenticated links from the same conversation
API used by native Chat attachments.
Inbound Attachment Download Limits
External chat mirroring selects at most 10 attachments per message, processes them sequentially, and accepts at most 25 MiB of actual bytes per attachment. Generic attachment URL downloads and the concrete personal Zalo media callback enforce the limit while reading the response stream, including when Content-Length is missing or understates the body. Existing response-status checks and 30-second fetch signals remain in place. Empty bodies remain zero-byte attachment data. In-memory Buffer and Blob sizes are checked before copying or materializing their bytes. Other injected attachment callbacks are checked after returning; their internal work and allocations are outside this streamed-reader guarantee. Personal Zalo attachment downloads retain User-Agent but do not forward channel cookies to message-selected media URLs. Media that requires those cookies can fail closed. Provider/channel login remains unchanged. This policy does not establish a URL allowlist, redirect policy, DNS pinning or general SSRF protection; those need separate product admission. Regression coverage lives inpackages/utils/src/read-bounded-response.test.ts,
packages/ai/src/chat-sdk/zalo-personal-attachment.test.ts and
apps/web/src/lib/ai-agents/external-chat-attachment-limits.test.ts.
Teams MSAL Security Compatibility
The root dependency override pins@azure/msal-node to 7.1.1 for
GHSA-xcx6-jx8p-x3h5. The direct Microsoft package already uses the patched
major; Teams apps 2.1.1 still requests ^5.6.0, including through Chat SDK’s
Teams adapter 4.43.0. Both are the latest published versions checked for this
upgrade. Remove the override only when the upstream Teams dependency range
resolves a patched MSAL version without it.
Teams’ token manager uses confidential client credentials with a tenant
specific authority. It does not enable instanceAware, request
instance_aware, or use interactive responseMode. MSAL 7 removes interactive
response-mode selection and rejects instance-aware confidential clients; retain
those rejections rather than enabling legacy behavior for the adapter.
scripts/teams-msal-compatibility.test.js follows the installed Teams ancestry,
requires the patched version, and exercises the actual Teams token manager and
MSAL client-credentials exchange using a fixture network transport. It also
checks the interactive and instance-aware rejection boundaries. Run it with
node --test scripts/teams-msal-compatibility.test.js after dependency changes.
These fixtures do not establish hosted Azure credential acceptance, managed
identity, or federated identity behavior. Require exact-commit CI and independent
security review before integration.
Upstream references: MSAL advisory
and MSAL v7 migration guide.
Discord mapping scope
A Discord integration binds one guild to one workspace. Reading an integration requires theallow_discord_integrations platform flag and MEMBER access to its
workspace. Connecting, changing or disconnecting one also requires
manage_workspace_integrations in that workspace, the same permission that
gates the integrations pages, and a connect must record the actor as creator.
The guild, workspace and creator of an existing integration are immutable for
every role, including service_role; rebinding means disconnecting and
connecting again. This also blocks the workspaces.id ON UPDATE CASCADE
path through ws_id and the users.id ON UPDATE CASCADE path through
creator_id, which are accepted because neither id is ever renumbered. The connect
handler reports a guild already bound elsewhere as 409, because the actor can
no longer see other workspaces’ integrations; other unique conflicts return a
generic 409.
Discord mapping reads require MEMBER access to the workspace linked to that
mapping’s guild. Creating, changing or deleting a mapping also requires
manage_workspace_integrations there: a mapping lets the bot and the AI agent
runtime act as the mapped user, so the platform flag alone must not let a member
map a coworker, including an admin, to an arbitrary Discord id. Mapped users
must be MEMBERs, not GUESTs, of the same workspace, matching the members
handler, and moving a mapping to another guild rechecks the destination
workspace. The web members handler applies the same
permission check before writing. Because the mapping policy reads the
integration under its own policy, the platform flag remains required; GUEST
members and anonymous clients cannot read or change integrations or mappings.
These rules apply to direct Data API access as well as the web handlers. The
Discord bot and the AI agent runtime read as service_role; the agent runtime
resolves a Discord user only when the channel’s configured guild is the one
bound to the channel’s workspace. Both web and infrastructure resolve the
mapping and binding in one inner-joined statement, filtered by the channel’s
workspace, guild and Discord user. A concurrent disconnect/reconnect cannot
substitute the new workspace’s mapping between an authorization read and an
identity read. A reconnect to the same workspace can resolve newly created
mappings normally; missing bindings or mappings resolve no identity.
Disconnecting a guild deletes all of its mappings in the same transaction,
through the discord_guild_members_discord_guild_id_fkey foreign key to
discord_integrations.discord_guild_id with ON DELETE CASCADE; deleting the
workspace does the same through its cascade to the integration. The disconnect
dialog states this, and reconnecting does not restore them. A foreign key
rather than a delete trigger closes the disconnect race: a mapping insert
racing a disconnect either commits first and is cascaded, or fails with
23503, so no mapping outlives its integration. A mapping can only be written
for a guild that has an integration.
The foreign key is added NOT VALID, so mappings already orphaned by earlier
disconnects do not fail the migration and stay until cleaned up.
VALIDATE CONSTRAINT is a later step, run only after a Mastermind-approved
orphan cleanup (Rollout step 5).
Once the unique index discord_guild_members_guild_discord_user_key exists,
each guild allows one mapping per Discord user. The migration skips the index
when duplicates exist; see Rollout step 4.
Coverage: apps/database/supabase/tests/discord-guild-mapping-boundary.sql,
apps/web/src/__tests__/discord-integration-route.test.ts,
apps/web/src/__tests__/discord-members-route.test.ts and
src/lib/ai-agents/discord-user-mapping.test.ts in web and infrastructure.
Rollout and triage
The migration changes no existing mapping rows. Cleaning up rows that predate it is a separate data change that Mastermind approves; it is never part of the migration. The migration setslock_timeout to 5s, so a long transaction
holding either table fails the apply instead of queueing the bot and agent
runtime behind it.
-
Before the PR merges, run the read-only
apps/database/scripts/discord-guild-mapping-exposure.sqlon staging and on production. Staging applies the migration on merge, so a post-merge run is too late. Run it withpsql, not the Supabase SQL editor, which shows only the last result set:The script runs in one read-only transaction and rolls back. Send every result set from both environments to Security and Mastermind. The first result is the duplicate(discord_guild_id, discord_user_id)count. If it is above0in either environment, STOP: do not merge until Mastermind approves a remap or purge. Applied with duplicates, the migration would skip the unique index with aNOTICEinstead of failing. -
Review the per-guild dangerous-shape counts with Security and Mastermind
before merge. A forged legacy mapping usually binds an attacker’s Discord id
to a real MEMBER of the guild’s workspace, so the outside-workspace count
alone misses it. Look at mappings to the creator or admins, platform users
with more than one Discord id, Discord ids with more than one mapping,
non-MEMBER targets, orphaned mappings for guilds with no integration, and
monthly creation bursts since 2025-09-13. Existing GUEST targets still
resolve for
service_roleuntil they are remapped or purged. - For each guild with suspicious counts, choose one path with Mastermind: the guild’s workspace owner re-verifies every mapping, or all of that guild’s mappings are purged and members are mapped again. Orphaned mappings have no owning workspace and are purged.
-
After apply, run the read-only
apps/database/scripts/discord-guild-mapping-index-check.sqlwithpsqlon staging and production, and send the result to Security and Mastermind:No row means the index was skipped and the finding stays open. After the approved remap or purge, the migration role runsselect public.ensure_discord_guild_member_identity_index();and repeats the check. -
After the approved orphan cleanup leaves no mapping without an
integration, the migration role runs
alter table public.discord_guild_members validate constraint discord_guild_members_discord_guild_id_fkey;as a separate, Mastermind-approved change. It takes only aSHARE UPDATE EXCLUSIVElock and fails without changing data if an orphan remains.