OpenClaw Token Governance: API Costs, Context Bloat, and Zombie Processes

An autonomous agent can look industrious while it burns through context, holds a stale session lock, or revives after a restart with work that should no longer run. OpenClaw makes it possible to connect messaging, tools, files, scheduled work, and a model behind one local Gateway. That power shifts the operating question from “Can the agent do it?” to “Can the operator see, limit, and recover the work?”
The dangerous costs are rarely the headline model price. They arrive through long transcripts, tool output that keeps getting reintroduced to the model, cache misses after idle periods, duplicated automation, and a service lifecycle nobody owns. A capable agent with no token budget, session policy, or restart discipline is an expensive unattended process.
OpenClaw has added useful controls: automatic compaction, pre-compaction memory flushes, session compaction commands, usage reporting, cache-aware pruning, and restart recovery. They reduce operational risk, but they do not replace a deliberate policy. This field guide explains the platform and the operator practices that keep an agent system from eating its own context or haunting its host.
Overview
OpenClaw is an open-source agent runtime that puts a local Gateway between communication channels, model providers, tools, sessions, and scheduled work. It can receive a request through a supported channel, route it to an agent, let that agent use approved tools, and retain the work in local state. The model supplies reasoning; the Gateway supplies the persistent control plane.
The project was built by Peter Steinberger and the community and is now presented in the official documentation as an OpenClaw Foundation project. Its appeal is practical: operators can choose their model provider, keep the Gateway and local state on infrastructure they control, and connect an agent to work that occurs outside a chat window.
That same design introduces an operational surface. A conversation is a stateful resource. A background service has a lifecycle. A browser or shell tool can produce far more text than an operator intended to send back into the next model call. Token governance is the discipline of setting limits and observing those interactions before a small workflow becomes a recurring bill or a recovery problem.
Runtime Reality
OpenClaw requires a supported Node.js runtime. The project currently supports Node 22.22.3 or newer, Node 24.15 or newer, and Node 25.9 or newer; Node 24 is the recommended default. Bun can install the package, but the executable still depends on Node because OpenClaw state uses node:sqlite. See the official Node requirements before treating an old server image as ready.
Docker is optional, not mandatory. It is useful for an isolated or disposable Gateway, and it is the default sandbox backend when agent sandboxing is enabled. A Docker deployment needs Docker Desktop or Engine, Compose v2, at least 2 GB of RAM for image builds, and enough disk for images and logs. A normal local install remains the simpler choice for a single operator who does not need container isolation.
The standard CLI path is straightforward:
npm install -g openclaw@latest
openclaw onboard --install-daemon
openclaw --version
openclaw doctor
openclaw gateway status
The installation guide documents equivalent pnpm, Bun, source, container, and hosted paths. Run openclaw doctor before connecting a channel or adding credentials. A clean install is a good moment to decide which machine, user account, service manager, model account, and notification channel own the system.
Where Tokens Go
OpenClaw cannot make model usage free, but it can report usage and manage session history. Token consumption normally rises through five paths:
| Cost driver | What happens | Operator response |
|---|---|---|
| Long conversations | The model receives recent transcript context, including prior decisions and tool results. | Put bounded tasks in separate sessions and compact oversized sessions. |
| Large tool output | Web pages, logs, files, and command output can become durable session context. | Ask tools for structured, limited output; save full artifacts outside the chat. |
| Retry loops | A failing task can keep issuing model calls or tool calls. | Set stop conditions and alert on repeated failures. |
| Cache expiry | A session that idles past provider cache TTL can require fresh cache writes. | Use cache retention deliberately; keep only valuable recurring sessions warm. |
| Background work | Heartbeats, crons, and subagents can all create billable activity. | Give each job an owner, purpose, frequency, and budget. |
Use /usage tokens when the immediate question is token volume. Use /usage full when local pricing data is configured and you need estimated cost. OpenClaw can also show usage details through a custom messages.usageTemplate. The token-use reference notes that estimated cost depends on model pricing configuration and provider usage metadata, so treat a blank cost display as missing telemetry, not proof that work was free.
Compaction is the first response to a bloated session. It summarizes older turns into a persisted compaction entry and retains recent messages. Transcript retention still depends on the session-maintenance and compaction settings. The CLI command below calls the Gateway’s session-compaction path:
openclaw sessions compact "agent:main:main"
For a fixed history tail rather than a model-generated summary, use --max-lines. The sessions reference shows both modes and reports an example that reduced a session from 243,868 tokens to 34,941. That is an example, not a promised reduction rate. Verify the result against the task that needs to continue.
Governance Before Autonomy
Start with a written operating policy. It can be short, but it must answer questions the agent cannot answer safely on its own.
| Policy decision | Recommended starting point |
|---|---|
| Session ownership | One named owner per persistent agent and scheduled job. |
| Task boundary | One deliverable per session; export the result, then start fresh for the next phase. |
| Token review | Check usage after every new workflow and on a regular operating cadence. |
| Spend ceiling | Define a provider-side hard limit where available, plus an operator alert before it. |
| Tool output | Return a concise schema or summary; store raw results in a file or database. |
| Credentials | Use least-privilege secrets; rotate any token exposed to a transcript, shell history, or log. |
| Restart authority | One service manager and one documented restart command per Gateway. |
| Recovery rule | Never blindly repeat a side-effecting task after an interruption. Review state first. |
OpenClaw offers a pre-compaction memory flush that can write durable state before context is compressed. It is enabled by default for embedded OpenClaw sessions. The session-management reference explains that it can trigger before the compaction threshold and can use a separate model for the housekeeping turn. That is useful for preserving decisions, but it should not become an excuse to keep a sprawling project in one endless conversation.
Zombie Processes, Defined Properly
“Zombie process” is often used loosely for any agent that seems stuck. In Unix terms, a zombie is a terminated process awaiting parent cleanup. In an OpenClaw operating context, the more common hazards are orphaned service processes, stale session locks, duplicate Gateways, failed subagents, and interrupted work that a restart tries to resume.
The symptom is usually mundane: a port is already in use, a channel appears connected to the wrong instance, the same job sends two messages, a session reports busy long after the user stopped it, or a restart duplicates a task. Treat this as a lifecycle defect, not an invitation to rotate credentials at random.
Current OpenClaw restart recovery is designed to be conservative. A requested restart stops accepting new work, drains active work for up to five minutes by default, marks interrupted sessions for recovery, and scans for sessions that claim to be running without a live owner on startup. It retries recovery with durable identifiers and avoids blindly re-running a turn when the transcript ends on a stale approval or another unsafe state. Read the restart-recovery documentation before replacing it with homemade restart scripts.
A Safe Restart Workflow
Use a controlled restart when configuration, an update, or a service problem requires one. Do not start a second Gateway merely because the first one feels unresponsive.
- Check the active process and service state with
openclaw gateway status. - Inspect the affected session and note whether it has pending external writes, approvals, payments, messages, or destructive tools.
- Let a normal restart drain active work when possible:
openclaw gateway restart. - After startup, inspect the operator-facing result before approving any resumed side-effecting work.
- If the host reports a port conflict or duplicated process, stop the service through its owning service manager, identify the listener, and remove the duplicate before starting one managed instance.
- Run
openclaw doctorafter repair. Do not allow a second user-level service to compete with a system-level service for the same profile and port.
On macOS, OpenClaw uses a LaunchAgent for managed startup. On Linux, it supports a systemd user service; a system service is the better fit for multi-user or always-on hosts. The Gateway runbook explicitly warns against installing a user-level service alongside a system-level service for the same profile and port. One Gateway, one owner, one service definition.
Workflows Worth Copying
Research With a Handoff
Ask one agent to gather sources and return a compact evidence file: URLs, dates, short findings, and unresolved conflicts. Start a separate writing session with that file. The writer receives an intentional brief, not every search result and browser transcript.
Build With Checkpoints
For coding or configuration work, define a checkpoint after discovery, plan, implementation, and verification. Save artifacts at each checkpoint. A restart can then resume from an inspected artifact instead of replaying a long tool history with unclear side effects.
Scheduled Work With a Budget
Give every cron or heartbeat a one-line contract: purpose, schedule, expected output size, maximum retries, channel, and owner. If the task has no useful output for several runs, disable it and inspect the logs. Persistence is not a reason to keep spending.
Multi-Agent Work With Narrow Briefs
Give each subagent a scoped input and a structured output contract. The coordinator should receive a table, JSON object, or concise memo, not raw browsing logs. Separate workspaces and sessions prevent one agent’s detritus from becoming every other agent’s context tax.
Starter Prompts
Use prompts that set output limits and handoff boundaries at the beginning.
Research [topic] using up to five primary sources. Return a table with source URL,
publication date, claim, and one supporting quotation of no more than 20 words.
List unresolved facts separately. Do not include browsing narration.
Inspect [directory or repository] for [specific issue]. Do not edit files. Return:
1) affected files, 2) evidence, 3) proposed minimal fix, and 4) verification command.
Stop after the report.
Run this task in phases: discovery, plan, execution, verification. After each phase,
write a concise checkpoint to [path]. Do not begin the next phase until the checkpoint
exists. Ask before any external action or destructive change.
Extract only these fields from [URL or document]: [field list]. Cap each text field at
60 words. Save the complete raw extract to [path] and return only the structured result.
Troubleshooting
| Symptom | Likely cause | First response |
|---|---|---|
| Costs are absent from usage output | The model’s local price configuration or provider metadata is missing. | Use token counts first; configure pricing before treating estimates as an accounting system. |
| The same task gets more expensive over time | Large transcript, tool-result bloat, or a long-lived session. | Compact the session, split the task, and narrow tool output. |
| Frequent compaction | Context window is too small, reserve tokens are too high, or tools produce too much text. | Check the model window, reserve configuration, and tool-return limits. |
| Session remains busy | Stale lock, legitimate slow cleanup, or a failed process. | Inspect session ownership and lock timing before changing timeouts. |
| Gateway restarts unexpectedly | Competing service managers, host restart policy, or a crash. | Identify the single authoritative service and review its logs and restart policy. |
| A job may repeat after restart | Interrupted work was eligible for recovery. | Check the durable result and side effects before resending or re-running anything. |
The session layer exposes lock timing controls, but the official guidance is clear: raise a timeout only when legitimate preparation, cleanup, compaction, or transcript work needs it. Increasing timeouts to hide an orphaned process converts a visible failure into a longer invisible one.
Gotchas
- Auto-compaction persists a summary and keeps recent messages while changing what the model sees next. Transcript storage still follows the configured maintenance, disk-budget, and compaction settings, so sensitive material needs a retention policy.
- A cache-warming heartbeat can reduce cache-write cost for a genuinely active session, but it also creates recurring activity. Do not add one to every agent by reflex.
- Containerization isolates a deployment boundary; it does not make broad tool permissions, poor secret handling, or unsafe prompts harmless.
- An agent restart can be safe for read-only work and unsafe for a task that has already sent a message, changed a record, or initiated a payment. Design idempotency before automation.
- Treat Gateway authentication tokens and model-provider keys as secrets. Never paste them into a prompt, commit them to a workspace, or leave them in a support transcript.
Operator Verdict
OpenClaw is compelling for operators who need an agent that persists beyond a browser tab and can work across channels, tools, schedules, and local state. The platform is no longer accurately described as a raw experiment with no controls. Its current session, cost, and restart features provide a credible operating base.
The boundary is discipline. OpenClaw works best when each agent has a narrow remit, each workflow has an explicit output and budget, and the Gateway has one lifecycle owner. Let a conversational agent accumulate every file, page, log, and retry in a permanent session, and the system will eventually charge you to rediscover its own history.
Start small: one read-heavy workflow, one owner, one model account, one channel, and a visible usage review. Add scheduled work and broader permissions only after the first workflow is predictable. Autonomy earns its keep when it creates a reliable output without creating a second operations job.