Hooks
Hooks provide an extensible event-driven system for automating actions in response to agent commands and events. Hooks are automatically discovered from directories and can be managed via CLI commands, similar to how skills work in OpenClaw.Getting Oriented
Hooks are small scripts that run when something happens. There are two kinds:- Hooks (this page): run inside the Gateway when agent events fire, like
/new,/reset,/stop, or lifecycle events. - Webhooks: external HTTP webhooks that let other systems trigger work in OpenClaw. See Webhook Hooks or use
openclaw webhooksfor Gmail helper commands.
- Save a memory snapshot when you reset a session
- Keep an audit trail of commands for troubleshooting or compliance
- Trigger follow-up automation when a session starts or ends
- Write files into the agent workspace or call external APIs when events fire
Getting Started
Bundled Hooks
OpenClaw ships with five bundled hooks that are automatically discovered:- 💾 session-memory: Saves session context to your agent workspace (default
~/.openclaw/workspace/memory/) when you issue/new - 📔 session-journal: Writes a reflective LLM journal entry to the lane’s
journal/folder when an opted-in agent issues/newor/reset - 📎 bootstrap-extra-files: Injects additional workspace bootstrap files from configured glob/path patterns during
agent:bootstrap - 📝 command-logger: Logs all command events to
~/.openclaw/logs/commands.log - 🚀 boot-md: Runs
BOOT.mdwhen the gateway starts (requires internal hooks enabled)
Onboarding
During onboarding (openclaw onboard), you’ll be prompted to enable recommended hooks. The wizard automatically discovers eligible hooks and presents them for selection.
Hook Discovery
Hooks are automatically discovered from three directories (in order of precedence):- Workspace hooks:
<workspace>/hooks/(per-agent, highest precedence) - Managed hooks:
~/.openclaw/hooks/(user-installed, shared across workspaces) - Bundled hooks:
<openclaw>/dist/hooks/bundled/(shipped with OpenClaw)
Hook Packs (npm/archives)
Hook packs are standard npm packages that export one or more hooks viaopenclaw.hooks in
package.json. Install them with:
package.json:
HOOK.md and handler.ts (or index.ts).
Hook packs can ship dependencies; they will be installed under ~/.openclaw/hooks/<id>.
Each openclaw.hooks entry must stay inside the package directory after symlink
resolution; entries that escape are rejected.
Security note: openclaw hooks install installs dependencies with npm install --ignore-scripts
(no lifecycle scripts). Keep hook pack dependency trees “pure JS/TS” and avoid packages that rely
on postinstall builds.
Hook Structure
HOOK.md Format
TheHOOK.md file contains metadata in YAML frontmatter plus Markdown documentation:
Metadata Fields
Themetadata.openclaw object supports:
emoji: Display emoji for CLI (e.g.,"💾")events: Array of events to listen for (e.g.,["command:new", "command:reset"])export: Named export to use (defaults to"default")homepage: Documentation URLrequires: Optional requirementsbins: Required binaries on PATH (e.g.,["git", "node"])anyBins: At least one of these binaries must be presentenv: Required environment variablesconfig: Required config paths (e.g.,["workspace.dir"])os: Required platforms (e.g.,["darwin", "linux"])
always: Bypass eligibility checks (boolean)install: Installation methods (for bundled hooks:[{"id":"bundled","kind":"bundled"}])
Handler Implementation
Thehandler.ts file exports a HookHandler function:
Event Context
Each event includes:Event Types
Command Events
Triggered when agent commands are issued:command: All command events (general listener)command:new: When/newcommand is issuedcommand:reset: When/resetcommand is issuedcommand:stop: When/stopcommand is issued
Agent Events
agent:bootstrap: Before workspace bootstrap files are injected (hooks may mutatecontext.bootstrapFiles)
agent:bootstrap receives context.workspaceLane only when lane resolution
is allowed for that bootstrap pass. context.workspaceDir is the effective workspace. Use
context.workspaceLane.personaWorkspaceDir when a hook deliberately needs the shared persona
workspace. See Workspace Lanes.
Gateway Events
Triggered when the gateway starts:gateway:startup: After channels start and hooks are loaded
Message Events
Triggered when messages are received or sent:message: All message events (general listener)message:received: When an inbound message is received from any channel. Fires early in processing before media understanding. Content may contain raw placeholders like<media:audio>for media attachments that haven’t been processed yet.message:transcribed: When a message has been fully processed, including audio transcription and link understanding. At this point,transcriptcontains the full transcript text for audio messages. Use this hook when you need access to transcribed audio content.message:preprocessed: Fires for every message after all media + link understanding completes, giving hooks access to the fully enriched body (transcripts, image descriptions, link summaries) before the agent sees it.message:sent: When an outbound message is successfully sent
Message Event Context
Message events include rich context about the message:Example: Message Logger Hook
Tool Result Hooks (Plugin API)
These hooks are not event-stream listeners; they let plugins synchronously adjust tool results before WednesdayAI persists them.tool_result_persist: transform tool results before they are written to the session transcript. Must be synchronous; return the updated tool result payload orundefinedto keep it as-is. See Agent Loop.
Plugin API Hooks (api.on)
Plugin hooks registered via api.on(hookName, handler) intercept the agent pipeline at specific points. Unlike the file-based hook system above, these hooks are registered in code inside a plugin’s register or activate function and are typed end-to-end.
Hook event reference
Runtime and turn identity context
Most plugin API hooks receive optional nested identity objects when WednesdayAI has real identity for that point in the lifecycle:turn.turnId is the same stable string value as runId.
The value is minted before message_received on normal inbound dispatch, then
carried by value through later hooks. Do not depend on the same object reference
being reused across hooks.
Important boundaries:
conversationIdremains the legacy channel conversation id. It is an alias forchannelConversationId, never forproviderConversationId.providerConversationIdis opaque provider/cache identity. It is safe to store as an opaque correlation key, but plugins must not try to reverse or derive it.- Early hooks may not have
sessionIdorsessionKey; WednesdayAI omits those fields rather than fabricating session identity. - Public hook contexts do not expose raw
identityLinks. Usectx.runtimeIdentity.canonicalIdentity,ctx.runtimeIdentity.senderIsOwner, orapi.runtime.identity.resolveCanonicalIdentity(...)for canonical sender resolution.
turnId, so dedupe with the entry or cursor
identity as well:
context.collect, context.project,
context.prune, and storage.afterAppend) use ContextLifecycleContext. That
context includes sessionId, sessionKey, runId, storage cursor data when
available, sender identity fields, and the same optional runtimeIdentity and
turn objects. Use context.collect for context contributions and
storage.afterAppend for background capture or extraction queues.
model_call_ended carries the completed runId and receives a context whose
turn.turnId is aligned to that runId, so usage and provider metadata can be
joined back to the same turn.
Tool lifecycle hooks also receive foreground identity when it exists. In
particular, the production agent tool wrapper passes runtimeIdentity and
turn through to before_tool_call, so authorization, audit, and dedupe logic
can use the same SDK-owned identity fields before and after a tool executes.
PluginHookAgentContext
The shared context passed to all agent-lifecycle hooks:
trigger and channelId are included in every agent-context hook. Use them to gate logic per channel or trigger type — for example, only apply an output transform for channelId === "telegram" messages triggered by a user.
transform_llm_input
Fires immediately before the messages array is sent to the LLM. Use it to inject additional context, redact sensitive fields, or reorder messages.
{ messages: [...] } to replace the array, or return nothing to keep the current state.
Example — append a confidentiality reminder to the system prompt for every LLM call:
transform_llm_output
Fires after the LLM returns its response, before the reply is delivered to the user. Use it to filter language, redact patterns, or append standard disclaimers.
before_prompt_build
Fires after session messages are loaded and the prompt is about to be assembled. Use it to inspect or modify the system prompt, or inject context.
systemPrompt field on the event is read-only context. To modify it, return { systemPrompt: "..." } in your result.
prependContext wrapping: OpenClaw prepends the returned string directly before the user prompt without any automatic XML wrapping. If you want the model to treat the injected text as a system context rather than user-authored input, wrap it yourself:
Future Events
Planned event types:session:start: When a new session beginssession:end: When a session endsagent:error: When an agent encounters an error
Creating Custom Hooks
1. Choose Location
- Workspace hooks (
<workspace>/hooks/): Per-agent, highest precedence - Managed hooks (
~/.openclaw/hooks/): Shared across workspaces
2. Create Directory Structure
3. Create HOOK.md
4. Create handler.ts
5. Enable and Test
Configuration
New Config Format (Recommended)
Per-Hook Configuration
Hooks can have custom configuration:Extra Directories
Load hooks from additional directories:Legacy Config Format (Still Supported)
The old config format still works for backwards compatibility:module must be a workspace-relative path. Absolute paths and traversal outside the workspace are rejected.
Migration: Use the new discovery-based system for new hooks. Legacy handlers are loaded after directory-based hooks.
CLI Commands
List Hooks
Hook Information
Check Eligibility
Enable/Disable
Bundled hook reference
session-memory
Saves session context to memory when you issue/new.
Events: command:new
Requirements: workspace.dir must be configured
Output: <workspace>/memory/YYYY-MM-DD-slug.md (defaults to ~/.openclaw/workspace)
What it does:
- Uses the pre-reset session entry to locate the correct transcript
- Extracts the last 15 lines of conversation
- Uses LLM to generate a descriptive filename slug
- Saves session metadata to a dated memory file
2026-01-16-143045-vendor-pitch.md2026-01-16-143045-api-design.md2026-01-16-143045-journal.md(fallback when slug generation fails or session has no content)
bootstrap-extra-files
Injects additional bootstrap files (for example monorepo-localAGENTS.md / TOOLS.md) during agent:bootstrap.
Events: agent:bootstrap
Requirements: workspace.dir must be configured
Output: No files written; bootstrap context is modified in-memory only.
Config:
- Paths are resolved relative to workspace.
- Files must stay inside workspace (realpath-checked).
- Only recognized bootstrap basenames are loaded.
- Subagent allowlist is preserved (
AGENTS.mdandTOOLS.mdonly).
command-logger
Logs all command events to a centralized audit file. Events:command
Requirements: None
Output: ~/.openclaw/logs/commands.log
What it does:
- Captures event details (command action, timestamp, session key, sender ID, source)
- Appends to log file in JSONL format
- Runs silently in the background
boot-md
RunsBOOT.md when the gateway starts (after channels start).
Internal hooks must be enabled for this to run.
Events: gateway:startup
Requirements: workspace.dir must be configured
What it does:
- Reads
BOOT.mdfrom your workspace - Runs the instructions via the agent runner
- Sends any requested outbound messages via the message tool
session-journal
Writes a reflective LLM journal entry when an opted-in agent’s session resets. Events:command:new, command:reset
Requirements: opt-in per agent via sessionJournal.enabled: true. workspace.dir is optional — falls back to ~/.openclaw/workspace when not set.
Output: <effectiveWorkspaceDir>/journal/YYYY-MM-DD-HHMMss-<slug>.md
When workspaceLane is in context (multi-user mode), effectiveWorkspaceDir is the lane-local directory. Otherwise it falls back to the agent’s configured workspace.
What it does:
- Reads the previous session transcript (JSONL) before it is cleared
- Extracts user/assistant turns from the transcript
- Calls the LLM to produce a reflective journal entry (patient notes, coaching notes, or a custom prompt)
- Writes a dated Markdown file; the filename slug is derived from the first heading in the LLM output
- If the LLM call fails or there is no session content, writes a header-only stub so the reset event is still recorded
openclaw.json:
Filename examples:
2026-06-21-143045-vendor-onboarding-session.md2026-06-21-143045-anxiety-management-techniques.md2026-06-21-143045-journal.md(fallback when slug generation fails or session has no content)
/new or /reset. Sessions that end without a reset command (process exit, connection drop, idle timeout) do not produce a journal entry.
Enable:
Best Practices
Keep Handlers Fast
Hooks run during command processing. Keep them lightweight:Handle Errors Gracefully
Always wrap risky operations:Filter Events Early
Return early if the event isn’t relevant:Use Specific Event Keys
Specify exact events in metadata when possible:Debugging
Enable Hook Logging
The gateway logs hook loading at startup:Check Discovery
List all discovered hooks:Check Registration
In your handler, log when it’s called:Verify Eligibility
Check why a hook isn’t eligible:Testing
Gateway Logs
Monitor gateway logs to see hook execution:Test Hooks Directly
Test your handlers in isolation:Architecture
Core Components
src/hooks/types.ts: Type definitionssrc/hooks/workspace.ts: Directory scanning and loadingsrc/hooks/frontmatter.ts: HOOK.md metadata parsingsrc/hooks/config.ts: Eligibility checkingsrc/hooks/hooks-status.ts: Status reportingsrc/hooks/loader.ts: Dynamic module loadersrc/cli/hooks-cli.ts: CLI commandssrc/gateway/server-startup.ts: Loads hooks at gateway startsrc/auto-reply/reply/commands-core.ts: Triggers command events
Discovery Flow
Event Flow
Troubleshooting
Hook Not Discovered
-
Check directory structure:
-
Verify HOOK.md format:
-
List all discovered hooks:
Hook Not Eligible
Check requirements:- Binaries (check PATH)
- Environment variables
- Config values
- OS compatibility
Hook Not Executing
-
Verify hook is enabled:
- Restart your gateway process so hooks reload.
-
Check gateway logs for errors:
Handler Errors
Check for TypeScript/import errors:Migration Guide
From Legacy Config to Discovery
Before:-
Create hook directory:
-
Create HOOK.md:
-
Update config:
-
Verify and restart your gateway process:
- Automatic discovery
- CLI management
- Eligibility checking
- Better documentation
- Consistent structure