AI & Agents

OpenClaw Hooks: Automate Your Agent Gateway with Event-Driven Scripts

OpenClaw hooks are event-driven TypeScript scripts that run automatically when Gateway events fire, from new session commands to message receipt and context compaction. The system exposes 20+ event types across four categories, ships with five bundled hooks for session memory, command logging, and bootstrap injection, and resolves custom handlers through a four-level discovery hierarchy.

Fastio Editorial Team 14 min read
AI agent automating gateway tasks through event-driven hooks

How OpenClaw Hooks Work

Gartner projects that 40% of enterprise applications will embed task-specific AI agents by end of 2026, up from under 5% in 2024. Scaling from a handful of agents to production fleets makes manual orchestration impractical. OpenClaw hooks address this gap with 20+ event types that fire TypeScript handlers automatically, covering everything from session commands to gateway lifecycle transitions.

An OpenClaw hook is a TypeScript script that subscribes to one or more Gateway events through a HOOK.md metadata file. When a matching event fires, the Gateway executes the hook's handler function and passes a typed event object with context specific to what happened. No HTTP endpoint to configure, no polling interval to tune, no external scheduler. The handler runs, processes the event data, and returns.

The 20+ event types fall into four categories: command events (when users issue directives like /new or /reset), session events (context management and compaction), message events (the inbound/outbound message pipeline), and agent/gateway lifecycle events (startup, shutdown, restarts, and bootstrap). Each category targets a different phase of the agent interaction cycle. The full reference is in the OpenClaw hooks documentation.

Hooks run inside the Gateway process, which gives them direct access to session state and configuration without network overhead. That also means a slow hook can delay event processing, so handlers should stay focused and use async patterns for I/O-heavy work.

Hooks differ from other automation patterns you might already use. Webhooks push events to an external URL and depend on network availability. Cron jobs run on fixed schedules regardless of agent activity. Hooks fire the moment the event occurs, receive typed context data, and can modify the event's payload (as with bootstrap events). They complement rather than replace webhooks and scheduled tasks: use hooks for real-time reactions to agent events, webhooks for cross-system notifications, and cron jobs for periodic maintenance.

The practical result is that you can build automations that respond to agent activity without modifying the agent itself. Save session context on every reset. Log every command for compliance. Inject custom files during bootstrap. Notify a channel when compaction runs. Each of these patterns requires one HOOK.md file and one handler function.

The Four Event Categories

OpenClaw organizes its hook events into four categories. Each event passes a context object with properties specific to what triggered it. All events share a base structure with type, action, sessionKey, and timestamp fields. The context property carries the event-specific data described below.

Command Events

Command events fire when users issue Gateway directives:

  • command:new fires when a user starts a fresh session with /new
  • command:reset fires on /reset, which clears the current conversation
  • command:stop fires when /stop halts the agent
  • command is a catch-all that fires on any command, useful for universal logging

Command event contexts include sessionEntry (current session state), previousSessionEntry (for transitions), commandSource (where the command originated), workspaceDir, and cfg (Gateway configuration).

Session Events

Session events track context management operations:

  • session:compact:before fires before compaction summarizes conversation history, with messageCount and tokenCount in context
  • session:compact:after fires after compaction completes, adding compactedCount, summaryLength, tokensBefore, and tokensAfter
  • session:patch fires when session properties change, carrying the patch object and current sessionEntry

The compaction before/after pair is useful for tracking token usage over time. You can measure exactly how much context was compressed and log the compression ratio for each session.

Message Events

Message events cover the full pipeline from receipt to delivery:

  • message:received fires on inbound messages from any channel, with from, content, channelId, and metadata
  • message:transcribed fires after audio transcription completes, adding the transcript text and mediaPath
  • message:preprocessed fires after media and link preprocessing, with the final bodyForAgent text
  • message:sent fires on outbound delivery, with to, content, success status, and channelId

These events support message auditing, content filtering, or custom preprocessing without touching the agent's core logic.

Agent and Gateway Lifecycle Events

Lifecycle events handle infrastructure transitions:

  • agent:bootstrap fires before workspace bootstrap files are injected, with a mutable bootstrapFiles array and agentId
  • gateway:startup fires after channels start and hooks finish loading
  • gateway:shutdown fires when Gateway shutdown begins
  • gateway:pre-restart fires before an expected restart, with restartExpectedMs in context

The agent:bootstrap event deserves attention because bootstrapFiles is mutable. A hook subscribed to this event can add, remove, or modify the files injected into the agent's context at startup. This is how the bundled bootstrap-extra-files hook works.

Event flow through the four OpenClaw hook categories

Bundled Hooks That Ship with OpenClaw

OpenClaw ships five hooks that handle common automation needs. Each is enabled by default and runs without configuration, though most accept optional settings through the Gateway config.

session-memory

Events: command:new, command:reset

When you start a new session or reset the current one, session-memory extracts the last 15 user/assistant messages and saves them to a markdown file in the workspace memory directory. The filename includes the local date and a generated slug, building a searchable archive of past work sessions. The hook runs asynchronously so it does not delay the session transition.

You can enable LLM-generated slugs for better file naming by setting hooks.internal.entries.session-memory.llmSlug to true in your Gateway configuration.

bootstrap-extra-files

Events: agent:bootstrap

This hook injects additional markdown instruction files during agent startup. When a monorepo has AGENTS.md, TOOLS.md, or similar files spread across packages, bootstrap-extra-files loads them into the agent's context automatically. Configure it by adding glob patterns (like packages/*/AGENTS.md) to the hook's entry in the hooks.internal.entries configuration block. The hook recognizes eight basenames: AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, HEARTBEAT.md, BOOTSTRAP.md, and MEMORY.md.

command-logger

Events: command (all commands)

Every command issued to the Gateway gets logged as structured JSON to ~/.openclaw/logs/commands.log. You can grep through the file, pipe it to jq, or forward it to a centralized logging system. Useful for compliance auditing and debugging session issues after the fact.

compaction-notifier

Events: session:compact:before, session:compact:after

Sends visible chat notices when compaction starts and finishes. Without this hook, compaction happens silently, which can confuse users when the agent appears to lose context mid-conversation. The before notice includes message count and token count. The after notice reports how many messages were compacted and the resulting summary length.

boot-md

Events: gateway:startup

Runs the BOOT.md file when the Gateway starts. BOOT.md is a markdown instruction file that gets executed on every Gateway boot, useful for environment-specific setup or startup checks.

You can disable any bundled hook through the CLI or Gateway configuration without removing it.

How to Write a Custom OpenClaw Hook

A custom hook needs two files: HOOK.md for metadata and a handler file (typically handler.ts) for logic. Both go in the same directory, placed either under ~/.openclaw/hooks/ for a managed hook or under your workspace's hooks/ directory for workspace-scoped use.

The HOOK.md File

HOOK.md uses YAML frontmatter to declare the hook's name, description, and an openclaw metadata block that controls when and where the hook runs. The metadata block contains the event subscriptions, OS constraints, dependency requirements, and export type. For example, a hook that tracks compaction statistics would set its events list to session:compact:after, require node as a binary dependency, and list any needed environment variables.

Key fields in the metadata block:

  • events declares which event types this hook subscribes to
  • requires.bins lists binaries that must exist on the system before the hook loads
  • requires.anyBins means at least one listed binary must be present
  • requires.env lists environment variables that must be set
  • requires.config lists Gateway config paths that must exist
  • os restricts the hook to specific operating systems (darwin, linux, or both)
  • always set to true skips all eligibility checks, useful when you know requirements are met

The Handler Function

The handler exports a default async function that receives the event object:

export default async function handler(event) {
  if (event.action !== "compact:after") return;

const { tokensBefore, tokensAfter, compactedCount } = event.context;
  const reduction = Math.round(
    (1 - tokensAfter / tokensBefore) * 100
  );

console.log(
    `Compaction: ${compactedCount} messages, ${reduction}% reduction`
  );
}

Every event object includes type (the category), action (the specific event), sessionKey, and timestamp. The context property varies by event type and contains the fields described in the event categories section above.

For hooks that subscribe to multiple event types, check event.type and event.action before processing. The Gateway calls the handler for every subscribed event, so returning early from unrelated events keeps execution fast.

Testing and Deploying Custom Hooks

After writing your handler, place the hook directory in the correct location for your use case. Managed hooks go under ~/.openclaw/hooks/ and apply to every workspace on the machine. Workspace hooks go under your project's hooks/ directory for project-specific automation. Run openclaw hooks list to confirm the Gateway discovers the hook, and openclaw hooks check to verify all requirements are met before testing with live events. For hooks that generate output files like session logs or audit records, consider routing that output to a shared workspace so the data persists across deployments and stays searchable.

How to Configure and Manage OpenClaw Hooks

OpenClaw loads hooks from four locations, checked in order of ascending precedence:

  1. Bundled hooks ship with OpenClaw itself
  2. Plugin hooks come from installed ClawHub plugins
  3. Managed hooks live at ~/.openclaw/hooks/ and apply across all workspaces
  4. Workspace hooks live at your-workspace/hooks/ and apply only to that workspace

Higher-precedence hooks do not override lower-precedence hooks with the same name. Workspace hooks cannot replace a bundled, plugin, or managed hook that shares their identifier. If two hooks at the same level share a name, the first one loaded wins.

Workspace hooks are disabled by default. This prevents untrusted code from running automatically when you clone a repository. Enable them explicitly through the CLI or configuration after reviewing the hook source code.

CLI Commands

The openclaw hooks CLI provides five management commands:

  • openclaw hooks list shows all discovered hooks. Add --eligible to filter to runnable hooks, --verbose for full metadata, or --json for machine-readable output.
  • openclaw hooks info displays detailed information about a specific hook, including subscribed events, requirements, and status.
  • openclaw hooks check runs an eligibility summary across all hooks, reporting which have unmet dependencies.
  • openclaw hooks enable activates a disabled hook.
  • openclaw hooks disable deactivates a hook without removing its files.

Gateway Configuration

The hooks.internal config object controls hook behavior:

{
  "hooks": {
    "internal": {
      "enabled": true,
      "entries": {
        "session-memory": {
          "enabled": true,
          "env": { "CUSTOM_VAR": "value" }
        }
      },
      "load": {
        "extraDirs": ["/path/to/additional/hooks"]
      }
    }
  }
}

The entries object configures individual hooks by name. Set enabled to false to disable a specific hook. The env property passes custom environment variables to the hook's handler. The load.extraDirs array adds search paths beyond the default four locations.

Installing Third-Party Hooks

ClawHub plugins can bundle hooks alongside skills:

openclaw plugins install <package-name>

The installer accepts npm registry specs (package name, version, or dist-tag). Git URLs, local file paths, and semver ranges are rejected for security. Third-party installs run with --ignore-scripts, and OpenClaw validates integrity hashes on updates.

Configuration panel showing hook discovery hierarchy and enablement status
Fastio features

Give Your Agent Hooks a Persistent Workspace

generous storage with built-in semantic search and MCP access for your agent's session memories, command logs, and file handoffs. No credit card required.

Persistent Storage for Hook Output

Several bundled hooks write to the local filesystem. session-memory saves markdown files to the workspace memory directory. command-logger appends JSON to a log file. For a single developer working on one machine, local storage works fine. When agents run across multiple environments, or when compliance requires durable audit trails, you need the hook output to land somewhere persistent and searchable.

Local disk is the simplest option and works out of the box. The tradeoff is that hook output stays siloed on whatever machine runs the Gateway. If you redeploy the agent or switch hardware, that session history disappears unless you manually copy it.

Object storage services like S3 or Google Cloud Storage can serve as a persistence layer if you write a custom hook that uploads output on each event. This approach scales well but requires managing credentials, bucket policies, and a separate search solution to make the data queryable.

Fastio offers a workspace-based alternative. Instead of configuring a storage backend, agents get a workspace with generous storage, built-in semantic search, and an audit trail. A custom hook can upload session memory files or command logs to a Fastio workspace through the MCP server or REST API. Once files land in a workspace with Intelligence enabled, they are auto-indexed for semantic search, making past session context findable by meaning rather than filename. The audit trail tracks every file operation without additional infrastructure.

For teams running multiple agents, a shared workspace acts as a central repository for hook output. Each agent writes its session memories and logs to the same workspace. Human team members access the same files through the web UI, and the built-in AI chat can answer questions across the full archive. When an agent's work is ready for handoff, ownership transfer moves the workspace to a human account while the agent retains admin access.

The choice depends on your deployment scale. Single-developer setups work with local files. Teams that need searchable, shared hook output across agents and humans benefit from a workspace that handles storage, indexing, and access control together. Start with local storage and add a shared workspace when your agent count grows, since only the hook handler code needs to change.

Frequently Asked Questions

What are OpenClaw hooks?

OpenClaw hooks are event-driven TypeScript scripts that run automatically when specific Gateway events occur. They subscribe to events like session commands, message receipt, context compaction, and gateway lifecycle changes through a HOOK.md metadata file. When a subscribed event fires, the Gateway executes the hook's handler function with a typed context object containing event-specific data. Five hooks ship bundled with OpenClaw, covering session memory, file bootstrapping, command logging, compaction notices, and startup execution.

How do I create a custom OpenClaw hook?

Create a directory with two files: HOOK.md for metadata and handler.ts for logic. HOOK.md uses YAML frontmatter to declare the hook's name, subscribed events, OS requirements, and dependencies like required binaries or environment variables. handler.ts exports a default async function that receives the event object with type, action, sessionKey, timestamp, and a context property containing event-specific data. Place the directory under ~/.openclaw/hooks/ for a managed hook that applies across workspaces, or under your workspace's hooks/ directory for workspace-scoped use. Run openclaw hooks list to verify the Gateway discovers your new hook.

What events can OpenClaw hooks listen for?

OpenClaw exposes 20+ event types across four categories. Command events cover /new, /reset, /stop, and a general catch-all. Session events track compaction (before and after) and property patches. Message events handle received, transcribed, preprocessed, and sent messages. Lifecycle events cover agent bootstrap, gateway startup, shutdown, and pre-restart. Each event type passes context data specific to what triggered it, such as token counts for compaction events or channel IDs for message events.

How do OpenClaw hooks differ from cron jobs?

Hooks are event-driven: they run in direct response to a specific Gateway event with zero delay. Cron jobs run on a fixed time schedule regardless of agent activity. Hooks also receive typed context data about the triggering event (session state, message content, token counts), while a cron job would need to query for state changes independently. Use hooks when you need to react to agent activity in real time. Use cron jobs for periodic maintenance tasks unrelated to specific events.

Are workspace hooks enabled by default?

No. Workspace hooks (those in your-workspace/hooks/) are disabled by default to prevent untrusted code from executing when you clone a repository. You must enable them explicitly through the openclaw hooks enable CLI command or Gateway configuration after reviewing the hook source. Bundled, plugin, and managed hooks are enabled by default.

Can hooks modify what files an agent loads at startup?

Yes. The agent:bootstrap event provides a mutable bootstrapFiles array in its context object. A hook subscribed to this event can add, remove, or reorder the files injected into the agent's context during startup. The bundled bootstrap-extra-files hook uses this mechanism to load additional markdown instruction files (AGENTS.md, TOOLS.md, SOUL.md, and others) based on configurable glob patterns.

Related Resources

Fastio features

Give Your Agent Hooks a Persistent Workspace

generous storage with built-in semantic search and MCP access for your agent's session memories, command logs, and file handoffs. No credit card required.