> 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.3-session-lifecycle.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 13.3 Session Lifecycle

> **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`)

***

Sessions are not static data containers — they have a complete lifecycle of creation, activity, expiration, and reset. OpenClaw controls the renewal of sessions through flexible reset strategies and provides a runtime patching mechanism that allows users and Agents to dynamically adjust session attributes. This section analyzes the core source code for session lifecycle management.

## 13.3.1 Creation and Initialization: First Message Triggers Session Creation

OpenClaw adopts a **lazy creation** strategy for sessions: there is no pre-creation step, but rather automatic creation when the first message arrives. The `initSessionState()` function in `src/auto-reply/reply/session.ts` is the core entry point for session initialization.

```typescript
// src/auto-reply/reply/session.ts
export async function initSessionState(params: {
  ctx: MsgContext;
  cfg: OpenClawConfig;
  commandAuthorized: boolean;
}): Promise<SessionInitResult> {
  const { ctx, cfg } = params;
  const sessionCfg = cfg.session;

  // 1. Load session store
  const storePath = resolveStorePath(sessionCfg?.store, { agentId });
  const sessionStore: Record<string, SessionEntry> = loadSessionStore(storePath);

  // 2. Parse session key
  sessionKey = resolveSessionKey(sessionScope, sessionCtxForState, mainKey);
  const entry = sessionStore[sessionKey];

  // 3. Determine if this is a new session
  const freshEntry = entry
    ? evaluateSessionFreshness({ updatedAt: entry.updatedAt, now, policy: resetPolicy }).fresh
    : false;

  if (!isNewSession && freshEntry) {
    // Reuse existing session
    sessionId = entry.sessionId;
    systemSent = entry.systemSent ?? false;
  } else {
    // Create new session
    sessionId = crypto.randomUUID();
    isNewSession = true;
    systemSent = false;
  }
  // ...
}
```

The key to this process is the "freshness" check in step 3: if the session key doesn't exist in storage (`entry` is `undefined`), `freshEntry` is `false` and the session is automatically created; if it exists but has expired (no longer "fresh"), a new session is also created.

When a session is marked as new, the system resets a series of states:

```typescript
// src/auto-reply/reply/session.ts (new session initialization)
if (isNewSession) {
  sessionEntry.compactionCount = 0;         // Reset compaction count
  sessionEntry.memoryFlushCompactionCount = undefined;
  sessionEntry.memoryFlushAt = undefined;
  sessionEntry.totalTokens = undefined;      // Clear token usage
  sessionEntry.inputTokens = undefined;
  sessionEntry.outputTokens = undefined;
  sessionEntry.contextTokens = undefined;
}
```

This ensures that new sessions start from a clean state and don't inherit token statistics and compaction state from old sessions.

### Reset Triggers

Users can manually trigger session reset by sending specific commands (such as `/new` or `/reset`). These commands are called **reset triggers**:

```typescript
// src/auto-reply/reply/session.ts
const resetTriggers = sessionCfg?.resetTriggers?.length
  ? sessionCfg.resetTriggers
  : DEFAULT_RESET_TRIGGERS;  // Default ["/new", "/reset"]

for (const trigger of resetTriggers) {
  if (!resetAuthorized) break;   // Unauthorized users cannot reset
  const triggerLower = trigger.toLowerCase();
  if (trimmedBodyLower === triggerLower || strippedForResetLower === triggerLower) {
    isNewSession = true;
    bodyStripped = "";
    resetTriggered = true;
    break;
  }
  // Also supports "/new hello" style reset with message
  const triggerPrefixLower = `${triggerLower} `;
  if (trimmedBodyLower.startsWith(triggerPrefixLower)) {
    isNewSession = true;
    bodyStripped = strippedForReset.slice(trigger.length).trimStart();
    resetTriggered = true;
    break;
  }
}
```

Note that trigger matching is **case-insensitive** (user input `/NEW` also matches), and supports appending a message after the reset command (e.g., `/new write me an email`). In this case, the appended message becomes the first message of the new session after reset.

## 13.3.2 Reset Strategies: Daily Reset and Idle Reset

In addition to manual reset, OpenClaw supports two automatic reset strategies. `src/config/sessions/reset.ts` defines the related types and logic.

```typescript
// src/config/sessions/reset.ts
export type SessionResetMode = "daily" | "idle";

export type SessionResetPolicy = {
  mode: SessionResetMode;
  atHour: number;         // Hour for daily reset (0-23)
  idleMinutes?: number;   // Idle timeout in minutes
};

export const DEFAULT_RESET_MODE: SessionResetMode = "daily";
export const DEFAULT_RESET_AT_HOUR = 4;  // Default 4 AM
```

### Daily Reset

Daily reset is the **default strategy**. Its semantics are: if the session's last update time is before today's reset time point, the session is considered expired.

```typescript
// src/config/sessions/reset.ts
export function resolveDailyResetAtMs(now: number, atHour: number): number {
  const resetAt = new Date(now);
  resetAt.setHours(normalizeResetAtHour(atHour), 0, 0, 0);
  // If current time hasn't reached today's reset time, use yesterday's reset time
  if (now < resetAt.getTime()) {
    resetAt.setDate(resetAt.getDate() - 1);
  }
  return resetAt.getTime();
}
```

Example: Assuming reset time is 4 AM:

* Now is February 18, 10 AM → Reset timeline is February 18, 04:00
* Now is February 18, 2 AM → Reset timeline is February 17, 04:00 (because today's 4 AM hasn't passed yet)

Any session last updated **before** the reset timeline is considered expired.

### Idle Reset

Idle reset is based on the session's last active time. If the session has no new messages within the specified number of minutes, it is considered expired.

### Freshness Evaluation

`evaluateSessionFreshness()` is the core function for determining if a session has expired:

```typescript
// src/config/sessions/reset.ts
export function evaluateSessionFreshness(params: {
  updatedAt: number;
  now: number;
  policy: SessionResetPolicy;
}): SessionFreshness {
  // Calculate daily reset timeline (only in daily mode)
  const dailyResetAt = params.policy.mode === "daily"
    ? resolveDailyResetAtMs(params.now, params.policy.atHour)
    : undefined;
  // Calculate idle expiration time (if idleMinutes is configured)
  const idleExpiresAt = params.policy.idleMinutes != null
    ? params.updatedAt + params.policy.idleMinutes * 60_000
    : undefined;
  // Two expiration conditions with OR: either one satisfies means expired
  const staleDaily = dailyResetAt != null && params.updatedAt < dailyResetAt;
  const staleIdle = idleExpiresAt != null && params.now > idleExpiresAt;
  return {
    fresh: !(staleDaily || staleIdle),
    dailyResetAt,
    idleExpiresAt,
  };
}
```

A key design: **both expiration conditions can take effect simultaneously**. Even in `daily` mode, if `idleMinutes` is also configured, idle timeout will also trigger expiration. This means you can set combined strategies like "reset at 4 AM daily, but also reset if idle for more than 2 hours".

## 13.3.3 Reset Strategy Overrides by Type/Channel

Different types of sessions may need different reset strategies. For example, DM conversations might be suitable for daily reset, while thread sessions in groups might be better suited for reset after a short idle period. OpenClaw provides fine-grained override mechanisms through `resetByType` and `resetByChannel`.

### Session Type Classification

`resolveSessionResetType()` classifies sessions into three types based on session key and message attributes:

```typescript
// src/config/sessions/reset.ts
export type SessionResetType = "dm" | "group" | "thread";

export function resolveSessionResetType(params: {
  sessionKey?: string | null;
  isGroup?: boolean;
  isThread?: boolean;
}): SessionResetType {
  // Priority: thread > group > dm
  if (params.isThread || isThreadSessionKey(params.sessionKey)) return "thread";
  if (params.isGroup) return "group";
  const normalized = (params.sessionKey ?? "").toLowerCase();
  if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) return "group";
  return "dm";
}
```

### Policy Resolution Priority

`resolveSessionResetPolicy()` resolves reset strategy according to the following priority:

```typescript
// src/config/sessions/reset.ts
export function resolveSessionResetPolicy(params: {
  sessionCfg?: SessionConfig;
  resetType: SessionResetType;
  resetOverride?: SessionResetConfig;  // Override from resetByChannel
}): SessionResetPolicy {
  const baseReset = params.resetOverride ?? sessionCfg?.reset;
  const typeReset = params.resetOverride
    ? undefined
    : sessionCfg?.resetByType?.[params.resetType];
  // Priority: resetByChannel > resetByType > reset (base config)
  const mode = typeReset?.mode ?? baseReset?.mode ?? DEFAULT_RESET_MODE;
  const atHour = typeReset?.atHour ?? baseReset?.atHour ?? DEFAULT_RESET_AT_HOUR;
  // ...
}
```

The following configuration example demonstrates this hierarchical override mechanism:

```json5
// openclaw.json5
{
  "session": {
    "reset": { "mode": "daily", "atHour": 4 },
    "resetByType": {
      "thread": { "mode": "idle", "idleMinutes": 180 }   // Threads: reset after 3 hours idle
    },
    "resetByChannel": {
      "discord": { "mode": "idle", "idleMinutes": 10080 } // Discord: reset after 7 days idle
    }
  }
}
```

Under this configuration:

* **DM sessions**: Use default strategy, reset at 4 AM daily
* **Thread sessions**: Reset after 3 hours of inactivity (overridden by `resetByType.thread`)
* **All sessions on Discord**: Reset after 7 days of inactivity (overridden by `resetByChannel.discord`, higher priority than `resetByType`)

`resolveChannelResetConfig()` is responsible for finding channel-specific override configuration:

```typescript
// src/config/sessions/reset.ts
export function resolveChannelResetConfig(params: {
  sessionCfg?: SessionConfig;
  channel?: string | null;
}): SessionResetConfig | undefined {
  const resetByChannel = params.sessionCfg?.resetByChannel;
  if (!resetByChannel) return undefined;
  const key = normalizeMessageChannel(params.channel) ?? params.channel?.trim().toLowerCase();
  if (!key) return undefined;
  return resetByChannel[key] ?? resetByChannel[key.toLowerCase()];
}
```

## 13.3.4 Session Patch: Runtime Modification of Session Attributes

Once a session is created, its attributes are not immutable. Users can modify session attributes such as model, thinking level, and send policy at runtime through the `sessions.patch` protocol method without resetting the entire session.

The `applySessionsPatchToStore()` function in `src/gateway/sessions-patch.ts` implements this mechanism:

```typescript
// src/gateway/sessions-patch.ts
export async function applySessionsPatchToStore(params: {
  cfg: OpenClawConfig;
  store: Record<string, SessionEntry>;
  storeKey: string;
  patch: SessionsPatchParams;
  loadGatewayModelCatalog?: () => Promise<ModelCatalogEntry[]>;
}): Promise<{ ok: true; entry: SessionEntry } | { ok: false; error: ErrorShape }> {
  const existing = store[storeKey];
  // Update if exists, create if not
  const next: SessionEntry = existing
    ? { ...existing, updatedAt: Math.max(existing.updatedAt ?? 0, now) }
    : { sessionId: randomUUID(), updatedAt: now };
  // ...apply patch field by field...
  store[storeKey] = next;
  return { ok: true, entry: next };
}
```

### Patchable Attributes

Session patching supports the following attributes:

| Attribute         | Type             | Description                                    |
| ----------------- | ---------------- | ---------------------------------------------- |
| `label`           | `string \| null` | Session label (must be unique)                 |
| `thinkingLevel`   | `string \| null` | Thinking level (low/medium/high/xhigh)         |
| `verboseLevel`    | `string \| null` | Verbose output level                           |
| `reasoningLevel`  | `string \| null` | Reasoning level (on/off/stream)                |
| `responseUsage`   | `string \| null` | Usage display (off/tokens/full)                |
| `model`           | `string \| null` | Model override (null restores default)         |
| `sendPolicy`      | `string \| null` | Send policy (allow/deny)                       |
| `execHost`        | `string \| null` | Execution host (sandbox/gateway/node)          |
| `execSecurity`    | `string \| null` | Execution security level (deny/allowlist/full) |
| `groupActivation` | `string \| null` | Group activation method (mention/always)       |

Each field has strict validation logic. For example, model override:

```typescript
// src/gateway/sessions-patch.ts (model patch snippet)
if ("model" in patch) {
  const raw = patch.model;
  if (raw === null) {
    // null means restore default model
    applyModelOverrideToSessionEntry({
      entry: next,
      selection: { provider: resolvedDefault.provider, model: resolvedDefault.model, isDefault: true },
    });
  } else if (raw !== undefined) {
    const trimmed = String(raw).trim();
    if (!trimmed) return invalid("invalid model: empty");
    // Need to verify model is valid from model catalog
    const catalog = await params.loadGatewayModelCatalog();
    const resolved = resolveAllowedModelRef({ cfg, catalog, raw: trimmed, ... });
    if ("error" in resolved) return invalid(resolved.error);
    applyModelOverrideToSessionEntry({ entry: next, selection: { ... } });
  }
}
```

An important feature of the patch mechanism is that **setting to `null` means clearing the override** (restoring default), while `undefined` (i.e., the field is not included in the patch) means no modification. This follows the semantic convention common in JSON Patch.

### Server-side Session Reset

The Gateway's `sessions.reset` method provides complete reset capability on the server side:

```typescript
// src/gateway/server-methods/sessions.ts
"sessions.reset": async ({ params, respond }) => {
  const next = await updateSessionStore(storePath, (store) => {
    const entry = store[primaryKey];
    const nextEntry: SessionEntry = {
      sessionId: randomUUID(),       // Generate new session ID
      updatedAt: now,
      systemSent: false,
      abortedLastRun: false,
      // Preserve user's personalization settings
      thinkingLevel: entry?.thinkingLevel,
      verboseLevel: entry?.verboseLevel,
      model: entry?.model,
      sendPolicy: entry?.sendPolicy,
      label: entry?.label,
      // Reset token counts
      inputTokens: 0, outputTokens: 0, totalTokens: 0,
    };
    store[primaryKey] = nextEntry;
    return nextEntry;
  });
};
```

When resetting, **personalization overrides are preserved** (such as model selection, thinking level), but **conversation state is cleared** (new session ID is generated, token counts are reset). This way users don't need to reconfigure preferences after `/reset`.

***

## Summary of This Section

OpenClaw's session lifecycle management has the following core characteristics:

1. **Lazy creation**: Sessions are automatically created when the first message arrives, no pre-initialization needed
2. **Dual expiration mechanism**: Daily reset (by fixed time point) and idle reset (by inactivity duration) can take effect simultaneously with OR semantics
3. **Hierarchical overrides**: `resetByChannel` > `resetByType` > `reset`, allowing different strategies for different channels and session types
4. **Manual triggers**: `/new` and `/reset` commands provide immediate reset capability, supporting case-insensitive matching and appended messages
5. **Runtime patching**: `sessions.patch` allows dynamic modification of session attributes, while `sessions.reset` preserves user preferences during reset

In the next section, we will analyze how OpenClaw prunes overly long context before LLM calls to maintain conversation quality within limited context windows.
