Four surfaces let a gateway grow without touching its core: skills, plugins, hooks and automations. Each one costs almost nothing until its moment. Forty skills baked into the prompt cost 240,000 characters a turn; loaded on demand they cost 17,280.
Choose Bake it in or Load on demand, add abilities, and press Fire the 8:00 job. Watch a scheduled run pass through a hook, a skill and a plugin channel, and watch the prompt bar. Then we build each surface: skills, plugins and their load policy, hooks and their precedence, the scheduler, webhooks, and the whole series in one run.
You need Lessons 1 to 10 in rough outline, or a rough idea of what a server process and a prompt are. A little Python helps for the labs. We build the rest from zero.
Lesson 11 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw, a self-hosted gateway between chat apps and an AI agent. We checked every OpenClaw detail here against its documentation.
Illustrative toy. A full skill is 6,000 characters and a menu entry is 282 (97 characters of markup, from OpenClaw's skills docs, plus a name, a description and a path). The 400,000-character window is our assumption, about 100,000 tokens.
Chapter 0
See why abilities must cost nothing until they are used, and meet the four surfaces that do it
Your gateway from Lessons 1 to 10 works. Now you want more. The agent should follow your deploy runbook, talk on Matrix, save notes when you reset a chat, and send a briefing at 8:00 while you sleep.
The easy way is to stuff the core. Paste the runbook into the prompt. Add a Matrix branch to the code. Add a timer somewhere. After a year the prompt is a wall the model skims, and nobody dares to touch the core.
Count what that costs. Call the number of installed skills N and the size of one full skill F, in characters. A menu line that names one skill is m characters. The agent uses k skills in this turn.
C-baked equals N times F, and C-demand equals N times m, plus k times F.
Baked in, every turn pays N full skills. On demand, every turn pays N short lines, plus the k full skills it reads.
With made-up sizes: N = 40, F = 6,000 and m = 282, as in Lesson 5. C-baked = 40 × 6,000 = 240,000. With k = 1, C-demand = 11,280 + 6,000 = 17,280, about 14 times less.
Grey is baked in, pink is on demand. Add skills and watch which line crosses the window.
F = 6,000 and m = 282 are illustrative. The 400,000-character window is our assumption.
The same idea holds for code. Every surface below keeps its cost away until its moment arrives:
| Surface | What it adds | When it costs |
|---|---|---|
| skill | a written procedure | one menu line; the full text when read |
| plugin | a subsystem: a channel, a provider, a tool | when its capability is called |
| hook | your code on a gateway event | when its event fires |
| automation | work with no message to start it | when its schedule or trigger fires |
/context list.Chapter 1
Check which skills may enter the menu, and decide which copy wins when two share a name
A skill is a written procedure in a SKILL.md file that the agent reads when it needs it. Lesson 5 showed the menu: one line per skill in the prompt, the full file on demand, and a character budget. Here we ask two earlier questions.
First: may this skill appear at all? A skill that runs ffmpeg is useless on a host without ffmpeg. So each skill declares its needs, and the gateway checks them before it writes the menu. A skill that fails a check is invisible. It costs not even a line.
| Gate in the SKILL.md metadata | Passes when |
|---|---|
os | the host is one of the listed systems, such as darwin or linux |
requires.bins | every listed program is on PATH |
requires.env | every listed variable is set, in the process or in config |
requires.config | every listed config key is on, such as browser.enabled |
Second: two folders hold a skill with the same name. Which one wins? For skills, the most specific place wins. The workspace, the project folder the agent works in, beats your machine-wide skills, which beat the bundled ones. Plugin skills sit lowest.
Each tile is one installed skill. Change the host and watch tiles enter or leave the menu.
The gate names and the precedence order are from OpenClaw's skills docs. The six skills are made up; a menu line is 282 characters as in Lesson 5.
Worked number. Six skills are installed. video-encode needs ffmpeg, which is missing. mac-notes needs macOS, but the host is Linux. Four pass, and one of them, report-format, exists twice. The menu holds 4 lines: 4 × 282 = 1,128 characters.
ffmpeg, but the agent still does not offer the video skill.openclaw skills check: the gate now passes.uv program. The host does not have it. What happens?Chapter 2
Plug many vendors into one capability contract, so no consumer needs to know a vendor
A skill changes what the agent knows. A plugin is a package of code that changes what the gateway can do: a new channel such as Matrix, a model provider, a speech engine, a tool, a memory store.
Picture speech. Reply-time speech and a phone-call plugin both need to turn text into audio. Four vendors can do it. If each consumer calls each vendor directly, every pair needs its own glue code. Call the number of vendors V and the number of consumers C. The count of glue pieces is G.
G-direct equals V times C, and G-contract equals V plus C.
Without a contract, multiply V by C. With a contract, each vendor implements it once and each consumer calls it once, so add V and C.
With made-up counts: V = 4 speech vendors and C = 3 consumers. G-direct = 4 × 3 = 12. G-contract = 4 + 3 = 7.
This is the hub of Lesson 1 again, one level down. OpenClaw calls the shared shape a capability: a typed contract owned by core, such as speech, web search or a channel. A plugin is the owner of an implementation. It registers it with calls such as api.registerSpeechProvider(...) or api.registerChannel(...).
Pink plugins on the left, consumers on the right. Switch to the contract and add a vendor.
The four vendor names own speech in OpenClaw's plugin docs; voice-call consumes the shared speech helper. The third consumer and the counts are illustrative.
Load happens in four steps. The gateway reads each plugin's manifest, openclaw.plugin.json, without running its code. It decides whether the plugin may load. It runs the plugin's register(api), which fills a central registry. Then channels, tools and routes read from that registry.
openclaw plugins inspect <id> shows a diagnostic for the duplicate.Chapter 3
Apply deny, allow and enable in order, and fill the one-of-a-kind slots
A plugin is code in your gateway's process. So the gateway needs a rule for which plugins may load. OpenClaw keeps it in config under plugins, and three switches decide.
For one plugin, call these three facts by letters. d is 1 if the plugin is on the deny list. a is 1 if the allow list is empty or names the plugin. e is 1 if the plugin is enabled. The plugin loads when L is 1.
L equals one minus d, times a, times e.
plugins.deny names it. One minus d flips it: denied gives 0.plugins.allow is empty or names it.Multiplying 0s and 1s is AND. Any 0 stops the plugin, so deny wins over allow and over enable.
With made-up plugins: voice-call has d = 0, a = 1, e = 1, so L = 1. A plugin on the deny list has d = 1, so L = 0 × 1 × 1 = 0. A new workspace plugin has e = 0, so L = 0.
Some categories hold exactly one plugin. A slot picks it: plugins.slots.memory chooses the one memory plugin, and plugins.slots.contextEngine the one context engine. Choosing a memory plugin counts as enabling it.
Each row is one plugin; the columns are d, a and e. Change the policy and read which rows load.
The rules are from OpenClaw's plugin docs. The rows are illustrative, and the docs list more exceptions to the allow list than we draw.
openclaw plugins list, but its hooks never run.openclaw plugins inspect <id> --runtime --json lists what it registered. Then trigger the event and check its effect.openclaw plugins reload <id>. A list reads config; it does not prove the running gateway loaded the code.plugins.allow and plugins.deny, and it is enabled. Does it load?Chapter 4
Run your code when the gateway emits an event, in a fixed order, and know what waits for it
You want every /new to save the last few messages to memory. You do not want to edit the agent loop for that. You want a small piece of code that the gateway calls when a /new happens.
That is a hook: a handler that runs when the gateway emits a named event. An OpenClaw internal hook is a folder with a HOOK.md, which lists its events, and a handler.js or handler.ts. Lesson 4 covered the other kind, typed plugin hooks such as before_tool_call, which can block a tool. Internal hooks only observe: their return value is ignored.
| Event | Fires when | Does the gateway wait? |
|---|---|---|
command:new, command:reset | an authorized /new or /reset | yes |
session:compact:before, :after | around compaction (Lesson 5) | yes |
agent:bootstrap | before the workspace files enter the context | yes |
gateway:startup | after hooks and channels start | no, the bind does not wait |
message:received, message:sent | a message enters or leaves | no, observation only |
Handlers for one event run one after another. Listeners for the whole family, such as command, go first, then listeners for the exact key, each group in registration order. A handler that throws is logged, and the next one still runs. There is no priority number. So the time a waited event adds is a sum. Call the run time of handler i ti.
T-wait equals the sum over i of t-i.
Handlers run in a line, so add their times t-i. For an event the gateway does not wait for, the turn pays nothing.
With made-up times on command:new: 5 ms, 40 ms and 120 ms. T-wait = 5 + 40 + 120 = 165 ms before the reply to /new.
Pick an event and press Emit. Handlers run left to right. Make one throw.
The order rules and the wait column are from OpenClaw's hook docs. The handler times and the audit handler are illustrative.
OpenClaw ships five bundled hooks: session-memory saves recent messages on /new, /reset and an automatic reset; command-logger appends commands to a log; bootstrap-extra-files adds named workspace files such as AGENTS.md; compaction-notifier reports compaction; boot-md runs your BOOT.md at startup through an agent run.
/new takes seconds.command:new; T-wait is their sum.command:new. The second one throws. What happens?Chapter 5
Find hooks in four places, pick one copy per name, and see why hooks and skills pick differently
Hooks come from four places. Bundled hooks ship with OpenClaw. Plugin hooks come from active plugins. Managed hooks live in ~/.openclaw/hooks/, machine-wide. Workspace hooks live in the project's hooks/ folder.
Two places can hold a hook with the same name. For skills, the workspace copy won (Chapter 1). For hooks, the rule turns around:
enabled: true entry in config.Why the difference? A skill is text the model reads. A hook is code that runs inside the gateway process, with its files, network and secrets. A workspace can be a repository you cloned this morning. If its hooks/session-memory could replace yours, cloning a repo would hand it your gateway.
The same name exists in several places. Switch between hook rules and skill rules, then add or remove copies.
Both rule sets are from OpenClaw's docs (hook discovery; skills loading order). Extra directories sit between plugin and managed for hooks; we leave them out.
Worked case. session-memory exists as bundled and as a workspace copy. Under hook rules the bundled copy runs and the workspace copy is ignored. Add a managed copy: now the managed copy runs. Under skill rules the workspace copy would win every time.
Discovery also has a master switch. With no hooks.internal settings at all, the gateway skips loading directory hooks. Named entries in hooks.internal.entries form an allow list.
hooks/session-memory, and the bundled session-memory is on. Which copy runs?Chapter 6
Write when a job fires in five fields, and catch the day rule before it fires five times
Hooks wait for an event. An automation starts work with no message at all: "every weekday at 7:00, summarize the night". OpenClaw's scheduler runs inside the gateway process and keeps its jobs in a SQLite database, so a restart does not lose them. You manage them with openclaw automations; openclaw cron is the same command.
A job has one of five schedule kinds: at (once), every (a fixed interval), cron, on-exit (when a command ends) and stream (from a command's output lines). The cron kind takes a cron expression: five fields for minute, hour, day of the month, month and day of the week. 0 8 * * * means minute 0 of hour 8, every day. */15 * * * * means every 15 minutes.
Now the trap. You want "9:00 on the 15th, but only if it is a Monday" and write 0 9 15 * 1. When both day fields are set, standard cron fires when either matches. Call the days in a month that match the day-of-month field Dm, the days that match the weekday field Dw, and the days that match both Db. The fire count is n.
n equals D-m plus D-w, minus D-b.
Count the 15th, count the Mondays, and take away the days you counted twice. That is how often the job fires, not 0 or 1.
December 2026 has Mondays on the 7th, 14th, 21st and 28th, and the 15th is a Tuesday. n = 1 + 4 − 0 = 5 fires. You wanted 0.
Pick an expression and a month. Warm days are fires. Compare the OR rule with the plus modifier.
The OR rule and the +1 modifier are from OpenClaw's schedule docs, which use the croner parser. The calendars are real.
Two more facts. A cron expression without --tz uses the gateway host's time zone. And a recurring top-of-hour expression, minute 0 with any hour, is spread out by up to 5 minutes to avoid a load spike. Pass --exact to turn that off.
openclaw automations runs <id>.Chapter 7
Pick the session a job runs in, size the run slots, and make an unattended run quiet when nothing changed
The clock says 2:00 and a job fires. Where does it run? A person is not there to answer questions, so the job must carry everything it needs. OpenClaw gives four execution styles, set with --session:
| Style | Runs in | Good for |
|---|---|---|
main | the agent's main session, with its history | reminders |
isolated | a fresh session, cron:<jobId>, each run | reports, chores |
current | a child run of the chat that created it | work that needs that chat |
session:<id> | a named session that keeps history | a standup that builds on yesterday |
An isolated run starts a new transcript each time, so last night's leftovers cannot steer tonight's report. Its result goes to its delivery target, not into your live chat. The ten-job burst in Lesson 6 showed why such runs need their own lane.
The scheduler also caps how many jobs run at once: up to 8, and up to 16 while at least 1 GiB of memory is free. Call the jobs due at once J, the slots S and the length of one job t. The last one finishes at T.
T equals the ceiling of J over S, times t.
Jobs start in waves of S. Divide J by S and round up to get the waves. Multiply by t.
With made-up jobs: J = 20, t = 6 minutes. With S = 8, the ceiling of 2.5 is 3 waves, so T = 18 minutes. With S = 16, 2 waves, so T = 12.
Each block is one 6-minute job. Add jobs, then free memory to open more slots.
The 8 and 16 slot limits are from OpenClaw's automation docs; the real scheduler adds slots one at a time as memory allows. Equal 6-minute jobs are illustrative.
An unattended run must end with the deliverable, not a plan or a question. When nothing needs doing, the agent replies NO_REPLY and nothing is sent. A one-shot at job deletes itself after success.
--session: it is main or a named session, so history carries over.isolated, and put what each run needs in the job's message or scratch.Chapter 8
Let another system start work over HTTP, and see what replaced the periodic heartbeat
Your build server finishes at a random time. You want the agent to hear about it now, not at the next scheduled check. The clock is the wrong trigger. You need an inbound webhook: an HTTP endpoint on the gateway that another system calls.
OpenClaw's webhooks are off by default. You turn them on with hooks.enabled and a dedicated token, and then the gateway serves two endpoints under /hooks:
| Endpoint | What it does | Session |
|---|---|---|
POST /hooks/wake | queues a short notice, a system event, for the agent | the main session, behind work already queued |
POST /hooks/agent | submits a full agent turn with a message | a fresh isolated session by default |
Every request carries the token in a header: Authorization: Bearer <token> or x-openclaw-token. A token in the URL is rejected, because URLs end up in logs. A 200 means the run was admitted. It does not mean the model finished or a message arrived.
The blue box is the build server. Pick an endpoint and how it sends the token, then press Send.
Endpoints, headers and the 200, 401 and 404 meanings are from OpenClaw's webhook docs. The docs say a URL token is rejected but give no code, so we show none.
Where did the heartbeat go? Older OpenClaw versions woke the agent on a fixed beat to look around. That runner is retired. openclaw doctor --fix turns old heartbeat settings into ordinary automation jobs, and setup creates one disabled job called Proactive check. A job can respect quiet hours with activeHours and wait for an idle agent with idleOnly.
Worked case. The build server posts to /hooks/wake with the right header. The gateway answers 200 with eventOutcome: "queued". The same notice sent twice in a row coalesces into one.
200, but no chat message appears.openclaw logs --follow for hook agent run completed and the runId.deliver, and give both channel and to for direct delivery.Chapter 9
Follow the 8:00 briefing step by step and light up every lesson it uses
Each surface alone is half a feature. The scheduler gives a time but no context. A hook gives context but never starts anything. A skill is a procedure with no occasion. A plugin is plumbing. Put together, they make a routine that runs while you sleep.
Step through the 8:00 briefing. On the left are the 11 lessons of this series. Each step lights the lessons it depends on, so the whole gateway shows up in one run.
Press Play, or Step one move at a time. Turn on the provider failure to see the run fail.
An illustrative run built from documented behaviour. The calendar tool and the Slack target are our example; each step names the lesson that covers it.
Read the run as a sentence: the right time (the scheduler), the right context (a hook), the right procedure (a skill), through the right channel (a plugin). Each piece loads only when its step arrives.
Now the series, as one spine:
openclaw automations runs <id> for the run, then the delivery log, then the channel.Chapter 10
Keep the terms, the numbers, a checklist and the core code in one place
Skills are text, gated and listed by one line each. Plugins are code that owns capabilities, behind a load policy. Hooks observe events, one copy per name, and the workspace can only add. Automations start work on a schedule or a trigger, usually in a fresh session.
| Term | Meaning | OpenClaw value |
|---|---|---|
| skill gates | checks before the menu | os, requires.bins, requires.env, requires.config |
| skill precedence | which copy of a name wins | workspace, then managed, then bundled, then plugin |
| plugin manifest | read before any code runs | openclaw.plugin.json |
| plugin policy | which plugins load | plugins.deny beats plugins.allow and enable |
| slots | one plugin per category | plugins.slots.memory, plugins.slots.contextEngine |
| internal hook | a handler on an event | HOOK.md + handler.js; config under hooks.internal |
| hook precedence | which copy of a name wins | managed, then plugin, then bundled; workspace adds only |
| schedule kinds | when a job fires | at, every, cron, on-exit, stream |
| top-of-hour stagger | spread for minute-0 jobs | up to 5 minutes; --exact turns it off |
| run slots | jobs at once | 8, up to 16 with 1 GiB free |
| webhooks | HTTP triggers | POST /hooks/wake, POST /hooks/agent, token in a header |
NO_REPLY when nothing changed.A toy extension layer: a plugin registry, a hook bus and a scheduler tick. It is a sketch for reading, not OpenClaw's code.
pythonimport math class Gateway: def __init__(self, deny, allow): self.deny, self.allow = set(deny), set(allow) self.caps, self.hooks, self.jobs = {}, {}, [] # capability -> provider, event -> handlers def load_plugin(self, pid, enabled, register): # L = (1 - d) * a * e d = pid in self.deny a = (not self.allow) or pid in self.allow if d or not a or not enabled: return False register(self) # the plugin fills the registry return True def register_capability(self, cap, provider_id, fn): if (cap, provider_id) in self.caps: raise ValueError("duplicate provider id") self.caps[(cap, provider_id)] = fn def on(self, event, handler): # registration order = run order self.hooks.setdefault(event, []).append(handler) def emit(self, event, ctx): # observe only; errors never stop the line family = event.split(":")[0] for h in self.hooks.get(family, []) + self.hooks.get(event, []): try: h(ctx) except Exception as err: print("hook failed:", err) def tick(self, now, run_turn, slots=8): # fire due jobs, at most `slots` at once due = [j for j in self.jobs if j["matches"](now)][:slots] for j in due: session = "cron:%s" % j["id"] # isolated: a fresh transcript per run self.emit("agent:bootstrap", {"session": session}) reply = run_turn(session, j["message"]) if reply != "NO_REPLY": j["deliver"](reply)
Now press Present or Teach and explain it from memory: the cost of baking in, skill gates, capability contracts, the load rule, hook order and precedence, the cron OR rule, isolated runs and the two webhooks. Then walk the series spine from the daemon to the extensions, and go back to the hero to fire the 8:00 job once more.