Extending the Agent

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.

Run the 8:00 briefing

40

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

Four Ways to Grow a Gateway

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.

Say it aloud

C-baked equals N times F, and C-demand equals N times m, plus k times F.

Cbaked
C-baked the prompt characters each turn when every skill is pasted in.
N
N the number of installed skills.
F
F the size of one full skill, in characters.
Cdemand
C-demand the characters each turn with a menu and on-demand reads.
m
m one menu line: a name, a description and a path.
k
k the skills the agent reads in this turn.
In plain words

Baked in, every turn pays N full skills. On demand, every turn pays N short lines, plus the k full skills it reads.

With numbers

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.

Grow the shelf

Grey is baked in, pink is on demand. Add skills and watch which line crosses the window.

40
1

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:

SurfaceWhat it addsWhen it costs
skilla written procedureone menu line; the full text when read
plugina subsystem: a channel, a provider, a toolwhen its capability is called
hookyour code on a gateway eventwhen its event fires
automationwork with no message to start itwhen its schedule or trigger fires

The road

  1. Skills, the cheapest surface: the gates a skill must pass, and which copy wins.
  2. Plugins add subsystems: one capability contract, many owners.
  3. Which plugins load: deny, allow, enable, and the one-of-a-kind slots.
  4. Hooks on lifecycle events: what fires, in what order, and what waits.
  5. Hook discovery and precedence: why a workspace hook cannot replace a managed one.
  6. The scheduler and cron: five fields, and the day rule that surprises everyone.
  7. How a scheduled run executes: sessions, slots and unattended replies.
  8. Webhooks, wake, and the old heartbeat: triggers that are not the clock.
  9. One run through the whole gateway: all 11 lessons in one briefing.
  10. Field guide: terms, numbers, a checklist, the core code and where to go next.
Why is pasting every procedure into the system prompt the wrong way to extend an agent?

Chapter 1

Skills, the Cheapest Surface

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 metadataPasses when
osthe host is one of the listed systems, such as darwin or linux
requires.binsevery listed program is on PATH
requires.envevery listed variable is set, in the process or in config
requires.configevery 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.

Stock the menu

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.

A skill requires the uv program. The host does not have it. What happens?

Chapter 2

Plugins Add Subsystems

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.

Say it aloud

G-direct equals V times C, and G-contract equals V plus C.

Gdirect
G-direct glue pieces when each consumer calls each vendor.
V
V the vendor plugins that implement the capability.
C
C the consumers that use the capability.
Gcontract
G-contract glue pieces when everyone meets at one core contract.
In plain words

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 numbers

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(...).

Wire the speech capability

Pink plugins on the left, consumers on the right. Switch to the contract and add a vendor.

4

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.

A new speech vendor ships a plugin. What must change in the voice-call plugin for it to use the new vendor?

Chapter 3

Which Plugins Load

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.

Say it aloud

L equals one minus d, times a, times e.

L
L 1 if the plugin loads, 0 if not.
d
d 1 if plugins.deny names it. One minus d flips it: denied gives 0.
a
a 1 if plugins.allow is empty or names it.
e
e 1 if it is enabled. Workspace plugins start at 0.
In plain words

Multiplying 0s and 1s is AND. Any 0 stops the plugin, so deny wins over allow and over enable.

With numbers

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.

Set the load policy

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.

A plugin is on both plugins.allow and plugins.deny, and it is enabled. Does it load?

Chapter 4

Hooks on Lifecycle Events

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.

EventFires whenDoes the gateway wait?
command:new, command:resetan authorized /new or /resetyes
session:compact:before, :afteraround compaction (Lesson 5)yes
agent:bootstrapbefore the workspace files enter the contextyes
gateway:startupafter hooks and channels startno, the bind does not wait
message:received, message:senta message enters or leavesno, 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.

Say it aloud

T-wait equals the sum over i of t-i.

Twait
T-wait how long a waited event holds up its turn, in milliseconds.
Σi
the sum over i one term for each handler on that event.
ti
t-i the run time of handler i.
In plain words

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 numbers

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.

Emit an event

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.

Three handlers listen on command:new. The second one throws. What happens?

Chapter 5

Hook Discovery and Precedence

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:

  1. A plugin hook can replace a bundled hook of the same name.
  2. A managed hook can replace a bundled or a plugin hook.
  3. A workspace hook can add a new name. It cannot replace any of the others.
  4. A workspace hook loads only with its own 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.

Resolve a name clash

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.

Your workspace has hooks/session-memory, and the bundled session-memory is on. Which copy runs?

Chapter 6

The Scheduler and Cron

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.

Say it aloud

n equals D-m plus D-w, minus D-b.

n
n how many days in the month the job fires.
Dm
D-m days matching the day-of-month field, here the 15th.
Dw
D-w days matching the weekday field, here every Monday.
Db
D-b days matching both. Subtract them so no day counts twice.
In plain words

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.

With numbers

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.

Read a cron expression

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.

A job uses 0 9 1 * 5. How often does it fire?

Chapter 7

How a Scheduled Run Executes

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:

StyleRuns inGood for
mainthe agent's main session, with its historyreminders
isolateda fresh session, cron:<jobId>, each runreports, chores
currenta child run of the chat that created itwork that needs that chat
session:<id>a named session that keeps historya 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.

Say it aloud

T equals the ceiling of J over S, times t.

T
T when the last job finishes, in minutes after the start.
⌈ ⌉
the ceiling of round up to a whole number: a half wave is still a wave.
J
J the jobs due at the same moment.
S
S the run slots: 8, or up to 16 with memory free.
t
t how long one job takes, in minutes.
In plain words

Jobs start in waves of S. Divide J by S and round up to get the waves. Multiply by t.

With numbers

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.

Fill the run slots

Each block is one 6-minute job. Add jobs, then free memory to open more slots.

20

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.

Twenty-five 4-minute jobs are due at once with 8 slots. When does the last one finish?

Chapter 8

Webhooks, Wake, and the Old Heartbeat

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:

EndpointWhat it doesSession
POST /hooks/wakequeues a short notice, a system event, for the agentthe main session, behind work already queued
POST /hooks/agentsubmits a full agent turn with a messagea 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.

Call the gateway

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.

A monitoring service must hand the agent a raw email to read. Which endpoint, and why?

Chapter 9

One Run Through the Whole Gateway

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.

Play the 8:00 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:

  1. One daemon owns every chat connection (Lesson 1).
  2. It speaks a strict wire protocol to its clients (2), and decides who may connect (3).
  3. Each message runs the agent loop (4), with a built prompt and a streamed reply (5).
  4. A queue with lanes keeps runs from colliding (6), and sessions keep conversations apart (7).
  5. Memory gives continuity (8), and the gateway heals its own failures (9).
  6. Tools and sandboxes let it act safely (10), and the four surfaces extend every layer (11).
In the 8:00 briefing, which surface supplies today's workspace files to the run?

Chapter 10

Field Guide

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.

TermMeaningOpenClaw value
skill gateschecks before the menuos, requires.bins, requires.env, requires.config
skill precedencewhich copy of a name winsworkspace, then managed, then bundled, then plugin
plugin manifestread before any code runsopenclaw.plugin.json
plugin policywhich plugins loadplugins.deny beats plugins.allow and enable
slotsone plugin per categoryplugins.slots.memory, plugins.slots.contextEngine
internal hooka handler on an eventHOOK.md + handler.js; config under hooks.internal
hook precedencewhich copy of a name winsmanaged, then plugin, then bundled; workspace adds only
schedule kindswhen a job firesat, every, cron, on-exit, stream
top-of-hour staggerspread for minute-0 jobsup to 5 minutes; --exact turns it off
run slotsjobs at once8, up to 16 with 1 GiB free
webhooksHTTP triggersPOST /hooks/wake, POST /hooks/agent, token in a header

Checklist for extending any agent gateway

The core, in code

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)

Where each thread continues

The takeaway. Make every ability cheap until used: skills as menu lines, plugins behind contracts and a deny list, hooks that observe and cannot be hijacked by a folder, and scheduled runs that start fresh and stay quiet when nothing changed.
In one sentence, what do the four surfaces give the gateway?

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.

Anatomy of an Agent Gateway, Lesson 11: Skills, Plugins, Hooks and Automation
OpenClaw docs · Back to Lesson 1 · Back to Gleams