Inbox adapter
inboxAdapter, a Chat SDK adapter whose threads are inbox conversations, so a bot answers visitors in the in-app widget and staff can take over.
inboxAdapter makes the inbox a Chat SDK platform.
A thread is a conversation (thread id inbox:<inboxId>:<conversationId>,
channel id inbox:<inboxId>), the bot's replies
are messages with the author type bot, and reactions, edits, typing and
read state go through the same createInbox client.
import { createInbox, sqlTransport } from "better-supabase/blocks/inbox";
import { inboxAdapter } from "better-supabase/chat-sdk";
const inbox = createInbox({ transport: sqlTransport(postgres.asService()) });
export const inboxBot = inboxAdapter({ inbox, userName: "Acme bot", streams });| Option | Default | Meaning |
|---|---|---|
inbox | required | createInbox on a service transport; the bot writes as the service |
userName | bot | The bot's name on its messages and reactions |
verify | none | Checks requests to handleWebhook; without it handleWebhook answers 401 |
reasoning | "drop" | "metadata" keeps the model's reasoning in metadata.reasoning; it is never in the body |
streams | none | A stream store for streamed replies a reader can resume |
identities | none | principalByIdentity (or server) and ticketFor: tickets for linked contacts |
concurrencyScope | none | What getConcurrencyScope() returns, such as the tenant id when one Chat serves several tenants |
dmInbox | none | The inbox openDM(contactId) opens a bot conversation in |
Running the bot
The module queues an inbox_bot job when a contact writes in a
conversation whose botMode is bot. Hand the job to dispatch, which
loads the message and runs the bot's Chat SDK handlers. Messages from
staff, notes and other bots are skipped, so the bot never answers itself:
await inboxBot.dispatch({ conversation_id, message_id, inbox_id });dispatch takes Chat SDK's WebhookOptions as its second argument and
passes them to processMessage. With waitUntil, the whole job (loading
the message, the ticket, the handlers) runs in the background and
dispatch returns at once; an error is logged through the Chat logger
unless propagateHandlerErrors is set. handleWebhook(request, options)
passes its options the same way:
import { after } from "next/server";
export const POST = (request: Request) =>
bot.webhooks.inbox(request, { waitUntil: (task) => after(() => task) });When the bot can't help, hand the conversation to staff. handoff sets
botMode to human, so later messages queue no bot job:
bot.onSubscribedMessage(async (thread, message) => {
if (/human|agent/i.test(message.text)) {
await inbox.conversations
.handoff(conversationIdOf(thread.id), "asked for a person")
.orThrow();
await thread.post("Someone from the team will reply here.");
}
});conversationIdOf(threadId) turns a thread id back into a conversation
id, and decodeInboxThreadId returns both ids; inboxThreadId({ inboxId, conversationId }) builds one. A staff reply in a bot conversation also
switches it to human.
Reading and errors
fetchMessages honours direction: backward (the default) pages from the
newest message toward older ones, forward from the cursor toward newer
ones, and each page comes back oldest first. markAsRead(threadId, messageId) marks the whole conversation read, since the inbox keeps one
read mark per conversation. Reactions resolve a Chat SDK emoji name
(thumbs_up) to its unicode character, the form the widget shows.
A failed call throws the error Chat SDK adapters throw: chatErrorOf
turns the DbError into a RateLimitError (with retryAfterMs), a
NotImplementedError for an operation the installed modules lack, or a
ChatError with the adapter codes (NOT_FOUND, AUTH_FAILED,
PERMISSION_DENIED, VALIDATION_ERROR, NETWORK_ERROR). The DbError is
the cause. A thread id of another shape throws INVALID_THREAD_ID.
Answering as the linked user
The bot writes its replies as the service, but what it looks up for a
visitor should stay within what that visitor may see. With identities,
dispatch resolves the contact before the handlers run, the same way
botJobs does:
it asks principalByIdentity about inboxIdentityOf(contactId) (kind: "chat", provider: "inbox"), and for a contact linked to a signed-in user
it calls ticketFor(userId). A handler reads the ticket with ticketOf
and runs its lookups through forContext:
export const inboxBot = inboxAdapter({
inbox,
identities: { server: bsb, ticketFor: (userId) => tickets.issue(userId) },
});
bot.onSubscribedMessage(async (thread, message) => {
const ticket = inboxBot.ticketOf(message);
if (ticket === undefined) {
await thread.post("Sign in to see your orders.");
return;
}
const db = await bsb.forContext({ ticket });
const orders = await db.orders.list().orThrow();
await thread.post(`You have ${String(orders.length)} open orders.`);
});A contact with no link, or one the resolver maps to a contact, stays a
visitor: ticketOf returns undefined, and nothing falls back to the
service role. When the resolver or ticketFor throws, dispatch rejects
before the handlers run. The ticket is only readable while the handlers
for that dispatch run.
Streamed replies
A streamed thread.post shows the bot as typing while it writes, then
posts one message with the full text. With streams, the chunks also go
to the stream store as they arrive, and the message's metadata.stream_id
names the stream, so a client can replay the reply chunk by chunk.
The adapter accepts reasoning chunks, so the Chat SDK does not strip them
before stream runs. They never become part of the message a contact reads.
By default they are dropped. With reasoning: "metadata", the text is kept in
the stored message's metadata.reasoning, for your own tooling. Choose it
only when the contact's client does not show message metadata.
DMs, replies and listing threads
With dmInbox, openDM(contactId) opens a conversation with the contact
in that inbox with botMode set to bot and returns its thread id, so
chat.openDM() works and thread.postEphemeral(..., { fallbackToDM: true })
falls back to it. Without dmInbox the adapter has no openDM.
reply(threadId, messageId, message) posts with replyTo set to the
message. fetchChannelInfo("inbox:<inboxId>") names the inbox, and
listThreads(channelId, { limit, cursor }) pages through the inbox's
conversations, newest activity first, each with its first message as
rootMessage. The cursor is opaque; pass nextCursor back as it is.
A card (thread.post(<Card>...) or { card }) is posted as its markdown
fallback, and the card itself lands in the message's metadata.card, so a
client can render its buttons.
Limits
scheduleMessage comes from a scheduler:
scheduledAdapter(inboxBot, scheduler). openModal and a native
postEphemeral aren't implemented, since the in-app widget has no surface
for them, and button presses on a card don't reach the bot yet.
Last updated on
State
createSupabaseState, a Chat SDK StateAdapter on Postgres with subscriptions, locks, a cache, lists and per-thread queues.
Scheduled messages
stateScheduler and scheduledAdapter, so thread.schedule() works on any Chat SDK adapter, with the messages held in your state adapter until a cron job posts them.