> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wednesdayai.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Hooks

# 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 WednesdayAI.

## 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 WednesdayAI. See [Webhook Hooks](https://docs.wednesdayai.dev/next/users/automation/webhook.md) or use `wednesdayai webhooks` for Gmail helper commands.

Hooks can also be bundled inside plugins; see [Plugins](https://docs.wednesdayai.dev/next/users/tools/plugin.md#plugin-hooks).

Common uses:

* 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

If you can write a small TypeScript function, you can write a hook. Hooks are discovered automatically, and you enable or disable them via the CLI.

## Getting Started

### Bundled Hooks

WednesdayAI 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 `/new` or `/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.md` when the gateway starts (requires internal hooks enabled)

List available hooks:

```bash theme={"dark"}
wednesdayai hooks list
```

Enable a hook:

```bash theme={"dark"}
wednesdayai hooks enable session-memory
```

Check hook status:

```bash theme={"dark"}
wednesdayai hooks check
```

Get detailed information:

```bash theme={"dark"}
wednesdayai hooks info session-memory
```

### Onboarding

During onboarding (`wednesdayai 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):

1. **Workspace hooks**: `<workspace>/hooks/` (per-agent, highest precedence)
2. **Managed hooks**: `~/.openclaw/hooks/` (user-installed, shared across workspaces)
3. **Bundled hooks**: `<openclaw>/dist/hooks/bundled/` (shipped with WednesdayAI)

Managed hook directories can be either a **single hook** or a **hook pack** (package directory).

Each hook is a directory containing:

```text theme={"dark"}
my-hook/
├── HOOK.md          # Metadata + documentation
└── handler.ts       # Handler implementation
```

## Hook Packs (npm/archives)

Hook packs are standard npm packages that export one or more hooks via `openclaw.hooks` in
`package.json`. Install them with:

```bash theme={"dark"}
wednesdayai hooks install <path-or-spec>
```

Npm specs are registry-only (package name + optional version/tag). Git/URL/file specs are rejected.

Example `package.json`:

```json theme={"dark"}
{
  "name": "@acme/my-hooks",
  "version": "0.1.0",
  "openclaw": {
    "hooks": ["./hooks/my-hook", "./hooks/other-hook"]
  }
}
```

Each entry points to a hook directory containing `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: `wednesdayai 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

The `HOOK.md` file contains metadata in YAML frontmatter plus Markdown documentation:

```markdown theme={"dark"}
---
name: my-hook
description: "Short description of what this hook does"
homepage: https://docs.wednesdayai.dev/users/automation/hooks#my-hook
metadata:
  { "openclaw": { "emoji": "🔗", "events": ["command:new"], "requires": { "bins": ["node"] } } }
---

# My Hook

Detailed documentation goes here...

## What It Does

- Listens for `/new` commands
- Performs some action
- Logs the result

## Requirements

- Node.js must be installed

## Configuration

No configuration needed.
```

### Metadata Fields

The `metadata.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 URL
* **`requires`**: Optional requirements
  * **`bins`**: Required binaries on PATH (e.g., `["git", "node"]`)
  * **`anyBins`**: At least one of these binaries must be present
  * **`env`**: Required environment variables
  * **`config`**: 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

The `handler.ts` file exports a `HookHandler` function:

```typescript theme={"dark"}
const myHandler = async (event) => {
  // Only trigger on 'new' command
  if (event.type !== "command" || event.action !== "new") {
    return;
  }

  console.log(`[my-hook] New command triggered`);
  console.log(`  Session: ${event.sessionKey}`);
  console.log(`  Timestamp: ${event.timestamp.toISOString()}`);

  // Your custom logic here

  // Optionally send message to user
  event.messages.push("✨ My hook executed!");
};

export default myHandler;
```

#### Event Context

Each event includes:

```typescript theme={"dark"}
{
  type: 'command' | 'session' | 'agent' | 'gateway' | 'message',
  action: string,              // e.g., 'new', 'reset', 'stop', 'received', 'sent'
  sessionKey: string,          // Session identifier
  timestamp: Date,             // When the event occurred
  messages: string[],          // Push messages here to send to user
  context: {
    // Command events:
    sessionEntry?: SessionEntry,
    sessionId?: string,
    sessionFile?: string,
    commandSource?: string,    // e.g., 'whatsapp', 'telegram'
    senderId?: string,
    workspaceDir?: string,
    bootstrapFiles?: WorkspaceBootstrapFile[],
    cfg?: OpenClawConfig,
    // Message events (see Message Events section for full details):
    from?: string,             // message:received
    to?: string,               // message:sent
    content?: string,
    channelId?: string,
    success?: boolean,         // message:sent
  }
}
```

## Event Types

### Command Events

Triggered when agent commands are issued:

* **`command`**: All command events (general listener)
* **`command:new`**: When `/new` command is issued
* **`command:reset`**: When `/reset` command is issued
* **`command:stop`**: When `/stop` command is issued

### Agent Events

* **`agent:bootstrap`**: Before workspace bootstrap files are injected (hooks may mutate `context.bootstrapFiles`)

For lane-aware agents, `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](https://docs.wednesdayai.dev/next/developers/concepts/workspace-lanes.md).

```typescript theme={"dark"}
event.context.workspaceLane?: WorkspaceLaneResolution;
```

### 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, `transcript` contains 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 was dispatched to the platform (a provable no-send — e.g. a suppressed empty reply — fires nothing). Plugin `message_sent` also fires on inbound channel replies. Internal `message:sent` still needs a session key, so inbound replies typically fire only the plugin hook.

#### Message Event Context

Message events include rich context about the message:

```typescript theme={"dark"}
// message:received context
{
  from: string,            // Sender identifier (phone number, user ID, etc.)
  content: string,         // Message content
  timestamp?: number,      // Unix timestamp when received
  channelId: string,       // Channel (e.g., "whatsapp", "telegram", "discord")
  accountId?: string,      // Provider account ID for multi-account setups
  conversationId?: string, // Legacy alias for channelConversationId
  channelConversationId?: string,
  messageProvider?: string,
  sessionId?: string,      // Present only if a real session is already known
  sessionKey?: string,
  runId?: string,          // Same value as turn.turnId in the v1 turn contract
  messageId?: string,      // Message ID from the provider
  senderId?: string,
  senderName?: string,
  senderUsername?: string,
  senderE164?: string,
  canonicalIdentity?: string,
  senderIsOwner?: boolean,
  runtimeIdentity?: PluginRuntimeIdentity,
  turn?: PluginTurnIdentity,
  metadata?: {             // Additional provider-specific data
    to?: string,
    provider?: string,
    surface?: string,
    threadId?: string,
    senderId?: string,
    senderName?: string,
    senderUsername?: string,
    senderE164?: string,
    senderIsBot?: boolean, // true when the channel reports a bot author (Discord, Slack, Telegram, Google Chat, Mattermost, Feishu, A2A); absent when unknown
  }
}

// message:sent context
{
  to: string,             // Recipient identifier
  content: string,        // Message content that was sent
  success: boolean,       // Whether the send succeeded
  error?: string,         // Error message if sending failed
  channelId: string,      // Channel (e.g., "whatsapp", "telegram", "discord")
  accountId?: string,     // Provider account ID
  conversationId?: string, // Chat/conversation ID
  messageId?: string,     // Message ID returned by the provider
  isGroup?: boolean,      // Whether this outbound message belongs to a group/channel context
  groupId?: string,       // Group/channel identifier for correlation with message:received
}

// message:transcribed context
{
  body?: string,          // Raw inbound body before enrichment
  bodyForAgent?: string,  // Enriched body visible to the agent
  transcript: string,     // Audio transcript text
  channelId: string,      // Channel (e.g., "telegram", "whatsapp")
  conversationId?: string,
  messageId?: string,
}

// message:preprocessed context
{
  body?: string,          // Raw inbound body
  bodyForAgent?: string,  // Final enriched body after media/link understanding
  transcript?: string,    // Transcript when audio was present
  channelId: string,      // Channel (e.g., "telegram", "whatsapp")
  conversationId?: string,
  messageId?: string,
  isGroup?: boolean,
  groupId?: string,
}
```

#### Example: Message Logger Hook

```typescript theme={"dark"}
const isMessageReceivedEvent = (event: { type: string; action: string }) =>
  event.type === "message" && event.action === "received";
const isMessageSentEvent = (event: { type: string; action: string }) =>
  event.type === "message" && event.action === "sent";

const handler = async (event) => {
  if (isMessageReceivedEvent(event as { type: string; action: string })) {
    console.log(`[message-logger] Received from ${event.context.from}: ${event.context.content}`);
  } else if (isMessageSentEvent(event as { type: string; action: string })) {
    console.log(`[message-logger] Sent to ${event.context.to}: ${event.context.content}`);
  }
};

export default handler;
```

### 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 or `undefined` to keep it as-is. See [Agent Loop](https://docs.wednesdayai.dev/next/developers/concepts/agent-loop.md).

## 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 names are validated at registration: an `api.on` name that core does not dispatch is ignored with a `PLUGIN_HOOK_NOT_DISPATCHED` warning, and the plugin shows as `degraded` in `wednesdayai plugins list`. Upstream openclaw hook names, their disposition and the WednesdayAI hook to use instead are listed in the [hook parity map](https://docs.wednesdayai.dev/next/developers/plugins/hook-parity.md).

### Hook event reference

| Event | Fires when | Context type | Return value |
| - | - | - | - |
| `before_model_resolve` | Before the model is resolved for a run | `PluginHookAgentContext` | `{ modelOverride?, providerOverride? }` or void |
| `before_prompt_build` | After session messages are prepared, before the prompt is assembled | `PluginHookAgentContext` | `{ systemPrompt?, prependSystemContext?, appendSystemContext?, appendContext?, prependContext? }` or void |
| `before_context_send` | Just before the full context is sent to the LLM | `PluginHookAgentContext` | `{ messages? }` or void |
| `before_agent_start` | Legacy combined hook (pre-session phase) | `PluginHookAgentContext` | `{ systemPrompt?, prependContext?, modelOverride?, providerOverride? }` or void |
| `llm_input` | Immediately before the LLM API call (observe only) | `PluginHookAgentContext` | void |
| `llm_output` | Immediately after the LLM API call (observe only) | `PluginHookAgentContext` | void |
| `transform_llm_input` | Before messages are sent to the LLM; handlers execute sequentially, each receiving the prior handler's output | `PluginHookAgentContext` | `{ messages: AgentMessage[] }` |
| `transform_llm_output` | After the LLM returns; handlers execute sequentially | `PluginHookAgentContext` | `{ assistantTexts?: string[] }` |
| `agent_end` | When an agent run completes (success or error) | `PluginHookAgentContext` | void |
| `before_compaction` | Before compaction begins | `PluginHookAgentContext` | void; the payload's `sessionFile` is deprecated and never set (see below) |
| `after_compaction` | After compaction completes | `PluginHookAgentContext` | void; the payload's `sessionFile` is deprecated and never set (see below) |
| `before_reset` | When `/new` or `/reset` clears a session | `PluginHookAgentContext` | void |
| `message_received` | Inbound message received | `PluginHookMessageContext` | void |
| `message_sending` | Outbound payload about to be sent (inbound channel replies and CLI/cron) | `PluginHookMessageContext` | `{ content?, cancel? }` or void |
| `message_sent` | Outbound payload was dispatched to the platform (inbound channel replies and CLI/cron); suppressed no-sends fire nothing | `PluginHookMessageContext` | void |
| `before_tool_call` | Before a tool is invoked | `PluginHookToolContext` | `{ params?, block?, blockReason? }` or void |
| `after_tool_call` | After a tool returns | `PluginHookToolContext` | void |
| `tool_result_persist` | Before a tool result is written to session storage (synchronous) | `PluginHookToolResultPersistContext` | `{ message? }` or void |
| `before_message_write` | Before any agent message is written to session storage | `{ agentId?, sessionKey?, runtimeIdentity?, turn? }` | `{ block?, message? }` or void |
| `model_call_ended` | After an agent model-call attempt finishes | `PluginHookAgentContext` | void; handlers may update `usage` (`event.proxyMetadata` is deprecated — removed next minor) |
| `storage.afterAppend` | After a conversation entry is appended to context storage | `ContextLifecycleContext` | void |
| `context.collect` | During context construction, before prompt assembly | `ContextLifecycleContext` | `PromptContribution` or void |
| `context.project` | During context projection, after collection | `ContextLifecycleContext` | `{ messages?, projection?, contribution?, failedPluginIds? }` or void |
| `context.prune` | During context pruning | `ContextLifecycleContext` | `{ messages?, dropped?, contribution?, compactionHandled?, freezeToolResults? }` or void |
| `session_start` | A session begins (new or resumed) | `PluginHookSessionContext` | void |
| `session_end` | A session ends | `PluginHookSessionContext` | void |
| `subagent_spawning` | A sub-agent is about to be spawned | `PluginHookSubagentContext` | `{ status: "ok" \| "error", ... }` or void |
| `subagent_delivery_target` | Before a spawned sub-agent's reply delivery target is resolved | `PluginHookSubagentContext` | `{ origin? }` or void |
| `subagent_spawned` | A sub-agent was successfully spawned | `PluginHookSubagentContext` | void |
| `subagent_ended` | A sub-agent run finished | `PluginHookSubagentContext` | void |
| `gateway_start` | Gateway has started | `PluginHookGatewayContext` | void |
| `gateway_stop` | Gateway is stopping | `PluginHookGatewayContext` | void |
| `agent_idle` | The core idle monitor sees an agent cross the idle threshold or a schedule window open (`tasks.idle` / `tasks.schedule` config) | `PluginHookAgentContext` | void |
| `task_outcome` | A task run or sub-agent run reaches a terminal outcome | `PluginHookAgentContext` | void |

`agent_idle` carries `{ agentId, idleSinceMs, idleForMs, trigger: "idle" | "schedule" }`.
`task_outcome` carries
`{ taskRunId?, agentId?, source: "task" | "subagent" | "session", outcome: "completed" | "failed" | "preempted" | "cancelled", quality?, meta? }`.
Both were added for background engines like [Dream Cycle](https://docs.wednesdayai.dev/next/developers/plugins/dream-cycle); the idle
monitor only runs when `tasks.idle.enabled` is true or `tasks.schedule.windows` is non-empty
(see [Task operations](https://docs.wednesdayai.dev/next/admin/gateway/tasks.md)).

The `before_compaction` and `after_compaction` payloads used to carry a `sessionFile` path to the
JSONL transcript. SQL session storage keeps transcripts in the database, so the field is
deprecated, never set, and is removed in the next release. Read the session's history with
`getConversationReadQuery` from the plugin SDK instead (see
[Session identity keying](https://docs.wednesdayai.dev/next/developers/plugins/session-identity-keying.md)); `session_end.sessionFile` is a
separate contract and is unaffected here.

### Inbound channel replies

Inbound replies fire plugin `message_sending` then `message_sent` once per payload on Telegram,
Slack, Discord, Signal, iMessage, WhatsApp, Matrix, and Microsoft Teams. CLI and cron sends use
the same helpers. WednesdayAI does not fire these hooks from the Slack outbound adapter, so a
CLI or cron Slack send is one `message_sending` (via the shared deliver path), not two.

LINE and Zalo inbound replies do not fire these hooks.

`message_sending` can return `{ cancel: true }` to skip that payload, or `{ content }` to rewrite
the text that is sent. A thrown handler is logged as `applyMessageSendingHook: hook failed` and
the original payload is sent. Telegram chunking does not re-run the hook.

`message_sent` fires only when the message was dispatched to the platform. Send errors fire with
`success: false` and `error`. `ctx.messageId` is the platform id of the last message sent for the
payload; it is absent when the platform returns none. A payload that ends up as a provable
no-send — `message_sending` cancelled it, rewrote it to empty, or the channel suppressed it
(e.g. the Slack `NO_REPLY` guard) — is a terminal no-op: the assistant message the turn generated
is already stored, but the delivery itself adds no transcript entry, no queue receipt id, no
delivery result, and no `message_sent` event.

Inbound `message_sending` context is `channelId` and `accountId` only. It does not set
`sessionKey` or `trigger`. Plugin `message_sent` still fires after a successful inbound send.
Internal `message:sent` does not, unless a session key is passed (CLI/cron can).

To confirm a live inbound reply reached the hook (Linux systemd user service):

```bash theme={"dark"}
journalctl --user -u openclaw-gateway --since "15 min ago" | grep -F "[hooks] running message_sending"
```

A matching line looks like `[plugins] [hooks] running message_sending (1 handlers, sequential)`.
`message_sent` follows on a successful send. Plugin authors: see [Plugin hooks](https://docs.wednesdayai.dev/next/users/tools/plugin.md#inbound-channel-replies).

### 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:

```typescript theme={"dark"}
type PluginRuntimeIdentity = {
  agentId?: string;
  agentName?: string;
  agentWorkspacePath?: string;
  agentWorkspaceName?: string;
  sessionId?: string;
  sessionKey?: string;
  channelConversationId?: string;
  providerConversationId?: string;
  hashedUserId?: string;
  senderId?: string;
  senderName?: string;
  senderUsername?: string;
  senderE164?: string;
  canonicalIdentity?: string;
  senderIsOwner?: boolean;
  identitySource?: "sender" | "parent-session" | "job-config";
  messageProvider?: string;
  channelId?: string;
  /** Session classification derived from the session key (never guessed from message text). */
  sessionKind?: "user" | "cron" | "heartbeat" | "hook" | "subagent" | "acp" | "unknown";
  accountId?: string;
  peerKind?: "direct" | "group" | "channel";
  peerId?: string;
  /** `sessionKey === mainSessionKey`; never inferred by consumers from the session key shape. */
  isMainSession?: boolean;
};

type PluginTurnIdentity = {
  turnId: string;
  runId?: string;
  sessionId?: string;
  sessionKey?: string;
  turnNumber?: number;
  inboundMessageId?: string;
  userEntryId?: string;
  assistantEntryId?: string;
  userSeq?: number;
  assistantSeq?: number;
  userGlobalSeq?: number;
  assistantGlobalSeq?: number;
};
```

In the v1 contract, `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:

* `conversationId` remains the legacy channel conversation id. It is an alias for
  `channelConversationId`, never for `providerConversationId`.
* `providerConversationId` is 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 `sessionId` or `sessionKey`; WednesdayAI omits those
  fields rather than fabricating session identity.
* Public hook contexts do not expose raw `identityLinks`. Use
  `ctx.runtimeIdentity.canonicalIdentity`, `ctx.runtimeIdentity.senderIsOwner`,
  or `api.runtime.identity.resolveCanonicalIdentity(...)` for canonical sender
  resolution.
* `identitySource` reports provenance of the resolved identity: `"sender"`
  (live message sender), `"parent-session"` (inherited from the spawning
  session), or `"job-config"` (operator-configured cron/heartbeat attribution).
  It is absent when the run has no resolved identity, and also whenever the
  producing seam supplies a `canonicalIdentity` without knowing its provenance —
  provenance is never guessed. Treat `identitySource` as implying
  `canonicalIdentity`, never the reverse.
* On gateway turns (`chat.send`, `sessions.steer`, talk) `senderId` is the verified
  device: `device:<deviceId>` when the connect frame carried a verified device block, otherwise
  the app id (for example `openclaw-user-client`, shared by every user of that app).
  `canonicalIdentity` resolves only when the operator linked `device:<id>` to a person in
  `session.identityLinks`; see [Workspace Lanes](https://docs.wednesdayai.dev/next/developers/concepts/workspace-lanes.md). After ADR 0104 a
  linked device's `senderName` is that person, and the client's display name is a Sender-block
  `client` field, never a person name.
* `session_start` and `session_end` contexts carry `runtimeIdentity` when the
  session has real identity: the ending session's stored `actor` (channel,
  account, peer kind/id, canonical identity) on `session_end`, and the session's
  actor at creation on `session_start`. `runtimeIdentity.isMainSession` is true
  only for the agent's main session key. `runtimeIdentity.sessionKind`
  classifies the session as `"user"` (a normal conversation session, including
  the main session), `"cron"`, `"heartbeat"`, `"hook"`, `"subagent"`, `"acp"`, or
  `"unknown"` (missing or malformed session key). The kind is derived
  structurally from the session key; WednesdayAI never guesses it from message
  text. Main sessions stay display fail-open elsewhere — `sessionKind` is a
  runtime classification, not a UI gate.
* `runtimeIdentity.sessionKind` values mirror the session key grammar:
  agent-prefixed keys whose first segment is an internal root (`cron`,
  `heartbeat`, `hook`, `subagent`, `acp`) map to that kind; every other
  well-formed agent key maps to `"user"`.

Storage append hooks can fire once for the user entry and once for the assistant
entry. Both appends share the same `turnId`, so dedupe with the entry or cursor
identity as well:

```typescript theme={"dark"}
const key = `${ctx.turn?.turnId}:${event.entry.entryId ?? event.cursor?.entryId ?? event.entry.rawSha256}`;
```

The typed context lifecycle hooks (`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.

`context.project` and `context.prune` run on every model call of a run,
including the continuations that follow overflow compaction or an automatic
retry, and each call gets fresh per-call fields on `ContextLifecycleContext`.
`context.collect` runs once per attempt, before the first model call; it
receives `ContextLifecycleContext` without the per-call fields.
`transform_llm_input` runs on every model call and receives
`PluginHookAgentContext`, which does not carry the per-call lifecycle fields.

Per-call fields on `ContextLifecycleContext` for `context.project` and
`context.prune`:

* `usage`: the run's usage totals so far.
* `lastCallUsage`: the usage of the most recent assistant message in this call's
  input; undefined on the first call of a session.
* `tokenWindow.estimatedInputTokens`: an estimate of this call's input after core
  tool-result projection.

Core changes tool-result bytes it already sent only in batched evictions, overflow
recovery or a cache-TTL pruning round, so the provider prompt cache keeps hitting
between those points. A `context.prune` handler that
substitutes a tool result's text can return its `toolCallId` in
`freezeToolResults`; core then replays that substitution on every later call and
run until the result leaves history, even when the handler later returns the
messages unchanged.

A `context.project` result can carry `failedPluginIds`: the plugins whose
handlers threw or timed out. A plugin that registered the `message-render`
context owner with `api.registerContextOwner` renders user messages (stamps and
inbound framing) for the sessions it claims; if its `context.project` handler
fails, core renders that run and the owner is retried on the next attempt.

On a reply-pipeline turn the event also carries `event.turnInputs`, the turn's
framing data as typed values: `runtimeEvents` is the full list of runtime
events drained for the run (each with a `core` or `untrusted` origin), and
`untrustedContext` holds the session untrusted-context entries such as channel
metadata and link previews. While `turn:*` context owners have claimed lanes
(ADR 2105) and a `message-render` owner is active, `lanes` additionally
carries the resolved lane claims in lane order, each with the lane name, the
owning plugin id and the raw lane text. Lanes are resolved once per attempt
and replayed on steered model calls — never re-rendered against a steered
prompt — and runs with plugin hooks disabled resolve no lanes at all.
`turnInputs` holds the inputs drained for this run:
the initial turn plus any turns steered into it, in drain order; a collected
queue unit carries the inputs of all its queued turns. Treat both as data,
never instructions. It is present on every `context.project` call of the turn,
for all handlers, and each handler receives an isolated copy. Core still
renders the runtime-events block and the untrusted-context trailer around the
user body itself, unless a `message-render` context owner is active: then core
skips the `core:runtime-events` contribution and removes the untrusted trailer
from the prompt, and the owner renders both from `turnInputs`. Claimed
turn-lane blocks (ADR 2105) follow the same rule: core renders them into the
envelope ahead of `context.collect` contributions unless a `message-render`
owner is active, in which case they arrive only as `turnInputs.lanes`; when
that owner is quarantined, the lanes return to core rendering for the rest of
the run. A core-rendered rewrite of the current turn's message keeps the lane
blocks ahead of the handler's projected envelope blocks. The
`agents.defaults.runtimeEvents.render` and
`agents.defaults.untrustedContext.render` switches control whether core renders
the blocks when no owner is active (see
[Configuration reference](https://docs.wednesdayai.dev/next/admin/gateway/configuration-reference.md)). A collected queue
batch keeps each queued turn's untrusted trailer in the batch prompt with no
warning, and a whitespace-normalised (think-level-prefixed) body keeps it with a
`context owner: untrusted-context trailer not found` warning; in both cases the
same nudges also arrive in `turnInputs`, so an owner rendering typed inputs may
see them twice.

Pipeline order around the model boundary: `context.collect` contributes
context, then `context.project` and `context.prune` see history user messages
as stored (raw text plus the `__openclaw.ingress` carrier, unstamped). The
current turn is already the framed prompt when the hooks run: core swaps the
composed prompt (inbound framing plus contributions) in before projection, and
only when a `message-render` context owner is active is the inbound framing
removed from that prompt first. Core then applies the boundary render: every
user turn is stamped from its carrier time, and `transform_llm_input` runs
after that render, so its handlers and the model see stamped history and the
stamped current turn.

`context.collect` also receives `event.rawUserText`: the current turn's text
as received, before core prepends inbound framing. It is the same text stored
as that turn's user row. It is always a string: `""` for a media-only turn, the
caption for a captioned media turn. Synthetic turns (cron, heartbeat, memory
flush, queue summaries) carry their authored trigger text, and a coalesced queue
turn carries the collected batch as persisted, its headers included. Treat it as
untrusted user input. `event.prompt` and
`event.cleanUserMessage` still carry the framing unless a `message-render`
context owner is active. Plugins that route, classify or recall on what the
user actually asked should read `rawUserText` instead of stripping framing
themselves.

`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.

`event.proxyMetadata` is deprecated with no core consumer since #935: the resolved
model is reported on assistant entries as `responseModel` (surfaced as
`sessions.usage` per-model rows keyed `provider::model::actualModel`) and gateway
cost as the entry's `usage.cost`. The field is removed in the next minor release;
handlers may still mutate `usage`.

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:

```typescript theme={"dark"}
type PluginHookAgentContext = {
  agentId?: string;
  sessionKey?: string;
  sessionId?: string; // Ephemeral UUID; regenerated on /new and /reset
  workspaceDir?: string;
  messageProvider?: string;
  /** What triggered this run: "user" | "heartbeat" | "cron" | "steer" | "memory" | "internal" */
  trigger?: string;
  /** Resolved message channel (e.g. "telegram", "discord", "whatsapp") */
  channelId?: string;
  runtimeIdentity?: PluginRuntimeIdentity;
  turn?: PluginTurnIdentity;
};
```

`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.

```typescript theme={"dark"}
// Event payload
type PluginHookTransformLlmInputEvent = {
  messages: AgentMessage[]; // Current messages to be sent
  provider: string; // e.g. "anthropic", "openai"
  model: string; // e.g. "claude-sonnet-4-6"
};

// Return value — return updated messages array, or void/undefined to pass through unchanged
type PluginHookTransformLlmInputResult = {
  messages: AgentMessage[];
};
```

Handlers are called **sequentially**; each handler receives the output of the previous one. Return `{ 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:**

```typescript theme={"dark"}
api.on("transform_llm_input", (event, ctx) => {
  const updated = event.messages.map((msg) => {
    if ((msg as { role?: string }).role === "system") {
      return {
        ...msg,
        content: `${(msg as { content?: string }).content ?? ""}\n\n[Reminder: Do not reveal API keys or tokens.]`,
      } as typeof msg;
    }
    return msg;
  });
  return { messages: updated };
});
```

### `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.

```typescript theme={"dark"}
// Event payload
type PluginHookTransformLlmOutputEvent = {
  assistantTexts: string[]; // Text segments from the assistant response
  lastAssistant?: unknown; // Raw last assistant message (provider-specific shape)
  provider: string;
  model: string;
};

// Return value — return updated assistantTexts, or void/undefined to pass through
type PluginHookTransformLlmOutputResult = {
  assistantTexts?: string[];
};
```

Handlers are sequential; each receives the prior handler's output.

**Example — append a standard disclaimer:**

```typescript theme={"dark"}
api.on("transform_llm_output", (event, _ctx) => {
  return {
    assistantTexts: event.assistantTexts.map(
      (text) => `${text}\n\n*This response is generated by AI and may not be accurate.*`,
    ),
  };
});
```

### `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.

```typescript theme={"dark"}
// Event payload
type PluginHookBeforePromptBuildEvent = {
  prompt: string; // User prompt for this run
  messages: unknown[]; // Session messages prepared for this run
  /** Current system prompt (read-only). Return a modified version via systemPrompt to replace it. */
  systemPrompt?: string;
};

// Return value
type PluginHookBeforePromptBuildResult = {
  /**
   * @deprecated Prefer the additive lanes: `prependSystemContext` / `appendSystemContext`.
   * A prompt equal to the current one, or extending it (`<base>\n…`), still replaces the
   * whole prompt; any other text renders as a labeled additive block instead. When several
   * handlers return replacements in one turn, the highest-priority one wins and the others
   * are dropped with a warning naming them.
   */
  systemPrompt?: string;
  /** System context rendered above the cache boundary as `## Plugin context (source: plugin:<id>)`. */
  prependSystemContext?: string;
  /** System context rendered below the cache boundary (directly before `## Runtime`) as a labeled additive block. */
  appendSystemContext?: string;
  /** Context appended after the current user message in the turn envelope. */
  appendContext?: string;
  /** Prepend additional context text before the user prompt. */
  prependContext?: string;
};
```

The `systemPrompt` field on the event is read-only context. To modify it, return `{ systemPrompt: "..." }` in your result. Prefer the additive lanes: `prependSystemContext` renders above the cache boundary and `appendSystemContext` directly before `## Runtime`, each wrapped in a `## Plugin context (source: plugin:<your plugin id>)` heading, in priority order (ties keep registration order). Blank or whitespace-only strings contribute nothing.

**`systemPrompt` replacement precedence:** a returned prompt that equals the current system prompt or starts with it (`<base>\n…`) still replaces the prompt: the assembled prompt renders with every other plugin's additive blocks at their placements (before `## Runtime`), and only the replacing plugin's own remainder (its text after the base) is appended at the end of the prompt — the position the legacy replace semantics put it. If more than one handler returns a replacement in the same turn, the highest-priority one wins; the rest are dropped with one warning naming the ignored plugin ids and the winner. A prompt that does not contain the base is treated as additive: it renders as its own labeled block in the `custom.session` slot instead of replacing anything.

**`prependContext` wrapping:** WednesdayAI 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:

```typescript theme={"dark"}
// Wrap in <injected-context> so the model treats it as system context
// and downstream stripping can remove it from prior turns.
return {
  prependContext: `<injected-context source="plugin">\n${yourContent}\n</injected-context>`,
};
```

Omit the wrapper when you want the content to appear as part of the conversation without special XML markup.

**Example — inject a per-channel system prompt prefix:**

```typescript theme={"dark"}
api.on("before_prompt_build", (event, ctx) => {
  if (ctx.channelId === "slack") {
    return {
      systemPrompt: `You are responding in a Slack channel. Keep replies concise.\n\n${event.systemPrompt ?? ""}`,
    };
  }
});
```

### Future Events

Planned event types:

* **`session:start`**: When a new session begins
* **`session:end`**: When a session ends
* **`agent: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

```bash theme={"dark"}
mkdir -p ~/.openclaw/hooks/my-hook
cd ~/.openclaw/hooks/my-hook
```

### 3. Create HOOK.md

```markdown theme={"dark"}
---
name: my-hook
description: "Does something useful"
metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } }
---

# My Custom Hook

This hook does something useful when you issue `/new`.
```

### 4. Create handler.ts

```typescript theme={"dark"}
const handler = async (event) => {
  if (event.type !== "command" || event.action !== "new") {
    return;
  }

  console.log("[my-hook] Running!");
  // Your logic here
};

export default handler;
```

### 5. Enable and Test

```bash theme={"dark"}
# Verify hook is discovered
wednesdayai hooks list

# Enable it
wednesdayai hooks enable my-hook

# Restart your gateway process (menu bar app restart on macOS, or restart your dev process)

# Trigger the event
# Send /new via your messaging channel
```

## Configuration

### New Config Format (Recommended)

```json5 theme={"dark"}
{
  hooks: {
    internal: {
      enabled: true,
      entries: {
        "session-memory": { enabled: true },
        "command-logger": { enabled: false },
      },
    },
  },
}
```

### Per-Hook Configuration

Hooks can have custom configuration:

```json5 theme={"dark"}
{
  hooks: {
    internal: {
      enabled: true,
      entries: {
        "my-hook": {
          enabled: true,
          env: {
            MY_CUSTOM_VAR: "value",
          },
        },
      },
    },
  },
}
```

### Extra Directories

Load hooks from additional directories:

```json5 theme={"dark"}
{
  hooks: {
    internal: {
      enabled: true,
      load: {
        extraDirs: ["/path/to/more/hooks"],
      },
    },
  },
}
```

### Legacy Config Format (Still Supported)

The old config format still works for backwards compatibility:

```json5 theme={"dark"}
{
  hooks: {
    internal: {
      enabled: true,
      handlers: [
        {
          event: "command:new",
          module: "./hooks/handlers/my-handler.ts",
          export: "default",
        },
      ],
    },
  },
}
```

Note: `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

```bash theme={"dark"}
# List all hooks
wednesdayai hooks list

# Show only eligible hooks
wednesdayai hooks list --eligible

# Verbose output (show missing requirements)
wednesdayai hooks list --verbose

# JSON output
wednesdayai hooks list --json
```

### Hook Information

```bash theme={"dark"}
# Show detailed info about a hook
wednesdayai hooks info session-memory

# JSON output
wednesdayai hooks info session-memory --json
```

### Check Eligibility

```bash theme={"dark"}
# Show eligibility summary
wednesdayai hooks check

# JSON output
wednesdayai hooks check --json
```

### Enable/Disable

```bash theme={"dark"}
# Enable a hook
wednesdayai hooks enable session-memory

# Disable a hook
wednesdayai hooks disable command-logger
```

## 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**:

1. Uses the pre-reset session entry to locate the correct transcript
2. Extracts the last 15 lines of conversation
3. Uses LLM to generate a descriptive filename slug
4. Saves session metadata to a dated memory file

**Example output**:

```markdown theme={"dark"}
# Session: 2026-01-16 14:30:00 UTC

- **Session Key**: agent:main:main
- **Session ID**: abc123def456
- **Source**: telegram
```

**Filename examples**:

* `2026-01-16-143045-vendor-pitch.md`
* `2026-01-16-143045-api-design.md`
* `2026-01-16-143045-journal.md` (fallback when slug generation fails or session has no content)

**Enable**:

```bash theme={"dark"}
wednesdayai hooks enable session-memory
```

### bootstrap-extra-files

Injects additional bootstrap files (for example monorepo-local `AGENTS.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**:

```json5 theme={"dark"}
{
  hooks: {
    internal: {
      enabled: true,
      entries: {
        "bootstrap-extra-files": {
          enabled: true,
          paths: ["packages/*/AGENTS.md", "packages/*/TOOLS.md"],
        },
      },
    },
  },
}
```

**Notes**:

* Paths are resolved relative to workspace.
* Files must stay inside workspace (realpath-checked).
* Only recognized bootstrap basenames are loaded.
* Subagent allowlist is preserved (`AGENTS.md` and `TOOLS.md` only).

**Enable**:

```bash theme={"dark"}
wednesdayai hooks enable bootstrap-extra-files
```

### command-logger

Logs all command events to a centralized audit file.

**Events**: `command`

**Requirements**: None

**Output**: `~/.openclaw/logs/commands.log`

**What it does**:

1. Captures event details (command action, timestamp, session key, sender ID, source)
2. Appends to log file in JSONL format
3. Runs silently in the background

**Example log entries**:

```jsonl theme={"dark"}
{"timestamp":"2026-01-16T14:30:00.000Z","action":"new","sessionKey":"agent:main:main","senderId":"+1234567890","source":"telegram"}
{"timestamp":"2026-01-16T15:45:22.000Z","action":"stop","sessionKey":"agent:main:main","senderId":"user@example.com","source":"whatsapp"}
```

**View logs**:

```bash theme={"dark"}
# View recent commands
tail -n 20 ~/.openclaw/logs/commands.log

# Pretty-print with jq
cat ~/.openclaw/logs/commands.log | jq .

# Filter by action
grep '"action":"new"' ~/.openclaw/logs/commands.log | jq .
```

**Enable**:

```bash theme={"dark"}
wednesdayai hooks enable command-logger
```

### boot-md

Runs `BOOT.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**:

1. Reads `BOOT.md` from your workspace
2. Runs the instructions via the agent runner
3. Sends any requested outbound messages via the message tool

`BOOT.md` is not created for you: new workspaces are not seeded with it, and a missing or empty file
is skipped. Write it in the workspace root yourself; the [BOOT.md template](https://docs.wednesdayai.dev/next/developers/reference/templates/BOOT.md)
is a starting point.

**Enable**:

```bash theme={"dark"}
wednesdayai hooks enable boot-md
```

### 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**:

1. Reads the previous session transcript (JSONL) before it is cleared
2. Extracts user/assistant turns from the transcript
3. Calls the LLM to produce a reflective journal entry (patient notes, coaching notes, or a custom prompt)
4. Writes a dated Markdown file; the filename slug is derived from the first heading in the LLM output
5. If the LLM call fails or there is no session content, writes a header-only stub so the reset event is still recorded

**Configuration**:

Enable per agent in `openclaw.json`:

```json5 theme={"dark"}
{
  agents: {
    list: [
      {
        id: "claire",
        sessionJournal: {
          enabled: true,
          // optional — include {transcript} where session text should be injected
          prompt: "Write structured patient notes in SOAP format.\n\nSession transcript:\n{transcript}",
        },
      },
    ],
  },
}
```

| Field | Type | Default | Description |
| - | - | - | - |
| `enabled` | `boolean` | `false` | Enable journal generation for this agent |
| `prompt` | `string` | built-in | LLM prompt. Include `{transcript}` where the session text should be injected; if absent, the transcript is appended after the prompt. |

**Filename examples**:

* `2026-06-21-143045-vendor-onboarding-session.md`
* `2026-06-21-143045-anxiety-management-techniques.md`
* `2026-06-21-143045-journal.md` (fallback when slug generation fails or session has no content)

**Limitations**:

Journal entries are written only when a session **explicitly resets** via `/new` or `/reset`. Sessions that end without a reset command (process exit, connection drop, idle timeout) do not produce a journal entry.

**Enable**:

```bash theme={"dark"}
wednesdayai hooks enable session-journal
```

## Best Practices

### Keep Handlers Fast

Hooks run during command processing. Keep them lightweight:

```typescript theme={"dark"}
// ✓ Good - async work, returns immediately
const handler: HookHandler = async (event) => {
  void processInBackground(event); // Fire and forget
};

// ✗ Bad - blocks command processing
const handler: HookHandler = async (event) => {
  await slowDatabaseQuery(event);
  await evenSlowerAPICall(event);
};
```

### Handle Errors Gracefully

Always wrap risky operations:

```typescript theme={"dark"}
const handler: HookHandler = async (event) => {
  try {
    await riskyOperation(event);
  } catch (err) {
    console.error("[my-handler] Failed:", err instanceof Error ? err.message : String(err));
    // Don't throw - let other handlers run
  }
};
```

### Filter Events Early

Return early if the event isn't relevant:

```typescript theme={"dark"}
const handler: HookHandler = async (event) => {
  // Only handle 'new' commands
  if (event.type !== "command" || event.action !== "new") {
    return;
  }

  // Your logic here
};
```

### Use Specific Event Keys

Specify exact events in metadata when possible:

```yaml theme={"dark"}
metadata: { "openclaw": { "events": ["command:new"] } } # Specific
```

Rather than:

```yaml theme={"dark"}
metadata: { "openclaw": { "events": ["command"] } } # General - more overhead
```

## Debugging

### Enable Hook Logging

The gateway logs hook loading at startup:

```text theme={"dark"}
Registered hook: session-memory -> command:new
Registered hook: session-journal -> command:new, command:reset
Registered hook: bootstrap-extra-files -> agent:bootstrap
Registered hook: command-logger -> command
Registered hook: boot-md -> gateway:startup
```

### Check Discovery

List all discovered hooks:

```bash theme={"dark"}
wednesdayai hooks list --verbose
```

### Check Registration

In your handler, log when it's called:

```typescript theme={"dark"}
const handler: HookHandler = async (event) => {
  console.log("[my-handler] Triggered:", event.type, event.action);
  // Your logic
};
```

### Verify Eligibility

Check why a hook isn't eligible:

```bash theme={"dark"}
wednesdayai hooks info my-hook
```

Look for missing requirements in the output.

## Testing

### Gateway Logs

Monitor gateway logs to see hook execution:

```bash theme={"dark"}
# macOS
./scripts/clawlog.sh -f

# Other platforms
tail -f ~/.openclaw/gateway.log
```

### Test Hooks Directly

Test your handlers in isolation:

```typescript theme={"dark"}
import { test } from "vitest";
import myHandler from "./hooks/my-hook/handler.js";

test("my handler works", async () => {
  const event = {
    type: "command",
    action: "new",
    sessionKey: "test-session",
    timestamp: new Date(),
    messages: [],
    context: { foo: "bar" },
  };

  await myHandler(event);

  // Assert side effects
});
```

## Architecture

### Core Components

* **`src/hooks/types.ts`**: Type definitions
* **`src/hooks/workspace.ts`**: Directory scanning and loading
* **`src/hooks/frontmatter.ts`**: HOOK.md metadata parsing
* **`src/hooks/config.ts`**: Eligibility checking
* **`src/hooks/hooks-status.ts`**: Status reporting
* **`src/hooks/loader.ts`**: Dynamic module loader
* **`src/cli/hooks-cli.ts`**: CLI commands
* **`src/gateway/server-startup.ts`**: Loads hooks at gateway start
* **`src/auto-reply/reply/commands-core.ts`**: Triggers command events

### Discovery Flow

```bash theme={"dark"}
Gateway startup
    ↓
Scan directories (workspace → managed → bundled)
    ↓
Parse HOOK.md files
    ↓
Check eligibility (bins, env, config, os)
    ↓
Load handlers from eligible hooks
    ↓
Register handlers for events
```

### Event Flow

```sql theme={"dark"}
User sends /new
    ↓
Command validation
    ↓
Create hook event
    ↓
Trigger hook (all registered handlers)
    ↓
Command processing continues
    ↓
Session reset
```

## Troubleshooting

### Hook Not Discovered

1. Check directory structure:

   ```bash theme={"dark"}
   ls -la ~/.openclaw/hooks/my-hook/
   # Should show: HOOK.md, handler.ts
   ```

2. Verify HOOK.md format:

   ```bash theme={"dark"}
   cat ~/.openclaw/hooks/my-hook/HOOK.md
   # Should have YAML frontmatter with name and metadata
   ```

3. List all discovered hooks:

   ```bash theme={"dark"}
   wednesdayai hooks list
   ```

### Hook Not Eligible

Check requirements:

```bash theme={"dark"}
wednesdayai hooks info my-hook
```

Look for missing:

* Binaries (check PATH)
* Environment variables
* Config values
* OS compatibility

### Hook Not Executing

1. Verify hook is enabled:

   ```bash theme={"dark"}
   wednesdayai hooks list
   # Should show ✓ next to enabled hooks
   ```

2. Restart your gateway process so hooks reload.

3. Check gateway logs for errors:

   ```bash theme={"dark"}
   ./scripts/clawlog.sh | grep hook
   ```

### Handler Errors

Check for TypeScript/import errors:

```bash theme={"dark"}
# Test import directly
node -e "import('./path/to/handler.ts').then(console.log)"
```

## Migration Guide

### From Legacy Config to Discovery

**Before**:

```json5 theme={"dark"}
{
  hooks: {
    internal: {
      enabled: true,
      handlers: [
        {
          event: "command:new",
          module: "./hooks/handlers/my-handler.ts",
        },
      ],
    },
  },
}
```

**After**:

1. Create hook directory:

   ```bash theme={"dark"}
   mkdir -p ~/.openclaw/hooks/my-hook
   mv ./hooks/handlers/my-handler.ts ~/.openclaw/hooks/my-hook/handler.ts
   ```

2. Create HOOK.md:

   ```markdown theme={"dark"}
   ---
   name: my-hook
   description: "My custom hook"
   metadata: { "openclaw": { "emoji": "🎯", "events": ["command:new"] } }
   ---

   # My Hook

   Does something useful.
   ```

3. Update config:

   ```json5 theme={"dark"}
   {
     hooks: {
       internal: {
         enabled: true,
         entries: {
           "my-hook": { enabled: true },
         },
       },
     },
   }
   ```

4. Verify and restart your gateway process:

   ```bash theme={"dark"}
   wednesdayai hooks list
   # Should show: 🎯 my-hook ✓
   ```

**Benefits of migration**:

* Automatic discovery
* CLI management
* Eligibility checking
* Better documentation
* Consistent structure

## See Also

* [CLI Reference: hooks](https://docs.wednesdayai.dev/next/users/cli/hooks.md)
* [Bundled Hooks README](https://github.com/ExpansionX/WednesdayAI-core/tree/main/src/hooks/bundled)
* [Webhook Hooks](https://docs.wednesdayai.dev/next/users/automation/webhook.md)
* [Configuration](https://docs.wednesdayai.dev/next/admin/gateway/configuration.md#hooks)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.