> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch19-channel-adapter-abstraction/19.1-channel-adapter-design-pattern.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 19.1 Channel Adapter Design Pattern

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~560k tokens, Output \~50k tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

OpenClaw's core positioning is a "multi-channel AI agent gateway"—a single AI agent can simultaneously appear on Telegram, WhatsApp, Discord, Slack, Signal, and dozens of other messaging platforms. This means the system must convert each platform's unique API into a unified internal format. The key architecture for achieving this goal is the **Channel Adapter Pattern**.

> **Sidebar: Adapter Pattern**
>
> The Adapter Pattern is one of the classic GoF (Gang of Four) design patterns, belonging to the structural pattern category. It converts the interface of one class into another interface that clients expect, allowing classes that would otherwise be incompatible to work together. In OpenClaw, each channel plugin is an adapter—it converts the Telegram Bot API, WhatsApp Web protocol, Discord.js, and other vastly different interfaces into a unified `ChannelPlugin` interface that the Gateway can handle uniformly.

***

## 19.1.1 Channel Core Interface Analysis

### ChannelPlugin: Unified Channel Contract

The complete definition of each channel in OpenClaw is described by the `ChannelPlugin` type. This is a massive interface containing 20+ optional adapters, defined in `src/channels/plugins/types.plugin.ts`:

```typescript
// src/channels/plugins/types.plugin.ts (simplified)
export type ChannelPlugin<ResolvedAccount = any, Probe = unknown, Audit = unknown> = {
  id: ChannelId;                          // Channel identifier, e.g., "telegram"
  meta: ChannelMeta;                      // Display metadata (name, icon, docs link, etc.)
  capabilities: ChannelCapabilities;      // Capability declaration

  // ── Configuration and Setup ──
  config: ChannelConfigAdapter<ResolvedAccount>;   // Account configuration management (required)
  configSchema?: ChannelConfigSchema;              // JSON Schema config validation
  setup?: ChannelSetupAdapter;                     // CLI initialization wizard
  onboarding?: ChannelOnboardingAdapter;           // Onboarding flow

  // ── Security and Permissions ──
  security?: ChannelSecurityAdapter<ResolvedAccount>;
  pairing?: ChannelPairingAdapter;
  auth?: ChannelAuthAdapter;
  elevated?: ChannelElevatedAdapter;

  // ── Message Processing ──
  outbound?: ChannelOutboundAdapter;       // Outbound message sending
  messaging?: ChannelMessagingAdapter;     // Message tool target resolution
  streaming?: ChannelStreamingAdapter;     // Streaming parameters
  threading?: ChannelThreadingAdapter;     // Threading/quoted replies
  mentions?: ChannelMentionAdapter;        // @mention handling
  actions?: ChannelMessageActionAdapter;   // Message actions (reactions, edits, unsends)

  // ── Runtime ──
  gateway?: ChannelGatewayAdapter<ResolvedAccount>;  // Gateway service lifecycle
  commands?: ChannelCommandAdapter;                   // Command permissions
  groups?: ChannelGroupAdapter;                       // Group behavior
  heartbeat?: ChannelHeartbeatAdapter;                // Heartbeat checks
  status?: ChannelStatusAdapter<...>;                 // Status probing and auditing

  // ── Extensions ──
  agentPrompt?: ChannelAgentPromptAdapter;  // Inject channel-specific system prompts
  directory?: ChannelDirectoryAdapter;       // Contact/group directory
  resolver?: ChannelResolverAdapter;         // Target resolution
  agentTools?: ChannelAgentToolFactory | ChannelAgentTool[];  // Channel-specific tools
};
```

This interface embodies the **Interface Segregation Principle (ISP)**—each adapter is an independent optional field. A minimal channel only needs to implement four required items: `id`, `meta`, `capabilities`, and `config`; all other adapters can be added as needed.

### ChannelCapabilities: Capability Declaration

`ChannelCapabilities` declares which features a channel supports, enabling the system to adaptively enable or disable features at runtime:

```typescript
// src/channels/plugins/types.core.ts
export type ChannelCapabilities = {
  chatTypes: Array<NormalizedChatType | "thread">;  // Supported conversation types
  polls?: boolean;          // Polls
  reactions?: boolean;      // Emoji reactions
  edit?: boolean;           // Message editing
  unsend?: boolean;         // Message unsending
  reply?: boolean;          // Quoted replies
  effects?: boolean;        // Message effects
  groupManagement?: boolean;  // Group management
  threads?: boolean;        // Threads
  media?: boolean;          // Media attachments
  nativeCommands?: boolean; // Native slash commands
  blockStreaming?: boolean; // Streamed block replies
};
```

The capability differences between channels are substantial:

| Channel  | chatTypes                      | polls | reactions | threads | nativeCommands | blockStreaming |
| -------- | ------------------------------ | ----- | --------- | ------- | -------------- | -------------- |
| Telegram | direct, group, channel, thread | ❌     | ❌         | ❌       | ✅              | ✅              |
| WhatsApp | direct, group                  | ✅     | ✅         | ❌       | ❌              | ❌              |
| Discord  | direct, channel, thread        | ✅     | ✅         | ✅       | ✅              | ❌              |
| Slack    | direct, channel, thread        | ❌     | ✅         | ✅       | ✅              | ❌              |
| Signal   | direct, group                  | ❌     | ✅         | ❌       | ❌              | ❌              |

These declarations are not merely documentation—the system checks them at runtime. For example, only channels with `blockStreaming: true` will enable streamed block replies (Chapter 18).

### ChannelMeta: Display Metadata

Each channel has a set of descriptive metadata used for CLI interfaces, Web UI, and documentation links:

```typescript
// src/channels/plugins/types.core.ts (simplified)
export type ChannelMeta = {
  id: ChannelId;
  label: string;              // Display name, e.g., "Telegram"
  selectionLabel: string;     // Selection UI label, e.g., "Telegram (Bot API)"
  docsPath: string;           // Documentation path, e.g., "/channels/telegram"
  blurb: string;              // One-line description
  order?: number;             // Sort weight
  aliases?: string[];         // Aliases (e.g., "imsg" → "imessage")
  systemImage?: string;       // SF Symbols icon name
  // ...more UI-related fields
};
```

Core channel metadata is hardcoded in `src/channels/registry.ts`:

```typescript
// src/channels/registry.ts (excerpt)
const CHAT_CHANNEL_META: Record<ChatChannelId, ChannelMeta> = {
  telegram: {
    id: "telegram",
    label: "Telegram",
    selectionLabel: "Telegram (Bot API)",
    blurb: "simplest way to get started — register a bot with @BotFather and get going.",
    systemImage: "paperplane",
    // ...
  },
  whatsapp: {
    id: "whatsapp",
    label: "WhatsApp",
    selectionLabel: "WhatsApp (QR link)",
    blurb: "works with your own number; recommend a separate phone + eSIM.",
    // ...
  },
  // ...other channels
};
```

***

## 19.1.2 Channel Configuration Type System

### Federated Configuration

OpenClaw's channel configuration adopts a **federated** structure—each channel's configuration type is defined independently, then composed at the top level in `ChannelsConfig`:

```typescript
// src/config/types.channels.ts
export type ChannelsConfig = {
  defaults?: ChannelDefaultsConfig;
  whatsapp?: WhatsAppConfig;
  telegram?: TelegramConfig;
  discord?: DiscordConfig;
  googlechat?: GoogleChatConfig;
  slack?: SlackConfig;
  signal?: SignalConfig;
  imessage?: IMessageConfig;
  msteams?: MSTeamsConfig;
  [key: string]: unknown;       // Dynamic config for extension channels
};
```

Note the final index signature `[key: string]: unknown`—this allows extension channels (such as Matrix, Twitch, LINE, etc.) to add their own configuration without modifying the core type definitions.

Each channel's configuration type is defined by its own type file (such as `types.telegram.ts`, `types.whatsapp.ts`, etc.) and is managed through the channel plugin's `config` adapter.

### ChannelConfigAdapter: Configuration Access Layer

`ChannelConfigAdapter` is an adapter that **every channel must implement**, providing basic operations like account listing, account resolution, and enable/disable:

```typescript
// src/channels/plugins/types.adapters.ts (simplified)
export type ChannelConfigAdapter<ResolvedAccount> = {
  listAccountIds: (cfg: OpenClawConfig) => string[];       // List all account IDs
  resolveAccount: (cfg: OpenClawConfig, accountId?) => ResolvedAccount;  // Resolve account
  defaultAccountId?: (cfg: OpenClawConfig) => string;      // Default account
  setAccountEnabled?: (...) => OpenClawConfig;             // Enable/disable
  deleteAccount?: (...) => OpenClawConfig;                 // Delete account
  isEnabled?: (account, cfg) => boolean;                   // Is enabled
  isConfigured?: (account, cfg) => boolean | Promise<boolean>;  // Is configured
  describeAccount?: (account, cfg) => ChannelAccountSnapshot;   // Account snapshot
  resolveAllowFrom?: (...) => string[] | undefined;        // Allowlist
  formatAllowFrom?: (...) => string[];                     // Allowlist formatting
};
```

`ResolvedAccount` is a generic parameter—the "resolved account" structure differs completely between channels. For example, Telegram's resolved account contains `token`, `allowFrom`, `replyToMode` and other fields; WhatsApp's contains QR code login state, reconnection parameters, etc. Through generics, the system maintains type safety while allowing each channel to freely define its internal structure.

### Channel Default Configuration

`ChannelDefaultsConfig` provides global default values across channels:

```typescript
// src/config/types.channels.ts
export type ChannelDefaultsConfig = {
  groupPolicy?: GroupPolicy;
  heartbeat?: ChannelHeartbeatVisibilityConfig;
};

export type ChannelHeartbeatVisibilityConfig = {
  showOk?: boolean;         // Whether to show healthy heartbeats (default false)
  showAlerts?: boolean;     // Whether to show alerts (default true)
  useIndicator?: boolean;   // Whether to use UI status indicator (default true)
};
```

This allows users to set default behavior for all channels in one place, while individual channels can override these defaults.

***

## 19.1.3 Connection Bridge Between Channels and Gateway

### ChannelDock: Lightweight Connection Layer

Between `ChannelPlugin` and the Gateway, there exists a lightweight intermediate layer called `ChannelDock` (channel dock), defined in `src/channels/dock.ts`:

```typescript
// src/channels/dock.ts (simplified)
export type ChannelDock = {
  id: ChannelId;
  capabilities: ChannelCapabilities;
  commands?: ChannelCommandAdapter;
  outbound?: { textChunkLimit?: number };
  streaming?: ChannelDockStreaming;
  elevated?: ChannelElevatedAdapter;
  config?: { resolveAllowFrom?; formatAllowFrom? };
  groups?: ChannelGroupAdapter;
  mentions?: ChannelMentionAdapter;
  threading?: ChannelThreadingAdapter;
  agentPrompt?: ChannelAgentPromptAdapter;
};
```

Why is this intermediate layer needed? Because `ChannelPlugin` is "heavyweight"—it may import monitors, web login flows, puppeteer, and other large dependencies. However, many of the Gateway's shared code paths (reply handling, command authorization, sandbox interpretation, etc.) only need a small portion of lightweight channel information.

```
┌────────────────────────┐
│   Gateway Shared Code   │
│  (reply, commands,     │
│   auth, sandbox...)    │
└──────────┬─────────────┘
           │ Lightweight access
           ▼
┌────────────────────────┐
│     ChannelDock         │  ← Contains only metadata + lightweight adapters
│   (dock.ts)            │
└──────────┬─────────────┘
           │ Only when needed
           ▼
┌────────────────────────┐
│     ChannelPlugin       │  ← Full channel implementation (heavyweight)
│  (plugins/*.ts)        │
└────────────────────────┘
```

The source code comments explicitly clarify this design intent:

```typescript
// src/channels/dock.ts
// Channel docks: lightweight channel metadata/behavior for shared code paths.
//
// Rules:
// - keep this module *light* (no monitors, probes, puppeteer/web login, etc)
// - OK: config readers, allowFrom formatting, mention stripping patterns
// - shared code should import from here, not from the plugins registry
```

### Core Channel Dock Registration

The docks for seven core channels are hardcoded in the `DOCKS` object:

```typescript
// src/channels/dock.ts (excerpt)
const DOCKS: Record<ChatChannelId, ChannelDock> = {
  telegram: {
    id: "telegram",
    capabilities: {
      chatTypes: ["direct", "group", "channel", "thread"],
      nativeCommands: true,
      blockStreaming: true,
    },
    outbound: { textChunkLimit: 4000 },
    groups: { resolveRequireMention: resolveTelegramGroupRequireMention, ... },
    threading: {
      resolveReplyToMode: ({ cfg }) => cfg.channels?.telegram?.replyToMode ?? "first",
      buildToolContext: ({ context, hasRepliedRef }) => ({ ... }),
    },
  },
  discord: {
    id: "discord",
    capabilities: {
      chatTypes: ["direct", "channel", "thread"],
      polls: true, reactions: true, threads: true, nativeCommands: true,
    },
    outbound: { textChunkLimit: 2000 },           // Discord 2000 character limit
    streaming: {
      blockStreamingCoalesceDefaults: { minChars: 1500, idleMs: 1000 },
    },
    // ...
  },
  // ...other channels
};
```

Note that each channel has a different `textChunkLimit`—Telegram and WhatsApp are 4000 characters, while Discord is only 2000 characters. These differences directly affect the chunking strategy for outbound messages.

### Channel Registry

All channels (core + extensions) are managed uniformly through `registry.ts`:

```typescript
// src/channels/registry.ts
export const CHAT_CHANNEL_ORDER = [
  "telegram", "whatsapp", "discord", "googlechat",
  "slack", "signal", "imessage",
] as const;

export type ChatChannelId = (typeof CHAT_CHANNEL_ORDER)[number];

// Alias mapping
export const CHAT_CHANNEL_ALIASES: Record<string, ChatChannelId> = {
  imsg: "imessage",
  "google-chat": "googlechat",
  gchat: "googlechat",
};
```

The channel ID normalization function `normalizeChannelId` supports case-insensitive matching and alias resolution:

```typescript
// src/channels/registry.ts
export function normalizeChatChannelId(raw?: string | null): ChatChannelId | null {
  const normalized = raw?.trim().toLowerCase();
  if (!normalized) return null;
  const resolved = CHAT_CHANNEL_ALIASES[normalized] ?? normalized;
  return CHAT_CHANNEL_ORDER.includes(resolved) ? resolved : null;
}
```

For extension channels (non-core seven channels), `normalizeAnyChannelId` queries the plugin registry:

```typescript
// src/channels/registry.ts
export function normalizeAnyChannelId(raw?: string | null): ChannelId | null {
  const key = raw?.trim().toLowerCase();
  if (!key) return null;

  const registry = requireActivePluginRegistry();
  const hit = registry.channels.find((entry) => {
    const id = String(entry.plugin.id).trim().toLowerCase();
    if (id === key) return true;
    // Check aliases
    return (entry.plugin.meta.aliases ?? []).some(alias => alias.trim().toLowerCase() === key);
  });
  return hit?.plugin.id ?? null;
}
```

### Bridge from Plugin to Dock

Extension channel `ChannelPlugin` can be automatically converted to `ChannelDock`:

```typescript
// src/channels/dock.ts
function buildDockFromPlugin(plugin: ChannelPlugin): ChannelDock {
  return {
    id: plugin.id,
    capabilities: plugin.capabilities,
    commands: plugin.commands,
    outbound: plugin.outbound?.textChunkLimit
      ? { textChunkLimit: plugin.outbound.textChunkLimit }
      : undefined,
    streaming: plugin.streaming
      ? { blockStreamingCoalesceDefaults: plugin.streaming.blockStreamingCoalesceDefaults }
      : undefined,
    elevated: plugin.elevated,
    config: plugin.config ? { resolveAllowFrom: ..., formatAllowFrom: ... } : undefined,
    groups: plugin.groups,
    mentions: plugin.mentions,
    threading: plugin.threading,
    agentPrompt: plugin.agentPrompt,
  };
}
```

This function extracts the lightweight parts from `ChannelPlugin` and constructs a `ChannelDock` that doesn't depend on heavyweight imports. This means extension channel developers don't need to manually maintain two separate definitions—they only need to implement `ChannelPlugin`, and the system will automatically generate the corresponding dock.

### Complete Channel Resolution Flow

The complete path from an inbound message to finding the corresponding channel:

```
Inbound message (Channel="telegram")
    │
    ▼
normalizeChannelId("telegram")
    │ Query core registry
    ▼
ChatChannelId = "telegram"
    │
    ├── getChannelDock("telegram")  → ChannelDock (lightweight, for shared code)
    │
    └── getChannelPlugin("telegram") → ChannelPlugin (complete, for channel-specific operations)
```

This layered design ensures:

* Shared code paths remain lightweight and fast
* Channel-specific logic is isolated in plugins
* New channels can be integrated zero-invasively through the plugin system

***

## Summary of This Section

1. **`ChannelPlugin` interface** is the core contract for channel adapters, containing 20+ optional adapter fields and following the Interface Segregation Principle—only the necessary `id`, `meta`, `capabilities`, and `config` need to be implemented.
2. **`ChannelCapabilities`** enables the system to adaptively enable features at runtime through declarative capability markers (polls, reactions, threads, etc.).
3. **Federated configuration type system** allows each channel to independently define its configuration structure, supporting dynamic configuration for extension channels through the index signature `[key: string]: unknown`.
4. **ChannelDock intermediate layer** separates lightweight metadata from heavyweight plugins, ensuring shared code paths don't incur unnecessary dependencies from importing channel implementations.
5. **Channel registry** implements flexible channel ID normalization through three-level lookup: `CHAT_CHANNEL_ORDER`, alias mapping, and plugin registry.
6. The entire architecture embodies OpenClaw's core design philosophy: **unified interface, differentiated implementation, on-demand loading**.
