> 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/ch26-cron-scheduling-and-automation/26.3-webhooks-and-gmail-pubsub.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 26.3 Webhooks and Gmail Pub/Sub

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

***

The Cron system lets Agents execute tasks on a schedule. But some scenarios aren't time-triggered—"automatically process when a new email arrives," "trigger Agent when an external system sends a Webhook." This section analyzes OpenClaw's Webhook triggers and Gmail Pub/Sub integration.

***

## 26.3.1 Webhook Triggers

### Concept: HTTP-Triggered Agent Execution

Webhooks allow external systems to trigger Agent execution via HTTP requests. Examples:

* Notify Agent to perform code review when code is pushed to GitHub
* Let Agent generate analysis report when monitoring system detects anomaly
* Have Agent process sensor data when IoT device sends data

OpenClaw provides a Webhook endpoint in the Gateway's HTTP layer, with default path `/hooks`.

### Configuration and Authentication

Webhooks must be explicitly enabled in the config file:

```yaml
hooks:
  enabled: true
  token: "my-secret-webhook-token"  # Required
  path: "/hooks"                     # Default
  maxBodyBytes: 262144               # 256KB, default
```

```typescript
// src/gateway/hooks.ts — resolveHooksConfig

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 rawPath = cfg.hooks?.path?.trim() || "/hooks";
  if (trimmed === "/") throw new Error("hooks.path may not be '/'");

  return {
    basePath: trimmed,
    token,
    maxBodyBytes: cfg.hooks?.maxBodyBytes ?? 256 * 1024,
    mappings: resolveHookMappings(cfg.hooks),
  };
}
```

Authentication supports three methods:

```typescript
// src/gateway/hooks.ts — extractHookToken

export function extractHookToken(req: IncomingMessage): string | undefined {
  // Method 1: Bearer Token
  const auth = req.headers.authorization;
  if (auth?.toLowerCase().startsWith("bearer ")) {
    return auth.slice(7).trim();
  }

  // Method 2: Custom header
  const headerToken = req.headers["x-openclaw-token"];
  if (headerToken) return headerToken.trim();

  // Method 3: URL query parameter (handled at HTTP layer)
  return undefined;
}
```

| Method          | Example                          | Description                                           |
| --------------- | -------------------------------- | ----------------------------------------------------- |
| Bearer Token    | `Authorization: Bearer my-token` | Standard OAuth2 style                                 |
| Custom Header   | `X-OpenClaw-Token: my-token`     | For scenarios that don't support Authorization header |
| Query Parameter | `?token=my-token`                | Simple cases (note URL logging risk)                  |

### Two Webhook Modes

Webhooks support two trigger modes:

#### Wake Mode: Inject System Event

```
POST /hooks/wake
{
  "text": "GitHub repository openclaw/openclaw received new PR #123",
  "mode": "now"
}
```

```typescript
// src/gateway/server/hooks.ts — dispatchWakeHook

const dispatchWakeHook = (value: { text: string; mode: "now" | "next-heartbeat" }) => {
  const sessionKey = resolveMainSessionKeyFromConfig();
  enqueueSystemEvent(value.text, { sessionKey });
  if (value.mode === "now") {
    requestHeartbeatNow({ reason: "hook:wake" });
  }
};
```

Wake mode directly injects a system event text into the main session, similar to Cron's main-session mode.

#### Agent Mode: Start Isolated Agent

```
POST /hooks/agent
{
  "message": "Please review the code changes in this PR...",
  "name": "GitHub PR Review",
  "channel": "whatsapp",
  "to": "+1234567890",
  "deliver": true
}
```

```typescript
// src/gateway/server/hooks.ts — dispatchAgentHook (simplified)

const dispatchAgentHook = (value) => {
  // Construct a temporary CronJob object
  const job: CronJob = {
    id: randomUUID(),
    name: value.name,
    schedule: { kind: "at", at: new Date().toISOString() },
    sessionTarget: "isolated",
    wakeMode: value.wakeMode,
    payload: {
      kind: "agentTurn",
      message: value.message,
      model: value.model,
      deliver: value.deliver,
      channel: value.channel,
      to: value.to,
    },
    state: { nextRunAtMs: Date.now() },
  };

  // Execute asynchronously (don't block HTTP response)
  void (async () => {
    const result = await runCronIsolatedAgentTurn({ job, message: value.message, ... });

    // Inject result summary into main session
    enqueueSystemEvent(`Hook ${value.name}: ${result.summary}`, { sessionKey });
    if (value.wakeMode === "now") {
      requestHeartbeatNow({ reason: `hook:${jobId}` });
    }
  })();

  return runId;
};
```

Agent mode reuses Cron's isolated execution infrastructure—it constructs a temporary `CronJob` object and calls `runCronIsolatedAgentTurn` to execute. This exemplifies OpenClaw's design philosophy: **Cron and Webhooks share the same execution engine**, differing only in trigger method.

### Request Body Parsing

```typescript
// src/gateway/hooks.ts — readJsonBody

export async function readJsonBody(req, maxBytes): Promise<Result> {
  return new Promise((resolve) => {
    let total = 0;
    const chunks: Buffer[] = [];

    req.on("data", (chunk: Buffer) => {
      total += chunk.length;
      if (total > maxBytes) {
        resolve({ ok: false, error: "payload too large" });
        req.destroy();  // Immediately close connection
        return;
      }
      chunks.push(chunk);
    });

    req.on("end", () => {
      const raw = Buffer.concat(chunks).toString("utf-8").trim();
      if (!raw) { resolve({ ok: true, value: {} }); return; }
      try {
        resolve({ ok: true, value: JSON.parse(raw) });
      } catch (err) {
        resolve({ ok: false, error: String(err) });
      }
    });
  });
}
```

Note the security measures: if payload exceeds `maxBodyBytes`, immediately `req.destroy()` to close the connection, preventing large payloads from exhausting memory.

***

## 26.3.2 Gmail Pub/Sub Email Hook (`src/hooks/gmail.ts`)

### Concept: Email-Driven Agent

Gmail Pub/Sub integration lets Agents **automatically process when new emails arrive**—for example, auto-reply, archive and categorize, extract key information.

How it works:

```
New Gmail message
    │
    ↓ Google Cloud Pub/Sub push
OpenClaw Gateway /hooks/gmail endpoint
    │
    ↓ Parse email content
Webhook Agent mode
    │
    ↓ runCronIsolatedAgentTurn
Agent processes email and delivers result
```

> **Sidebar—Google Cloud Pub/Sub**: Pub/Sub (Publish/Subscribe) is Google Cloud's message queue service. Gmail API allows monitoring mailbox changes via Pub/Sub—when a new email arrives, Google sends a push notification to your specified HTTPS endpoint (containing the email's `historyId`). OpenClaw listens to this push, then fetches email content via Gmail API.

### Gmail Configuration

```yaml
hooks:
  enabled: true
  token: "webhook-token"
  gmail:
    account: "user@gmail.com"       # Gmail account
    topic: "gog-gmail-watch"        # Pub/Sub topic
    subscription: "gog-gmail-watch-push"  # Pub/Sub subscription
    pushToken: "gmail-push-secret"  # Pub/Sub push verification token
    includeBody: true               # Whether to extract email body
    maxBytes: 20000                 # Max email size (default 20KB)
    model: "claude-sonnet"          # Optional: specify model for Gmail hook
    thinking: "low"                 # Optional: thinking level
    allowUnsafeExternalContent: false  # Dangerous: disable external content safety wrapping
```

```typescript
// src/hooks/gmail.ts — defaults

export const DEFAULT_GMAIL_LABEL = "INBOX";
export const DEFAULT_GMAIL_TOPIC = "gog-gmail-watch";
export const DEFAULT_GMAIL_SUBSCRIPTION = "gog-gmail-watch-push";
export const DEFAULT_GMAIL_SERVE_BIND = "127.0.0.1";
export const DEFAULT_GMAIL_SERVE_PORT = 8788;
export const DEFAULT_GMAIL_MAX_BYTES = 20_000;
export const DEFAULT_GMAIL_RENEW_MINUTES = 12 * 60;  // 12 hour renewal
```

### Webhook URL Construction

Gmail push requires an accessible HTTPS URL. OpenClaw defaults to using the local Gateway address:

```typescript
// src/hooks/gmail.ts — buildDefaultHookUrl

export function buildDefaultHookUrl(hooksPath?: string, port = 18789): string {
  const basePath = normalizeHooksPath(hooksPath);
  return `http://127.0.0.1:${port}${basePath}/gmail`;
  // Example: http://127.0.0.1:18789/hooks/gmail
}
```

Since Google Pub/Sub requires HTTPS endpoints, local development needs to expose the local port as a public HTTPS address via **Tailscale Funnel** or similar tunneling service. The `tailscale` field in Gmail config is designed for this.

### Token Security

Gmail integration involves two tokens:

* **`hooks.token`**—Gateway Webhook authentication token
* **`hooks.gmail.pushToken`**—Pub/Sub push verification token

```typescript
export function generateHookToken(bytes = 24): string {
  return randomBytes(bytes).toString("hex");  // 48-character hex
}
```

The security audit module (`src/security/audit-extra.ts`) checks:

* Whether token length is sufficient (warns if too short)
* Whether `hooks.token` duplicates Gateway auth token (duplication increases attack surface)
* Whether `hooks.path` is `"/"` (would shadow other HTTP endpoints)

***

## 26.3.3 Hook System Overview (`src/hooks/hooks.ts`)

### Internal Hooks vs External Hooks

OpenClaw has two "hook" systems that are easy to confuse:

| Name                         | Location               | Trigger                | Purpose                        |
| ---------------------------- | ---------------------- | ---------------------- | ------------------------------ |
| **External Hooks** (Webhook) | `src/gateway/hooks.ts` | HTTP request           | External systems trigger Agent |
| **Internal Hooks**           | `src/hooks/hooks.ts`   | Agent lifecycle events | Extend Agent behavior          |

The earlier parts of this section discuss external hooks. Internal hooks are a separate system—they allow developers to inject custom logic into Agent lifecycle.

### Internal Hook Mechanism

`src/hooks/hooks.ts` is the entry point for the internal hook system, re-exporting all functionality from `internal-hooks.ts`:

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

export * from "./internal-hooks.js";

export {
  registerInternalHook as registerHook,
  unregisterInternalHook as unregisterHook,
  clearInternalHooks as clearHooks,
  triggerInternalHook as triggerHook,
  createInternalHookEvent as createHookEvent,
} from "./internal-hooks.js";
```

Internal hooks work via event registration and triggering:

```typescript
// Register hook (at Agent startup)
registerHook("session:new", async (event) => {
  // Execute when new session is created
  console.log("New session created:", event.sessionId);
});

// Trigger hook (at Agent runtime)
await triggerHook("session:new", createHookEvent({
  sessionId: "ses_abc123",
  // ...
}));
```

### Built-in Hooks

OpenClaw comes with several built-in hooks (located in `src/hooks/bundled/`):

| Hook                    | Directory                        | Function                                   |
| ----------------------- | -------------------------------- | ------------------------------------------ |
| `boot-md`               | `bundled/boot-md/`               | Load Markdown config file at Agent startup |
| `session-memory`        | `bundled/session-memory/`        | Cross-session memory persistence           |
| `command-logger`        | `bundled/command-logger/`        | Log user commands                          |
| `bootstrap-extra-files` | `bundled/bootstrap-extra-files/` | Inject extra bootstrap files by glob/path  |

### Hook Loading

Enabling internal hooks requires configuration:

```yaml
hooks:
  internal:
    enabled: true     # Enable internal hook system
    entries:          # Enable/disable individual hooks
      session-memory:
        enabled: true
      command-logger:
        enabled: false
```

Loading happens at Gateway startup (`src/hooks/loader.ts`), scanning these locations:

1. **Built-in hook directory**—`src/hooks/bundled/` (distributed with OpenClaw)
2. **Managed directory**—`~/.openclaw/hooks/` (installed via `openclaw hooks install`)
3. **Workspace hooks**—`<workspace>/hooks/` (project-level hooks)
4. **Extra directories**—custom paths configured in `hooks.internal.load.extraDirs`

Each hook directory must contain a `HOOK.md` frontmatter file (hook metadata) and a `handler.ts`/`handler.js` handler function.

### Relationship Between Cron, Webhooks, and Internal Hooks

```
┌─────────────────────────────────────────────────────────┐
│ Trigger Source                                           │
│                                                          │
│  Time Schedule (Cron)    ──→ CronService ──→ executeJobCore │
│  HTTP Request (Webhook)  ──→ /hooks/*   ──→ dispatchHook   │
│                                          │              │
│                               ┌──────────┘              │
│                               ↓                         │
│                  runCronIsolatedAgentTurn                │
│                        (Shared Execution Engine)         │
│                               │                         │
│                               ↓                         │
│                    Agent Lifecycle                       │
│                               │                         │
│                    Internal Hook Trigger Points          │
│                    ├── session:new                       │
│                    ├── agent:bootstrap                   │
│                    ├── agent:end                         │
│                    └── ...                               │
└─────────────────────────────────────────────────────────┘
```

The relationship:

* **Cron** and **Webhooks** are different **trigger sources**, but share the same Agent execution engine
* **Internal hooks** are **extension points** in Agent runtime; regardless of whether Agent is triggered by Cron, Webhook, or user message, internal hooks execute at corresponding lifecycle points

***

## Section Summary

1. **Webhooks** receive external requests via HTTP endpoint (default `/hooks`); support Bearer Token, custom header, query parameter authentication
2. Webhooks have two modes: **Wake** (inject system event into main session) and **Agent** (start isolated Agent execution)
3. Agent mode reuses Cron's isolated execution infrastructure—constructs temporary `CronJob` object and calls `runCronIsolatedAgentTurn`
4. **Gmail Pub/Sub** integration lets Agent automatically process when new emails arrive, implemented via Google Cloud Pub/Sub push notifications
5. Gmail integration requires HTTPS endpoint; local development can expose via **Tailscale Funnel**
6. **Internal hooks** are a separate system—Agent lifecycle extension points supporting `session:new`, `agent:bootstrap` events
7. Built-in hooks include session memory (`session-memory`), command logging (`command-logger`)
8. Cron, Webhooks, and internal hooks are complementary: Cron/Webhooks are trigger sources, internal hooks are Agent runtime extension points

***

> ### 🔬 Going Deeper: 26.4 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: [**26.4 Source Deep Dive: The Division of Labor Between Cron and Heartbeat**](https://www.openclawbook.xyz/en/ch26-cron-scheduling-and-automation/26.4-source-deep-dive-cron-vs-heartbeat.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.**
