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

# 5.2 Webhooks and Event-Driven Automation

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~202,000 tokens, Output \~9,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Cron handles "at this time." Webhooks handle "when this happens."

## 5.2.1 Webhook Triggers

### Enabling them

Webhooks are off by default and **require a token**:

```json5
{
  hooks: {
    enabled: true,
    token: "${OPENCLAW_HOOK_TOKEN}",
    path: "/hooks",             // default
    maxBodyBytes: 262144,        // 256 KB default
  },
}
```

Generate a token:

```bash
openclaw webhooks token         # generates a random token
```

**`hooks.token` must not be the same as your gateway token.** `openclaw security audit` flags reuse specifically — sharing them means anyone who can trigger a webhook can also reach the control plane.

### Two modes

**Wake mode** — inject an event into your main session:

```bash
curl -X POST https://your-gateway/hooks/wake \
  -H "Authorization: Bearer $HOOK_TOKEN" \
  -d '{"text": "New PR #123 opened in openclaw/openclaw", "mode": "now"}'
```

`mode: "now"` pulls up a heartbeat immediately; otherwise it's handled on the next cycle. Same shape as a `main` cron job.

**Agent mode** — start an isolated agent turn:

```bash
curl -X POST https://your-gateway/hooks/agent \
  -H "Authorization: Bearer $HOOK_TOKEN" \
  -d '{
    "message": "Review the code changes in this PR and summarize the risks",
    "name": "PR Review",
    "channel": "telegram",
    "to": "123456789",
    "deliver": true
  }'
```

> **Agent mode reuses the cron isolated-execution infrastructure** — it constructs a temporary job object and runs it through the same path. **Cron and webhooks share one execution engine**, differing only in trigger. That's a typical OpenClaw design move.

### Authentication

Three ways to present the token:

| Method          | Example                                               |
| --------------- | ----------------------------------------------------- |
| Bearer token    | `Authorization: Bearer my-token`                      |
| Custom header   | `X-OpenClaw-Token: my-token`                          |
| Query parameter | `?token=my-token` (**note the URL-logging exposure**) |

Use the header forms unless the caller can't set headers.

### Exposing the endpoint

Your gateway binds to loopback by default, so an external service can't reach it. Options, from safest:

| Approach                        | Notes                                                                             |
| ------------------------------- | --------------------------------------------------------------------------------- |
| **Tailscale Serve**             | Reachable within your tailnet only; no public exposure                            |
| **A reverse proxy you control** | You handle TLS and access control                                                 |
| **Tailscale Funnel**            | Public HTTPS; **forces password auth mode** and permits only ports 443/8443/10000 |

**Don't just set `gateway.bind: "lan"` and forward a port.** Chapter 32 and Appendix G explain why; the short version is that the HTTP surface is a **full operator-access surface** — past auth, the caller is a trusted operator.

## 5.2.2 Gmail Pub/Sub

The most useful built-in event source: **run an agent turn when new mail arrives.**

### How it works

```
new Gmail message
    ↓ Google Cloud Pub/Sub push
OpenClaw's /hooks/gmail endpoint
    ↓ parse the message
an isolated agent turn
    ↓
the agent processes it and delivers the result
```

> **Sidebar — Google Cloud Pub/Sub** A message queue service. The Gmail API can watch a mailbox and push a notification (containing a `historyId`) to an HTTPS endpoint you nominate whenever it changes. OpenClaw receives that push and then fetches the message content through the Gmail API.

### Configuration

```json5
{
  hooks: {
    enabled: true,
    token: "${OPENCLAW_HOOK_TOKEN}",
    gmail: {
      account: "you@gmail.com",
      topic: "gog-gmail-watch",
      subscription: "gog-gmail-watch-push",
      pushToken: "${GMAIL_PUSH_TOKEN}",
      includeBody: true,
      maxBytes: 20000,
      model: "claude-haiku",            // cheaper model for mail triage
      allowUnsafeExternalContent: false, // keep this false
    },
  },
}
```

Setup requires work on the Google Cloud side (creating a topic and subscription, granting Gmail publish rights). `openclaw webhooks gmail setup` walks through it.

Note that Pub/Sub requires an **HTTPS** endpoint, so you'll need Tailscale Funnel or a similar tunnel.

### The security point that matters most

**Email is completely untrusted input. Anyone can email you.**

OpenClaw wraps externally-triggered content with injection detection and delimiters (§26.4.5), and

> **`allowUnsafeExternalContent` must stay `false`.**

`SECURITY.md` says so explicitly — the flag exists for tightly-scoped debugging, not normal operation. Turning it on removes the wrapping, meaning a crafted email speaks to your agent with the same authority you do.

## 5.2.3 Event-Driven Patterns

### Useful shapes

| Pattern                 | Trigger            | Job                                                 |
| ----------------------- | ------------------ | --------------------------------------------------- |
| **PR review**           | GitHub webhook     | Read the diff, summarize risks, post a comment      |
| **Alert triage**        | Monitoring webhook | Correlate logs, assess severity, notify or escalate |
| **Mail triage**         | Gmail Pub/Sub      | Categorize, extract action items, draft replies     |
| **Deploy verification** | CI webhook         | Hit the deployed site, screenshot, confirm health   |

### Design guidance

**Prefer isolated sessions for external triggers.** A webhook fired by an external system shouldn't be reading your personal conversation context — and with `lightContext: true` the bootstrap context is empty entirely, making high-frequency hooks cheap.

**Use a cheap model for triage, a good one for judgment.** A hook that classifies mail can run on a small model; one that drafts a reply probably shouldn't.

**Restrict skills for automated turns.** Cron and hook sessions can run with an allowlisted skills snapshot (§29.5.5), shrinking what a manipulated turn can reach.

**Expect injection attempts eventually.** If your agent processes email or public webhooks, someone will eventually send content designed to manipulate it. The defense isn't detection — it's making sure a manipulated turn can't do anything dangerous (tool policy, exec approvals, sandbox).

***

## Section Summary

1. **Webhooks are off by default and require a token**, which **must differ from your gateway token** — `security audit` flags reuse.
2. **Two modes**: wake (inject into the main session) and agent (isolated turn). **Agent mode reuses cron's execution engine** — one engine, different triggers.
3. **Don't expose the gateway by binding to LAN and forwarding a port** — the HTTP surface is a full operator-access surface; use Tailscale Serve, a reverse proxy you control, or Funnel (which forces password auth).
4. **Gmail Pub/Sub turns new mail into an agent turn**, requiring Google Cloud setup and an HTTPS endpoint.
5. **Email is completely untrusted input** — external content gets injection detection and delimiter wrapping, and **`allowUnsafeExternalContent` must stay `false`**; the flag exists for scoped debugging only.
6. **Four design guidelines for event-driven work**: prefer isolated sessions for external triggers (with `lightContext` for cheap high-frequency hooks), cheap model for triage and good model for judgment, restrict skills for automated turns, and **assume injection attempts will come** — the defense is limiting what a manipulated turn can do.
