Channels
How core turns a provider webhook into an agent run and sends the reply back. Per-provider setup for users is under Channels. Paths are relative to apps/core/.
File map
| File | Owns |
|---|---|
src/harness/integrations.ts | Webhook routing, the credential scan, record lookup, policy gate, provider ACK |
src/harness/handler.ts | handleChannelRequest admission, runChannelTurns on the worker pool, final reply |
src/shared/channels.ts | The contracts: ChannelAdapter, ChannelActions, InboundMessage |
src/shared/<channel>-channel.ts | Provider auth, parsing, formatting and reply calls |
src/shared/commands.ts | /new and /clear, /compact, /steer, /stop and /cancel, /queue, /help |
src/harness/tools/channel.tool.ts | The model-facing send-* tools |
src/harness/channel-media.ts | Inbound attachment download, storage and model hand-off |
src/shared/media-ticket.ts | Sealed /v1/media/{ticket} links |
Slack, Telegram, Discord, GitHub, Linear, WhatsApp, Teams, Google Chat, Twilio, Messenger and Instagram use Chat SDK adapters (@chat-adapter/*) as transport only: verify, parse, post. Core never creates a Chat instance and builds a fresh adapter per request, so nothing kept in Chat state survives. That is why Linear takes a personal API key only (OAuth tokens are refreshed and cached in Chat state). Messenger and Instagram share Meta webhook handling in meta-channel.ts. Pancake and Zalo are Broods-native.
Inbound paths
Webhook URLs are /v1/webhooks/{accountId}/{channel} for the production stage and /v1/webhooks/{accountId}/dev/{endpointId}/{channel} for any other stage, so two stages sharing one bot never see each other's traffic. The URL names no agent. Traefik (apps/edge/src/routes.ts) sends the path straight to core with no per-address limit, because providers post from shared egress addresses.
A GET with no query string answers {"status":"ok"} so a provider console sees the URL live. A GET with a query string is a subscription handshake and goes through the same scan as a delivery. WhatsApp checks hub.verify_token in authenticate and echoes hub.challenge from parse. A GET no channel claims, such as Pancake's ?secret= URL, still answers ok.
Runtime flow
Which agent gets a delivery, and what parse decides:
- Ties between agents that verify the same request go to the lowest agent id (
localeCompare), so the choice never varies. A channel record is how users resolve that tie. WhatsApp, Messenger and Instagram setroutesEachEntry: every verifier gets the delivery and keeps only its own entries. - A record lookup that finds nothing falls back to the credential holder. One that fails refuses the turn, since running without the record's policies and
denyToolswould be an escalation. Acontextmessage whose lookup fails is dropped with a warning. eventIdandconversationKeyare scoped withaccountIdandagentIdbefore the session sees them. A run only sees its own channel's config; core strips other channels' credentials.
One message, from webhook to reply. The critical block is what the provider ACK waits on:
The 2 s budget starts once every receiver has parsed the delivery, so it covers admission only; scan and parse come on top. It stays under Slack's and Discord's 3 s retry limit when those are quick. A provider that times out first treats the delivery as failed and resends it, the same as after a 503. Whatever is still admitting when the budget runs out carries on after the ACK.
Like an API run, a message holds one run queue place while it is admitted (withQueuePlace in handleChannelRequest). A full queue turns it away before the plan counts it or ingress records it, and an account out of budget hears its refusal first. A turn whose parse result sets redelivers (the provider or its forwarder resends after a 5xx) rejects, and the webhook answers 503 with Retry-After; in a batch that answers the whole delivery, and the turns already admitted come back as duplicates. Any other turn, or one turned away after the ACK went, says the agent is busy in the channel and is acked. Slack slash commands and buttons, Discord interactions, GitHub, Pancake, Zalo, Teams, Google Chat and Twilio do not resend, so they get the busy reply. Discord Gateway messages get it too: the Discord forwarder gives up after 3 tries in about 10 s, too soon to outlast a full queue, and a dropped message would leave the chat with nothing.
A queued or duplicate outcome starts no worker: the current owner drains the queue on its own worker slot (runChannelTurns loops on takeNext). Busy-conversation rules are in queue and steer. Model work runs on the MAX_INPROCESS_WORKERS pool shared with streamed, async and WebSocket runs.
Adapter contract
Each provider implements ChannelAdapter from src/shared/channels.ts:
ChannelAdapter member | Purpose |
|---|---|
name | URL segment and config key, such as telegram |
routesEachEntry? | Hand the delivery to every verifying agent (Meta batches) |
canHandle(req) | Quick provider-shape check, usually on headers |
authenticate(req) | Provider-native signature or secret check |
parse(req) | One ChannelParseResult, below. May be async. Never downloads. |
actions(msg) | ChannelActions scoped to the inbound message |
applyReplyIn?() | Rewrites reply routing for a record's replyIn. Only Slack implements it. |
rehydrateAttachment?() | Rebuilds an attachment reader from stored metadata so a later turn can re-read it |
parse() kind | Meaning |
|---|---|
message | Run the agent, after sending ack or a default 200. redelivers when the provider resends after a 5xx |
context | Store as conversation context, no run. Slack, Discord and Telegram use it for messages not to the bot. |
batch | Several message or context results from one POST, admitted in order under one ACK budget (Meta batching) |
cleanup | Delete the conversation's partition folders. GitHub returns it when an issue or PR closes. |
ignore | Stop without a run, usually an unsupported event |
response | Answer the provider at once, such as a challenge reply |
InboundMessage carries eventId (provider id, used for dedup), conversationKey (thread, chat or channel), channelName, content (AI SDK UserContent), attachments (named readers, no bytes yet), events (extra model messages such as a one-turn system message), identity (ChannelIdentity: workspaceRef, channelId, threadId, userId, userName, userRoles), source (opaque reply routing, which can hold interaction tokens) and answer (an ask_questions button click).
ChannelActions requires sendText, sendTyping and reactToMessage. A provider declares more by implementing them, and the tools follow:
| Tool | Registers when |
|---|---|
send-message | the run has a session dispatcher and the agent has at least one channel, channel turn or not |
send-update | always on a channel turn |
send-images | sendImages or sendFiles exists |
send-files | a workspace is attached |
send-sticker | sendSticker exists |
send-reactions | supportsReactions is true |
Only Slack, Telegram and GitHub implement stream() (GitHub buffers and posts one comment). Every other channel sends one final sendText.
Shared pipeline behavior
Adapters do not implement these:
- Commands. Channels in
INLINE_COMMAND_CHANNELS(Discord, Google Chat, Instagram, Messenger, Slack, Teams, Telegram, Twilio, WhatsApp, Zalo) route/commandtext throughcommands.ts. GitHub, Linear and Pancake pass it to the agent. - Typing and reaction never fail the turn.
- Tools with
needsApprovalare denied on channel turns. - A failed turn replies with
formatChannelErrorText(): the provider's reason, secrets redacted, plus the step that fixes it.sendChannelFailure()adds a Retry button wheresendReplyButtonsexists (Telegram), orReply "retry"text. - A turn that finishes in the background replies through
sendChannelReply(), which rebuilds the adapter from config and the storedsourceand runsonMessageSendingfirst. See architecture. - Trace links are omitted unless the connection sets
trace: "enabled".
Outbound files and images
The model names workspace paths or public URLs. The tool seals each workspace file into a durable /v1/media/{ticket} link and keeps a reader beside it, then falls down a ladder:
| Channel | Pictures | Documents | Batch |
|---|---|---|---|
| Telegram | fetches the URL | fetches the URL | album of 2 to 10 |
| Slack | Block Kit image blocks | uploads bytes (files.uploadV2) | one message, one upload |
| Discord | uploads bytes | uploads bytes | one multipart message |
| Pancake | uploads bytes (upload_contents) | uploads bytes | one per message |
| Zalo | fetches the URL | none | one per message |
| uploads bytes, or links a URL | uploads bytes, or links a URL | one per message | |
| uploads bytes, or fetches the URL | uploads bytes, or fetches the URL | one per message | |
| Twilio | fetches the URL (MMS) | none | one per message |
| Teams, Google Chat, Messenger, GitHub, Linear | none | none | text links only |
The link expires: the sealed ticket carries an expiry, MEDIA_TICKET_TTL_SECONDS (default 30 days) from sealing, and a pre-expiry ml1 link is refused outright. Some providers re-fetch on every view and Zalo stores the URL itself, so an expired link 404s in old chat history; the route's cache headers let a provider CDN keep bytes it fetched in time, but only until the ticket expires. A conversation replayed past the expiry shows the model [a linked file is no longer available] in place of the file. Storage stays private and the sealed ticket is the only credential. Dropping a value from MEDIA_TICKET_SECRET stops every link sealed with it at the origin; a CDN copy fetched in time lives until the ticket would have expired. A copy fetched before the route bounded its cache lifetime (2026-11) keeps the old one-year max-age. A caption rides the first message only. Rejection reasons go to the log, not the chat.
Inbound attachments
- Download happens after parse and before admission, so a queued turn still carries its media. Each adapter uses the provider's own auth, and Slack and Teams only send their token to their own hosts.
- The attachment store is a managed-bucket prefix no sandbox mounts, so the link survives the agent tidying its workspace. Nothing is inlined as base64. Deleting the account deletes the store.
- Without a workspace, a later turn re-reads the provider's copy, so the provider decides how long media works (a Telegram file id lasts, a Discord link expires within a day).
- Limits: 6 MB per picture, 25 MB otherwise, ten attachments per message (
src/shared/media-types.ts,channel-media.ts). An unreadable attachment becomes a line of text. - Transcription fails fast at ingest, and the note says whether the provider was busy, refused the file, or has no speech-to-text.
config.transcriptionnames another provider or model:providerdefaults toconfig.model.provider,modelIdto that provider's default.
Forwarders
Discord sends regular messages only over a Gateway socket, so a single-replica deployment holds the connection and POSTs to the channel webhook. It reads connections from every plane in BROODS_CONFIG_PLANES, keeps one connection per bot token, and fans each event out to every webhook that token serves. It does not filter: which message runs is core's decision.
| Forwarder | POSTs | Header | Core calls back |
|---|---|---|---|
apps/discord-forwarder | { "type": "GATEWAY_MESSAGE_CREATE", "data": ... } | x-discord-gateway-token | nothing, replies use Discord REST |
Core's Discord adapter takes interactions and forwarded messages on one URL and tells them apart by x-discord-gateway-token, whose value is discordForwarderToken(botToken) from apps/core/src/shared/discord-wire.ts; core refuses the raw bot token there. A deployment without the forwarder can post MESSAGE_CREATE events itself in the same wrapper, deriving the header the same way: HKDF-SHA256 over the bot token with an empty salt, info broods-discord-forwarder and 32 bytes of output, base64url-encoded without padding. An absent author.bot means a human. For a thread message add thread: { "id": ..., "parent_id": ... } to data, because Discord sets channel_id to the thread and omits the parent. Deployment constraints are in operations, and each app's AGENTS.md lists its failure modes.
Add a channel
- Add the config type to
src/shared/domain/agent-config.ts. - Validate
config.channels.<channel>innormalizeChannelsConfig()inpackages/convex/model/agentRules.ts. - Create
src/shared/<channel>-channel.tsimplementingChannelAdapter. Use a Chat SDK adapter when one exists. Fillidentityso records and policies can match. - Add
create<Channel>ChannelFromConfig()tocreateChannelRegistry()insrc/harness/integrations.ts. - In
packages/broods/src/resources.ts, add the name toChannelType, the input types, anddefine<Channel>Connectionanddefine<Channel>Channel.packages/broods/src/client.tslists channel names for the webhook URL helpers. - If the provider cannot call a webhook, add a forwarder rather than polling from core.
- Update the API reference, the user docs under
channels/, apackages/demos/channel-*demo, and focused tests.
Never hardcode channel behavior in commands, shared handlers or the agent loop. Commands receive only ChannelActions.
Adapter skeleton
import type { ChannelAdapter, ChannelParseResult } from "./channels.ts";
export function createExampleChannel(
token: string,
webhookSecret: string,
): ChannelAdapter {
return {
name: "example",
canHandle(req) {
return "x-example-delivery" in req.headers;
},
authenticate(req) {
return req.headers["x-example-secret"] === webhookSecret;
},
parse(req): ChannelParseResult {
const body = JSON.parse(req.body) as {
id: string;
threadId: string;
text?: string;
};
if (!body.text) {
return { kind: "ignore", response: { statusCode: 200 } };
}
return {
kind: "message",
ack: { statusCode: 200 },
message: {
eventId: body.id,
conversationKey: body.threadId,
channelName: "example",
content: [{ type: "text", text: body.text }],
source: body as Record<string, unknown>,
},
};
},
actions(msg) {
return {
sendText: async (text) => {
await fetch("https://api.example.com/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ threadId: msg.conversationKey, text: text }),
});
},
sendTyping: async () => {},
reactToMessage: async () => {},
};
},
};
}
Rules
- Verify signatures or secrets before parsing user-controlled payloads deeply.
- Use stable provider ids for
eventIdso redeliveries dedup, and thread or chat ids forconversationKeyso follow-ups keep context. - Set
redelivers: trueon amessageresult only when the provider, or your forwarder, sends the delivery again after a 5xx and keeps trying long enough to outlast a full queue. A full run queue then answers503instead of a busy reply. - Never download attachments in
parse. - A provider
apiUrloverride must be a publichttpsURL, checked when the channel is saved, because core sends the token to it.