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

# 21.2 Extension API Surface

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

***

In the previous section, we learned the complete flow of plugins from discovery to loading. Once a plugin is loaded, it interacts with the OpenClaw main program through the `OpenClawPluginApi` "window." This section will conduct an in-depth analysis of three layers of this API surface: the internal extension API (`extensionAPI.ts`), the externally-facing plugin SDK (`plugin-sdk/index.ts`), and the plugin hook interface.

***

## 21.2.1 `src/extensionAPI.ts` — API Set Accessible to Extensions

### Positioning of Internal Extension API

`extensionAPI.ts` is an **internal re-export module** that carefully selects functions and types from OpenClaw's core modules that extensions might need, and exposes them uniformly to internal extensions:

```typescript
// src/extensionAPI.ts (complete)
export { resolveAgentDir, resolveAgentWorkspaceDir } from "./agents/agent-scope.ts";
export { DEFAULT_MODEL, DEFAULT_PROVIDER } from "./agents/defaults.ts";
export { resolveAgentIdentity } from "./agents/identity.ts";
export { resolveThinkingDefault } from "./agents/model-selection.ts";
export { runEmbeddedPiAgent } from "./agents/pi-embedded.ts";
export { resolveAgentTimeoutMs } from "./agents/timeout.ts";
export { ensureAgentWorkspace } from "./agents/workspace.ts";
export {
  resolveStorePath, loadSessionStore,
  saveSessionStore, resolveSessionFilePath,
} from "./config/sessions.ts";
```

This file currently exports only a small number of **Agent runtime** and **session storage** related interfaces. Its responsibility is to provide **bundled extensions** (modules in the `extensions/` directory shipped with the main package) with the ability to directly access internal modules.

> **Sidebar**: The **re-export pattern** is a common module organization pattern in TypeScript/JavaScript. A module contains no logic but "picks" symbols from other modules and re-exports them through `export { X } from "Y"` statements. The benefits are: (1) callers only need to import one module rather than scattered implementations; (2) module authors can precisely control which APIs are visible externally, forming a stable public interface boundary.

### Relationship with Plugin SDK

Both `extensionAPI.ts` and `plugin-sdk/index.ts` appear to "export APIs," but they have different positioning:

| Dimension     | `extensionAPI.ts`                          | `plugin-sdk/index.ts`                                     |
| ------------- | ------------------------------------------ | --------------------------------------------------------- |
| Audience      | Bundled extensions (same repository)       | External third-party plugins                              |
| Import Method | `import { ... } from "../extensionAPI.js"` | `import { ... } from "openclaw/plugin-sdk"`               |
| Stability     | Can change with main package version       | Promised stable API for external use                      |
| Scope         | Agent runtime, session storage             | Channel types, config Schema, tool helper functions, etc. |

Bundled extensions (such as `extensions/discord/`, `extensions/slack/`) can directly reference internal module paths because they're in the same repository as the main package; third-party plugins can only import through the `openclaw/plugin-sdk` package name, which is mapped to the actual file by jiti's alias mechanism.

***

## 21.2.2 Plugin SDK (`src/plugin-sdk/`)

### SDK Design Philosophy

`plugin-sdk/index.ts` is a **375-line giant re-export module** and is the sole public API for external plugin developers to interact with OpenClaw. This design follows the "narrow interface, wide implementation" principle—internal implementation can be freely refactored as long as the SDK surface remains stable, and third-party plugins won't break due to internal changes.

### SDK Export Categories

The content exported by the SDK can be divided into the following categories:

#### (1) Channel Adapter Types

This is the largest section of the SDK, exporting all type definitions needed for channel plugin development:

```typescript
// src/plugin-sdk/index.ts
export type {
  ChannelPlugin,                // Main channel plugin type
  ChannelConfigSchema,          // Config Schema type
  ChannelConfigAdapter,         // Config adapter
  ChannelOutboundAdapter,       // Outbound message adapter
  ChannelSecurityAdapter,       // Security policy adapter
  ChannelSetupAdapter,          // Initialization adapter
  ChannelPairingAdapter,        // Pairing adapter
  ChannelGroupAdapter,          // Group adapter
  ChannelMentionAdapter,        // @mention adapter
  ChannelStatusAdapter,         // Status monitoring adapter
  ChannelGatewayAdapter,        // Gateway integration adapter
  ChannelAuthAdapter,           // Authentication adapter
  ChannelElevatedAdapter,       // Permission elevation adapter
  ChannelCommandAdapter,        // Command adapter
  ChannelStreamingAdapter,      // Streaming adapter
  ChannelThreadingAdapter,      // Threading/topic adapter
  ChannelMessagingAdapter,      // Messaging adapter
  ChannelDirectoryAdapter,      // Directory adapter
  ChannelResolverAdapter,       // Target resolver adapter
  ChannelHeartbeatAdapter,      // Heartbeat detection adapter
  ChannelMessageActionAdapter,  // Message action adapter
  // ... and context types needed by each adapter
} from "../channels/plugins/types.js";
```

These types form the complete interface of the channel adapter abstraction layer introduced in Chapter 19.

#### (2) Plugin Core Types

Core types related to plugin registration and service management:

```typescript
export type {
  OpenClawPluginApi,            // Plugin registration API (most core interface)
  OpenClawPluginService,        // Background service definition
  OpenClawPluginServiceContext,  // Service runtime context
} from "../plugins/types.js";

export type { PluginRuntime } from "../plugins/runtime/types.js";
export type { OpenClawConfig } from "../config/config.js";
export type { ChannelDock } from "../channels/dock.js";
```

#### (3) Configuration Schema Builders

Provides Zod Schema for various channels, used for configuration validation:

```typescript
export {
  DiscordConfigSchema,
  GoogleChatConfigSchema,
  IMessageConfigSchema,
  MSTeamsConfigSchema,
  SignalConfigSchema,
  SlackConfigSchema,
  TelegramConfigSchema,
} from "../config/zod-schema.providers-core.js";

export { WhatsAppConfigSchema } from "../config/zod-schema.providers-whatsapp.js";
export { LineConfigSchema } from "../line/config-schema.js";
```

The export of these Schema is significant—extension plugins typically need to **reuse** the configuration structure of core channels in their own configuration validation. For example, an enhanced plugin based on WhatsApp can `extend` WhatsApp's Schema.

#### (4) Channel-Specific Helper Functions

The SDK exports a set of helper functions for each core channel, allowing extensions to reuse core channel logic:

```typescript
// Channel: Discord
export { listDiscordAccountIds, resolveDefaultDiscordAccountId,
         resolveDiscordAccount } from "../discord/accounts.js";
export { discordOnboardingAdapter } from "../channels/plugins/onboarding/discord.js";

// Channel: Telegram
export { listTelegramAccountIds, resolveTelegramAccount } from "../telegram/accounts.js";
export { telegramOnboardingAdapter } from "../channels/plugins/onboarding/telegram.js";

// Channel: WhatsApp
export { listWhatsAppAccountIds, resolveWhatsAppAccount } from "../web/accounts.js";
export { whatsappOnboardingAdapter } from "../channels/plugins/onboarding/whatsapp.js";

// Channel: LINE
export { createInfoCard, createListCard, createImageCard,
         createActionCard } from "../line/flex-templates.js";
export { processLineMessage, hasMarkdownToConvert } from "../line/markdown-to-line.js";
```

This design means extension plugins don't need to "reinvent the wheel"—if you're developing a WhatsApp Business extension, you can directly reuse the core WhatsApp channel's account parsing and media loading logic.

#### (5) Shared Infrastructure

Tool functions and types commonly used across channels:

```typescript
// Message action tools
export { createActionGate, jsonResult, readNumberParam,
         readStringParam } from "../agents/tools/common.js";

// Allowlist management
export { mergeAllowlist, summarizeMapping } from "../channels/allowlists/resolve-utils.js";

// Mention gating
export { resolveMentionGating } from "../channels/mention-gating.js";

// ACK reactions
export { shouldAckReaction, removeAckReactionAfterReply } from "../channels/ack-reactions.js";

// Media handling
export { detectMime, extensionForMime } from "../media/mime.js";
export { loadWebMedia } from "../web/media.js";

// Logging transport
export { registerLogTransport } from "../logging/logger.js";

// Diagnostic events
export { emitDiagnosticEvent, isDiagnosticsEnabled,
         onDiagnosticEvent } from "../infra/diagnostic-events.js";
```

### PluginRuntime: Plugin's Runtime Sandbox

The largest type in the SDK is `PluginRuntime`. It's a giant object containing **all core function references** that a plugin might need at runtime. Let's look at its layered structure:

```typescript
// src/plugins/runtime/types.ts (simplified structure)
export type PluginRuntime = {
  version: string;               // OpenClaw version
  
  config: {
    loadConfig();                // Read current configuration
    writeConfigFile();           // Write configuration file
  };
  
  system: {
    enqueueSystemEvent();        // Enqueue system event
    runCommandWithTimeout();     // Execute external command (with timeout)
  };
  
  media: {
    loadWebMedia();              // Load web media
    detectMime();                // MIME type detection
    getImageMetadata();          // Image metadata
    resizeToJpeg();              // Image compression
  };
  
  tts: {
    textToSpeechTelephony();     // Text-to-speech synthesis
  };
  
  tools: {
    createMemoryGetTool();       // Memory retrieval tool
    createMemorySearchTool();    // Memory search tool
  };
  
  channel: {
    text: { /* Text chunking, command detection, Markdown conversion */ };
    reply: { /* Reply dispatch, envelope formatting, human delay */ };
    routing: { /* Route resolution */ };
    pairing: { /* Pairing management */ };
    media: { /* Media fetching and storage */ };
    activity: { /* Channel activity recording */ };
    session: { /* Session storage operations */ };
    mentions: { /* @mention matching */ };
    reactions: { /* Reaction/emoji management */ };
    groups: { /* Group policies */ };
    debounce: { /* Inbound debouncing */ };
    commands: { /* Command handling */ };
    
    // Complete operation functions for each core channel
    discord: { sendMessageDiscord(), monitorDiscordProvider(), ... };
    slack: { sendMessageSlack(), monitorSlackProvider(), ... };
    telegram: { sendMessageTelegram(), monitorTelegramProvider(), ... };
    signal: { sendMessageSignal(), monitorSignalProvider(), ... };
    imessage: { sendMessageIMessage(), monitorIMessageProvider(), ... };
    whatsapp: { sendMessageWhatsApp(), monitorWebChannel(), ... };
    line: { sendMessageLine(), pushFlexMessage(), ... };
  };
  
  logging: {
    shouldLogVerbose();          // Log level judgment
    getChildLogger();            // Create child logger
  };
  
  state: {
    resolveStateDir();           // Resolve state storage directory
  };
};
```

> **Sidebar**: The **Facade pattern** (also called the Facade design pattern) is a structural design pattern. It provides a simplified interface to access a complex subsystem. `PluginRuntime` is a typical Facade—it consolidates functions scattered across dozens of internal modules into a single object, allowing plugins to call deeply buried internal functionality through `api.runtime.channel.telegram.sendMessageTelegram()`.

An important characteristic of `PluginRuntime`'s design is that it contains operation functions for **all core channels**. This means a Feishu extension can call `runtime.channel.telegram.sendMessageTelegram()` to send a message to Telegram. This "cross-channel operation" capability opens doors to advanced scenarios (such as message bridging and multi-channel coordination).

***

## 21.2.3 Plugin Hooks Interface

### Hook System Overview

OpenClaw's plugin hook system covers all critical nodes in the message processing pipeline. There are **14 hook events** in total, divided into five groups by lifecycle domain:

| Hook Domain | Hook Name             | Execution Mode      | Return Value                 |
| ----------- | --------------------- | ------------------- | ---------------------------- |
| **Agent**   | `before_agent_start`  | Sequential (serial) | Can modify system prompt     |
|             | `agent_end`           | Parallel            | None                         |
|             | `before_compaction`   | Parallel            | None                         |
|             | `after_compaction`    | Parallel            | None                         |
| **Message** | `message_received`    | Parallel            | None                         |
|             | `message_sending`     | Sequential (serial) | Can modify/cancel message    |
|             | `message_sent`        | Parallel            | None                         |
| **Tool**    | `before_tool_call`    | Sequential (serial) | Can modify params/block call |
|             | `after_tool_call`     | Parallel            | None                         |
|             | `tool_result_persist` | Sync serial         | Can modify persisted content |
| **Session** | `session_start`       | Parallel            | None                         |
|             | `session_end`         | Parallel            | None                         |
| **Gateway** | `gateway_start`       | Parallel            | None                         |
|             | `gateway_stop`        | Parallel            | None                         |

An important pattern is visible in the table: **only hooks that can modify data use serial execution**, while purely notification-type hooks all execute in parallel for performance.

### Two Hook Registration Methods

Plugins have two ways to register hooks:

**Method 1: Register traditional hooks via `registerHook()`**

This is the registration method for the internal hook system (`src/hooks/`), compatible with older versions:

```typescript
api.registerHook(
  "message_received",        // Event name
  async (event) => {         // Handler function
    console.log(`Received message: ${event.content}`);
  },
  {
    name: "my-logger-hook",  // Hook name (required)
    description: "Log received messages",
  }
);
```

**Method 2: Register type-safe hooks via `on()`**

This is the recommended new way, providing complete TypeScript type inference:

```typescript
api.on("before_agent_start", async (event, ctx) => {
  // event: PluginHookBeforeAgentStartEvent (auto-inferred)
  // ctx: PluginHookAgentContext (auto-inferred)
  return {
    prependContext: "Today is the weekend, please use a relaxed tone.",
  };
}, { priority: 10 });
```

Differences between the two methods:

| Dimension           | `registerHook()`                       | `on()`                          |
| ------------------- | -------------------------------------- | ------------------------------- |
| Type Safety         | Weak (handler type is broad)           | Strong (inferred from hookName) |
| Registration Target | Internal hook system + plugin registry | Plugin type-safe registry only  |
| Priority            | Configured via HookEntry               | Configured via opts.priority    |
| Recommendation      | Compatible with legacy code            | ✅ Recommended for new code      |

### Hook Runner Implementation

Hook execution is handled by the `HookRunner` created by the `createHookRunner()` factory function. It has two execution strategies internally:

```typescript
// src/plugins/hooks.ts
export function createHookRunner(registry: PluginRegistry, options = {}) {
  const catchErrors = options.catchErrors ?? true;

  // Parallel execution: for pure notification hooks
  async function runVoidHook(hookName, event, ctx) {
    const hooks = getHooksForName(registry, hookName);
    const promises = hooks.map(async (hook) => {
      try {
        await hook.handler(event, ctx);
      } catch (err) {
        if (catchErrors) logger?.error(msg);
        else throw new Error(msg, { cause: err });
      }
    });
    await Promise.all(promises);  // All handlers execute in parallel
  }

  // Serial execution: for hooks that can modify data
  async function runModifyingHook(hookName, event, ctx, mergeResults?) {
    const hooks = getHooksForName(registry, hookName);
    let result;
    for (const hook of hooks) {   // Execute serially in priority order
      const handlerResult = await hook.handler(event, ctx);
      if (handlerResult != null) {
        result = mergeResults ? mergeResults(result, handlerResult) : handlerResult;
      }
    }
    return result;
  }
  // ...
}
```

The **priority sorting** implementation is in `getHooksForName()`:

```typescript
function getHooksForName(registry, hookName) {
  return registry.typedHooks
    .filter((h) => h.hookName === hookName)
    .toSorted((a, b) => (b.priority ?? 0) - (a.priority ?? 0));  // Higher priority executes first
}
```

### Key Hook Details

#### `before_agent_start`: Inject Context

This is one of the most powerful hooks, allowing plugins to modify the system prompt before Agent starts:

```typescript
api.on("before_agent_start", async (event, ctx) => {
  // event.prompt — current system prompt
  // event.messages — history messages
  return {
    systemPrompt: event.prompt + "\nYou are an enterprise customer service bot.",
    prependContext: "Current user VIP level: Diamond",
  };
});
```

When multiple plugins register this hook, results are **merged**:

```typescript
// hooks.ts — merge strategy for before_agent_start
runModifyingHook("before_agent_start", event, ctx, (acc, next) => ({
  systemPrompt: next.systemPrompt ?? acc?.systemPrompt,      // Latter overrides
  prependContext: acc?.prependContext && next.prependContext
    ? `${acc.prependContext}\n\n${next.prependContext}`       // Concatenate
    : (next.prependContext ?? acc?.prependContext),
}));
```

#### `message_sending`: Intercept/Modify Outbound Messages

Allows plugins to modify content or cancel sending before a message is sent:

```typescript
api.on("message_sending", async (event, ctx) => {
  // Sensitive word filtering
  if (containsSensitiveWords(event.content)) {
    return { cancel: true };  // Cancel sending
  }
  return {
    content: event.content.replace(/confidential/g, "[redacted]"),
  };
});
```

#### `before_tool_call`: Tool Call Interception

Allows plugins to modify tool parameters or prevent tool execution:

```typescript
api.on("before_tool_call", async (event, ctx) => {
  if (event.toolName === "web_search" && event.params.query?.includes("competitor")) {
    return { block: true, blockReason: "Searching competitor information is policy-prohibited" };
  }
});
```

#### `tool_result_persist`: Tool Result Persistence Control

This is the only **synchronous hook** because it executes on the hot path of session transcript appending. Handler functions cannot return a Promise:

```typescript
// hooks.ts — sync execution + Promise safeguard
function runToolResultPersist(event, ctx) {
  for (const hook of hooks) {
    const out = hook.handler({ ...event, message: current }, ctx);
    
    // Safeguard: if handler incorrectly returned a Promise, ignore its result
    if (out && typeof out.then === "function") {
      logger?.warn("tool_result_persist handler returned a Promise; this hook is sync-only");
      continue;
    }
    
    if (out?.message) current = out.message;
  }
  return { message: current };
}
```

### Global Hook Runner

To allow code anywhere in the codebase to trigger hooks, OpenClaw uses a **global singleton** pattern:

```typescript
// src/plugins/hook-runner-global.ts
let globalHookRunner: HookRunner | null = null;

// Initialize when plugins are loaded
export function initializeGlobalHookRunner(registry: PluginRegistry): void {
  globalHookRunner = createHookRunner(registry, {
    logger: { debug: ..., warn: ..., error: ... },
    catchErrors: true,          // Hook exceptions shouldn't crash main program in production
  });
}

// Get from anywhere
export function getGlobalHookRunner(): HookRunner | null {
  return globalHookRunner;
}

// Quick check if a hook has registrations
export function hasGlobalHooks(hookName): boolean {
  return globalHookRunner?.hasHooks(hookName) ?? false;
}
```

The existence of `hasGlobalHooks()` is a performance optimization—callers can check if anyone is listening before constructing hook event objects, avoiding unnecessary object creation overhead.

***

## Summary of This Section

1. **OpenClaw's extension API is divided into two layers**: `extensionAPI.ts` for bundled extensions, exporting Agent runtime and session storage interfaces; `plugin-sdk/index.ts` for third-party plugins, exporting complete channel types, configuration Schema, and helper functions.
2. **Plugin SDK is a 375-line re-export module** following the "narrow interface, wide implementation" principle, with exports divided into five major categories: channel adapter types, plugin core types, configuration Schema, channel helper functions, and shared infrastructure.
3. **`PluginRuntime` is the largest runtime Facade**, consolidating functionality distributed across dozens of internal modules and supporting cross-channel operations (such as a Feishu plugin calling Telegram send functions).
4. **The hook system contains 14 events**, divided into two modes: parallel execution (pure notification) and serial execution (data modification), with `tool_result_persist` being the only synchronous hook.
5. **Using the `on()` method to register hooks is recommended**, as it provides complete TypeScript type inference; key modification hooks (`before_agent_start`, `message_sending`, `before_tool_call`) support result merge strategies.
