Channel Adapters
The ChannelHub pattern — how 14 messaging platforms plug into Anvio's channel-agnostic agent runtime.
7 min read
Anvio's Channel Hub architecture (ADR 0008) exists to solve one problem: let the agent runtime stay completely unaware of where a message came from — Telegram, WhatsApp, a REST call, the CLI — while still supporting rich per-platform features like progress updates, approval buttons, and threaded resume.
The three pieces
1. ChannelAdapter — the transport-only contract
Defined in packages/core/src/ports/channel.port.ts. Every channel implements this; the agent runtime never imports channel-specific code.
export interface ChannelAdapter {
readonly channelType: ChannelType;
sendMessage(sessionId: string, message: OutboundMessage): Promise<void>;
sendProgress?(sessionId: string, update: ProgressUpdate): Promise<void>;
sendNotification?(sessionId: string, notification: AgentNotification): Promise<void>;
sendApprovalRequest?(sessionId: string, request: ApprovalRequestMessage): Promise<void>;
onMessage(handler: InboundMessageHandler): void;
start(): Promise<void>;
stop(): Promise<void>;
}Only sendMessage, onMessage, start, and stop are required. sendProgress, sendNotification, and sendApprovalRequest are optional — a channel that can't render native progress indicators or approve/reject buttons simply omits them (BaseChannelAdapter, in packages/channels/src/base-channel-adapter.ts, provides sensible text-based fallbacks for all three).
The full ChannelType union (packages/core/src/types/common.ts) — 14 values:
export type ChannelType =
| 'web-chat' | 'telegram' | 'whatsapp' | 'discord' | 'slack'
| 'teams' | 'matrix' | 'email' | 'signal' | 'google-chat'
| 'feishu' | 'sms' | 'mattermost' | 'rest' | 'cli';(That's 15 string literals in source; web-chat and cli/rest bring the total surface documented in the README to "14 channel adapters" plus the two always-on local interfaces.)
2. ChannelHub — registry and router
packages/channels/src/channel-hub.ts implements ChannelHubPort. It holds a Map<ChannelType, ChannelAdapter> and provides the single dispatch point used by the rest of the platform — controllers and the runtime call the hub, never an adapter directly:
export class ChannelHub implements ChannelHubPort {
private readonly adapters = new Map<ChannelType, ChannelAdapter>();
register(adapter: ChannelAdapter): void {
this.adapters.set(adapter.channelType, adapter);
}
getAdapter(channel: ChannelType): ChannelAdapter | undefined {
return this.adapters.get(channel);
}
async sendMessage(channel, sessionId, message): Promise<void> {
const adapter = this.adapters.get(channel);
if (!adapter) return;
await adapter.sendMessage(sessionId, message);
}
// sendProgress, sendNotification, sendApprovalRequest follow the same
// "look up adapter, no-op if missing or method unsupported" pattern
async startAll(): Promise<void> {
await Promise.all([...this.adapters.values()].map((a) => a.start()));
}
}getAdapter() is exactly what the webhook controllers use to check whether a channel is live before processing a payload — e.g. apps/api/src/teams.controller.ts calls channelHub.getAdapter('teams') and returns 404 if it's undefined.
3. ChannelSessionBridge — thread-to-session mapping
packages/channels/src/channel-session-bridge.ts resolves an external platform's thread/conversation ID to an Anvio session, creating one if it doesn't exist yet:
export class ChannelSessionBridge {
async resolveOrCreate(
channel: ChannelType,
threadId: string,
userId?: string,
agentName?: string,
): Promise<StoredSession> {
const existing = await this.sessions.getByChannelThread(channel, threadId);
if (existing) return existing;
return this.sessions.create({
userId: userId ?? this.defaults.defaultUserId,
agentName: agentName ?? this.defaults.defaultAgent,
channel,
messages: [],
status: 'idle',
channelThread: { channel, threadId },
detached: true,
});
}
}This is what lets a Telegram user resume a conversation days later and land back in the same session — the bridge looks up by (channel, threadId) instead of creating a new session every message. Sessions created this way default to detached: true, meaning they can run and produce output in the background without a client actively waiting on the HTTP response (see ADR 0008's "background/detached execution" requirement).
Registering adapters: createChannelHub()
packages/channels/src/create-channels.ts is the composition function that builds a fully wired ChannelHub from config + environment. Every adapter follows the same pattern: build options from ChannelConfig (falling back to process.env.*), and only register the adapter if its required credentials are present (with three exceptions — WebChatChannel, CliChannel, RestApiChannel, TeamsChannel, and MatrixChannel register unconditionally, and gate real functionality behind an internal isConfigured() check instead).
registerAdapter(hub, new WebChatChannel(), onInbound);
registerAdapter(hub, new CliChannel(), onInbound);
registerAdapter(hub, new RestApiChannel(), onInbound);
if (options.channels?.telegram?.enabled && telegramToken) {
registerAdapter(hub, new TelegramChannel({ botToken: telegramToken, ... }), onInbound);
}
// ...same conditional pattern for discord, slack, whatsapp, signal, google-chat, feishu, sms, mattermost| Channel | Adapter class | Source | Registration condition |
|---|---|---|---|
| Web Chat | WebChatChannel | web-chat.ts | Always |
| CLI | CliChannel | cli-channel.ts | Always |
| REST | RestApiChannel | rest-api.ts | Always |
| Telegram | TelegramChannel | telegram.ts | enabled + TELEGRAM_BOT_TOKEN |
| Discord | DiscordChannel | discord.ts | enabled + DISCORD_BOT_TOKEN |
| Slack | SlackChannel | slack.ts | enabled + SLACK_BOT_TOKEN + SLACK_APP_TOKEN |
WhatsAppChannel | whatsapp.ts | enabled + WHATSAPP_ACCESS_TOKEN + WHATSAPP_PHONE_NUMBER_ID | |
| Teams | TeamsChannel | teams.ts | Always registered; needs appId/appPassword/serviceUrl to be functional |
| Matrix | MatrixChannel | matrix.ts | Always registered; needs homeserverUrl/accessToken/roomId to be functional |
EmailChannel | email.ts | channels.email.enabled | |
| Signal | SignalChannel | signal.ts | channels.signal.enabled |
| Google Chat | GoogleChatChannel | google-chat.ts | enabled + webhook URL or service account |
| Feishu | FeishuChannel | feishu-channel.ts | enabled + FEISHU_WEBHOOK_URL |
| SMS | SmsChannel | sms-channel.ts | enabled + Twilio SID/token/from-number |
| Mattermost | MattermostChannel | mattermost.ts | enabled + server URL + bot token |
Per the gap register, all 14 channels are implemented (not stubs) as of the latest shipped phases (P12–P14) — Signal uses signal-cli over REST, Google Chat uses JWT service-account auth, Teams/Matrix have retry-with-backoff hardening. The remaining caveats are production credential/soak-testing items, not missing code.
Outbound: how the runtime talks back to a channel
The runtime (or anything downstream of AGENT_RUN_COMPLETED/AGENT_RUN_CHUNK/APPROVAL_REQUESTED) never calls an adapter directly — it goes through the ChannelHub:
await channelHub.sendMessage(session.channel, session.id, { sessionId, type: 'chunk', delta });
await channelHub.sendProgress(session.channel, session.id, { sessionId, phase: 'tool_executing', status: 'running' });
await channelHub.sendApprovalRequest(session.channel, session.id, { sessionId, requestId, toolName, reason, actions: ['approve', 'reject'] });BaseChannelAdapter (packages/channels/src/base-channel-adapter.ts) provides default implementations of sendProgress and sendNotification that just format an emoji-prefixed text message and call sendMessage — so a channel adapter that can't render rich UI still degrades gracefully:
async sendProgress(sessionId: string, update: ProgressUpdate): Promise<void> {
const emoji = update.emoji ?? (update.status === 'completed' ? '✅' : '🔄');
await this.sendMessage(sessionId, {
sessionId, type: 'message',
content: `${emoji} ${update.phase}`,
metadata: { progress: update },
});
}sendApprovalRequestWithActions is left abstract — every adapter must decide for itself how to render approve/reject (native buttons on Slack/Teams, text prompts elsewhere).
Inbound: how a channel message reaches the event bus
Every adapter calls dispatchInbound() (from BaseChannelAdapter), which invokes whatever handler was registered via onMessage(). createChannelHub() wires the same handler — createInboundHandler() — to every adapter:
function createInboundHandler(eventBus, sessions, defaultAgent, harness) {
return async (message: InboundMessage) => {
if (harness?.enabled) {
const gate = await harness.handleInbound({ /* ... */ });
if (gate.decision !== 'allow') return; // harness can block/redirect before the runtime sees it
}
const session = await sessions.get(message.sessionId);
await eventBus.publish(EventSubjects.AGENT_RUN_REQUESTED, 'anvio.agent.run.requested', {
sessionId: message.sessionId,
userId: message.userId,
agentId: session?.agentName ?? defaultAgent,
content: message.content,
channel: message.channel,
detached: true,
});
};
}Every inbound message, regardless of channel, ends up as the same anvio.agent.run.requested.v1 event on the event bus — this is the payoff of the whole architecture: one runtime code path handles Telegram, Slack, a REST call, and everything else identically.
Configuration reference
Channel credentials are read from process.env.* first if not supplied in ChannelConfig (the channels: block of anvio.yaml). None of these appear in .env.example by default — they're optional, Level 2+ additions:
| Channel | Env vars |
|---|---|
| Telegram | TELEGRAM_BOT_TOKEN |
| Discord | DISCORD_BOT_TOKEN |
| Slack | SLACK_BOT_TOKEN, SLACK_APP_TOKEN |
WHATSAPP_ACCESS_TOKEN, WHATSAPP_PHONE_NUMBER_ID, WHATSAPP_VERIFY_TOKEN | |
| Teams | TEAMS_APP_ID, TEAMS_APP_PASSWORD, TEAMS_SERVICE_URL |
| Matrix | MATRIX_HOMESERVER_URL, MATRIX_ACCESS_TOKEN, MATRIX_USER_ID, MATRIX_ROOM_ID |
EMAIL_SMTP_HOST, EMAIL_IMAP_HOST, EMAIL_IMAP_PORT, EMAIL_POLL_INTERVAL_MS, EMAIL_USERNAME, EMAIL_PASSWORD, EMAIL_FROM | |
| Signal | SIGNAL_CLI_PATH, SIGNAL_PHONE_NUMBER |
| Google Chat | GOOGLE_CHAT_WEBHOOK_URL, GOOGLE_CHAT_SERVICE_ACCOUNT, GOOGLE_CHAT_SPACE |
| Feishu | FEISHU_WEBHOOK_URL |
| SMS | TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM_NUMBER |
| Mattermost | MATTERMOST_SERVER_URL, MATTERMOST_BOT_TOKEN |
Last updated on