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

# 30.1 Internal Hooks (Gateway Hooks)

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

***

OpenClaw's Hook System is an event-driven extension mechanism that allows injecting custom logic at critical nodes in the Agent lifecycle without modifying core code. This section focuses on **Internal Hooks**, a hook system that runs inside the Gateway process through event registration and triggering.

> **Sidebar**: Hook is a classic pattern in software engineering. It reserves extension points at certain "nodes" in the program execution flow, allowing external code to "hook" their own logic at these nodes. React's lifecycle methods, Git's pre-commit/post-commit hooks, and Webpack's tapable plugin system are all different implementations of the hook pattern. OpenClaw's hooks adopt a **Pub/Sub variant**—handlers register to listen for event keys, and when an event is triggered, registered handlers are called in registration order.

***

## 30.1.1 Hook Loader (`src/hooks/loader.ts`)

### Loading Process Overview

`loadInternalHooks` is the entry point of the hook system. It is called when the Gateway starts, responsible for discovering, filtering, importing, and registering all internal hook handlers.

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

export async function loadInternalHooks(
  cfg: OpenClawConfig,
  workspaceDir: string,
): Promise<number> {
  // Pre-check: is the hook system enabled?
  if (!cfg.hooks?.internal?.enabled) {
    return 0;
  }

  let loadedCount = 0;

  // Phase 1: Discover hooks from directory (new system)
  const hookEntries = loadWorkspaceHookEntries(workspaceDir, { config: cfg });
  const eligible = hookEntries.filter(entry =>
    shouldIncludeHook({ entry, config: cfg })
  );

  for (const entry of eligible) {
    // Skip hooks explicitly disabled in configuration
    const hookConfig = resolveHookConfig(cfg, entry.hook.name);
    if (hookConfig?.enabled === false) continue;

    // Dynamic import of handler module (with cache busting)
    const url = pathToFileURL(entry.hook.handlerPath).href;
    const mod = await import(`${url}?t=${Date.now()}`);

    // Get the exported handler function
    const exportName = entry.metadata?.export ?? "default";
    const handler = mod[exportName];

    // Register handler for each event declared in metadata
    const events = entry.metadata?.events ?? [];
    for (const event of events) {
      registerInternalHook(event, handler);
    }
    loadedCount++;
  }

  // Phase 2: Load legacy configuration handlers (backward compatibility)
  const handlers = cfg.hooks.internal.handlers ?? [];
  for (const handlerConfig of handlers) {
    const modulePath = path.isAbsolute(handlerConfig.module)
      ? handlerConfig.module
      : path.join(process.cwd(), handlerConfig.module);
    const mod = await import(pathToFileURL(modulePath).href);
    registerInternalHook(handlerConfig.event, mod[handlerConfig.export ?? "default"]);
    loadedCount++;
  }

  return loadedCount;
}
```

The entire loading process is divided into two phases:

| Phase   | Source              | Mechanism                                                                    | Description                                 |
| ------- | ------------------- | ---------------------------------------------------------------------------- | ------------------------------------------- |
| Phase 1 | Directory Discovery | `loadWorkspaceHookEntries` → `shouldIncludeHook` filter → dynamic `import()` | New system, based on HOOK.md file discovery |
| Phase 2 | Configuration File  | `cfg.hooks.internal.handlers` array                                          | Legacy system, backward compatible          |

Two key details are worth noting:

1. **Cache Busting**: The dynamically imported URL has a `?t=${Date.now()}` timestamp parameter appended, ensuring that each load retrieves the latest version of the handler code and is not affected by Node.js's module cache.
2. **Dual Disable Checks**: First, `shouldIncludeHook` performs eligibility filtering, then `hookConfig?.enabled === false` performs configuration-level disabling. Two gates ensure only eligible and enabled hooks are loaded.

### Hook Discovery: Four-Source Merge

Hook discovery is similar to the skill system (Chapter 29), loading and merging from four directory sources:

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

function loadHookEntries(workspaceDir: string, opts?): HookEntry[] {
  const bundledHooksDir = opts?.bundledHooksDir ?? resolveBundledHooksDir();
  const managedHooksDir = opts?.managedHooksDir ?? path.join(CONFIG_DIR, "hooks");
  const workspaceHooksDir = path.join(workspaceDir, "hooks");
  const extraDirs = opts?.config?.hooks?.internal?.load?.extraDirs ?? [];

  // Load by priority from low to high: extra < bundled < managed < workspace
  const merged = new Map<string, Hook>();
  for (const hook of extraHooks)    merged.set(hook.name, hook);
  for (const hook of bundledHooks)  merged.set(hook.name, hook);
  for (const hook of managedHooks)  merged.set(hook.name, hook);
  for (const hook of workspaceHooks) merged.set(hook.name, hook);

  return Array.from(merged.values()).map(hook => ({
    hook,
    frontmatter: parseFrontmatter(readHookMd(hook.filePath)),
    metadata: resolveOpenClawMetadata(frontmatter),
    invocation: resolveHookInvocationPolicy(frontmatter),
  }));
}
```

| Source    | Directory                      | Source ID            | Priority |
| --------- | ------------------------------ | -------------------- | -------- |
| Extra     | Configured extra directories   | `openclaw-workspace` | Lowest   |
| Bundled   | `<package>/src/hooks/bundled/` | `openclaw-bundled`   | Low      |
| Managed   | `~/.openclaw/hooks/`           | `openclaw-managed`   | High     |
| Workspace | `<workspace>/hooks/`           | `openclaw-workspace` | Highest  |

Hooks with the same name follow the **higher priority overrides lower priority** principle—if the workspace has a `session-memory` hook, it will override the built-in hook with the same name.

### Hook File Structure

Each hook is a directory containing at least two files:

```
my-hook/
├── HOOK.md          # Hook description file (Front Matter + documentation)
└── handler.ts       # Hook handler (exports a function as default)
```

The Front Matter in `HOOK.md` defines the hook's metadata:

```markdown
---
name: session-memory
description: "Save session context to memory when /new command is issued"
metadata:
  {
    "openclaw":
      {
        "emoji": "...",
        "events": ["command:new"],
        "requires": { "config": ["workspace.dir"] },
        "install": [{ "id": "bundled", "kind": "bundled" }],
      },
  }
---
```

`resolveOpenClawMetadata` is responsible for parsing the `openclaw` object under the `metadata` field in Front Matter, extracting `OpenClawHookMetadata`:

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

export type OpenClawHookMetadata = {
  always?: boolean;         // Whether to bypass all pre-checks
  hookKey?: string;         // Configuration key name (defaults to hook name)
  emoji?: string;           // Display icon
  events: string[];         // List of subscribed events, e.g., ["command:new"]
  export?: string;          // Handler export name (default "default")
  os?: string[];            // Operating system requirements
  requires?: {
    bins?: string[];        // Required binary commands
    anyBins?: string[];     // At least one of these commands
    env?: string[];         // Required environment variables
    config?: string[];      // Configuration paths that must be truthy
  };
  install?: HookInstallSpec[];  // Installation options
};
```

### Eligibility Filtering

`shouldIncludeHook` performs multi-dimensional eligibility checks on each hook:

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

export function shouldIncludeHook(params: {
  entry: HookEntry;
  config?: OpenClawConfig;
}): boolean {
  const { entry, config } = params;

  // 1. Hooks managed by plugins are not controlled by user configuration
  // 2. Explicitly disabled in configuration → exclude
  if (!pluginManaged && hookConfig?.enabled === false) return false;

  // 3. Operating system mismatch → exclude
  if (osList.length > 0 && !osList.includes(process.platform)) return false;

  // 4. always flag → bypass all subsequent checks
  if (entry.metadata?.always === true) return true;

  // 5. All required binary commands exist?
  for (const bin of requiredBins) {
    if (!hasBinary(bin)) return false;
  }

  // 6. At least one optional command exists?
  if (requiredAnyBins.length > 0 && !requiredAnyBins.some(hasBinary)) return false;

  // 7. Required environment variables exist? (env in config also counts)
  for (const envName of requiredEnv) {
    if (!process.env[envName] && !hookConfig?.env?.[envName]) return false;
  }

  // 8. Required configuration paths are truthy?
  for (const configPath of requiredConfig) {
    if (!isConfigPathTruthy(config, configPath)) return false;
  }

  return true;
}
```

This filtering mechanism is highly symmetric with the skill system's `shouldIncludeSkill` (Section 29.1)—the same design philosophy, with hooks having the same check dimensions available as skills. This means hooks can declare "I only run on macOS", "I need the `ffmpeg` command", "I need the `OPENAI_API_KEY` environment variable", and other prerequisites.

***

## 30.1.2 Hook Installation (`src/hooks/install.ts`)

### Installation Sources

OpenClaw supports three hook installation sources:

| Entry Function            | Source       | How It Works                                          |
| ------------------------- | ------------ | ----------------------------------------------------- |
| `installHooksFromPath`    | Local path   | Directory → direct copy; Archive → extract then copy  |
| `installHooksFromArchive` | Archive file | `.tar.gz` / `.zip` → extract to temp directory → copy |
| `installHooksFromNpmSpec` | npm package  | `npm pack` download → install as archive              |

All paths ultimately converge to two core functions:

```
installHooksFromPath ─┬─→ installHookPackageFromDir (hook package with package.json)
                      └─→ installHookFromDir (single hook directory)

installHooksFromArchive ──→ Extract ──→ Same two paths above
installHooksFromNpmSpec ──→ npm pack ──→ installHooksFromArchive
```

### Hook Package vs Single Hook

OpenClaw distinguishes two installation granularities:

**Single Hook**—a directory containing `HOOK.md` + `handler.ts`:

```
my-hook/
├── HOOK.md
└── handler.ts
```

**Hook Package**—an npm-style package that can contain multiple hooks:

```
my-hook-pack/
├── package.json        # Contains "openclaw": { "hooks": ["./hook-a", "./hook-b"] }
├── hook-a/
│   ├── HOOK.md
│   └── handler.ts
└── hook-b/
    ├── HOOK.md
    └── handler.ts
```

In `package.json`, the `openclaw.hooks` array declares the hook subdirectories included:

```json
{
  "name": "my-hook-pack",
  "version": "1.0.0",
  "openclaw": {
    "hooks": ["./hook-a", "./hook-b"]
  }
}
```

### Installation Process

Taking `installHookPackageFromDir` as an example, the complete process of installing a hook package:

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

async function installHookPackageFromDir(params): Promise<InstallHooksResult> {
  // 1. Read and validate package.json
  const manifest = await readJsonFile<HookPackageManifest>(manifestPath);
  const hookEntries = await ensureOpenClawHooks(manifest);

  // 2. Determine hook package ID (take package.json name, remove scope)
  const hookPackId = unscopedPackageName(manifest.name) || path.basename(packageDir);

  // 3. Resolve safe installation target path (prevent path traversal)
  const targetDir = resolveSafeInstallDir(hooksDir, hookPackId);

  // 4. Validate all sub-hook directories (HOOK.md + handler exist)
  for (const entry of hookEntries) {
    await validateHookDir(path.resolve(packageDir, entry));
  }

  // 5. If update mode, backup old version first
  if (mode === "update" && await fileExists(targetDir)) {
    backupDir = `${targetDir}.backup-${Date.now()}`;
    await fs.rename(targetDir, backupDir);
  }

  // 6. Copy to target directory
  await fs.cp(packageDir, targetDir, { recursive: true });

  // 7. Install npm dependencies (if any)
  if (Object.keys(manifest.dependencies ?? {}).length > 0) {
    await runCommandWithTimeout(["npm", "install", "--omit=dev", "--silent"], {
      cwd: targetDir,
    });
  }

  // 8. Clean up backup
  if (backupDir) await fs.rm(backupDir, { recursive: true, force: true });

  return { ok: true, hookPackId, hooks: resolvedHooks, targetDir };
}
```

### Path Traversal Protection

The installation path calculation has built-in path traversal detection:

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

function resolveSafeInstallDir(hooksDir: string, hookId: string) {
  const targetDir = path.join(hooksDir, safeDirName(hookId));
  const resolvedBase = path.resolve(hooksDir);
  const resolvedTarget = path.resolve(targetDir);
  const relative = path.relative(resolvedBase, resolvedTarget);

  // If relative path starts with ".." or is absolute, traversal is detected
  if (!relative || relative === ".." ||
      relative.startsWith(`..${path.sep}`) ||
      path.isAbsolute(relative)) {
    return { ok: false, error: "path traversal detected" };
  }
  return { ok: true, path: targetDir };
}
```

> **Sidebar**: Path Traversal is a common security vulnerability where attackers construct paths containing `../` to access files outside the target directory. For example, when a hook name is `../../etc`, the concatenated path might point to system directories. OpenClaw uses `path.relative()` to calculate the relative path, ensuring the target always stays within the hook installation base directory.

### Update and Rollback

Hook updates use a **backup-replace-cleanup** strategy:

1. If the target directory exists, rename it to `<dir>.backup-<timestamp>`
2. Copy the new version to the target directory
3. If copying or `npm install` fails, automatically restore from backup
4. Delete backup after success

This strategy guarantees update atomicity—there's no intermediate state where "old version is deleted but new version installation failed".

***

## 30.1.3 Built-in Hooks (`src/hooks/bundled/`)

OpenClaw includes four built-in hooks covering typical scenarios from startup initialization to session management:

| Hook Name               | Subscribed Event  | Function                                                         | Prerequisites          |
| ----------------------- | ----------------- | ---------------------------------------------------------------- | ---------------------- |
| `boot-md`               | `gateway:startup` | Run `BOOT.md` bootstrap checklist when Gateway starts            | `workspace.dir` config |
| `session-memory`        | `command:new`     | Save session to memory file when `/new` is executed              | `workspace.dir` config |
| `command-logger`        | `command`         | Log all command events to audit log                              | None                   |
| `bootstrap-extra-files` | `agent:bootstrap` | Inject additional workspace bootstrap files by glob/path pattern | `workspace.dir` config |

> **Historical note**: earlier versions shipped a fifth bundled hook, `soul-evil`, which could swap the injected content of `SOUL.md` for `SOUL_EVIL.md` at runtime. It was **removed as a security problem in `v2026.2.12`** (`CHANGELOG.md`: `Security: remove bundled soul-evil hook. (#14757)`). If you encounter it in older articles or configs, that information is stale — **§32.5.2 explains why a "novelty feature" was judged a security problem**, and it's one of the most instructive cautionary cases in this book.

### boot-md: Startup Bootstrap

`boot-md` is the simplest built-in hook—it listens to the `gateway:startup` event and automatically runs the workspace's `BOOT.md` bootstrap file when the Gateway starts:

```typescript
// src/hooks/bundled/boot-md/handler.ts

const runBootChecklist: HookHandler = async (event) => {
  if (event.type !== "gateway" || event.action !== "startup") return;

  const context = event.context as BootHookContext;
  if (!context.cfg || !context.workspaceDir) return;

  // Execute BOOT.md bootstrap checklist
  const deps = context.deps ?? createDefaultDeps();
  await runBootOnce({ cfg: context.cfg, deps, workspaceDir: context.workspaceDir });
};
```

The value of this hook lies in automation—users can place a `BOOT.md` file in the workspace defining preparation work to execute when the Gateway starts (such as checking dependencies, initializing databases, pulling latest configuration, etc.), and it will be automatically executed every time the Gateway restarts.

### session-memory: Session Memory Saving

`session-memory` is the most complex of the four built-in hooks. When a user executes the `/new` command (starting a new session), it saves the **old session content about to be discarded** to the memory directory:

```typescript
// src/hooks/bundled/session-memory/handler.ts (simplified)

const saveSessionToMemory: HookHandler = async (event) => {
  if (event.type !== "command" || event.action !== "new") return;

  const cfg = event.context.cfg as OpenClawConfig;
  const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
  const memoryDir = path.join(workspaceDir, "memory");

  // 1. Read the most recent N messages from session file
  const messageCount = hookConfig?.messages ?? 15;
  const sessionContent = await getRecentSessionContent(sessionFile, messageCount);

  // 2. Use LLM to generate descriptive filename
  let slug = await generateSlugViaLLM({ sessionContent, cfg });
  if (!slug) slug = formatTimeSlug(event.timestamp);  // Fallback to timestamp

  // 3. Write Markdown memory file
  const filename = `${dateStr}-${slug}.md`;  // e.g., 2026-01-16-api-design.md
  await fs.writeFile(path.join(memoryDir, filename), buildMarkdownEntry());
};
```

The process has three steps:

1. **Extract Session Content**: Parse the most recent N user/assistant messages from the JSONL-format session file (skipping command messages starting with `/`).
2. **LLM Generate Filename**: Call the configured LLM provider to generate a 1-2 word filename alias (slug) based on session content, such as `vendor-pitch` or `api-design`. This is implemented through the `generateSlugViaLLM` function, which launches a temporary embedded Agent to complete this small task. If the LLM call fails or in test environments, it falls back to timestamp format `HHMM`.
3. **Save Memory File**: Create a `YYYY-MM-DD-slug.md` file in the `<workspace>/memory/` directory, with content including session key, session ID, source information, and conversation summary.

### command-logger: Command Audit Log

`command-logger` subscribes to all `command` type events (note: not specific `command:new`, but wildcard `command`), appending each command execution to a log file in JSONL format:

```typescript
// src/hooks/bundled/command-logger/handler.ts (simplified)

const logCommand: HookHandler = async (event) => {
  if (event.type !== "command") return;

  const logFile = path.join(stateDir, "logs", "commands.log");
  const logLine = JSON.stringify({
    timestamp: event.timestamp.toISOString(),
    action: event.action,         // "new", "reset", "stop", etc.
    sessionKey: event.sessionKey,
    senderId: event.context.senderId ?? "unknown",
    source: event.context.commandSource ?? "unknown",
  }) + "\n";

  await fs.appendFile(logFile, logLine, "utf-8");
};
```

The log file is located at `~/.openclaw/logs/commands.log`, with each line being an independent JSON object, convenient for analysis with tools like `jq`:

```json
{"timestamp":"2026-01-16T14:30:00.000Z","action":"new","sessionKey":"agent:main:main","senderId":"+1234567890","source":"telegram"}
```

### bootstrap-extra-files: Injecting Additional Bootstrap Files

The fourth built-in hook solves a very practical need: **the default bootstrap files are a fixed handful** (`AGENTS.md` / `SOUL.md` / `IDENTITY.md` / `USER.md` / `TOOLS.md`), **but you may want the agent to see something else every time** — the project's `README.md`, an API convention, your team's coding standards.

Its declaration (`src/hooks/bundled/bootstrap-extra-files/HOOK.md`):

```markdown
---
name: bootstrap-extra-files
description: "Inject additional workspace bootstrap files via glob/path patterns"
metadata:
  { "openclaw":
      { "emoji": "📎",
        "events": ["agent:bootstrap"],
        "requires": { "config": ["workspace.dir"] },
        "install": [{ "id": "bundled", "kind": "bundled", ... }] } }
---
```

The core of the implementation (`handler.ts`) is a three-level fallback for config resolution:

```typescript
function resolveExtraBootstrapPatterns(hookConfig: Record<string, unknown>): string[] {
  const fromPaths = normalizeStringArray(hookConfig.paths);
  if (fromPaths.length > 0) {
    return fromPaths;
  }
  const fromPatterns = normalizeStringArray(hookConfig.patterns);
  if (fromPatterns.length > 0) {
    return fromPatterns;
  }
  return normalizeStringArray(hookConfig.files);
}
```

It accepts `paths`, `patterns`, or `files`, taking whichever is non-empty first. **That's a pragmatic concession to "users won't remember what the config key is called"** — all three names are reasonable, so rather than insisting in the docs that it must be `paths`, it accepts all of them.

Loading goes through `loadExtraBootstrapFilesWithDiagnostics`, and crucially **reuses `filterBootstrapFilesForSession`** (§28.5.2) — so injected extra files obey the same "subagent and cron sessions get only the minimal bootstrap set" rule and can't bypass the privacy boundary.

> It's a small hook, but it demonstrates correct extension-point usage: **it adds no new mechanism, it just opens an input hole in an existing one** (bootstrap file loading), and it reuses all of the original filtering rules.

***

## 30.1.4 `agent:bootstrap` Hook

`agent:bootstrap` is the most powerful event in the internal hook system—it triggers before the Agent builds the system prompt, allowing hooks to modify the Agent's bootstrap file list.

### Event Structure

```typescript
// src/hooks/internal-hooks.ts

export type AgentBootstrapHookContext = {
  workspaceDir: string;                    // Workspace directory
  bootstrapFiles: WorkspaceBootstrapFile[]; // Bootstrap file list (modifiable)
  cfg?: OpenClawConfig;                    // Global configuration
  sessionKey?: string;                     // Session key
  sessionId?: string;                      // Session ID
  agentId?: string;                        // Agent ID
};

export type AgentBootstrapHookEvent = InternalHookEvent & {
  type: "agent";
  action: "bootstrap";
  context: AgentBootstrapHookContext;
};
```

Unlike other events, the `context` in `agent:bootstrap` contains a `bootstrapFiles` array—this is the list of workspace files used by the Agent when building the system prompt (such as `SOUL.md`, `AGENTS.md`, `BOOT.md`, etc.). Hooks can **directly modify** this array, thus affecting Agent behavior.

### Type Guard

Since `InternalHookEvent.context` has a broad type of `Record<string, unknown>`, OpenClaw provides type guard functions to safely narrow the type:

```typescript
// src/hooks/internal-hooks.ts

export function isAgentBootstrapEvent(
  event: InternalHookEvent
): event is AgentBootstrapHookEvent {
  if (event.type !== "agent" || event.action !== "bootstrap") return false;
  const context = event.context as Partial<AgentBootstrapHookContext>;
  if (typeof context.workspaceDir !== "string") return false;
  return Array.isArray(context.bootstrapFiles);
}
```

> **Sidebar**: TypeScript's **Type Guard** is a mechanism to narrow types through runtime checks. `event is AgentBootstrapHookEvent` is a **Type Predicate**—when the function returns `true`, the TypeScript compiler narrows the type of `event` from `InternalHookEvent` to `AgentBootstrapHookEvent`, allowing safe access to fields like `context.bootstrapFiles`.

### Practical Application: bootstrap-extra-files Injection

`bootstrap-extra-files` is a typical consumer of the `agent:bootstrap` event:

```typescript
// src/hooks/bundled/bootstrap-extra-files/handler.ts (simplified)

const bootstrapExtraFilesHook: HookHandler = async (event) => {
  if (!isAgentBootstrapEvent(event)) {
    return;
  }
  const context = event.context;
  const hookConfig = resolveHookConfig(context.cfg, HOOK_KEY);
  if (!hookConfig || hookConfig.enabled === false) {
    return;
  }
  const patterns = resolveExtraBootstrapPatterns(hookConfig);
  // load by glob/path, then apply the same session filtering as default bootstrap files
  const extra = await loadExtraBootstrapFilesWithDiagnostics({ ... });
  context.bootstrapFiles = filterBootstrapFilesForSession(
    [...context.bootstrapFiles, ...extra],
    context.sessionKey,
  );
};
```

Three key design points:

**1. It modifies the in-memory list, never disk.** The `context.bootstrapFiles` the hook receives is a **mutable** array reference — precisely where `agent:bootstrap` breaks the fire-and-forget semantics (§30.3.3). It affects only this request's system prompt construction.

**2. It reuses the session filtering rules.** That trailing `filterBootstrapFilesForSession` call isn't optional — it guarantees injected extra files obey the same "subagent and cron sessions get only the minimal bootstrap set" privacy boundary (§28.5.2).

> **A general requirement for extension points: new inputs must pass through all the original filters.** Skip one and the extension point becomes a back door around policy.

**3. It skips only on `enabled === false`.** Note the direction of the test: it is *not* "run only if `enabled === true`." **Unconfigured means active** (just with no patterns, so nothing is injected); only an explicit disable stops it. That way "added config but forgot `enabled: true`" doesn't silently do nothing.

***

## 30.1.5 Command Hooks: `/new`, `/reset`, `/stop`

### Event Model

The internal hook event system is based on a simple two-dimensional model: **type + action**.

```typescript
// src/hooks/internal-hooks.ts

// src/hooks/internal-hooks.ts:13
export type InternalHookEventType = "command" | "session" | "agent" | "gateway" | "message";

export interface InternalHookEvent {
  type: InternalHookEventType;    // Event type
  action: string;                  // Specific action
  sessionKey: string;              // Associated session key
  context: Record<string, unknown>; // Additional context
  timestamp: Date;                 // Timestamp
  messages: string[];              // Messages hooks can push back
}
```

### Registration and Triggering

When registering, you can subscribe to events at two granularities:

```typescript
// Subscribe to all command events (command:new, command:reset, command:stop, etc.)
registerInternalHook("command", myHandler);

// Only subscribe to /new command
registerInternalHook("command:new", myHandler);
```

When triggering, the system calls both types of subscribed handlers:

```typescript
// src/hooks/internal-hooks.ts

export async function triggerInternalHook(event: InternalHookEvent): Promise<void> {
  // Get type-level handlers (e.g., "command")
  const typeHandlers = handlers.get(event.type) ?? [];
  // Get action-level handlers (e.g., "command:new")
  const specificHandlers = handlers.get(`${event.type}:${event.action}`) ?? [];

  // Merge and execute in registration order
  for (const handler of [...typeHandlers, ...specificHandlers]) {
    try {
      await handler(event);
    } catch (err) {
      // Error isolation: one hook failure doesn't affect others
      console.error(`Hook error [${event.type}:${event.action}]:`, err.message);
    }
  }
}
```

This design has two important characteristics:

1. **Dual-layer Subscription**: `command` can capture all command events (like `command-logger`'s audit needs), while `command:new` only captures specific commands (like `session-memory`'s precise triggering).
2. **Error Isolation**: Each handler execution is wrapped in try/catch, so one hook throwing an exception doesn't interrupt other hooks. This is critical for production—a third-party hook bug shouldn't crash the entire command processing flow.

### Command Event Lifecycle

When a user executes the `/new` command, the system creates and triggers a command event:

```typescript
// System internal call (simplified)
const event = createInternalHookEvent(
  "command",     // type
  "new",         // action
  sessionKey,    // sessionKey
  {
    cfg,
    previousSessionEntry,  // Info about previous session
    commandSource: "telegram",
    senderId: "+1234567890",
  }
);

await triggerInternalHook(event);
```

For this event, the following hooks will be triggered:

| Hook             | Subscription Key | Match Method                        |
| ---------------- | ---------------- | ----------------------------------- |
| `command-logger` | `command`        | Type match (all commands trigger)   |
| `session-memory` | `command:new`    | Action match (only `/new` triggers) |

### Message Push-back

The `messages` array in `InternalHookEvent` is a bidirectional communication mechanism—hooks can push messages to this array, which will be returned to the user:

```typescript
// Hook handler can push back messages
const myHook: InternalHookHandler = async (event) => {
  event.messages.push("Session saved to memory/2026-01-16-api-design.md");
};
```

This mechanism allows hooks not only to perform background operations but also to provide execution results to users—although the built-in hooks choose to run silently (not pushing user-visible messages), this capability provides rich interaction space for custom hooks.

***

## Section Summary

1. **Internal Hooks** are OpenClaw's event-driven extension mechanism, based on a Pub/Sub pattern where handlers register to event keys and are called in registration order when events trigger.
2. **Hook Loading** has two phases: directory discovery (new system) and configuration handlers (legacy compatibility), loading from four sources (extra/bundled/managed/workspace) and merging by priority.
3. **Hook Installation** supports three sources (local path, archive file, npm package), with built-in path traversal protection and backup rollback mechanisms.
4. **Four built-in hooks** cover startup bootstrap (`boot-md`), session memory (`session-memory`), command audit (`command-logger`), and bootstrap-file injection (`bootstrap-extra-files`). The former fifth hook `soul-evil` was removed as a security problem in `v2026.2.12` (see §32.5.2).
5. **`agent:bootstrap` Event** is the most powerful extension point, allowing hooks to modify the bootstrap file list before system prompt construction, enabling dynamic control of Agent behavior.
6. **Event Model** uses type + action two-dimensional keys, supporting both type-level and action-level subscription granularities, with error isolation via try/catch ensuring system stability.
