> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch13-session-management/13.1-session-model-design.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 13.1 Session Model Design

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~250,000 tokens, Output \~18,000 tokens (Chapter 13 total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

A Session is a container for conversation context in OpenClaw. Every interaction with the AI occurs within a session, which stores conversation history, configuration overrides, metadata, and other information. This section analyzes the core design of the session model.

## 13.1.1 Session Key Structure

In OpenClaw, each session is uniquely identified by a **Session Key**. The standard format for a session key is:

```
agent:<agentId>:<rest>
```

Where:

* `agent` is a fixed prefix indicating this is an Agent session key
* `<agentId>` is the Agent's identifier (e.g., `main`, `coding-assistant`)
* `<rest>` is the specific identification part of the session, which varies based on message type and configuration

The `parseAgentSessionKey()` function in `src/sessions/session-key-utils.ts` is responsible for parsing this structure:

```typescript
// src/sessions/session-key-utils.ts
export type ParsedAgentSessionKey = {
  agentId: string;
  rest: string;
};

export function parseAgentSessionKey(
  sessionKey: string | undefined | null,
): ParsedAgentSessionKey | null {
  const raw = (sessionKey ?? "").trim();
  if (!raw) return null;
  const parts = raw.split(":").filter(Boolean);
  if (parts.length < 3) return null;       // At least 3 parts required
  if (parts[0] !== "agent") return null;   // Must start with "agent"
  const agentId = parts[1]?.trim();
  const rest = parts.slice(2).join(":");   // Remaining parts may contain colons
  if (!agentId || !rest) return null;
  return { agentId, rest };
}
```

Here are several typical session keys:

| Session Key                             | Meaning                                         |
| --------------------------------------- | ----------------------------------------------- |
| `agent:main:main`                       | Main session of the default Agent               |
| `agent:main:dm:alice`                   | DM session between default Agent and alice      |
| `agent:main:telegram:group:12345`       | Default Agent's session in Telegram group 12345 |
| `agent:main:slack:dm:U123:thread:T456`  | Session for a thread in a Slack DM              |
| `agent:coding:subagent:task-1`          | Sub-agent session of the coding Agent           |
| `agent:main:cron:daily-report:run:uuid` | Run session for a scheduled task                |

### Agent ID Normalization

Agent IDs undergo strict normalization before storage:

```typescript
// src/routing/session-key.ts
const VALID_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
const INVALID_CHARS_RE = /[^a-z0-9_-]+/g;

export function normalizeAgentId(value: string | undefined | null): string {
  const trimmed = (value ?? "").trim();
  if (!trimmed) return DEFAULT_AGENT_ID; // "main"
  if (VALID_ID_RE.test(trimmed)) return trimmed.toLowerCase();
  // Best-effort fallback: replace invalid characters with "-"
  return trimmed.toLowerCase()
    .replace(INVALID_CHARS_RE, "-")
    .replace(/^-+/, "")  // Remove leading "-"
    .replace(/-+$/, "")  // Remove trailing "-"
    .slice(0, 64) || DEFAULT_AGENT_ID;
}
```

This design ensures that session keys are **path-safe** and **shell-friendly** — because session keys ultimately become part of file paths.

### Special Session Keys

In addition to the standard `agent:*:*` format, there are two special session keys:

* `global` — Global session shared by all Agents
* `unknown` — Session for messages from unrecognized sources

Helper functions can detect special types of session keys:

```typescript
// Detect if it's a sub-agent session
export function isSubagentSessionKey(sessionKey: string): boolean {
  const raw = (sessionKey ?? "").trim();
  if (raw.toLowerCase().startsWith("subagent:")) return true;
  const parsed = parseAgentSessionKey(raw);
  return Boolean((parsed?.rest ?? "").toLowerCase().startsWith("subagent:"));
}

// Detect thread session and extract parent session key
export function resolveThreadParentSessionKey(sessionKey: string): string | null {
  const normalized = sessionKey.toLowerCase();
  const markers = [":thread:", ":topic:"];
  let idx = -1;
  for (const marker of markers) {
    const candidate = normalized.lastIndexOf(marker);
    if (candidate > idx) idx = candidate;
  }
  if (idx <= 0) return null;
  return sessionKey.slice(0, idx).trim() || null;
}
```

## 13.1.2 Session Scope (DM Scope)

When a user interacts with OpenClaw through direct messages (DM), a key question arises: **Should conversations with the same user on different channels (Telegram, Slack, Discord, etc.) share the same session, or should they be independent?**

OpenClaw provides four strategies through the `dmScope` configuration option:

| Scope                      | Session Key Format                           | Behavior                         |
| -------------------------- | -------------------------------------------- | -------------------------------- |
| `main`                     | `agent:<id>:main`                            | All DMs share the same session   |
| `per-peer`                 | `agent:<id>:dm:<peerId>`                     | One session per sender           |
| `per-channel-peer`         | `agent:<id>:<channel>:dm:<peerId>`           | One session per channel + sender |
| `per-account-channel-peer` | `agent:<id>:<channel>:<account>:dm:<peerId>` | Finest granularity               |

The `buildAgentPeerSessionKey()` function generates the corresponding session key based on `dmScope`:

```typescript
// src/routing/session-key.ts
export function buildAgentPeerSessionKey(params: {
  agentId: string;
  mainKey?: string;
  channel: string;
  accountId?: string | null;
  peerKind?: "dm" | "group" | "channel" | null;
  peerId?: string | null;
  dmScope?: "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
  identityLinks?: Record<string, string[]>;
}): string {
  const peerKind = params.peerKind ?? "dm";

  if (peerKind === "dm") {
    const dmScope = params.dmScope ?? "main";
    let peerId = (params.peerId ?? "").trim().toLowerCase();

    // Identity links: map multiple platform user IDs to a canonical ID
    const linkedPeerId = resolveLinkedPeerId({ ... });
    if (linkedPeerId) peerId = linkedPeerId;

    if (dmScope === "per-account-channel-peer" && peerId) {
      return `agent:${agentId}:${channel}:${accountId}:dm:${peerId}`;
    }
    if (dmScope === "per-channel-peer" && peerId) {
      return `agent:${agentId}:${channel}:dm:${peerId}`;
    }
    if (dmScope === "per-peer" && peerId) {
      return `agent:${agentId}:dm:${peerId}`;
    }
    // dmScope === "main"
    return buildAgentMainSessionKey({ agentId, mainKey });
  }

  // Group/channel messages
  return `agent:${agentId}:${channel}:${peerKind}:${peerId}`;
}
```

> **Sidebar**: Identity Links (身份链接) is a cross-platform user identity merging mechanism. Under `per-peer` or finer-grained scopes, the same person on Telegram (ID: `tg:12345`) and Slack (ID: `slack:U678`) would be treated as different senders, creating separate sessions. By configuring `identityLinks`, you can map these IDs to the same canonical identity, allowing that user to share the same session context across all channels.

## 13.1.3 Session Persistence: JSON Store + JSONL Transcript Files

OpenClaw uses a **two-layer storage model** to persist sessions:

### Layer 1: Session Metadata (JSON Store)

Session metadata (labels, configuration overrides, timestamps, etc.) is stored in a JSON file, typically at `<stateDir>/agents/<agentId>/sessions.json`. Each session key corresponds to a `SessionEntry` object:

```typescript
// src/gateway/session-utils.types.ts (simplified)
export type GatewaySessionRow = {
  key: string;                    // Session key
  kind: "direct" | "group" | "global" | "unknown";
  label?: string;                 // User-visible label
  displayName?: string;           // Display name
  channel?: string;               // Associated channel
  updatedAt: number | null;       // Last update timestamp
  sessionId?: string;             // UUID format session ID
  thinkingLevel?: string;         // Thinking level override
  model?: string;                 // Model override
  sendPolicy?: "allow" | "deny";  // Send policy
  // ... more fields
};
```

### Layer 2: Conversation Transcript (JSONL Transcript)

The actual conversation history (content of each message, role, tool call results, etc.) is stored as a JSONL (JSON Lines) format file. Each line is a JSON object representing a message. The JSONL format has several advantages:

1. **Append-friendly**: New messages only require appending a line, no need to read and rewrite the entire file
2. **Streaming reads**: Can read line-by-line without loading the entire file into memory
3. **Partial reads**: Can read only the first N or last N lines

The transcript file path is related to the session key and stored in the Agent's working directory. `session-utils.fs.ts` provides utility functions for reading transcript files:

```typescript
// Functions exported from session-utils.fs.ts (re-exported from session-utils.ts)
export {
  readFirstUserMessageFromTranscript,   // Read first user message (for title derivation)
  readLastMessagePreviewFromTranscript,  // Read last message preview
  readSessionPreviewItemsFromTranscript, // Read preview items
  readSessionMessages,                   // Read complete message list
  resolveSessionTranscriptCandidates,    // Resolve transcript file path candidates
};
```

### Session Classification

The `classifySessionKey()` function determines the session type based on the session key structure:

```typescript
export function classifySessionKey(
  key: string, entry?: SessionEntry
): "direct" | "group" | "global" | "unknown" {
  if (key === "global") return "global";
  if (key === "unknown") return "unknown";
  if (entry?.chatType === "group" || entry?.chatType === "channel") return "group";
  if (key.includes(":group:") || key.includes(":channel:")) return "group";
  return "direct";
}
```

***

## Summary of This Section

OpenClaw's session model design has several core characteristics:

1. **Structured session keys**: The `agent:<agentId>:<rest>` format encodes Agent identity, message source, and channel information into the key name, making the session key itself parseable metadata
2. **Flexible DM scope**: Four scope strategies cover the complete spectrum from "everyone shares" to "each channel, each account, each user independent"
3. **Two-layer persistence**: JSON Store for metadata (fast queries), JSONL for conversation history (efficient appending), each serving its purpose
4. **Identity linking**: Cross-channel user identity merging, preventing the same person on different platforms from creating fragmented sessions

In the next section, we will dive into the source code of session routing, examining how the Gateway automatically determines which session to use based on the source of an inbound message.
