# Compaction

> Keep long sessions inside the model's context window, and compact on demand.

zelk keeps a session's requests inside the model's window: it clears old
tool results, then summarizes older history, while the log keeps
everything. [Context and compaction](/concepts/context/) explains the steps.

The defaults derive from the window the provider reports. A host declares
the window where the provider reports none, moves the bounds, or asks for
a summary at once:

```go
// core/guide_example_test.go
p, err := replay.New(provider.Caps{},
	replay.Reported("met", "The API takes JSON."),
	replay.Summary("The user chose JSON for the API."))
if err != nil {
	panic(err)
}
ctx := context.Background()
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass),
	zelk.WithContextWindow(200_000),
	zelk.WithCompaction(event.Compaction{Threshold: 150_000, Keep: 20_000}))
if err != nil {
	panic(err)
}
defer a.Close(ctx)
s, err := a.Session(ctx, "long-1")
if err != nil {
	panic(err)
}
for _, cmd := range []event.Command{
	zelk.UserMessage("Use JSON for the API."),
	zelk.Compact("keep the API decisions"),
} {
	x, err := s.Start(ctx, zelk.WithCommands(cmd))
	if err != nil {
		panic(err)
	}
	if _, err := x.Wait(ctx); err != nil {
		panic(err)
	}
}
// The model's window now opens with the summary; the log keeps
// everything, and HistoryOptions.Compacted reads it back.
page, err := s.History(ctx, zelk.HistoryOptions{})
if err != nil {
	panic(err)
}
fmt.Println(strings.Contains(page.Items[0].Parts[0].Text, "The user chose JSON for the API."))
// Output: true
```

| Option | Effect |
|---|---|
| `WithContextWindow(tokens)` | the window of a model whose provider reports none; a reported one wins |
| `WithCompaction(event.Compaction{…})` | `Threshold` (when to summarize), `Keep` (recent history kept as it is), `Clear` and `ClearAtLeast` (when to clear old tool results); zero keeps a default |
| `WithoutCompaction()` | none: a request that overflows ends the run with an error |

`zelk.Compact(focus)` summarizes now: an idle session runs a compaction
alone, and a running one compacts before its next model call. The focus
says what the summary must keep.

`Session.History` returns the model's window as it is now;
`HistoryOptions{Compacted: true}` includes the turns compaction removed,
with the summaries that replaced them.

## Next

[Observability](/go/observability/) reports what sessions do.
