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

# 13.4 Session Pruning

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

***

As conversations progress, the messages accumulated in a session grow larger and larger. For large language models (LLMs), each call requires the complete conversation history as input, but models have a fixed Token limit on their context window. OpenClaw manages this through two mechanisms: **context pruning** and **context window guard**.

> **Sidebar**: The context window is a core constraint of LLMs. Each model has a Token limit (e.g., Claude's 200K tokens, GPT-4o's 128K tokens), and all system prompts, conversation history, and tool results must fit within this window. Tokens can be roughly understood as "sub-words" — in English, approximately 4 characters equal 1 token; in Chinese, each character is roughly 1-2 tokens. When conversation history exceeds the window size, the LLM refuses to process it, so excess content must be pruned before calling the model.

## 13.4.1 Tool Result Pruning: Trimming Old Tool Results Before LLM Calls

During an Agent's operation, tool call results (such as bash command output, file contents, search results, etc.) often occupy large amounts of context space. OpenClaw implements a two-stage pruning strategy in the `src/agents/pi-extensions/context-pruning/` directory: **soft trim** and **hard clear**.

### Pruning Configuration

`src/agents/pi-extensions/context-pruning/settings.ts` defines the pruning configuration structure and default values:

```typescript
// src/agents/pi-extensions/context-pruning/settings.ts
export const DEFAULT_CONTEXT_PRUNING_SETTINGS: EffectiveContextPruningSettings = {
  mode: "cache-ttl",
  ttlMs: 5 * 60 * 1000,          // 5-minute cache TTL
  keepLastAssistants: 3,          // Protect last 3 Assistant replies
  softTrimRatio: 0.3,             // Trigger soft trim when context usage > 30%
  hardClearRatio: 0.5,            // Trigger hard clear when context usage > 50%
  minPrunableToolChars: 50_000,   // Only execute hard clear if prunable tool results >= 50K chars
  tools: {},                       // Tool whitelist/blacklist
  softTrim: {
    maxChars: 4_000,              // Only soft trim tool results > 4K chars
    headChars: 1_500,             // Keep first 1500 characters
    tailChars: 1_500,             // Keep last 1500 characters
  },
  hardClear: {
    enabled: true,
    placeholder: "[Old tool result content cleared]",
  },
};
```

The `mode` currently only supports `"cache-ttl"` mode: pruning results are cached, and the pruning logic won't be recalculated before the TTL (default 5 minutes) expires. This avoids re-executing the pruning logic on every LLM call.

### Pruning Trigger Mechanism

Pruning is injected into the Agent runtime as an extension of Pi Agent. Before each LLM call, the extension checks whether pruning is needed:

```typescript
// src/agents/pi-extensions/context-pruning/extension.ts
export default function contextPruningExtension(api: ExtensionAPI): void {
  api.on("context", (event: ContextEvent, ctx: ExtensionContext) => {
    const runtime = getContextPruningRuntime(ctx.sessionManager);
    if (!runtime) return undefined;

    // cache-ttl mode: skip if TTL hasn't expired
    if (runtime.settings.mode === "cache-ttl") {
      const lastTouch = runtime.lastCacheTouchAt ?? null;
      if (!lastTouch || Date.now() - lastTouch < runtime.settings.ttlMs) {
        return undefined;
      }
    }

    const next = pruneContextMessages({
      messages: event.messages,
      settings: runtime.settings,
      ctx,
    });

    if (next === event.messages) return undefined;  // No pruning occurred
    runtime.lastCacheTouchAt = Date.now();          // Update cache timestamp
    return { messages: next };                      // Return pruned message list
  });
}
```

> **Sidebar**: This uses an event-driven extension pattern. Pi Agent Core triggers a `context` event each time it prepares an LLM call, and extensions can intercept this event and modify the message list about to be sent to the LLM. This design completely decouples pruning logic from the Agent core — it can be independently configured, enabled, or disabled.

### Two-Stage Pruning Algorithm

`pruneContextMessages()` is the core pruning algorithm, located in `src/agents/pi-extensions/context-pruning/pruner.ts`:

```typescript
// src/agents/pi-extensions/context-pruning/pruner.ts
const CHARS_PER_TOKEN_ESTIMATE = 4;  // Rough conversion: 1 token ≈ 4 characters

export function pruneContextMessages(params: {
  messages: AgentMessage[];
  settings: EffectiveContextPruningSettings;
  ctx: Pick<ExtensionContext, "model">;
}): AgentMessage[] {
  const { messages, settings } = params;
  const contextWindowTokens = ctx.model?.contextWindow;
  if (!contextWindowTokens) return messages;

  const charWindow = contextWindowTokens * CHARS_PER_TOKEN_ESTIMATE;

  // 1. Determine protected region: last N Assistant replies cannot be pruned
  const cutoffIndex = findAssistantCutoffIndex(messages, settings.keepLastAssistants);
  if (cutoffIndex === null) return messages;

  // 2. Safety boundary: content before first user message cannot be pruned
  //   (protects reading results of bootstrap files like SOUL.md)
  const firstUserIndex = findFirstUserIndex(messages);
  const pruneStartIndex = firstUserIndex ?? messages.length;

  let totalChars = estimateContextChars(messages);
  let ratio = totalChars / charWindow;

  // If usage ratio is below soft trim threshold, no pruning needed
  if (ratio < settings.softTrimRatio) return messages;

  // Collect prunable tool result indexes
  const prunableToolIndexes: number[] = [];
  // ...
}
```

The algorithm's key lies in two protected regions:

1. **Tail protection**: The last `keepLastAssistants` (default 3) Assistant replies and their associated tool results cannot be pruned, as they are the direct context of the current conversation
2. **Head protection**: All content before the first `user` message cannot be pruned, as these are typically reading results of bootstrap files (like `SOUL.md`, `AGENTS.md`), which are critical to Agent behavior

Tool result messages between the two protected regions are processed according to the following flow:

| Stage                   | Trigger Condition                      | Operation                                                         | Effect                                     |
| ----------------------- | -------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------ |
| **Stage 1: Soft Trim**  | `ratio > softTrimRatio` (default 0.3)  | Keep first 1500 + last 1500 characters, replace middle with `...` | Preserve key information from tool results |
| **Stage 2: Hard Clear** | `ratio > hardClearRatio` (default 0.5) | Replace entire tool result with placeholder text                  | Completely free up space                   |

Implementation of soft trim:

```typescript
// src/agents/pi-extensions/context-pruning/pruner.ts
function softTrimToolResultMessage(params: {
  msg: ToolResultMessage;
  settings: EffectiveContextPruningSettings;
}): ToolResultMessage | null {
  const { msg, settings } = params;
  // Don't trim image tool results (hard to safely partially trim)
  if (hasImageBlocks(msg.content)) return null;

  const parts = collectTextSegments(msg.content);
  const rawLen = estimateJoinedTextLength(parts);
  if (rawLen <= settings.softTrim.maxChars) return null;  // Not long enough, skip

  // Keep head and tail, truncate middle
  const head = takeHeadFromJoinedText(parts, settings.softTrim.headChars);
  const tail = takeTailFromJoinedText(parts, settings.softTrim.tailChars);
  const trimmed = `${head}\n...\n${tail}`;
  const note = `\n\n[Tool result trimmed: kept first ${headChars} chars ` +
    `and last ${tailChars} chars of ${rawLen} chars.]`;
  return { ...msg, content: [asText(trimmed + note)] };
}
```

Hard clear is more aggressive — directly replacing the entire tool result with a placeholder:

```typescript
// src/agents/pi-extensions/context-pruning/pruner.ts (hard clear snippet)
for (const i of prunableToolIndexes) {
  if (ratio < settings.hardClearRatio) break;  // Already below threshold
  const msg = outputAfterSoftTrim[i];
  // Replace with placeholder
  const cleared = { ...msg, content: [asText(settings.hardClear.placeholder)] };
  next[i] = cleared;
  // Recalculate usage ratio
  totalChars += estimateMessageChars(cleared) - estimateMessageChars(msg);
  ratio = totalChars / charWindow;
}
```

### Tool Result Integrity Guard

In addition to pruning, OpenClaw must ensure **pairing integrity** of tool calls and results in session transcripts. Some LLM providers (like Anthropic Claude) require that every tool call (`toolCall`) has a corresponding tool result (`toolResult`), otherwise they reject the request.

`src/agents/session-tool-result-guard.ts` uses monkey-patching to intercept the `SessionManager.appendMessage` method to track incomplete tool calls:

```typescript
// src/agents/session-tool-result-guard.ts
export function installSessionToolResultGuard(sessionManager: SessionManager) {
  const originalAppend = sessionManager.appendMessage.bind(sessionManager);
  const pending = new Map<string, string | undefined>();  // toolCallId → toolName

  const flushPendingToolResults = () => {
    // Generate synthetic results for all tool calls that haven't received results
    for (const [id, name] of pending.entries()) {
      const synthetic = makeMissingToolResult({ toolCallId: id, toolName: name });
      originalAppend(synthetic);
    }
    pending.clear();
  };

  sessionManager.appendMessage = (message: AgentMessage) => {
    if (message.role === "assistant") {
      // Extract tool call IDs, add to pending set
      const toolCalls = extractAssistantToolCalls(message);
      if (pending.size > 0 && toolCalls.length === 0) flushPendingToolResults();
      for (const call of toolCalls) pending.set(call.id, call.name);
    }
    if (message.role === "toolResult") {
      // Received tool result, remove from pending
      const id = extractToolResultId(message);
      if (id) pending.delete(id);
    }
    return originalAppend(message);
  };

  return { flushPendingToolResults, getPendingIds: () => Array.from(pending.keys()) };
}
```

> **Sidebar**: Monkey-patching is a technique for replacing object methods at runtime. Here, by replacing the `appendMessage` method, tool result tracking logic is added without modifying the Pi Agent Core source code. While this technique should be used cautiously in production code, it's a practical solution when you need to intercept third-party library behavior.

## 13.4.2 Context Window Guard

The pruning mechanism handles "how to reduce context", while the context window guard handles "whether the context window size itself is reasonable". `src/agents/context-window-guard.ts` provides parsing and validation of context window sizes.

### Context Window Size Resolution

Different models have different context window sizes, and users can also override this value through configuration files. `resolveContextWindowInfo()` determines the final window size according to priority:

```typescript
// src/agents/context-window-guard.ts
export type ContextWindowSource = "model" | "modelsConfig" | "agentContextTokens" | "default";

export function resolveContextWindowInfo(params: {
  cfg: OpenClawConfig | undefined;
  provider: string;
  modelId: string;
  modelContextWindow?: number;     // Window size from model metadata
  defaultTokens: number;
}): ContextWindowInfo {
  // Priority 1: Value manually configured by user in models.providers
  const fromModelsConfig = /* cfg.models.providers[provider].models[modelId].contextWindow */;
  // Priority 2: Value reported by the model itself
  const fromModel = normalizePositiveInt(params.modelContextWindow);
  // Priority 3: Default value
  const baseInfo = fromModelsConfig
    ? { tokens: fromModelsConfig, source: "modelsConfig" }
    : fromModel
      ? { tokens: fromModel, source: "model" }
      : { tokens: Math.floor(params.defaultTokens), source: "default" };

  // Agent-level hard cap: if contextTokens is configured and smaller than base, use it
  const capTokens = normalizePositiveInt(params.cfg?.agents?.defaults?.contextTokens);
  if (capTokens && capTokens < baseInfo.tokens) {
    return { tokens: capTokens, source: "agentContextTokens" };
  }
  return baseInfo;
}
```

### Safety Threshold Check

After determining the window size, `evaluateContextWindowGuard()` checks if it's below the safety threshold:

```typescript
// src/agents/context-window-guard.ts
export const CONTEXT_WINDOW_HARD_MIN_TOKENS = 16_000;   // Hard minimum: 16K
export const CONTEXT_WINDOW_WARN_BELOW_TOKENS = 32_000; // Warning threshold: 32K

export function evaluateContextWindowGuard(params: {
  info: ContextWindowInfo;
}): ContextWindowGuardResult {
  const warnBelow = CONTEXT_WINDOW_WARN_BELOW_TOKENS;
  const hardMin = CONTEXT_WINDOW_HARD_MIN_TOKENS;
  const tokens = params.info.tokens;
  return {
    ...params.info,
    tokens,
    shouldWarn: tokens > 0 && tokens < warnBelow,   // Below 32K: issue warning
    shouldBlock: tokens > 0 && tokens < hardMin,     // Below 16K: refuse to run
  };
}
```

When `shouldBlock` is `true`, the Gateway refuses to start the Agent, because below 16K tokens, the system prompt, tool definitions, and basic conversation history may not all fit, and continuing would only produce low-quality responses.

***

## Summary of This Section

OpenClaw's session pruning system consists of three complementary mechanisms:

1. **Two-stage context pruning**: Progressive strategy of soft trim (keep head/tail, truncate middle) and hard clear (replace with placeholder), controlling context size while preserving valuable information
2. **Intelligent protected regions**: Last N replies and bootstrap files are never pruned, ensuring Agent's current conversation context and fundamental personality are unaffected
3. **Tool result integrity guard**: By tracking the pairing relationship between tool calls and results, automatically generates synthetic responses for missing results, satisfying strict LLM provider requirements
4. **Context window guard**: Validates the model's context window size before Agent startup, refusing to run below 16K tokens, warning below 32K tokens

This mechanism enables OpenClaw to maintain stable operation during long conversations without crashing due to context overflow or producing low-quality responses.
