> 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/ch21-channel-extension-mechanism/21.1-extension-architecture-design.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 21.1 Extension Architecture Design

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

***

In the previous two chapters, we conducted an in-depth analysis of OpenClaw's six built-in core channels (WhatsApp, Telegram, Discord, Slack, Signal, iMessage). However, with hundreds of messaging platforms in existence, it's impossible to include them all natively. OpenClaw achieves channel extensibility through a **plugin system** (Plugin System)—anyone can write a plugin to integrate a new messaging platform. This chapter will provide a deep dive into the design and implementation of this extension mechanism.

***

## 21.1.1 Differences Between Extensions and Core Channels

Channels in OpenClaw fall into two categories:

| Dimension              | Core Channels                               | Extension Channels                                |
| ---------------------- | ------------------------------------------- | ------------------------------------------------- |
| Code Location          | `src/web/`, `src/telegram/`, etc.           | `extensions/` or `~/.config/openclaw/extensions/` |
| Loading Method         | Static import at compile time               | Dynamic loading via jiti at runtime               |
| Configuration Location | `channels.slack`, `channels.telegram`, etc. | `plugins.entries.<id>`                            |
| Distribution Method    | Shipped with OpenClaw main package          | npm package or local directory                    |
| Monitoring Method      | Direct call to `monitor*Provider()`         | Registration via Plugin Service or Hook           |
| Examples               | WhatsApp, Telegram, Discord, Slack          | MS Teams, Matrix, Twitch, Feishu                  |

This distinction is not about capability—extension channels can implement exactly the same functionality as core channels. The distinction is fundamentally about **deployment strategy**: core channels are OpenClaw's "factory configuration," while extension channels are "installed on demand."

### Why Extensions Are Needed

1. **Reduce main package size**: Not every user needs Feishu or Matrix
2. **Independent version management**: Extensions can be updated independently of the main package
3. **Community-friendly contribution**: Third parties can publish new channels without modifying the main repository
4. **Native dependency isolation**: Some channels (like Matrix) require native modules (`matrix-sdk-crypto-nodejs`), and placing them in extensions avoids installation failures affecting the main package

***

## 21.1.2 Extension Loading Mechanism (`src/plugins/loader.ts`)

### Loading Flow Overview

Plugin loading is orchestrated by the `loadOpenClawPlugins()` function, which is the core entry point of the entire plugin system:

```typescript
// src/plugins/loader.ts (simplified)
export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegistry {
  // 1. Normalize plugin configuration
  const normalized = normalizePluginsConfig(cfg.plugins);
  
  // 2. Check cache (avoid duplicate loading)
  const cacheKey = buildCacheKey({ workspaceDir, plugins: normalized });
  if (registryCache.has(cacheKey)) return registryCache.get(cacheKey);
  
  // 3. Discover all candidate plugins
  const discovery = discoverOpenClawPlugins({ workspaceDir, extraPaths: normalized.loadPaths });
  
  // 4. Load plugin manifests
  const manifestRegistry = loadPluginManifestRegistry({ config, candidates: discovery.candidates });
  
  // 5. Initialize jiti runtime (supports loading TypeScript directly)
  const jiti = createJiti(import.meta.url, {
    interopDefault: true,
    extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json"],
    alias: { "openclaw/plugin-sdk": pluginSdkAlias },
  });
  
  // 6. Load and register plugins one by one
  for (const candidate of discovery.candidates) {
    // 6a. Check enabled state
    const enableState = resolveEnableState(pluginId, candidate.origin, normalized);
    if (!enableState.enabled) continue;
    
    // 6b. Load module
    const mod = jiti(candidate.source);
    
    // 6c. Validate configuration
    const validatedConfig = validatePluginConfig({ schema, value: entry?.config });
    
    // 6d. Call register() to register
    const api = createApi(record, { config: cfg, pluginConfig: validatedConfig.value });
    register(api);
  }
  
  // 7. Set up global Hook Runner and cache
  initializeGlobalHookRunner(registry);
  return registry;
}
```

The entire flow can be summarized in four phases:

```
Discovery → Manifest Parsing → Loading (jiti) → Registration (register/activate)
```

### Plugin Discovery

`discoverOpenClawPlugins()` searches for plugins from four locations, in order of priority (highest to lowest):

```typescript
// src/plugins/discovery.ts
export function discoverOpenClawPlugins(params) {
  // 1. Paths explicitly specified in configuration (highest priority)
  for (const extraPath of normalized.loadPaths) {
    discoverFromPath({ rawPath: trimmed, origin: "config" });
  }
  
  // 2. Workspace directory (project-level)
  const workspaceExtDirs = [path.join(workspaceRoot, ".openclaw", "extensions")];
  for (const dir of workspaceExtDirs) {
    discoverInDirectory({ dir, origin: "workspace" });
  }
  
  // 3. Global configuration directory (user-level)
  const globalDir = path.join(resolveConfigDir(), "extensions");
  discoverInDirectory({ dir: globalDir, origin: "global" });
  
  // 4. Bundled plugins directory (package-level)
  const bundledDir = resolveBundledPluginsDir();
  discoverInDirectory({ dir: bundledDir, origin: "bundled" });
}
```

| Source      | Path                              | origin Identifier | Use Case                                 |
| ----------- | --------------------------------- | ----------------- | ---------------------------------------- |
| Config Path | Specified in `plugins.loadPaths`  | `"config"`        | Development debugging, custom deployment |
| Workspace   | `.openclaw/extensions/`           | `"workspace"`     | Project-level plugins                    |
| Global      | `~/.config/openclaw/extensions/`  | `"global"`        | User-level plugins                       |
| Bundled     | `extensions/` in OpenClaw package | `"bundled"`       | Official extensions (MS Teams, etc.)     |

Each discovery location supports two organizational forms:

1. **Single-file plugins**: Place `.ts` or `.js` files directly in the directory
2. **Package-form plugins**: Subdirectory contains `package.json` with `openclaw.extensions` field declaring entry files

```json
// package.json for package-form plugins
{
  "name": "@openclaw/msteams",
  "openclaw": {
    "extensions": ["src/index.ts"]
  }
}
```

### Plugin Manifest

Each plugin must include a `openclaw.plugin.json` manifest file:

```json
{
  "id": "msteams",
  "name": "Microsoft Teams",
  "description": "MS Teams channel integration via Bot Framework",
  "version": "0.1.0",
  "kind": null,
  "channels": ["msteams"],
  "configSchema": {
    "type": "object",
    "properties": {
      "appId": { "type": "string" },
      "appPassword": { "type": "string" }
    },
    "required": ["appId", "appPassword"]
  }
}
```

Key manifest fields:

| Field          | Required | Description                                                                |
| -------------- | -------- | -------------------------------------------------------------------------- |
| `id`           | ✅        | Globally unique identifier                                                 |
| `configSchema` | ✅        | JSON Schema for validating plugin configuration                            |
| `kind`         | ❌        | Plugin type (currently only `"memory"` for memory plugin mutual exclusion) |
| `channels`     | ❌        | Declares channel IDs provided by this plugin                               |
| `providers`    | ❌        | Declares model Providers provided by this plugin                           |
| `uiHints`      | ❌        | UI hints for configuration fields (used in control panel)                  |

### jiti Dynamic Loading

> **Sidebar**: [jiti](https://github.com/unjs/jiti) is a just-in-time compilation runtime for TypeScript/ESM. It allows Node.js to directly `require()` TypeScript files without pre-compilation. This is particularly valuable for the plugin system—users can write plugins directly in TypeScript without needing to configure a build toolchain.

OpenClaw uses jiti to load plugin modules:

```typescript
const jiti = createJiti(import.meta.url, {
  interopDefault: true,
  extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json"],
  alias: { "openclaw/plugin-sdk": pluginSdkAlias },
});

// Load TypeScript files directly
const mod = jiti(candidate.source) as OpenClawPluginModule;
```

The `alias` configuration maps `openclaw/plugin-sdk` to the actual SDK source file path, allowing plugins to import like this:

```typescript
// In plugin code
import type { OpenClawPluginApi, ChannelPlugin } from "openclaw/plugin-sdk";
```

### Enable/Disable Control

A plugin's enabled state is determined by multiple layers of configuration:

```typescript
const enableState = resolveEnableState(pluginId, candidate.origin, normalized);
```

Control methods include:

1. **Explicit enable**: `plugins.entries.<id>.enabled: true`
2. **Explicit disable**: `plugins.entries.<id>.enabled: false`
3. **Deny list**: `plugins.deny: ["msteams"]`
4. **Allow list**: `plugins.allow: ["msteams"]` (if set, only listed plugins are loaded)
5. **Default behavior**: Plugins from `bundled` origin are enabled by default; plugins from other origins are enabled by default

***

## 21.1.3 Extension Directory Structure Analysis (MS Teams as Example)

Although we cannot display the source code of all extensions in this book, we can understand how extensions should be organized through a typical extension directory structure. A typical channel extension directory structure looks like this:

```
extensions/msteams/
├── package.json                 # npm package configuration
│   └── "openclaw": { "extensions": ["src/index.ts"] }
├── openclaw.plugin.json         # Plugin manifest (required)
├── src/
│   ├── index.ts                 # Entry point: exports register function
│   ├── config.ts                # Configuration parsing and validation
│   ├── monitor.ts               # Message listening (similar to core channel's monitorProvider)
│   ├── send.ts                  # Message sending
│   ├── format.ts                # Markdown → platform format conversion
│   ├── types.ts                 # Type definitions
│   └── adapters/
│       ├── config.ts            # ChannelConfigAdapter implementation
│       ├── outbound.ts          # ChannelOutboundAdapter implementation
│       ├── security.ts          # ChannelSecurityAdapter implementation
│       └── status.ts            # ChannelStatusAdapter implementation
└── tsconfig.json
```

Basic structure of the entry file:

```typescript
// extensions/msteams/src/index.ts
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";

export function register(api: OpenClawPluginApi) {
  const pluginConfig = api.pluginConfig;
  
  // Register channel
  api.registerChannel({
    plugin: createMSTeamsPlugin(pluginConfig),
    dock: createMSTeamsDock(pluginConfig),
  });
  
  // Register background service (message listening loop)
  api.registerService({
    id: "msteams-monitor",
    start: async (ctx) => {
      await startMSTeamsMonitor(ctx, pluginConfig);
    },
    stop: async () => {
      await stopMSTeamsMonitor();
    },
  });
  
  // Register Hook (optional)
  api.on("message_sending", (event, ctx) => {
    // Perform format conversion before message sending
  });
}
```

### Interaction Interface Between Extensions and Main Program

Extensions interact with the OpenClaw main program through `OpenClawPluginApi`. This API object is injected when `register()` is called, providing methods to register various capabilities:

```typescript
type OpenClawPluginApi = {
  id: string;                           // Plugin ID
  config: OpenClawConfig;               // Global configuration (read-only)
  pluginConfig?: Record<string, unknown>; // Plugin's own configuration
  runtime: PluginRuntime;               // Runtime environment
  logger: PluginLogger;                 // Logging interface
  
  // Registration methods
  registerChannel(...);      // Register channel adapter
  registerTool(...);         // Register Agent tool
  registerHook(...);         // Register event hook
  registerHttpHandler(...);  // Register HTTP handler
  registerHttpRoute(...);    // Register HTTP route
  registerGatewayMethod(...); // Register Gateway RPC method
  registerCli(...);          // Register CLI subcommand
  registerService(...);      // Register background service
  registerProvider(...);     // Register model provider
  registerCommand(...);      // Register custom command
  
  // Lifecycle hooks
  on(hookName, handler);     // Listen to lifecycle events
  
  // Utility methods
  resolvePath(input);        // Resolve relative paths
};
```

This design follows the **Inversion of Control (IoC)** principle—plugins don't directly call OpenClaw's internal APIs; instead, they declare their capabilities by registering callbacks, which the runtime invokes at appropriate times.

### Loading into Gateway Flow

When the Gateway server starts, `loadGatewayPlugins()` is responsible for integrating the plugin system into Gateway:

```typescript
// src/gateway/server-plugins.ts
export function loadGatewayPlugins(params) {
  const pluginRegistry = loadOpenClawPlugins({
    config: params.cfg,
    workspaceDir: params.workspaceDir,
    coreGatewayHandlers: params.coreGatewayHandlers,
  });
  
  // Merge plugin-registered Gateway methods into the main method list
  const pluginMethods = Object.keys(pluginRegistry.gatewayHandlers);
  const gatewayMethods = [...new Set([...params.baseMethods, ...pluginMethods])];
  
  // Output diagnostic information
  for (const diag of pluginRegistry.diagnostics) {
    if (diag.level === "error") params.log.error(`[plugins] ${diag.message}`);
    else params.log.info(`[plugins] ${diag.message}`);
  }
  
  return { pluginRegistry, gatewayMethods };
}
```

***

## Summary of This Section

1. **OpenClaw's channels are divided into core channels and extension channels**, with equivalent capabilities but different deployment strategies. Extension channels are installed on demand through the plugin system, reducing main package size and supporting independent version management.
2. **The plugin loading flow follows a "discovery → manifest parsing → loading → registration" four-phase process**: discovering candidate plugins from four locations, reading the `openclaw.plugin.json` manifest, dynamically loading TypeScript/JavaScript modules via jiti, and finally calling the `register()` function to complete registration.
3. **The jiti runtime allows direct loading of TypeScript**, and combined with the `openclaw/plugin-sdk` alias mapping, plugin development requires no build toolchain configuration.
4. **`OpenClawPluginApi` is the sole interaction interface between plugins and the main program**, adopting an Inversion of Control (IoC) pattern where plugins declare capabilities by registering callbacks, which the runtime invokes at appropriate times.
5. **The plugin manifest is required**, defining plugin ID, configuration Schema, channel/Provider declarations, and other metadata that form the foundation for plugin system validation and management.
