> 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.3-source-deep-dive-two-event-systems.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 30.3 Source Deep Dive: Two Event Systems and the Hook Package Convention

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~238,000 tokens, Output \~8,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§30.1 and §30.2 covered internal hooks and plugin hooks respectively. This section looks at their actual shape in the source — `src/hooks/` in fact carries **two distinct layers of mechanism**.

## 30.3.1 Layer One: The Internal Event Bus

`src/hooks/internal-hooks.ts` defines five event types (`:13`):

```
command | session | agent | gateway | message
```

The gateway fires them at these moments: command handling (`/new`, `/reset`, `/stop`), agent bootstrap, gateway startup, and message send/receive.

## 30.3.2 Layer Two: User-Installable Hook Packages

This layer is a **directory convention**:

```
<hook-name>/
  ├── HOOK.md      frontmatter declaring subscribed events, required bins/env/config, OS limits
  └── handler.ts   the actual handler
```

Origins come in four kinds (`src/hooks/types.ts:38`):

```
"openclaw-bundled" | "openclaw-managed" | "openclaw-workspace" | "openclaw-plugin"
```

**Exactly isomorphic to the skills discovery and priority rules** (§29.5.2) — deliberate design consistency.

### One example: session-memory

```markdown
<!-- src/hooks/bundled/session-memory/HOOK.md:1-14 -->
---
name: session-memory
description: "Save session context to memory when /new or /reset command is issued"
metadata:
  { "openclaw":
      { "emoji": "💾",
        "events": ["command:new", "command:reset"],
        "requires": { "config": ["workspace.dir"] },
        "install": [{ "id": "bundled", "kind": "bundled" }] } }
---
```

On `/new` or `/reset` it finds the previous session's transcript and writes a summary into `memory/`.

**This is the junction between the memory system and the command system, and the implementation of "reset the session without forgetting."**

The design is worth sitting with: `/new` means "start a new conversation," and what the user expects is a cleared context — **not to forget what was just discussed**. The gap between those two is closed by a twenty-line hook, rather than by hard-coding memory logic into the command implementation.

### The other three built-in hooks

| Hook                    | Purpose                                                                                        |
| ----------------------- | ---------------------------------------------------------------------------------------------- |
| `bootstrap-extra-files` | Inject additional workspace files during bootstrap                                             |
| `command-logger`        | Command audit log                                                                              |
| `boot-md`               | Execute the workspace's `BOOT.md` at gateway startup — **effectively the agent's boot script** |

`boot-md` is interesting: it lets users write "things to do at startup" in natural language, and the agent executes them itself on launch.

## 30.3.3 Trigger Semantics: Fire-and-Forget, With One Exception

**The default is fire-and-forget** (`src/hooks/fire-and-forget.ts`) — a broken hook doesn't drag down the main flow.

That's the right default: hooks are extension points and shouldn't let one slow or broken plugin block message processing.

**But there's an important exception**: for events like `agent:bootstrap`, **the return value can modify the bootstrap file list** (`internal-hooks.ts:16-29`'s `AgentBootstrapHookContext` carries a **mutable** `bootstrapFiles`).

> So **hooks are also a legitimate channel for injecting context.** Worth noting during a security audit: anyone who can install a hook can change the bootstrap files the agent sees. That's consistent with §44.4's trust model (anyone who can modify `~/.openclaw` is already a trusted operator), but it's worth knowing explicitly.

## 30.3.4 The External World's Entry Point: Gmail Watcher

`src/hooks/gmail-watcher.ts` uses Google Pub/Sub to **turn a new email into an agent turn in a hook session**.

It's the representative entry point for "external world event → agent turn."

Which is precisely why the external-content wrapping described in §26.4.5 is necessary:

```
an email from a stranger
   ↓ Pub/Sub push
an agent turn in a hook session
   ↓
buildSafeExternalPrompt / detectSuspiciousPatterns wrapping and detection
```

An email body is **entirely untrusted input** — anyone can email you.

The matching config switches are blunt about it: `hooks.gmail.allowUnsafeExternalContent` and `hooks.mappings[].allowUnsafeExternalContent`. `SECURITY.md` explicitly requires both stay disabled outside tightly scoped debugging.

## 30.3.5 The Connection Map to Other Subsystems

Hooks are the glue layer between subsystems. A connection map:

```
command system  ──/new /reset──→  session-memory hook   ──→  memory system
external world  ──Gmail Pub/Sub──→ gmail-watcher        ──→  agent turn + safety wrapping
gateway startup ──gateway:startup─→ boot-md             ──→  agent boot script
bootstrap       ──agent:bootstrap─→ bootstrap-extra-files ─→ context injection (mutable return)
any command     ──command:*──────→ command-logger       ──→  audit log
```

That map says everything about the hook system's role: **it doesn't implement features, it connects them.** Every hook is short; the value lies in the two things it joins.

***

## Section Summary

1. **`src/hooks/` carries two layers of mechanism**: the internal event bus (five types: command / session / agent / gateway / message) and user-installable hook packages (the `HOOK.md` + `handler.ts` directory convention).
2. **Hook packages' discovery and priority rules are exactly isomorphic to skills'** (four origins) — learn one set, use it twice.
3. **The `session-memory` hook implements "reset the session without forgetting"** — `/new` means clearing context, not forgetting content, and a short hook closes that gap without hard-coding memory logic into the command implementation.
4. **Triggering defaults to fire-and-forget** (a broken hook doesn't drag down the main flow), **but `agent:bootstrap`'s return value can modify the bootstrap file list** — **hooks are a legitimate context-injection channel**, worth knowing during a security audit.
5. **The Gmail watcher is the representative "external world → agent turn" entry point**; email bodies are entirely untrusted, hence the paired external-content detection and wrapping plus two `allowUnsafeExternalContent` switches required to stay off.
6. **The hook system's role is connection, not implementation**: every hook is short, and the value lies in the two things it joins.
