Skip to main content
Every incoming message (WhatsApp, Telegram, or command-line) is handled by a single entry point: runEmbeddedPiAgent(). That function contains the core agent loop — understanding it explains how the whole system behaves in production.
The loop executes in five ordered phases. They always occur in sequence:
  1. Setup — load session and prepare the environment
  2. Context window validation — ensure the model has room to reason
  3. Attempt loop — the perceive → reason → act cycle with tool execution
  4. Error handling — structured recovery for different failure modes
  5. Persistence — safely save results and auth state
Below is a concise reference for each phase, followed by implementation details and production considerations. Phase 1 — Setup
The agent loads the session history from disk. Sessions are stored in JSONL (one JSON object per line). From that session the agent resolves:
  • which model to use,
  • which auth profile to pull credentials from (with failover configured),
  • the system prompt,
  • and the list of available tools, determined by the tool policy for this request.
This prepares the messages and the tool set that will be sent to the model. Phase 2 — Context window validation
Before calling the model, the agent calculates available tokens: model maximum context minus space reserved for the response. If the session history is too large to fit, the agent runs a compaction step (described below) to free tokens. If there still isn’t enough space after compaction, the agent aborts with a clear error rather than silently mangling the conversation.
Reserve at least a buffer of tokens for the model’s reply. Simultaneously reserving reply space and validating history avoids implicit truncation and preserves deterministic behavior.
Phase 3 — The attempt loop (perceive → reason → act)
This is the core interaction with the model and tools:
  • Send session messages, system prompt, and tool definitions to the model.
  • If the model responds with tool calls, execute each tool in a sandbox, capture output, append the result to the message history, and send everything back to the model.
  • Repeat until the model returns a final text response (no more tool calls), then exit.
Example pseudocode for the loop:
This implements perceive (tool outputs), reason (model call), and act (tool execution). OpenClaw surrounds this core cycle with production-grade controls described below. Phase 4 — Error handling
Each error class is handled intentionally and specifically:
  • Auth errors: rotate to a different API key or provider automatically.
  • Rate limits: trigger exponential backoff before retrying.
  • Context overflow (if not caught earlier): compress the session and retry the request.
  • Model errors: downgrade the reasoning level and retry at a lower setting.
  • Timeouts: abort immediately with no retry.
Each error type has a clearly defined response rather than a generic retry policy.
A retro-style infographic titled "PHASE 4: ERROR HANDLING" listing four error types—Auth Errors, Rate Limits, Context Overflow, and Model Errors—with brief remedies like rotating API keys, exponential backoff/retry, compressing sessions, and downgrading model. The colored, outlined boxes sit on a dark grid background.
Phase 5 — Persistence
When the agent finishes handling a message, it persists state safely:
  • Acquire a write lock on the session file.
  • Save the updated conversation and any session metadata.
  • Update auth-profile tracking to record which keys succeeded and which failed.
  • Release the lock.
The write lock prevents two simultaneous messages from corrupting the same session file.
A retro-style infographic titled "PHASE 5: PERSISTENCE" lists four steps: 1) Acquire write lock, 2) Save updated conversation, 3) Update auth profile tracking, 4) Release lock. A red banner at the bottom says "LOCK PREVENTS CONCURRENT CORRUPTION."
Context compaction (detailed)
Long conversations can exhaust the model context window. OpenClaw avoids dropping messages arbitrarily — instead it compresses older parts of the session using summarization and trimming:
  • Detect proximity to the context limit.
  • Summarize older messages and trim verbose tool outputs where safe.
  • Replace original messages with compressed representations in the session history.
  • Continue processing with more available tokens.
This preserves key information while freeing tokens for fresh reasoning and tool calls.
Compaction is lossy by design: it preserves essential context and removes low-value verbosity. Ensure your downstream tools and prompts tolerate summarized history.
An infographic titled "Context Compaction" that explains compressing older messages when the context window fills up. It lists four numbered steps and banners reading "Never drops old messages — compresses instead" and "Preserves context · frees tokens."
Session files and debugging
Sessions are stored in JSONL specifically so you can open any session file in a text editor and read exactly what the agent did: every message, every tool call, and every result. Debugging a bad agent run often means reading the session file directly — no special tooling required.
Each session is keyed by channel and user, so the same user has different sessions on WhatsApp versus Telegram. Example session lines:
What makes this production-grade
The core loop itself is simple — send to the model, check for tool calls, execute tools, repeat. That’s the minimal implementation. What makes OpenClaw production-grade is everything layered around that loop:
  • Concurrency control (execution lanes and session locks) so multiple messages don’t collide.
  • Auth failover across multiple model providers so a single expired key doesn’t kill the service.
  • Context management that compresses instead of crashing.
  • Structured recovery that handles each failure mode specifically instead of catching all exceptions generically.
  • Comprehensive logging and session persistence for reliable debugging and auditing.
A retro-style infographic titled "PRODUCTION-GRADE" showing "WHAT'S AROUND IT:" with four colored boxes. The boxes list Concurrency Control, Auth Failover, Context Management, and Structured Recovery with brief descriptions beneath each.
Summary
The core agent loop (send messages → model → tool execution → repeat) is intentionally small and deterministic. Production readiness is achieved by robust error handling, careful context management (compaction), concurrency controls (session locks, execution lanes), auth failover, and reliable persistence with readable JSONL session logs.
Links and References

Watch Video

Practice Lab