---
title: Experimental Compaction Strategies
description: Replace how eve compacts the history, and decide when it runs.
url: "https://eve.dev/docs/experimental/compaction"
docs_index: /llms.txt
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

`experimental: { compaction }` on `defineAgent` replaces how eve compacts the agent's history. The API is experimental and can change in any release. A strategy decides when the history is due and what to keep. eve's own compaction stays available inside it as `below()`, and it keeps using the agent's [`compaction`](../agent-config#compaction) block (`model`, `threshold`).

A strategy is one function that decides whether the history is due and, if it is, rewrites it. eve asks it before every model call, including a retry, and when a client calls `session.compact()`. When the provider rejects a request as longer than the model's context window, eve asks again with `ctx.overflow` set and retries the call once. The strategy receives the stored history and returns the history to keep, or `undefined` to keep it as it is.

```ts title="agent/agent.ts"
import { defineAgent } from "eve";
import { type CompactionStrategy } from "eve/experimental/compaction";

/** Summarizes every turn before the latest user message, which it keeps word for word, at 80% of the window. */
const keepLatestTurn: CompactionStrategy = async (ctx) => {
  const { history } = ctx;
  const window = ctx.model.contextWindowTokens;
  if (!ctx.requested && !ctx.overflow && (window === undefined || ctx.tokens < 0.8 * window)) {
    return undefined;
  }
  const latest = history.findLastIndex((m) => m.role === "user" && m.kind === "user");
  const { text } = await ctx.call({
    messages: [
      ...history.slice(0, latest),
      { role: "user", kind: "context.compaction", content: "Summarize the conversation above." },
    ],
    system: "Keep every ticket ID exactly as written.",
  });
  return [
    { role: "user", kind: "context.compaction", content: "Summary of our conversation so far:" },
    { role: "assistant", content: text },
    ...history.slice(latest),
  ];
};

export default defineAgent({
  model: "anthropic/claude-opus-5.5",
  experimental: { compaction: keepLatestTurn },
});
```

## Run eve's compaction from a strategy

The second argument, `below`, is a function that runs eve's own compaction on `ctx` and returns its result. It runs once per call however often the strategy calls it. A strategy can return `below()` as it is, change what it returns, or catch a failure and fall back to it:

```ts title="agent/agent.ts"
const careful: CompactionStrategy = async (ctx, below) => {
  try {
    return await keepLatestTurn(ctx, below);
  } catch {
    return below();
  }
};
```

When the strategy throws or returns a history that fails the checks in [What eve checks](#what-eve-checks), the compaction fails and is recorded as failed, and the history stays as it was. The model call that asked for it fails the turn with the strategy's error, including the retry after the provider rejected a request as too long. A compaction that a client requested with `session.compact()` settles as failed with the strategy's error and fails no turn.

## Decide when it runs

The strategy decides from what `ctx` tells it. `ctx.tokens` is the next request's input tokens, including instructions, tools and recalled memory. `ctx.requested` is `true` only for `session.compact()`, and `ctx.overflow` is `true` only on the retry after a context-overflow error. Compact whatever the size when either is set. Otherwise return `undefined` while `ctx.tokens` is under the budget the strategy chose, and the history as it is when nothing needs to change. A strategy that rewrites on every call rewrites once more after each compaction, and in development and tests eve fails the strategy when it changes what it returned.

Without a strategy, eve runs the same compaction as `below()`, and retries the call once when the provider rejects a request as too long.

## What a strategy reads

- `ctx.history` is a copy of the stored history that the strategy may change.
- `ctx.call({ messages, model?, system?, providerOptions? })` calls a model and returns `{ messages, text }`. eve sends exactly `messages`, with no recalled memory, client context or announcements. `system` defaults to the agent's instructions, and `model` to the turn's model. The call declares no tools. eve bills the call to the compaction. A request longer than the model's context window rejects with `CompactionOverflowError`, which a strategy can catch before it drops part of what it sent and calls again.
- `ctx.requested` and `ctx.overflow` say why eve asks when it isn't an ordinary model call. Both are `false` for an ordinary call, and never both `true`.
- `ctx.model` is the session model's `provider` and `modelId` as the AI SDK names them, with its `contextWindowTokens` and `maxOutputTokens`.
- `ctx.tokens` is the next request's input tokens, as the provider counted the last request plus eve's estimate of what joined the history since. `ctx.estimate(messages)` is the estimate of a message list in the provider's units: a quarter of its serialized bytes plus media, scaled by the ratio eve measured between its own estimate and the provider's count. `ctx.fixedTokens` is what the request holds besides the history, in the same units.
- Every user message carries a `kind`: `"user"` for what a person sent, and a framework kind such as `"context.compaction"` for what eve or a strategy added.

## What eve checks

eve checks every result before it applies it, for every strategy. A result fails the compaction, and leaves the history as it was, when it drops a tool call's result or a call, puts a checkpoint after other messages, returns no messages from a history that had some, removes a user message's `kind`, or doesn't fit within the model's context window beside the instructions, tools and recall. In development and tests, a strategy that compacts what it already returned fails too. A failure leaves the history as it was.

What the model answers next is up to the strategy. Keep the turn's latest user message, or carry it in the summary and add a message, such as an `"execution.continuation"`, that tells the model to go on.

## Built-in strategies

`defaultCompaction({ model?, instructions?, threshold? })` is eve's text compaction as a helper, and what `below()` runs with the agent's `compaction` options. It caps oversized tool results in older history, and summarizes the older history when capping doesn't fit. `model` writes the summary with another model, `instructions` adds to eve's checkpoint prompt, and `threshold` is the fraction of the window at which it compacts, 0.9 by default. It counts the checkpoint prompt it adds, so it starts before the conversation alone reaches the threshold.

`withoutInjected(history)` removes the messages eve adds to every request (memory, instructions and state) and the previous checkpoint, its marker and its summary, from a history you send. eve adds memory, instructions and state again after the compaction but not the old checkpoint, so a strategy that wants the old summary to carry on puts it in the new one.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)