In an OpenClaw internal hook handler, what can returning a value or pushing to `event.messages` actually change?
answer
- observe, do not control
- the return value goes nowhere
- who consumes event.messages
- one mutable context field
- errors are caught and logged
basics
~20 sAn OpenClaw hook handler's return value is ignored, so it cannot block, cancel or rewrite anything. Strings pushed to event.messages become a chat reply only for /new and /reset from chat, reach compaction callbacks, and are dropped elsewhere.
solid answer
~40 sA handler exports a function returning `void` or `Promise<void>`; the dispatcher awaits it, catches and logs any throw, and moves on, so a returned value never blocks, cancels or rewrites a command or message. Treat `event.context` as an observation; the deliberate exception is `agent:bootstrap`, whose `context.bootstrapFiles` a handler may extend or replace, still subject to filtering and context budgets. `event.messages` starts empty and only some producers read it: chat handling of `/new` and `/reset` joins the strings and replies to the originating conversation, the two compaction events pass them to the compaction-notice callback, and every other core event, such as `/stop`, automatic reset, `message:*` and Gateway lifecycle, ignores them. Changing prompts, intercepting tools or controlling replies is the job of plugin hooks registered with `api.on(...)`, a separate system.
code
javascript · 13 linesimport { appendFile } from "node:fs/promises";
export default async function handler(event) {
if (event.type !== "message" || event.action !== "received") return;
const line = JSON.stringify({
at: event.timestamp.toISOString(),
channel: event.context.channelId,
session: event.sessionKey,
});
// awaited: a failure surfaces as "Hook error [message:received]"
await appendFile("/var/lib/inbound-audit/inbound.jsonl", line + "\n");
return false; // ignored: an internal hook cannot drop the message
}go deeper
Recall that a hook handler only reacts to an event: its return value is ignored and it cannot stop or rewrite the command or message.
Explain which producers read event.messages, why agent:bootstrap's file list is the one mutable field, and how the dispatcher treats a thrown error.
Show safe handler habits: filter early, await bounded work, avoid detached promises, keep bodies and credentials out of logs, and know that shutdown hooks can hold up the Gateway.
Draw the line between observation and control for a team: when a hook is enough, and when a plugin hook or a durable job owns the behaviour instead.
## The handler contract An OpenClaw **internal hook** is a `HOOK.md` file plus a handler module that the Gateway calls when a subscribed event fires. The handler exports a function that returns `void` or `Promise<void>`, and it receives one event object: | Field | What it holds | | --- | --- | | `type` | The family: `command`, `session`, `agent`, `gateway` or `message` | | `action` | The action within the family, such as `new` or `compact:before` | | `sessionKey` | The session the event belongs to; Gateway events use a Gateway key | | `timestamp` | When the event object was created | | `context` | Event-specific data, such as `channelId` and `content` on `message:received` | | `messages` | An initially empty array of strings that some producers read as replies | The contract is narrow on purpose. Internal hooks are **observation points with short side effects**, not a control surface. ## Why a return value cannot veto anything For one event the dispatcher builds the list of handlers (family listeners first, then exact listeners, in registration order) and awaits each in turn: - A **returned value is discarded**. Returning `false`, `null` or an object does not block, cancel or rewrite the command or message. - A **thrown error is caught**, logged as `Hook error [<type>:<action>]`, and the next handler still runs. The command itself goes ahead. - Different events are **not serialized** against each other: message notifications and automatic reset work can overlap with other events and with agent processing. - There is **no general handler timeout**, cancellation signal, durable queue, automatic retry or exactly-once guarantee, and a restart can lose in-flight work. ## Where `event.messages` goes Pushing a string is not a general send-message API. Whether it reaches anyone depends on the producer: | Producer | Fate of `event.messages` | | --- | --- | | Chat handling of `/new` and `/reset` | Awaited, joined with blank lines, sent as a reply to the originating chat | | Gateway session reset or create calls that emit `command:new` or `command:reset` | Handlers run; strings are not routed as chat replies | | `session:compact:before` and `session:compact:after` | Forwarded to the compaction caller's notice callback when one is present | | Every other core event | Ignored as replies: `/stop`, automatic reset, `message:*`, bootstrap, patch and Gateway lifecycle | Push before the handler's promise settles. Work detached from the handler that pushes later misses the producer's delivery step. A missing recipient, an unsupported route or a send policy can still stop a reply that would otherwise go out. ## The one mutable context field `context` is an observation, and patch events even carry cloned snapshots. The documented exception is **`agent:bootstrap`**: its `context.bootstrapFiles` is a mutable list of workspace files about to be injected into the agent's context, and a handler may replace or extend it. That is how the bundled `bootstrap-extra-files` hook adds matching `AGENTS.md` or `SOUL.md` files. Even then, path deduplication, session and privacy filtering and context budgets still apply after the handler returns. ## Writing handlers that behave - **Filter early**: check `event.type` and `event.action` and return on anything else. - **Await what you start**: work kept inside the handler stays inside the dispatcher's error boundary. Avoid `void doHeavyWork(event)`, which escapes that boundary and can outlive the session or the process. - **Bound everything**: set timeouts on network calls, cap data sizes, make repeatable operations idempotent. - **Do not hang on shutdown**: `gateway:shutdown` and `gateway:pre-restart` get bounded initial waits of 5 and 10 seconds, but a timeout does not cancel the handler, and a handler that never settles can stop in-process shutdown from finishing. - **Protect data**: do not log message bodies, whole config objects or credentials; keep only what the side effect needs. - **Long-lived resources** such as timers, watchers and sockets belong in a plugin service with an explicit shutdown lifecycle, not in an event handler. ## When you need control, not observation If the goal is to modify a prompt, intercept a tool call, change or suppress the agent's reply, or gate finalization, internal hooks are the wrong tool. Those need a plugin hook registered through `api.on(...)`, which has typed lifecycle names, priorities and return values. If the work needs a durable job lifecycle, use a scheduled job or a service that owns one.
- A handler must call a slow external API on every inbound message: what is the risk?Nothing times it out for you, nothing retries it, and a restart can lose the call in flight. Handlers for the same event run one after another, so a slow call delays later handlers. Set a timeout, cap payloads, make the call idempotent, and move durable work to a scheduled job or a service that owns it.
- Why does a reply pushed on `/new` not show up in Control UI?Only chat handling of `/new` and `/reset` from a chat channel routes `event.messages` back to the conversation. Resets from Control UI or webchat, and a `sessions.reset` call, still run the handlers but do not deliver those strings to the UI. The handler's own log marker still shows it ran.
A hook handler is like someone copied on an email thread: they see each message and can act on their own, but nothing they do edits, holds back or unsends what was sent. The one documented exception is agent:bootstrap, where a handler may edit the list of files about to be loaded.
- Returning false from a message:received handler drops the message.
- Pushing to event.messages sends a reply on any event, message:received included.
- A handler that throws stops the later handlers and aborts the command.
- Hook handlers have a built-in timeout, so a hung call cannot hold anything up.
- Kick slow work off with void so the handler returns quickly; it is safe.