Compaction: Managing Long Conversations in OpenClaw

Learn how OpenClaw compacts older messages to stay within model limits. This page explains the process for developers and users managing long sessions.

Read this when

  • You want to understand auto-compaction and /compact
  • You are debugging long sessions hitting context limits

Every model operates within a context window, which caps the total number of tokens it can handle. As a conversation nears that ceiling, OpenClaw compacts older messages into a condensed summary, allowing the dialogue to proceed.

How it works

  1. Earlier conversation turns get condensed into a single compact record.
  2. That record is written into the session transcript.
  3. The most recent messages remain untouched.

When OpenClaw selects a split point for compaction, it keeps assistant tool calls together with their corresponding toolResult entries. If the split point falls within a tool block, the boundary shifts so the pair remains intact, preserving the unsummarized tail.

The entire conversation history remains stored on disk. Compaction only alters what the model sees on the subsequent turn.

Note

New configs default agents.defaults.compaction.mode to "safeguard" (tighter guardrails, summary quality checks). To opt out, set mode: "default" explicitly.

With the built-in safeguard quality guard active, OpenClaw applies the final summary budget prior to validation. Required headings must stay in the retained generated body, while pending asks and exact identifiers must remain in the exact text destined for storage. Invalid output receives only the configured number of corrective attempts. If no finalized summary passes, compaction halts before writing a transcript entry, preserves the original history, and surfaces the existing recovery outcome.

Auto-compaction

Auto-compaction is enabled by default. It triggers when the session approaches the context limit, or when the model returns a context-overflow error, in which case OpenClaw compacts and retries.

To disable the embedded runtime's proactive threshold compaction, set agents.defaults.compaction.enabled: false. OpenClaw's preflight and overflow-recovery compaction paths stay available, along with manual /compact.

You will see:

  • embedded run auto-compaction start / complete in standard Gateway logs.
  • 🧹 Auto-compaction complete in verbose mode.
  • /status showing 🧹 Compactions: <count>.

Info

Prior to compacting, OpenClaw automatically prompts the agent to save important notes to memory files. This guards against context loss.

Overflow error patterns OpenClaw recognizes

OpenClaw recognizes dozens of provider-specific overflow error strings (Anthropic, OpenAI, Bedrock, Gemini, Ollama, OpenRouter, and others). Common examples:

  • request_too_large
  • context length exceeded
  • input exceeds the maximum number of tokens
  • input token count exceeds the maximum number of input tokens (Bedrock)
  • input is too long for the model
  • ollama error: context length exceeded

Manual compaction

To force a compaction, type /compact in any chat. You can add instructions to steer the summary:

/compact Focus on the API design decisions

Manual compaction uses agents.defaults.compaction.keepRecentTokens (default: 20,000) as its cut-point budget and keeps that recent tail in rebuilt context.

Configuration

Compaction settings live under agents.defaults.compaction in your openclaw.json. The most common knobs are listed below; for the full reference, see Session management deep dive.

Using a different model

By default, compaction relies on the agent's primary model. Set agents.defaults.compaction.model to hand summarization off to a more capable or specialized model. The override accepts a provider/model-id string or a bare alias configured under agents.defaults.models:

{
  "agents": {
    "defaults": {
      "compaction": {
        "model": "openrouter/anthropic/claude-sonnet-4-6"
      }
    }
  }
}

Bare configured aliases resolve to their canonical provider and model before compaction starts. If a bare value matches both an alias and a configured literal model ID, the literal model ID takes precedence. An unmatched bare value remains a model ID on the active provider.

Local models work here too, for instance a second Ollama model dedicated to summarization:

{
  "agents": {
    "defaults": {
      "compaction": {
        "model": "ollama/llama3.1:8b"
      }
    }
  }
}

When unset, compaction starts with the active session model. If summarization fails with a model-fallback-eligible provider error, OpenClaw retries that compaction attempt through the session's existing model fallback chain. The fallback choice is temporary and is not written back to session state. An explicit agents.defaults.compaction.model override remains exact and does not inherit the session fallback chain.

Identifier preservation

Compaction summarization preserves opaque identifiers by default (identifierPolicy: "strict"). Override with identifierPolicy: "off" to disable. Custom guidance belongs in a compaction provider's summarize() implementation.

Active transcript byte guard

When agents.defaults.compaction.maxActiveTranscriptBytes is set, OpenClaw triggers normal local compaction before a run if transcript history reaches that size. This suits long-running sessions where provider-side context management may keep model context healthy while persisted transcript history keeps growing. Set a positive byte count or size string such as "20mb" to opt in; 0 or an unset value disables the guard. It does not split raw bytes; it asks the normal compaction pipeline to create a semantic summary. For Codex app-server sessions, the same threshold caps native rollout transcripts and oversized native threads restart fresh.

Warning

The byte guard applies to the active SQLite transcript history. Legacy JSONL checkpoint artifacts are not the active compaction target.

Successor transcripts

A context engine may return an explicit compacted successor session identity. OpenClaw adopts that successor and records checkpoint metadata against it. The built-in SQLite compactor keeps the current session identity and does not create a second runtime transcript.

OpenClaw no longer writes separate .checkpoint.*.jsonl copies for new compactions. Existing legacy checkpoint files can still be used while referenced and are pruned by normal session cleanup.

Compaction notices

By default, compaction runs silently. Set notifyUser to show brief status messages when compaction starts and completes, and to surface a degraded notice when a pre-compaction memory flush is exhausted but the reply still continues:

{
  agents: {
    defaults: {
      compaction: {
        notifyUser: true,
      },
    },
  },
}

Memory flush

Before compaction, OpenClaw can run a silent memory flush turn to store durable notes to disk. Set agents.defaults.compaction.memoryFlush.model when this housekeeping turn should use a local model instead of the active conversation model:

{
  "agents": {
    "defaults": {
      "compaction": {
        "memoryFlush": {
          "model": "ollama/qwen3:8b"
        }
      }
    }
  }
}

The memory-flush model override is exact and does not inherit the active session fallback chain. See Memory for details and config.

Pluggable compaction providers

Plugins can register a custom compaction provider via registerCompactionProvider() on the plugin API. When a provider is registered and configured, OpenClaw delegates summarization to it instead of the built-in LLM pipeline.

To use a registered provider, set its id in your config:

{
  "agents": {
    "defaults": {
      "compaction": {
        "provider": "my-provider"
      }
    }
  }
}

Setting a provider automatically forces mode: "safeguard". Providers receive the same compaction instructions and identifier-preservation policy as the built-in path, and OpenClaw still preserves recent-turn and split-turn suffix context after provider output.

The built-in quality audit and its corrective retries apply only to built-in summarization. Configured provider output keeps the provider's existing validation semantics.

Note

If the provider fails or returns an empty result, OpenClaw falls back to built-in LLM summarization.

Compaction vs pruning

CompactionPruning
What it doesSummarizes older conversationTrims old tool results
Saved?Yes (in session transcript)No (in-memory only, per request)
ScopeEntire conversationTool results only

Session pruning is a lighter-weight complement that trims tool output without summarizing.

Troubleshooting

Running compaction too frequently? A small context window or oversized tool outputs could be the cause. Consider turning on session pruning.

Post-compaction context feeling outdated? Rely on /compact Focus on <topic> to steer the summary, or activate the memory flush so notes persist.

Want to start over? /new launches a new session without any compaction.

For advanced settings like reserved tokens, identifier preservation, custom context engines, or OpenAI server-side compaction, check the Session management deep dive.

  • Session: handling sessions and their lifecycle.
  • Session pruning: removing tool results.
  • Context: assembling context for each agent turn.
  • Hooks: lifecycle hooks for compaction (before_compaction, after_compaction).
1,303 words · updated Aug 13, 2026