The gateway formats text in two directions. It orders the prompt so 90% of it comes from the cache. It cuts the model's token drip into 3 clean chat messages instead of 150 fragments.
Choose a prompt order and a way to send the reply, then press Run a turn. Watch how much of the prompt the cache reuses and how many messages reach the chat. Then we build both pipes piece by piece: the budget, the renderer, the caps, the cache line, the chunker and the pacing.
You need Lessons 1 to 4 of this series, or the idea that a model reads a prompt and writes tokens. A little Python helps for the labs. We build the rest from zero.
Lesson 5 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. Section sizes, the 600-character reply and the 4 characters per token are made up. The two rules are OpenClaw's: stable sections sit above the cache boundary, and replies go out as blocks.
Chapter 0
Follow one turn in, through the model, and back out to the chat
Someone types "is the oven off?" into WhatsApp. Before the model can answer, the gateway must write the exact text the model reads. It holds who the agent is, its tools, its workspace and the question. That is the first pipe, context in.
The model answers one token at a time. A token is a piece of a word, about 4 characters of English. WhatsApp knows nothing about tokens. It shows finished messages. So the gateway must regroup the token drip into messages a person can read. That is the second pipe, tokens out.
The top row builds the prompt. The bottom row sends the reply. Press Step to move one stage, or Play to run the turn.
The stages follow OpenClaw's docs on the system prompt and on streaming. Stage names are ours.
Each pipe works under one hard limit:
| Pipe | The limit | The job |
|---|---|---|
| context in | the model's context window, and the price of each token | choose what goes in, cap it, and order it so the cache can reuse it |
| tokens out | a chat app shows whole messages and dislikes floods | cut the stream at clean breaks, merge small pieces, pace them |
The site's tokenization lesson covers what a token is, and long-context LLMs covers why the window is finite. Here we take both as given and look at what the gateway does about them.
Chapter 1
Add up everything the model reads, and keep room for its answer
A model reads at most a fixed number of tokens per request. This limit is its context window. OpenClaw's docs say that everything the model receives counts: the system prompt, the conversation so far, tool calls and their results, and attachments.
The answer also lives in the window, so the gateway must leave room for it. Call the system prompt's size P, the conversation history H, the room kept for the reply R, and the window W. All four are in tokens.
P plus H plus R is at most W.
Add the prompt P, the history H and the reply room R. If the total is bigger than the window W, the request does not fit and something must shrink.
With made-up numbers: a 6,000-character prompt is about P = 1,500 tokens. Twenty turns of 300 tokens give H = 6,000. Keep R = 2,000. The total is 9,500, so an 8,192-token window is 1,308 tokens short.
Pick a window size and drag the history. The bar turns red past the window line.
Illustrative: 300 tokens per turn, a 1,500-token prompt and 2,000 tokens of reply room. Real windows depend on the model.
History grows every turn, so a long chat always reaches the line. OpenClaw's answer is compaction: it writes a summary of old turns into the transcript and keeps recent messages whole. It can also prune old tool results from the prompt without touching the transcript on disk.
The prompt P is the part the gateway controls on every turn. Chapters 2 to 6 are about keeping it small, fixed in size, and cheap.
/context list for sizes per file and totals, or /context detail for each tool schema and skill entry.Chapter 2
Gather live facts, apply settings, and render the text in a function with no side effects
The system prompt is the text the model reads before the conversation: who it is, how to behave, which tools exist. One way to build it is a big template that reads files and settings as it goes. Then nobody can say why a prompt came out the way it did. The answer depends on the disk and the clock at that moment.
OpenClaw splits the job into three layers:
buildConfiguredAgentSystemPrompt applies the agent's settings: the owner's display name, voice hints, model aliases, how memory is cited, how sub-agents are used.buildAgentSystemPrompt renders the text from explicit inputs. It reads no global settings. It is a pure function: the same inputs always give the same output, byte for byte.Each button changes one input, or none. Watch which layer lights up, which named section changes, and the prompt's fingerprint.
The fingerprint is a 32-bit FNV-1a hash of the toy prompt text. The three layer names and the three swappable sections are OpenClaw's; the section texts are ours.
Why insist on purity? Because a prompt you can reproduce is a prompt you can debug. Give the renderer the inputs from a bad turn and you get that exact prompt back. Purity also helps the cache in Chapter 6: same inputs, same bytes, so the cache can reuse them.
The renderer writes the prompt as named sections. A provider plugin may replace one of three: interaction_style, tool_call_style and execution_bias. A model that prefers terse tool calls gets a different tool_call_style, and every other byte stays the same.
buildAgentSystemPrompt a pure renderer that reads no files and no global settings?Chapter 3
Give a sub-agent a smaller prompt by leaving out sections it never uses
A sub-agent is a helper run that the main agent starts for one narrow job, such as "summarise this file". It does not chat with the owner, so it does not need the messaging rules or the owner's profile. Sending them anyway costs tokens on every call.
So the renderer takes a prompt mode:
| Mode | Used for | What it renders |
|---|---|---|
full | the main agent (default) | every section |
minimal | sub-agents | leaves out Memory Recall, Model Aliases, User Identity, Assistant Output Directives, Messaging, Collapsible Details and Silent Replies |
none | a near-raw model | only the base identity line |
Each row is one section, its bar is its size. Pick a mode and watch rows drop out.
Section names and the minimal list are from OpenClaw's system-prompt docs. The sizes are made up for the toy.
What stays in minimal mode is what a helper needs to work: tooling, safety, skills, the workspace, the sandbox and runtime facts. The workspace files of Chapter 4 also shrink for a sub-agent: it gets only AGENTS.md.
The lab below builds an assembler with three rules: drop sections by mode, cap each section, and stop before the total passes the budget. The sizes are scaled down so the caps bite on short strings.
/context list.minimal mode. Compared with full, its system prompt:Chapter 4
Inject each file up to a limit, cap the total, and keep the full file one tool call away
The agent also needs to know its world. That lives in plain files in its workspace, injected when a session starts. OpenClaw calls them bootstrap files:
| File | What it holds |
|---|---|
AGENTS.md | operating instructions, including a Tools section with local notes |
SOUL.md | persona, tone and boundaries |
IDENTITY.md | the agent's name, vibe and emoji |
USER.md | the owner's stable preferences |
BOOTSTRAP.md | a first-run ritual, for brand-new workspaces only |
MEMORY.md | curated long-term facts; main private session only |
A busy MEMORY.md grows without limit, so two caps apply. Call the size of file i in characters ci, the per-file cap b, and the total cap B. The injected total is T.
T equals the sum over i of the minimum of c-i and b, and T is at most B.
bootstrapMaxChars: 20,000 by default.bootstrapTotalMaxChars: 60,000 by default.For each file, take its size c-i or the cap b, whichever is smaller. Add them up to get T. T must stay under the total cap B.
With made-up file sizes: AGENTS 12,000, SOUL 3,000, IDENTITY 800, USER 2,500 and MEMORY 45,000. MEMORY is cut to 20,000. T = 12,000 + 3,000 + 800 + 2,500 + 20,000 = 38,300, under B = 60,000.
Outlined bars are the files on disk; filled bars are what the prompt gets. Grow MEMORY.md, or switch to a sub-agent.
Caps and the sub-agent rule are OpenClaw defaults. File sizes are made up. When the total passes B, the toy trims the last file; the docs do not say which file loses first.
Is a cut MEMORY.md lost? No. OpenClaw keeps the file on disk whole and cuts only the copy it injects. When cutting happens it adds a short notice to the prompt. The model can read the rest with memory_get, which reads a memory file or a range of its lines, or find it with memory_search.
MEMORY.md is 45,000 characters and the per-file cap is 20,000. Has the agent lost 25,000 characters of memory?Chapter 5
Put a short menu entry in the prompt, and let the model read the full skill only when it uses it
A skill is a written procedure the agent can follow, kept in a SKILL.md file. A workspace can have hundreds. Pasting every full file into the prompt would fill the window before the owner speaks.
So OpenClaw injects a menu. Each eligible skill gets one entry in an <available_skills> block: its name, a description and its location, the path to the SKILL.md. When the model picks a skill, it reads the file at that path with the read tool.
How big is the menu? The docs give about 97 characters of fixed markup per entry. Call the number of skills N, and for skill i the lengths of its name, description and location ni, di and li. The menu size is S.
S equals the sum over i from 1 to N of 97 plus n-i plus d-i plus l-i.
For each skill, add 97 to the lengths of its name n-i, description d-i and location l-i. Add the entries for all N skills to get S.
With made-up lengths: N = 40 skills, each with a 20-character name, a 120-character description and a 45-character path. One entry is 97 + 20 + 120 + 45 = 282. S = 40 × 282 = 11,280 characters, about 2,820 tokens. Pasting 40 files of 6,000 characters would cost 240,000.
Each tile is one skill entry. Add skills or shrink the budget and watch the descriptions shorten, then go.
The 97-character overhead and the order of the fallback are from OpenClaw's skills docs. The docs give no default budget; 15,000 is ours. We reuse 97 characters for every format.
The menu has its own budget, skills.limits.maxSkillsPromptChars, with a per-agent override. If the block would pass it, OpenClaw first keeps as many names and locations as fit. It gives what is left to shortened descriptions, and drops descriptions if nothing is left. The prompt then points to openclaw skills check. When the skills_search tool is on, the model can still find a skill that the budget cut.
Chapter 6
Put stable text on top so the provider can reuse it, and push changing text below the line
Every turn the gateway sends nearly the same prompt as last turn. Model providers offer prefix caching: they keep the work done on the start of a prompt. If the next prompt begins with the same bytes, they reuse that work, and the reused tokens are cheaper and faster. The LLM inference lesson shows the cache inside the server.
The catch: reuse stops at the first byte that differs. One changing line near the top, such as the time, makes everything below it new.
The strip is the prompt, front on the left. Green is the cached prefix. Move the clock line and watch the green shrink and the cost bars grow.
Made-up prices: $3 per million input tokens, cached tokens at one tenth. Real prices differ by provider. Section sizes match the hero.
Call the prompt's size T and the cached prefix A, both in tokens. Call the price per token p, and the cached price as a fraction k of p. The cost of one turn's prompt is C.
C equals p times, open bracket, k times A, plus T minus A, close bracket.
Pay the cheap rate k times p for the A cached tokens. Pay the full rate p for the other T minus A tokens. Their sum is C. A bigger A means a smaller C.
With made-up prices: p = $3 per million, k = 0.1, T = 1,500. Stable first gives A = 1,350, so C = $0.000855 a turn. Clock second gives A = 100, so C = $0.00423. Over 1,000 turns: $0.86 against $4.23.
OpenClaw orders the prompt by how often each part changes. Large stable content stays above an internal cache boundary: the Project Context, workspace instructions, fixed policy and common runtime instructions. Below it go the parts that change with tools or channels: Tooling, Skills, Memory Recall, Model Aliases, Sandbox, and per-turn guidance.
Date, time zone and other per-turn facts go in a separate Runtime Context message, outside the system prompt. So the system prompt stays byte-identical even across midnight.
Chapter 7
Wait for enough text, never pass the maximum, and cut at the cleanest break in between
Now the other pipe. Most chat apps cannot grow one message a token at a time. A WhatsApp message goes out once, whole. So OpenClaw's block streaming sends the reply in coarse pieces, called blocks, as they become ready. It is off by default; blockStreamingDefault turns it on.
A component called EmbeddedBlockChunker decides where each block ends. It has two bounds:
minChars, the low bound: emit nothing until the buffer holds at least this many characters. This stops one-word messages.maxChars, the high bound: prefer to cut before this size, and if forced, cut at it. This stops walls of text. It is also clamped to the channel's own message limit.Between the bounds the chunker looks for the cleanest break. It walks down a break ladder: a paragraph break, a newline, a sentence end, any space, and last a hard cut.
Each shaded run is one block. The bar at its end is orange for a clean break and red for a cut through a word. Drag the bounds, or turn on blind cuts.
The bounds and the ladder are OpenClaw's. The reply and the slider ranges are made up; real bounds are larger.
A worked cut, with minChars 60 and maxChars 160. The chunker looks at characters 60 to 160 of the buffer. It finds no blank line, but finds a newline at 109, so the first block is 109 characters and ends on a whole line. The next window starts at 109.
blockStreamingBreak sets when blocks flush. With text_end blocks go out as soon as the chunker emits them. With message_end the gateway waits for the whole assistant message, then flushes.
Chapter 8
Edit one message in place, merge small blocks, space them like a person, and stay silent on purpose
Clean blocks fired the moment they are ready still feel wrong: five quick messages, then silence. OpenClaw has two ways to show a reply as it grows, plus two tools to calm block replies.
Preview streaming uses chat apps that can edit a sent message, such as Telegram, Discord and Slack. One message updates in place:
| Mode | What the person sees |
|---|---|
off | nothing until the final answer |
partial | one preview, replaced by the latest text |
block | one preview that grows in appended steps |
progress | a status line during the work, such as "searching the web", then the final answer |
Discord, Telegram and Slack default to progress. For block replies, coalescing waits for an idle gap, idleMs, and merges small blocks. Discord, Signal and Slack default to minChars 1,500 and idleMs 1,000. humanDelay adds a pause between block replies; its natural setting picks 800 to 2,500 ms at random.
The top lane is what the chunker emits. The bottom lane is what the chat gets. Pick a mode; for block replies, try merging and pacing.
Block sizes, arrival times and the pause values are made up. Mode names, the 1,500 and 1,000 defaults and the 800 to 2,500 ms range are OpenClaw's.
How much time does pacing add? Call the number of block replies n and the average pause d̄. The added time is D.
D equals n minus one, times d-bar.
natural, the middle of 800 and 2,500: 1,650 ms.Count the gaps between messages: n minus 1. Multiply by the average pause d-bar. That is D.
With made-up block counts: n = 4 block replies with natural pacing. D = 3 × 1,650 = 4,950 ms, about 5 seconds. Coalesce them into 2 messages and D = 1,650 ms.
Sometimes the right reply is none, for example in a group chat where the message was not for the agent. The model then answers with the silent token NO_REPLY. Only a final answer whose whole text is that token asks for silence:
| Final text | What the chat gets |
|---|---|
NO_REPLY (any case, any spaces around) | nothing; unsent text from this turn is dropped |
NO_REPLY on the first line, then an answer | the answer; the first line is removed |
an answer, then NO_REPLY on the last line | the answer; the last line is removed |
NO_REPLY. or "NO_REPLY" | that text, shown as a normal message |
Chapter 9
Stream a reply with code through the chunker and see it close and reopen the fence
Chat apps render Markdown, and a code fence is a code block between two lines of three backticks. Cut a reply inside a fence and the first message has an opening fence with no close. The chat then shows the rest of that message, and maybe the next, as broken code.
OpenClaw's rule: never split inside a fence. Sometimes a fence is longer than maxChars and a cut inside it is forced. Then the chunker closes the fence at the end of the block and reopens it at the start of the next. Every block is valid Markdown alone.
The top shows the reply and its blocks; the shaded run is the code fence. Below, each sent block is listed with how it ends. Press Stream, then turn the fence rule off and stream again.
The reply and the bounds are made up. The fence rule (never split inside, close and reopen when forced) is OpenClaw's.
With the rule on, every listed block has an even number of fence lines. With it off, some block opens a fence it never closes, and the list marks it red. Shrink maxChars below the length of the code to force the close-and-reopen case.
Chapter 10
Keep the terms, the numbers, a checklist and the core code in one place
Context in: three layers render a prompt by mode. Workspace files and the skills menu go in under caps. Stable text sits above the cache boundary, and the whole request must fit the window. Tokens out: the chunker cuts at clean breaks, never inside a fence. Previews, coalescing and pacing make the stream calm, and NO_REPLY makes it silent.
| Term | Meaning | OpenClaw value |
|---|---|---|
| context window | tokens a model reads per request | model-specific; /context list shows the sizes |
| compaction | summarise old turns into the transcript | recent messages stay whole |
| renderer | pure function from inputs to prompt | buildAgentSystemPrompt |
| prompt mode | how much of the prompt to render | full, minimal (sub-agents), none |
| per-file cap | most characters per bootstrap file | bootstrapMaxChars 20,000 |
| total cap | most characters of all bootstrap files | bootstrapTotalMaxChars 60,000 |
| skills entry | one menu line per skill | name, description, location; about 97 characters of markup |
| cache boundary | stable text above, changing text below | date and time in a separate Runtime Context message |
| block chunker | cuts the reply into blocks | EmbeddedBlockChunker, {minChars, maxChars, breakPreference} |
| break ladder | preferred cut points | paragraph, newline, sentence, space, hard cut |
| coalescing | merge blocks in short gaps | Discord, Signal, Slack: minChars 1,500, idleMs 1,000 |
| humanDelay | pause between block replies | natural: 800 to 2,500 ms |
| preview modes | one message edited in place | off partial block progress |
| silent token | a final answer that asks for no message | NO_REPLY, the whole text only |
A toy of both pipes. It is a sketch for reading, not OpenClaw's code.
pythondef inject(files, b=20000, B=60000): # chapter 4: T = sum of min(c_i, b) <= B out, total = [], 0 for name, text in files: part = text[:b] part = part[:max(0, B - total)] out.append((name, part, len(part) < len(text))) # flag: add a truncation notice total += len(part) return out def order(sections): # chapter 6: stable first, keep relative order return [s for s in sections if s.stable] + [s for s in sections if not s.stable] LADDER = ["\n\n", "\n", ". ", " "] def cut(buf, lo, hi, in_fence): # chapter 7: best break in (lo, hi] for mark in LADDER: p = buf.rfind(mark, lo, hi) while p != -1 and in_fence(p + len(mark)): # chapter 9: never inside a fence p = buf.rfind(mark, lo, p) if p != -1: return p + len(mark), False return hi, in_fence(hi) # hard cut; True means close and reopen the fence def is_silent(final): # chapter 8: the whole text only return final.strip().upper() == "NO_REPLY"
MEMORY.md, daily notes and memory search work.Now press Present or Teach and explain it from memory. Cover the window sum, the layers, the caps, the skills menu, the cache boundary, the chunker and the fence rule. Then go back to the hero and run a turn both ways again.