> 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/ch30-hook-system/30.2-plugin-hooks.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 30.2 Plugin Hooks

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

***

The previous section introduced Internal Hooks that run inside the Gateway process through event registration and triggering. This section focuses on another hook system in OpenClaw—**Plugin Hooks**, which is driven by the plugin system and provides more structured lifecycle interception capabilities, as well as a gateway hook mapping mechanism that converts external HTTP requests into Agent actions.

***

## 30.2.1 Hook Mapping (`src/gateway/hooks-mapping.ts`)

### Design Scenario

Imagine this scenario: you want OpenClaw's Agent to automatically process new emails when Gmail receives them. The traditional approach requires writing an intermediate service to bridge Gmail Webhook and Agent API. OpenClaw's **Hook Mapping** mechanism has this bridging capability built-in—it receives external HTTP requests, matches them by rules, and converts them into actions the Agent understands.

### Overall Architecture

```
External Systems (Gmail/GitHub/Custom Services)
        │
        ▼ HTTP POST /hooks/gmail
┌─────────────────────────────┐
│   Gateway HTTP Endpoint      │
│   ① Token Authentication     │
│   ② Path/Source Matching     │
│   ③ Template Rendering       │
│   ④ Transform Conversion     │
│   ⑤ Generate HookAction      │
└─────────────────────────────┘
        │
        ▼
   wake (heartbeat) or agent (send message to Agent)
```

### Hook Endpoint Configuration

Gateway hook endpoints are enabled through configuration and must set an authentication token:

```typescript
// src/gateway/hooks.ts (simplified)

export function resolveHooksConfig(cfg: OpenClawConfig): HooksConfigResolved | null {
  if (cfg.hooks?.enabled !== true) return null;

  const token = cfg.hooks?.token?.trim();
  if (!token) throw new Error("hooks.enabled requires hooks.token");

  const basePath = cfg.hooks?.path?.trim() || "/hooks";
  const maxBodyBytes = cfg.hooks?.maxBodyBytes ?? 256 * 1024;  // 256KB
  const mappings = resolveHookMappings(cfg.hooks);

  return { basePath, token, maxBodyBytes, mappings };
}
```

The token is extracted from the request, supporting two methods:

| Method        | HTTP Header                     | Example                |
| ------------- | ------------------------------- | ---------------------- |
| Bearer Token  | `Authorization: Bearer <token>` | Standard OAuth style   |
| Custom Header | `X-OpenClaw-Token: <token>`     | Simplified integration |

### Mapping Rules and Presets

Mapping rules define "what request triggers what action". Each rule contains matching conditions and action templates:

```typescript
// src/gateway/hooks-mapping.ts

export type HookMappingResolved = {
  id: string;                 // Rule ID
  matchPath?: string;         // Match URL path (e.g., "gmail")
  matchSource?: string;       // Match payload.source field
  action: "wake" | "agent";   // Action type
  wakeMode?: "now" | "next-heartbeat";
  messageTemplate?: string;   // Message template (Mustache style)
  sessionKey?: string;        // Session key template
  transform?: {               // Optional custom transform module
    modulePath: string;
    exportName?: string;
  };
  // ...more fields
};
```

OpenClaw includes a built-in Gmail preset mapping:

```typescript
const hookPresetMappings: Record<string, HookMappingConfig[]> = {
  gmail: [{
    id: "gmail",
    match: { path: "gmail" },
    action: "agent",
    wakeMode: "now",
    name: "Gmail",
    sessionKey: "hook:gmail:{{messages[0].id}}",
    messageTemplate:
      "New email from {{messages[0].from}}\n" +
      "Subject: {{messages[0].subject}}\n" +
      "{{messages[0].snippet}}\n{{messages[0].body}}",
  }],
};
```

Users can also define custom mapping rules in configuration:

```json
{
  "hooks": {
    "enabled": true,
    "token": "my-secret-token",
    "presets": ["gmail"],
    "mappings": [{
      "id": "github-pr",
      "match": { "path": "github", "source": "github" },
      "action": "agent",
      "sessionKey": "hook:github:{{pull_request.id}}",
      "messageTemplate": "PR #{{pull_request.number}}: {{pull_request.title}}"
    }]
  }
}
```

### Matching and Rendering

When an HTTP request arrives at the hook endpoint, `applyHookMappings` attempts to match in order:

```typescript
// src/gateway/hooks-mapping.ts (simplified)

export async function applyHookMappings(
  mappings: HookMappingResolved[],
  ctx: HookMappingContext,
): Promise<HookMappingResult | null> {
  for (const mapping of mappings) {
    // 1. Path matching
    if (mapping.matchPath && mapping.matchPath !== normalizeMatchPath(ctx.path)) continue;
    // 2. Source matching
    if (mapping.matchSource && ctx.payload.source !== mapping.matchSource) continue;

    // 3. Build base action (template rendering)
    const base = buildActionFromMapping(mapping, ctx);

    // 4. Optional: execute Transform module
    if (mapping.transform) {
      const transform = await loadTransform(mapping.transform);
      const override = await transform(ctx);
      if (override === null) return { ok: true, action: null, skipped: true };
    }

    // 5. Merge base action and Transform result
    return mergeAction(base.action, override, mapping.action);
  }
  return null;  // No match
}
```

### Template Engine

Message templates use Mustache-like `{{expr}}` syntax, supporting the following expressions:

```typescript
// src/gateway/hooks-mapping.ts

function resolveTemplateExpr(expr: string, ctx: HookMappingContext) {
  if (expr === "path")    return ctx.path;           // Request path
  if (expr === "now")     return new Date().toISOString(); // Current time
  if (expr.startsWith("headers."))  return getByPath(ctx.headers, ...);
  if (expr.startsWith("query."))    return getByPath(queryParams, ...);
  if (expr.startsWith("payload."))  return getByPath(ctx.payload, ...);
  return getByPath(ctx.payload, expr);  // Default lookup in payload
}
```

`getByPath` supports dot and bracket syntax (e.g., `messages[0].from`), allowing deep access to nested JSON data.

### Action Types

After successful matching, one of two actions is generated:

| Action  | Purpose               | Effect                                                           |
| ------- | --------------------- | ---------------------------------------------------------------- |
| `wake`  | Wake Agent heartbeat  | Send text to trigger Agent heartbeat processing                  |
| `agent` | Send message to Agent | Create a new Agent message with sessionKey, channel, model, etc. |

The `agent` action is most commonly used—it's equivalent to sending a message to the Agent from some channel, but the message content is filled from the external system's Webhook data.

### Transform Custom Conversion

For complex data transformation needs, template syntax may not be sufficient. OpenClaw supports loading custom Transform modules for complete control over mapping logic:

```typescript
// Custom Transform module example
export default function transform(ctx: HookMappingContext) {
  const payload = ctx.payload;
  // Filter events that don't need processing
  if (payload.action !== "opened") return null;  // Return null to skip

  return {
    message: `New issue: ${payload.issue.title}`,
    sessionKey: `hook:github:issue-${payload.issue.id}`,
  };
}
```

The Transform function receives the complete request context and returns partial action fields (merged with base template rendering result), or returns `null` to skip this request. Transform modules are cached—the same module path is only `import()`ed once.

***

## 30.2.2 Agent Lifecycle Hooks: `before_agent_start` / `agent_end`

From this subsection onward, we enter the realm of the **Plugin Hook System**. Unlike the Pub/Sub pattern of internal hooks, plugin hooks are managed through a Plugin Registry and uniformly dispatched by runners created by `createHookRunner`.

### Plugin Hooks Overview

OpenClaw defines 14 types of plugin hooks covering five lifecycle domains:

```typescript
// src/plugins/types.ts

export type PluginHookName =
  | "before_agent_start" | "agent_end"                    // Agent domain
  | "before_compaction"  | "after_compaction"              // Compaction domain
  | "message_received"   | "message_sending" | "message_sent"  // Message domain
  | "before_tool_call"   | "after_tool_call" | "tool_result_persist"  // Tool domain
  | "session_start"      | "session_end"                   // Session domain
  | "gateway_start"      | "gateway_stop";                 // Gateway domain
```

### Execution Model: Void vs Modifying

Plugin hooks have two execution modes corresponding to different use cases:

```typescript
// src/plugins/hooks.ts (simplified)

// Mode 1: Void Hook — parallel execution, fire and forget
async function runVoidHook(hookName, event, ctx): Promise<void> {
  const hooks = getHooksForName(registry, hookName);
  // All handlers execute in parallel
  await Promise.all(hooks.map(hook => hook.handler(event, ctx)));
}

// Mode 2: Modifying Hook — sequential execution, results merged
async function runModifyingHook(hookName, event, ctx, merge): Promise<TResult> {
  const hooks = getHooksForName(registry, hookName);
  let result;
  // Execute sequentially by priority, merging results
  for (const hook of hooks) {
    const next = await hook.handler(event, ctx);
    result = merge ? merge(result, next) : next;
  }
  return result;
}
```

| Mode      | Execution                | Return Value                   | Use Case                                  |
| --------- | ------------------------ | ------------------------------ | ----------------------------------------- |
| Void      | `Promise.all` (parallel) | None                           | Observational hooks (logging, statistics) |
| Modifying | Sequential               | Can return modification result | Interception hooks (modify, block)        |

> **Sidebar**: This dual-mode design is common in middleware architectures. Express.js middleware is purely sequential (each `next()` call invokes the next); Koa's onion model is also sequential. OpenClaw adds a parallel mode—for observational hooks that don't need to affect each other, parallel execution can significantly improve performance.

### before\_agent\_start

`before_agent_start` triggers before the Agent starts processing a request, allowing plugins to inject additional system prompts or context:

```typescript
// src/plugins/types.ts

export type PluginHookBeforeAgentStartEvent = {
  prompt: string;         // User prompt
  messages?: unknown[];   // Historical messages
};

export type PluginHookBeforeAgentStartResult = {
  systemPrompt?: string;     // Replace system prompt
  prependContext?: string;   // Prepend content to context
};
```

This is a **Modifying Hook**—results from multiple plugins are merged:

```typescript
// src/plugins/hooks.ts

async function runBeforeAgentStart(event, ctx) {
  return runModifyingHook("before_agent_start", event, ctx,
    (acc, next) => ({
      systemPrompt: next.systemPrompt ?? acc?.systemPrompt,
      prependContext: acc?.prependContext && next.prependContext
        ? `${acc.prependContext}\n\n${next.prependContext}`  // Concatenate
        : (next.prependContext ?? acc?.prependContext),
    }),
  );
}
```

The merge strategy is: `systemPrompt` is overridden by the latter (last plugin wins), `prependContext` is concatenated (all plugins' prepended context is preserved).

### agent\_end

`agent_end` triggers after the Agent completes processing, a **Void Hook** (parallel execution, no return value):

```typescript
export type PluginHookAgentEndEvent = {
  messages: unknown[];     // Complete conversation message list
  success: boolean;        // Whether completed successfully
  error?: string;          // Error message (if any)
  durationMs?: number;     // Processing duration
};
```

Typical uses include: conversation quality analysis, usage statistics reporting, exception monitoring and alerting.

***

## 30.2.3 Tool Lifecycle Hooks: `before_tool_call` / `after_tool_call` / `tool_result_persist`

Tool hooks are the finest-grained group in plugin hooks, covering the complete lifecycle of tool invocation.

### before\_tool\_call

Triggers before the Agent initiates a tool call. This is a **Modifying Hook**, allowing plugins to modify parameters or even block the call:

```typescript
export type PluginHookBeforeToolCallEvent = {
  toolName: string;                    // Tool name
  params: Record<string, unknown>;     // Call parameters
};

export type PluginHookBeforeToolCallResult = {
  params?: Record<string, unknown>;    // Modified parameters
  block?: boolean;                     // Whether to block the call
  blockReason?: string;                // Reason for blocking
};
```

Merge strategy:

```typescript
(acc, next) => ({
  params: next.params ?? acc?.params,
  block: next.block ?? acc?.block,
  blockReason: next.blockReason ?? acc?.blockReason,
})
```

This means if any plugin returns `block: true`, the tool call is blocked—this is a critical interception point for security policies. For example, a security plugin can inspect `bash` tool parameters and block dangerous commands:

```typescript
// Hypothetical security plugin
api.on("before_tool_call", (event) => {
  if (event.toolName === "bash" && event.params.command?.includes("rm -rf /")) {
    return { block: true, blockReason: "Dangerous command blocked" };
  }
});
```

### after\_tool\_call

Triggers after tool invocation completes, a **Void Hook** (parallel, observational):

```typescript
export type PluginHookAfterToolCallEvent = {
  toolName: string;                    // Tool name
  params: Record<string, unknown>;     // Call parameters
  result?: unknown;                    // Call result
  error?: string;                      // Error message
  durationMs?: number;                 // Execution duration
};
```

Typical uses: tool usage statistics, performance monitoring, error tracking.

### tool\_result\_persist (Synchronous Hook)

`tool_result_persist` is the **only synchronous hook** in the entire hook system—it triggers when tool results are written to session records and must return synchronously:

```typescript
// src/plugins/hooks.ts

function runToolResultPersist(event, ctx): PluginHookToolResultPersistResult | undefined {
  const hooks = getHooksForName(registry, "tool_result_persist");
  let current = event.message;

  for (const hook of hooks) {
    const out = hook.handler({ ...event, message: current }, ctx);

    // Defense: reject async handlers
    if (out && typeof out.then === "function") {
      logger?.warn(`tool_result_persist handler returned a Promise; ignored.`);
      continue;
    }

    const next = out?.message;
    if (next) current = next;  // Pipeline pass-through
  }
  return { message: current };
}
```

It's designed as synchronous because: this hook runs on the **hot path of session record appending**—writing to the session JSONL file is a synchronous operation, and introducing async waits here would break the atomicity and ordering of writes.

This hook adopts a **pipeline pattern**—each handler receives the output of the previous handler as input, and the final result is the last version of the message passed through the chain. Typical uses: filtering sensitive information before persistence, compressing large tool outputs, adding metadata annotations.

> **Sidebar**: The Pipeline Pattern is a data processing pattern where data passes through a series of processing stages, with each stage receiving the output of the previous stage and producing new output. Unix's pipe operator `|` is the classic example: `cat file | grep error | sort`. The `tool_result_persist` hook chain here is a synchronous in-memory pipeline.

***

## 30.2.4 Message Hooks: `message_received` / `message_sending` / `message_sent`

Message hooks intercept the message flow between users and the Agent, covering three stages of "in-process-out":

```
User Message ──→ message_received ──→ Agent Processing ──→ message_sending ──→ Send ──→ message_sent
             (observational)                              (can modify/cancel)      (observational)
```

### message\_received

Triggers when a user message arrives, a **Void Hook**:

```typescript
export type PluginHookMessageReceivedEvent = {
  from: string;                          // Sender identifier
  content: string;                       // Message content
  timestamp?: number;                    // Timestamp
  metadata?: Record<string, unknown>;    // Channel-specific metadata
};

export type PluginHookMessageContext = {
  channelId: string;      // Channel ID (telegram/discord/webchat, etc.)
  accountId?: string;     // Account ID
  conversationId?: string; // Conversation ID
};
```

Uses: message reception statistics, content audit logging, user behavior analysis.

### message\_sending

Triggers before Agent reply is sent, a **Modifying Hook**—plugins can modify content or even cancel sending:

```typescript
export type PluginHookMessageSendingEvent = {
  to: string;                 // Recipient
  content: string;            // Message content
  metadata?: Record<string, unknown>;
};

export type PluginHookMessageSendingResult = {
  content?: string;           // Modified content
  cancel?: boolean;           // Whether to cancel sending
};
```

Merge strategy:

```typescript
(acc, next) => ({
  content: next.content ?? acc?.content,
  cancel: next.cancel ?? acc?.cancel,
})
```

This hook gives plugins tremendous control:

* **Content Filtering**: Replace sensitive or inappropriate content before sending
* **Format Conversion**: Convert Markdown to formats supported by specific channels
* **Send Interception**: Block message sending when specific conditions are met

### message\_sent

Triggers after message is actually sent, a **Void Hook**:

```typescript
export type PluginHookMessageSentEvent = {
  to: string;
  content: string;
  success: boolean;    // Whether sending succeeded
  error?: string;      // Failure reason
};
```

Uses: send success rate monitoring, failure retry triggering, message archiving.

***

## 30.2.5 Gateway Hooks: `gateway_start` / `gateway_stop`

Gateway hooks trigger at Gateway server startup and shutdown, the outermost lifecycle hooks.

### gateway\_start

Triggers after Gateway HTTP server starts, a **Void Hook**:

```typescript
export type PluginHookGatewayStartEvent = {
  port: number;    // Listening port
};

export type PluginHookGatewayContext = {
  port?: number;
};
```

Uses: initialize external connections (databases, message queues), register service discovery, send startup notifications.

### gateway\_stop

Triggers when Gateway is about to shut down:

```typescript
export type PluginHookGatewayStopEvent = {
  reason?: string;   // Shutdown reason
};
```

Uses: clean up resources, disconnect external connections, send shutdown notifications, flush buffers.

### Hook Runner Factory

All plugin hooks are created through a unified `createHookRunner`:

```typescript
// src/plugins/hooks.ts

export function createHookRunner(registry: PluginRegistry, options = {}) {
  const logger = options.logger;
  const catchErrors = options.catchErrors ?? true;  // Default: catch errors

  return {
    // Agent hooks
    runBeforeAgentStart, runAgentEnd,
    runBeforeCompaction, runAfterCompaction,
    // Message hooks
    runMessageReceived, runMessageSending, runMessageSent,
    // Tool hooks
    runBeforeToolCall, runAfterToolCall, runToolResultPersist,
    // Session hooks
    runSessionStart, runSessionEnd,
    // Gateway hooks
    runGatewayStart, runGatewayStop,
    // Utility methods
    hasHooks,      // Check if a hook has registrations
    getHookCount,  // Get count of registrations for a hook
  };
}
```

Key design decisions of the runner:

1. **Default Fault Tolerance**: `catchErrors` defaults to `true`, so one plugin's hook failure doesn't affect other plugins and core flow.
2. **Priority Ordering**: Handlers are sorted by `priority` in descending order—higher priority executes first. For Modifying Hooks, this means high-priority plugins can set defaults, low-priority ones can override.
3. **Lazy Checking**: `hasHooks` lets callers determine if a hook has registrations without calling the runner, avoiding unnecessary event object construction overhead.

### Plugin Hook Registration

Plugins register hook handlers through the `OpenClawPluginApi.on()` method:

```typescript
// Plugin code example
export default function myPlugin(api: OpenClawPluginApi) {
  // Register Agent lifecycle hook
  api.on("before_agent_start", async (event, ctx) => {
    return { prependContext: "Always be concise." };
  });

  // Register tool hook (with priority)
  api.on("before_tool_call", async (event, ctx) => {
    if (event.toolName === "bash") {
      console.log(`[audit] bash: ${event.params.command}`);
    }
  }, { priority: 100 });

  // Register gateway hook
  api.on("gateway_start", async (event) => {
    console.log(`Gateway started on port ${event.port}`);
  });
}
```

Each registration creates a `PluginHookRegistration` record stored in the plugin registry:

```typescript
export type PluginHookRegistration<K extends PluginHookName> = {
  pluginId: string;          // Source plugin ID
  hookName: K;               // Hook name
  handler: PluginHookHandlerMap[K];  // Handler function
  priority?: number;         // Priority (higher executes first)
  source: string;            // Source description
};
```

### Comparison of Two Hook Systems

At this point, we've completely introduced OpenClaw's two hook systems. Here are their key differences:

| Dimension      | Internal Hooks                                        | Plugin Hooks                                  |
| -------------- | ----------------------------------------------------- | --------------------------------------------- |
| Source         | HOOK.md + handler.ts files                            | Registered via `api.on()` in plugin code      |
| Management     | Directory discovery + configuration control           | Plugin registry                               |
| Event Naming   | `type:action` string keys                             | Enum type `PluginHookName`                    |
| Execution Mode | All sequential                                        | Void (parallel) / Modifying (sequential)      |
| Return Value   | None (push back via `event.messages`)                 | Modifying Hook can return modification result |
| Typical Use    | Filesystem-level extensions (custom hook directories) | Programming-level extensions (plugin code)    |
| Installation   | `openclaw hooks install`                              | Automatically loaded by plugin system         |
| Error Handling | try/catch isolation                                   | Configurable (default: catch)                 |

The two systems don't conflict and can be used simultaneously. Internal hooks are better suited for "ops-level" lightweight extensions (like audit logging, session saving), while plugin hooks are better for "dev-level" deep integration (like security interception, content conversion, external system integration).

***

## Section Summary

1. **Hook Mapping** is Gateway's built-in HTTP→Agent bridging mechanism that converts external Webhook requests into Agent actions through path/source matching and template rendering, supporting presets (Gmail) and custom mapping rules, plus Transform modules for complex transformations.
2. **Plugin Hook System** defines 14 hooks covering five lifecycle domains (Agent, message, tool, session, gateway), uniformly dispatched by the `createHookRunner` factory.
3. **Agent Hooks**: `before_agent_start` allows injecting system prompts (sequentially merged), `agent_end` is for post-completion observation (parallel execution).
4. **Tool Hooks** provide the finest control—`before_tool_call` can modify parameters or block calls, `tool_result_persist` is the only synchronous pipeline hook running on the hot path of session record appending.
5. **Message Hooks** intercept the in-out flow of messages, with `message_sending` being the only interception point that can modify or cancel messages.
6. **Two Hook Systems** (internal + plugin) complement each other—internal hooks target filesystem-level extensions, plugin hooks target programming-level deep integration, together forming OpenClaw's complete extensibility foundation.

***

> ### 🔬 Going Deeper: 30.3 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**30.3 Source Deep Dive: Two Event Systems and the Hook Package Convention**](https://www.openclawbook.xyz/en/ch30-hook-system/30.3-source-deep-dive-two-event-systems.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
