runEmbeddedPiAgent(). That function contains the core agent loop — understanding it explains how the whole system behaves in production.
- Setup — load session and prepare the environment
- Context window validation — ensure the model has room to reason
- Attempt loop — the perceive → reason → act cycle with tool execution
- Error handling — structured recovery for different failure modes
- Persistence — safely save results and auth state
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.
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.
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.
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.

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.

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.
Compaction is lossy by design: it preserves essential context and removes low-value verbosity. Ensure your downstream tools and prompts tolerate summarized history.

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:
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.

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
- JSON Lines (JSONL) format — why per-line objects are simple for append-only logs.
- Exponential backoff best practices — reference for retry/backoff strategy.
- Concurrency patterns for distributed systems — design patterns for locks and coordination.