cd /news/ai-agents/opencode-compaction · home › topics › ai-agents › article
[ARTICLE · art-177399] src=opencode.ai ↗ pub= topic=ai-agents verified=true sentiment=· neutral

OpenCode Compaction

OpenCode introduced compaction, a feature that summarizes older conversation once a session nears the model's context limit, keeping roughly the most recent 15,000 tokens beside the summary so the session can continue. Automatic compaction is on by default, with a 15% buffer (minimum 16k tokens) of each model's context window kept free, and developers can tune `keep.tokens`, `buffer`, and `auto` in the OpenCode configuration file or trigger compaction manually via the `/api/session/{id}/compact` endpoint. Summaries are written by the session's model unless `agents.compaction.model` names another model, and OpenCode notes compaction is lossy, so users should raise `keep.tokens` when exact recent details matter.

key takeaway

OpenCode's compaction keeps 15,000 recent tokens beside a summary of older conversation by default and starts compacting once the session fills all but a 15% (minimum 16k) buffer of the model's context window, so raising `keep.tokens` preserves more exact detail at the cost of room for new work.

read7 min views4 publishedNov 27, 2026
OpenCode Compaction
Image: source

Compaction makes room in a long session by replacing older conversation with a summary, so the session can keep going past the model’s context limit.

When a session approaches the model’s context limit, OpenCode summarizes the entire current conversation. It also keeps the most recent conversation, about 15,000 tokens by default, beside the summary so exact recent details remain available.

before   [ system prompt ][ older conversation ............ ][ recent 15k ][ pending work ]
request  [ system prompt ][ older conversation ............ ][ recent 15k ][ summary instructions ]
after    [ system prompt ][ summary of older + recent ][ recent 15k ][ pending work ]

Sending the full conversation lets the summary request reuse the normal request’s prompt cache when the provider supports it. Later compactions update the existing summary using the conversation since that checkpoint.

Automatic compaction is on by default:

{
  "$schema": "https://opencode.ai/config.json",
  "compaction": {
    "auto": true,
    "keep": { "tokens": 15000 },
  },
}

Compaction is lossy. Increase keep.tokens when exact recent details matter, or request compaction yourself before the automatic one.

Request compaction at any time, even for a short history:

opencode api post /api/session/ses_example/compact --data '{}'

The api command discovers and authenticates with the background service. Its response confirms the request was accepted; it does not wait for the summary. Follow session.compaction.* events to learn when it finishes. See the API reference for the full operation.

Rule Behavior
Timing Runs at the next safe point, before prompts that are still waiting.
Repeats Requests made while one is pending merge into it.
Automation Works when compaction.auto isfalse .

Pass an id to make an exact retry idempotent. Reusing that ID for a different request returns a conflict.

opencode api post /api/session/ses_example/compact --data '{"id":"msg_compact_once"}'

Add compaction to any OpenCode configuration file:

{
  "$schema": "https://opencode.ai/config.json",
  "compaction": {
    "auto": false,
    "keep": { "tokens": 24000 },
    "buffer": "20%",
  },
}
Field Default Behavior
auto true Compact automatically near the context limit, and recover once when a provider rejects a request as too long. Manual compaction always works.
background true Write the summary ahead of time so automatic compaction doesn’t wait for it. See Background compaction .
keep.tokens 15000 Approximate recent conversation kept beside the summary. Larger values preserve more detail but leave less room for new work.
buffer "15%" , at least 16k Share of the model’s context window kept free. Automatic compaction starts once the conversation reaches the rest. Larger values compact earlier.

keep.tokens accepts a non-negative integer.

buffer is a percentage of each model’s window, so one setting fits every model:

Model window "buffer": "20%" compacts at
128k ~102k
1M 800k
  • It is the room kept free, not the point where compaction starts: "20%" compacts at 80% full.
  • Accepts "1%" to"99%" , including decimals such as"12.5%" .
  • A token count such as 20000 also works. The same count is a large share of a small window and a small share of a large one.
  • A token count at least as large as the model’s window is ignored and the default applies.

By default OpenCode writes the summary itself, using the session’s model. Set agents.compaction.model to use another model for summaries:

{
  "$schema": "https://opencode.ai/config.json",
  "agents": {
    "compaction": { "model": "anthropic/claude-sonnet-5-5" },
  },
}

If that model cannot be resolved, OpenCode falls back to the session’s model.

OpenCode writes the summary ahead of time, while the session keeps going, and swaps it in when compaction is due. Automatic compaction then doesn’t the session to write one:

60k tokens before the threshold   summary of the conversation so far starts in the background
                                  the session keeps going; the summary is held, not applied
threshold                         the held summary is swapped in; everything since it is kept as is

On small context windows, the summary starts at most halfway between the first response after the last compaction and the threshold.

Rule Behavior
Cost The summary request reuses the prompt cache. A summary that is never used, for example because the session ends before the threshold, still costs tokens.
Waits If the summary is still being written when compaction is due, the session waits for it to finish.
Falls back Compaction summarizes as usual if the conversation since the held summary grew past about 40% of the threshold, or if the start of the conversation changed.
Skipped Not used for native compaction. Right after a model switch, or after a break longer than the prompt cache lifetime, it starts from the next response instead.
Storage Held summaries live in memory and are lost on restart.

Turn it off to write the summary only when compaction is due:

{
  "$schema": "https://opencode.ai/config.json",
  "compaction": {
    "background": false,
  },
}

Some providers can compact the conversation on their side instead. Enable it per provider or model with settings.compaction:

{
  "$schema": "https://opencode.ai/config.json",
  "providers": {
    "openai": {
      "settings": { "compaction": { "type": "native" } },
      "models": {
        "gpt-6.1-sol": { "settings": { "compaction": { "type": "summary" } } },
      },
    },
  },
}

A model setting overrides the provider setting. native uses the provider’s compaction; summary uses OpenCode’s own.

With native compaction, OpenCode sends the conversation to the provider’s compaction endpoint. The provider returns an opaque, encrypted item that stands in for the older conversation. Your recent messages and attachments, up to keep.tokens, are kept alongside it:

before   [ older conversation ........................ ][ recent user messages ]
after    [ encrypted checkpoint + recent user messages ]
Topic Behavior
Support OpenAI Responses models. Support varies by deployment and model.
Threshold Same auto andbuffer settings as summary compaction. Manual requests work too.
Portability An encrypted checkpoint only works with the same provider and model. If you switch models, the session continues from the original conversation instead.
Too long If the provider rejects a compaction as too long, OpenCode retries it with a smaller request. It does not switch to a summary.

The summary is structured so another agent could pick the work up from it:

## Objective
Finish the authentication migration.

## Next Move
- Update the callback handler.
- Verify the login flow.

It covers the objective and requirements, decisions, completed and active work, blockers and next moves, and relevant files. In the recent conversation kept beside it, long tool output is shortened and attachment data is replaced by a short description.

After compaction, the current versions of your instruction files become the session’s baseline; see Instructions.

Limit Result
Model Summary compaction honors agents.compaction.model ; otherwise it uses the session’s model. Native compaction always uses the session’s model.
History Compaction needs older conversation to replace. It cannot create room when a request is mostly fixed instructions and tool schemas.
Size If the conversation to compact is itself too long, OpenCode sends a shortened text version and may leave out the oldest exchanges.
Recovery A request rejected as too long is compacted and retried once. A second rejection is returned as an error.
Storage Earlier messages remain stored even when they are no longer sent to the model.

For example, compaction cannot help here:

128k context = 120k fixed instructions and tools + 8k conversation

V1 used tail-turn and pruning behavior. V2 uses summaries and compaction.keep.tokens:

{
  "compaction": {
    "keep": { "tokens": 15000 }
  }
}

The settings and behavior on this page apply to V2.

── more in #ai-agents 4 stories · sorted by recency
── more on @opencode 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/opencode-compaction] indexed:0 read:7min 2026-11-27 · —