Skip to main content

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​

FileOwns
src/harness/integrations.tsWebhook routing, the credential scan, record lookup, policy gate, provider ACK
src/harness/handler.tshandleChannelRequest admission, runChannelTurns on the worker pool, final reply
src/shared/channels.tsThe contracts: ChannelAdapter, ChannelActions, InboundMessage
src/shared/<channel>-channel.tsProvider 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.tsThe model-facing send-* tools
src/harness/channel-media.tsInbound attachment download, storage and model hand-off
src/shared/media-ticket.tsSealed /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 set routesEachEntry: 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 denyTools would be an escalation. A context message whose lookup fails is dropped with a warning.
  • eventId and conversationKey are scoped with accountId and agentId before 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 memberPurpose
nameURL 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() kindMeaning
messageRun the agent, after sending ack or a default 200. redelivers when the provider resends after a 5xx
contextStore as conversation context, no run. Slack, Discord and Telegram use it for messages not to the bot.
batchSeveral message or context results from one POST, admitted in order under one ACK budget (Meta batching)
cleanupDelete the conversation's partition folders. GitHub returns it when an issue or PR closes.
ignoreStop without a run, usually an unsupported event
responseAnswer 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:

ToolRegisters when
send-messagethe run has a session dispatcher and the agent has at least one channel, channel turn or not
send-updatealways on a channel turn
send-imagessendImages or sendFiles exists
send-filesa workspace is attached
send-stickersendSticker exists
send-reactionssupportsReactions 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 /command text through commands.ts. GitHub, Linear and Pancake pass it to the agent.
  • Typing and reaction never fail the turn.
  • Tools with needsApproval are 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 where sendReplyButtons exists (Telegram), or Reply "retry" text.
  • A turn that finishes in the background replies through sendChannelReply(), which rebuilds the adapter from config and the stored source and runs onMessageSending first. 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:

ChannelPicturesDocumentsBatch
Telegramfetches the URLfetches the URLalbum of 2 to 10
SlackBlock Kit image blocksuploads bytes (files.uploadV2)one message, one upload
Discorduploads bytesuploads bytesone multipart message
Pancakeuploads bytes (upload_contents)uploads bytesone per message
Zalofetches the URLnoneone per message
WhatsAppuploads bytes, or links a URLuploads bytes, or links a URLone per message
Instagramuploads bytes, or fetches the URLuploads bytes, or fetches the URLone per message
Twiliofetches the URL (MMS)noneone per message
Teams, Google Chat, Messenger, GitHub, Linearnonenonetext 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.transcription names another provider or model: provider defaults to config.model.provider, modelId to 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.

ForwarderPOSTsHeaderCore calls back
apps/discord-forwarder{ "type": "GATEWAY_MESSAGE_CREATE", "data": ... }x-discord-gateway-tokennothing, 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​

  1. Add the config type to src/shared/domain/agent-config.ts.
  2. Validate config.channels.<channel> in normalizeChannelsConfig() in packages/convex/model/agentRules.ts.
  3. Create src/shared/<channel>-channel.ts implementing ChannelAdapter. Use a Chat SDK adapter when one exists. Fill identity so records and policies can match.
  4. Add create<Channel>ChannelFromConfig() to createChannelRegistry() in src/harness/integrations.ts.
  5. In packages/broods/src/resources.ts, add the name to ChannelType, the input types, and define<Channel>Connection and define<Channel>Channel. packages/broods/src/client.ts lists channel names for the webhook URL helpers.
  6. If the provider cannot call a webhook, add a forwarder rather than polling from core.
  7. Update the API reference, the user docs under channels/, a packages/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 eventId so redeliveries dedup, and thread or chat ids for conversationKey so follow-ups keep context.
  • Set redelivers: true on a message result 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 answers 503 instead of a busy reply.
  • Never download attachments in parse.
  • A provider apiUrl override must be a public https URL, checked when the channel is saved, because core sends the token to it.