Home Tutorials Categories Skills About
ZH EN JA KO
Configuration

OpenClaw Session Management and Persistence

· 18 min read

Introduction

In a multi-channel, multi-user AI gateway scenario, session management is one of the most critical foundational capabilities. OpenClaw uses a JSONL-based persistence approach combined with a tree-structured message model to enable advanced features like session branching, history backtracking, and automatic compaction. This article provides a comprehensive analysis of OpenClaw's session management mechanism, from low-level storage to high-level strategy.

Session Storage Location

Each Agent's session data is stored independently in its own directory:

~/.openclaw/agents/<agentId>/sessions/
├── telegram_123456.jsonl
├── discord_789012.jsonl
├── whatsapp_345678.jsonl
└── web_dashboard.jsonl

The filename format is <channel>_<userId>.jsonl, with each file corresponding to a user's complete conversation history on a given channel. This design naturally isolates sessions across different channels and users, preventing data cross-contamination.

JSONL Storage Format

OpenClaw uses the JSONL (JSON Lines) format to store each message, with one JSON object per line:

{"id":"msg_001","parentId":null,"role":"user","content":"Hello","timestamp":1710000000,"channel":"telegram"}
{"id":"msg_002","parentId":"msg_001","role":"assistant","content":"Hello! How can I help you?","timestamp":1710000001,"channel":"telegram"}
{"id":"msg_003","parentId":"msg_002","role":"user","content":"Help me translate a paragraph of English","timestamp":1710000010,"channel":"telegram"}

Core Field Descriptions

Field Type Description
id string Unique message identifier, auto-generated
parentId string/null Parent message ID, null for root messages
role string Role: user, assistant, system
content string Message text content
timestamp number Unix timestamp
channel string Source channel
metadata object Optional, additional metadata (e.g., media info)

Choosing JSONL over a database offers several key advantages: append-only writes deliver excellent performance; no external dependencies are required; easy backup and migration; and human-readable for debugging.

Tree-Structured Sessions

The most distinctive design in OpenClaw's session management is the tree structure. Through id and parentId fields, messages form parent-child relationships rather than a simple linear list.

Why Use a Tree Structure?

In practice, users often need to "go back to a certain point and restart the conversation." For example:

msg_001: Help me write an email
  ├── msg_002: [Assistant wrote a formal email]
  │     └── msg_003: Make it shorter → msg_004: [Assistant revised]
  └── msg_005: Write it in a casual tone → msg_006: [Assistant wrote a casual version]

When the user branches off from msg_001 to create msg_005, OpenClaw uses msg_001 as the new branch starting point and builds an independent context path. The model sees the conversation history as msg_001 → msg_005, without mixing in content from msg_002 or msg_003.

Using Branches in the Dashboard

In the Web Dashboard, you can visually see the tree structure of a session. Click the "Branch from here" button on any historical message to create a new conversation branch. Each branch maintains its own context independently without interference.

Context Building Strategy

When OpenClaw needs to call the model API, it traverses up the parentId chain from the current message node, collecting ancestor messages as context. This process is controlled by the following configuration:

{
  "sessions": {
    "maxHistoryMessages": 50,
    "maxHistoryTokens": 8000
  }
}

The backtracking process stops when any of the following conditions is met:

  1. The maxHistoryMessages message limit is reached
  2. The cumulative token count exceeds maxHistoryTokens
  3. The root node of the tree is reached

Automatic Compaction

When a conversation grows too long and approaches the model's context window limit, OpenClaw automatically triggers compaction. The compaction strategy is controlled by configuration:

{
  "sessions": {
    "autoCompaction": true,
    "compactionStrategy": "summary"
  }
}

Summary Strategy (Default)

OpenClaw sends the earlier conversation history to the model and requests a summary. This summary is inserted as a system role message at the beginning of the context, replacing the original history messages. This preserves key information while significantly reducing token consumption.

The summary message format looks like this:

{"id":"compact_001","parentId":null,"role":"system","content":"[Session Summary] The user previously asked about Python async programming, discussing basic asyncio usage and common pitfalls...","timestamp":1710001000,"metadata":{"type":"compaction","originalCount":35}}

Truncate Strategy

Simple truncation that directly discards the oldest messages, keeping only the most recent N messages. This strategy doesn't generate additional model calls but may lose important context. It's suitable for cost-sensitive scenarios where conversation continuity is less critical.

Channel-Specific Configuration

Different channels have very different usage patterns — DMs are typically long conversations, while group chats tend to be fragmented short interactions. OpenClaw supports overriding session configuration by channel type:

{
  "sessions": {
    "maxHistoryMessages": 50,
    "channelOverrides": {
      "dm": {
        "maxHistoryMessages": 100,
        "maxHistoryTokens": 16000
      },
      "group": {
        "maxHistoryMessages": 20,
        "maxHistoryTokens": 4000
      }
    }
  }
}

In the configuration above, DMs retain longer history to maintain coherent conversations, while group chats are limited to reduce costs and minimize irrelevant message noise.

Session Data Maintenance

Manual Cleanup

# Clear a specific user's session
openclaw session clear --agent default --session telegram_123456

# Clear all sessions for an Agent
openclaw session clear --agent myagent --all

# Export session as JSON (for analysis)
openclaw session export --session telegram_123456 --format json > history.json

Automatic Cleanup

You can configure automatic cleanup policies for session files:

{
  "sessions": {
    "retention": {
      "maxAge": "30d",
      "maxSize": "100mb"
    }
  }
}

Session data older than 30 days or exceeding 100MB total size will be automatically archived when OpenClaw starts.

Multi-Device Sync

Since session data is stored on the filesystem, synchronization must be considered in multi-instance deployments. Recommended approaches:

  • Single-machine deployment: No additional configuration needed; files are naturally consistent
  • Multi-machine deployment: Use shared storage (such as NFS) to mount the ~/.openclaw/agents/ directory, or switch to a Redis storage backend

Summary

OpenClaw's session management system is built on JSONL files, using id/parentId to construct a tree structure that supports session branching and flexible context backtracking. The automatic compaction mechanism ensures long conversations don't exceed model limits, and channel-specific configuration makes resource allocation more efficient. Understanding these mechanisms allows you to fine-tune session parameters for your specific use case, striking the right balance between conversation quality and cost.

OpenClaw is a free, open-source personal AI assistant that supports WhatsApp, Telegram, Discord, and many more platforms