---
title: Keep long sessions inside the context window (compaction)
description: Arm weft/thread's compaction with ContextWindow so a long session summarizes its older part behind a fixed marker and keeps the recent part raw; preview, apply, pin, hook and undo it, and nothing is ever deleted.
url: https://weftgo.dev/docs/sessions/compaction/
type: how-to
sources:
  - weft/AGENTS.md:569 (s.Pin), 570-575 (block 8, Compaction)
  - weft/README.md:738-742 (the overflow re-run), 744-769 (Compaction)
  - weft/docs/adr/0020-thread-compaction.md (§1 what a compaction is, §2 the default algorithm, §3 five layers, §4 pinning, trimmer, rate limits, cost ledger, §5 overflow, §7 the native seam; amendments 2026-09-29 and 2026-10-01 A–G)
  - weft/docs/adr/0021-thread-approvals.md (amendment 2026-09-29, the boundary holds the tail raw)
  - weft/docs/record-contract.md:743-768 (the compaction session marker)
  - weft/thread/compaction.go:19-34 (defaults), 42-52 (the marker), 58-77 (the skeleton), 81-127 (sentinels), 134-172 (Compaction), 217-235 (resolve), 253 (PreviewCompaction), 268 (Compact), 290-308 (the between-turns gate), 333 (ApplyCompaction), 594-606 (Uncompact), 916-924 (reportFailed), 951 (produceSummary), 1090-1135 (the cut), 1306-1423 (the trigger), 1427 (firesAt), 1472 (tryTrim), 1580 (rate limits)
  - weft/thread/compactopts.go:14-24 (naming and lock rules), 43 (ContextWindow), 66 (ModelWindows), 87 (ModelReserves), 104 (Reserve), 117 (KeepRecent), 123 (TriggerInput), 141 (TriggerFunc), 163 (MinTurnsBetween), 179 (MaxPerSession), 188 (Estimator), 202 (WithEstimator), 214 (NoAutoCompact), 232 (SummaryModel), 245 (SummaryPrompt), 259 (SummaryFocus), 273 (SummaryMaxTokens), 276 (CompactOption), 307 (SummaryInstructions), 321 (SummaryInput), 331 (Summary), 347 (Summarizer), 363 (Preparation), 397 (Compactor), 413 (WithSummarizer), 427 (WithCompactor), 450 (Trimmer), 465 (WithTrimmer), 469-471 (the stub), 531 (ClearOldToolResults), 538-555 (Verdict, Proceed, Cancel, Replace), 574 (BeforeCompact), 594 (AfterCompact), 618 (CompactFailed), 639 (CheckSummary), 651 (NativeCompactor), 669 (PreferNative), 677 (maxModelChain), 747 (Pin)
  - 'weft/thread/compaction.go:594-640 (Uncompact: the leaf entry targets parentOf the latest CompactionEntry on the path; later entries stay in the file, off the path)'
  - 'scratch proof (weft v0.17.0, docs a8 fix): thread.Memory, NoAutoCompact, KeepRecent(1); q1 to q3, Compact (context: summary, a3), q4 and q5 (summary, a3, q4, a4, q5, a5), then Uncompact gave [q1 a1 q2 a2 q3 a3] and 16 to 17 entries; Branch to the Leaf taken before the undo gave the summary, a3, q4, a4, q5, a5 again'
  - weft/thread/entry.go:101-122 (Reason), 141-169 (CompactionEntry), 184-198 (TrimRecord, TrimStub)
  - weft/thread/turn.go:1274-1276 (the post-turn trigger runs after the turn is decided)
  - weft/thread/interrupt.go:267-296 (compactForOverflow, ReRunOnOverflow)
  - weft/thread/compactmarker.go:21-74 (the marker)
  - weft/thread/session.go:1513-1535 (Usage.Summaries)
  - 'weft/thread/compaction.go:795 (SummarizerUsage: the accepted summary''s usage only), 951-989 (produceSummary: one retry per source on a rejected or truncated summary, a failed source falls back, nothing stored when every source fails); weft/thread/session.go:1532-1536 (Usage sums CompactionEntry alone)'
  - 'weft/thread/turn.go:951, 1282 (the trigger before and after each turn); weft/thread/compaction.go:1381-1385 (rate limits first), 1398-1419 (a failure leaves the session unchanged, the next trigger tries again, WARN thread: automatic compaction failed), 1580-1606 (rateLimitAllows counts compaction entries only; 1572-1590 MinTurnsBetween counts from the last stored one)'
  - 'scratch proof (weft v0.17.0): CheckSummary always rejecting and no SummaryModel, the first turn made two summary calls (the trigger before it stands down, nothing measured yet) and each later turn four (two attempts at each of the two triggers), Summaries zero; a failing SummaryModel''s call uncounted; SummarizeLeft''s call uncounted'
  - weft/thread/session.go:1046-1066 (Context is weft.Repair over the raw context)
  - weft/thread/compaction.go:995-1027, 1165-1200 (the summarizer gets role-tagged messages, previous summary first; the 2,000-character cap)
  - weft/thread/entry.go:82-89 and turn.go:1569-1578 (LastInput includes the estimated tail)
  - weft/CHANGELOG.md:5159 (the thread 0.2.0 heading over 4923 and 4927)
  - weft/core/errors.go:118-125 (ErrContextOverflow)
  - 'weft/core/agent.go:918-925 (Agent.Model: the WrapModel chain)'
  - weft/obsdb/db.go:59 (DB.Compactions); obsdb CompactionSession (godoc)
  - weft/studio/web/src/lib/compaction.ts:35-45 (the run page's session marker)
  - weft/CHANGELOG.md:3861 (the compaction sentinels and TrimRecord), 3894-3895 (Instructions → SummaryInstructions, Disabled → NoAutoCompact), 5145 (the overflow re-run), 5196 (Estimator outside the lock), 5200 (nativeOf never hashes a Model), 5321 (the trigger and the cut), 5328 (the summary), 5334 (the five layers)
  - weft/thread/example_test.go ExampleSession_Compact, ExampleSession_Pin, ExampleReRunOnOverflow
  - weft/thread/example_compaction_test.go ExampleSession_PreviewCompaction, ExampleSession_ApplyCompaction, ExampleBeforeCompact, ExampleCheckSummary, ExampleSummaryModel, ExampleClearOldToolResults, ExampleTriggerFunc, ExampleWithSummarizer
  - 'weft/thread/turn.go:1661-1671 (LastInput is the final step''s reported InputTokens plus the tail estimate, set for any turn with steps, 0 reported included), 1772 (the turn becomes the measured mark); weft/thread/compaction.go:1331-1338 (only a session never measured stands down, silently), 1424-1428 (the default trigger: LastInput + Estimated > Window − Reserve)'
  - weft/core/wefttest/model.go:32-36 (Say reports 10 input tokens), 57-74 (ToolCalls reports 10), 124-127 (Turn.WithUsage replaces a turn's usage)
  - 'weft/thread/compaction.go:1244-1250 (estimateMessage: a quarter of the message''s JSON bytes, an inline FilePart''s base64 Data included); weft/core/message.go:200-204 (FilePart: Data or URL); weft/thread/compactopts.go:188-202 (Estimator, WithEstimator)'
  - docs-site/examples/sessions/compaction.go, sessions_test.go TestDemos/compaction, TestCompactionAppendsAndUncompactBranchesBack, TestBeforeCompactCancel
  - 'weft v0.20.2: docs/record-contract.md:743-774 (the marker: held at Close, held: true, under no run; the body''s summarizer_model, summarizer_usage, held); weft/AGENTS.md:573-578 (block 8: held at Close; the summarizer''s chat span, weft.chat.role summarizer, never in the run''s usage; obsdb.SessionRow.SummarizerUsage); weft/CHANGELOG.md:225 (0.18.0: the summarizer''s cost; a failed call''s error.type summarizer)'
---

# Keep long sessions inside the context window (compaction)

[Compaction](https://weftgo.dev/docs/reference/glossary/#compaction) keeps a long session inside the model's context window: the older part of the conversation is summarized behind a fixed marker, the recent part stays raw, and the summarized entries stay in the file. [`thread.ContextWindow(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ContextWindow) arms the automatic trigger; [`s.Compact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Compact) compacts by hand; [`s.Uncompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Uncompact) undoes it.

`sessions/compaction.go` gives the session a 1,000-token window and a scripted model whose second reply reports 900 input tokens:

```go title="sessions/compaction.go"
agent := weft.New(wefttest.Script(
	wefttest.Say("Order 1234 shipped on Tuesday.").WithUsage(weft.Usage{InputTokens: 300}),
	wefttest.Say("Order 5678 is still processing.").WithUsage(weft.Usage{InputTokens: 900}),
	wefttest.Say("Goal: track orders 1234 and 5678."), // the summary, made by the same model
))
s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_window", "a"),
	thread.ContextWindow(1_000), // arms the trigger: fire past 1,000 − Reserve
	thread.Reserve(200),         // default 16,384
	thread.KeepRecent(40))       // default 20,000: estimated tokens kept raw
if err != nil {
	return err
}
for _, q := range []string{"Where is order 1234?", "And order 5678?"} {
	if err := send(ctx, s, q); err != nil { // send waits for WaitIdle: the trigger runs after the turn
		return err
	}
}
for _, e := range s.Entries() {
	if c, ok := e.(thread.CompactionEntry); ok {
		fmt.Fprintln(w, "compaction:", c.Reason, "first kept:", c.FirstKept, "tokens before:", c.TokensBefore)
	}
}
for _, m := range s.Context() {
	fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
}
fmt.Fprintln(w, "entries in the file:", len(s.Entries()))
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
compaction: threshold first kept: e_a4 tokens before: 81
user: "<weft-summary>\nGoal: track orders 1234 and 5678.\n</weft-summary>"
user: "And order 5678?"
assistant: "Order 5678 is still processing."
entries in the file: 7
```

The second turn crossed `window − Reserve` (800), so the session compacted after it. The model now sees the summary and the last turn; the file still holds both turns' six entries plus the compaction entry. The small `Reserve` and `KeepRecent` only make the demo fit; the defaults are 16,384 and 20,000 tokens.

## How compaction works

> **Diagram:** A session log holds e1 to e5. s.Compact(ctx) appends a compaction entry C, a summary of e1 to e3. Those entries stay in the file; the context at the leaf becomes the summary, then e4 and e5, the kept recent entries. s.Uncompact(ctx) undoes it by branching back to the entry before the compaction.

A compaction is a [`thread.CompactionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactionEntry) appended at the leaf: the summary text, the id of the first entry kept raw, the estimated tokens before, the reason, the summarizer's usage and model, the files the range read, the pinned ids and a hash of the summarized range. Nothing is deleted. A later compaction summarizes from the previous kept boundary and is fed the previous summary, so the chain is iterative.

**The trigger.** It runs on the session's runner before a turn starts (after the prompt is on the path) and after each turn ends. It fires when the last turn's measured input plus an estimate of the messages added since crosses `window − Reserve`. The measured input is the provider-reported input of the turn's final model step plus an estimate of that step's own messages, the tail the report cannot cover, recorded on the turn entry. The reported number is the signal; only what no report covers is estimated, never the whole context. When it fires, it checks the rate limits, tries the trimmer if one is set, and summarizes.

The trigger stands down when no step was ever measured, when a `Branch` or `Uncompact` moved the line since the measurement, or when a compaction landed after it; the next turn's report re-arms it. A turn that reported 0 input tokens counts as measured, so the trigger in practice never fires ([gotcha](#best-practices--gotchas)).

**The cut.** Walking back from the leaf, the session keeps about `KeepRecent` estimated tokens raw. The cut lands only on a user or assistant message and never between a tool call and its result. A single turn larger than `KeepRecent` is split at an assistant message inside it and summarized in one pass.

**The summary.** By default the session's own model writes it (`Agent.Model()`, middleware included, so `mw.Retry` and `mw.Fallback` apply), with no cache hints and the output capped at 0.8 × `Reserve`. The prompt is a fixed skeleton with the headings `Goal:`, `Constraints:`, `Progress:`, `Key Decisions:`, `Next Steps:`, `Critical Context:`, then cumulative `Files read:` and `Files modified:` lists. The range goes to the summarizer as the conversation's own role-tagged messages, the previous summary first, under the skeleton system prompt: tool results capped at 2,000 characters plus a `…[truncated]` marker, signed reasoning dropped, files reduced to `[file: name]`. (ADR 0020 §2 says a plain transcript; the code sends the messages.) A summary that hits the output cap is never stored.

**The context after it.** [`s.Context()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) is, in order:

1. The summary, as one user message: `<weft-summary>\n` + summary + `\n</weft-summary>`.
2. The pinned entries below the cut, raw, in path order.
3. The kept tail from `FirstKept` on, with every recorded trim replayed. Signed reasoning recorded before the latest compaction or trim is stripped.
4. Branch summaries where they sit on the path, behind the same marker.
5. `weft.Repair` last, so every tool call shown has a result.

**Undo is a navigation.** `Uncompact` appends a `leaf` entry pointing at the entry before the latest compaction or trim on the path, so the context is exactly what it was when that entry landed. Every turn sent after the compaction is off the new path too: it stays in the file, but the model no longer sees it ([gotcha](#best-practices--gotchas)). After a compaction and then a trim, the first `Uncompact` undoes the trim and a second one the compaction.

**Between turns only.** `Compact`, `ApplyCompaction` and `Uncompact` fail with `thread.ErrBusy` while a turn runs; `Compact` checks before it pays for a model call. `Compact` and `ApplyCompaction` fail with [`thread.ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) while approval requests are pending, and an open boundary holds the automatic trigger too: the parked calls must stay raw for their decisions to resolve ([approvals](https://weftgo.dev/docs/sessions/approvals/)). The trigger re-arms on the turn that resolves the boundary.

**Cost.** Each entry records its summarizer's usage, and `s.Usage().Summaries` sums them in their own bucket, never mixed with the turns' ([usage](https://weftgo.dev/docs/sessions/turns/#usage)). Only the summary call that was stored is counted: a rejected or truncated attempt, a `SummaryModel` that failed before the fallback, and a compaction that failed outright leave no entry, so their tokens are on no ledger ([gotcha](#best-practices--gotchas)).

Every compaction is logged at Info through the agent's logger, as `thread: compacted` or `thread: trimmed old tool results`, with `trace=compaction`, the session, the reason and `tokens_before`.

### With no window

Without `ContextWindow` (or a `ModelWindows` entry for the agent's model) there is no automatic compaction and the session logs one warning through the agent's logger, once per `Session` value:

```go title="sessions/compaction.go"
logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
	ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
		if a.Key == slog.TimeKey {
			return slog.Attr{} // stable output
		}
		return a
	},
}))
agent := weft.New(wefttest.Script(wefttest.Say("Shipped."), wefttest.Say("Processing.")),
	weft.Logger(logger))
s, err := thread.Create(ctx, thread.Memory(), agent) // no ContextWindow
if err != nil {
	return err
}
for _, q := range []string{"Order 1234?", "Order 5678?"} {
	if err := send(ctx, s, q); err != nil {
		return err
	}
}
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
level=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)"
```

Manual compaction and the overflow re-run still work. [`thread.NoAutoCompact()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoAutoCompact) turns the trigger off on purpose: no trigger, no trim and no warning, for a session that compacts only by hand. It took this name in thread 0.9.0; the CHANGELOG's migration checklist maps the old one.

A known window must leave room for the other two knobs: `Reserve` below the window, and `KeepRecent` below `window − Reserve`. Otherwise `Create` and `Open` fail with [`thread.ErrCompactConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactConfig) rather than build a session that never compacts.

### When a turn overflows

A turn that fails with [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow), which every first-party adapter maps, compacts with reason `overflow` and re-runs once over the shrunken path, under a fresh run id:

```go title="sessions/compaction.go"
agent := weft.New(wefttest.Script(
	wefttest.Say("Order 1234 shipped on Tuesday."),
	wefttest.Fail(weft.ErrContextOverflow),    // the provider refuses the request
	wefttest.Say("Goal: track order 1234."),   // the overflow compaction's summary
	wefttest.Say("Order 5678 is processing."), // the re-run, over the shrunken path
))
s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_overflow", "a"),
	thread.KeepRecent(40)) // ReRunOnOverflow is on by default
if err != nil {
	return err
}
if err := send(ctx, s, "Where is order 1234?"); err != nil {
	return err
}
turn, err := s.Send(ctx, weft.User("And order 5678?"))
if err != nil {
	return err
}
res, err := turn.Wait()
fmt.Fprintln(w, "turn:", err, "|", res.Text(), "| run:", turn.RunID())
fmt.Fprintln(w, "compaction:", lastCompaction(s).Reason)
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
turn: <nil> | Order 5678 is processing. | run: s_overflow-t3
compaction: overflow
```

The caller sees one turn with the re-run's answer; run `t2` is the attempt that overflowed. A second overflow fails the turn with both errors joined. [`thread.ReRunOnOverflow(false)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReRunOnOverflow) turns the re-run off, and the first overflow then fails the turn. `NoAutoCompact` does not affect it. While an approval boundary is open the overflow compaction is skipped and the turn fails ([`ExampleReRunOnOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-ReRunOnOverflow)).

## Compact by hand

[`s.PreviewCompaction(ctx, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.PreviewCompaction) runs the whole algorithm, the hook and the summarizer included, and returns the plan as a [`*thread.Compaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compaction) without writing anything. [`s.ApplyCompaction(ctx, plan)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ApplyCompaction) writes it as it stands, and `s.Compact(ctx, opts...)` does both. [`s.Pin(ctx, entryID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pin) keeps an entry in the context through every compaction:

```go title="sessions/compaction.go"
first := s.Entries()[0].(thread.MessageEntry) // "Where is order 1234?"
if err := s.Pin(ctx, first.ID); err != nil {  // keep it raw through every compaction
	return err
}
before := len(s.Context())
plan, err := s.PreviewCompaction(ctx, thread.SummaryInstructions("Keep every order number."))
if err != nil {
	return err
}
fmt.Fprintln(w, "plan:", plan.Summary, "| first kept:", plan.FirstKept, "| pinned:", plan.Pinned)
sys := model.Requests()[len(model.Requests())-1].System
fmt.Fprintln(w, "the summarizer's prompt ends:", sys[strings.LastIndex(sys, "\n")+1:])

if err := s.ApplyCompaction(ctx, plan); err != nil { // writes the plan as previewed
	return err
}
for _, m := range s.Context() {
	fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
}

if err := s.Uncompact(ctx); err != nil { // a branch back: nothing deleted
	return err
}
fmt.Fprintln(w, "after Uncompact:", len(s.Context()), "messages, as before:", len(s.Context()) == before)

// Preview and apply in one call; the session model summarizes again.
if err := s.Compact(ctx); err != nil {
	return err
}
fmt.Fprintln(w, "after Compact:", lastCompaction(s).Summary, "|", len(s.Context()), "messages")
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
plan: Goal: refund order 1234 and email the receipt. | first kept: e_a7 | pinned: [e_a1]
the summarizer's prompt ends: Keep every order number.
user: "<weft-summary>\nGoal: refund order 1234 and email the receipt.\n</weft-summary>"
user: "Where is order 1234?"
user: "Email me the receipt."
assistant: "The receipt is on its way."
after Uncompact: 6 messages, as before: true
after Compact: Goal: refund order 1234. | 4 messages
```

- **[`thread.SummaryInstructions(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryInstructions)** is the one [`thread.CompactOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactOption): it appends per-call instructions to this compaction's summary prompt, as the last line. The agent's own `weft.Instructions` are untouched. It took this name in thread 0.9.0, like `NoAutoCompact`.
- **`Uncompact` rewinds later turns too.** The example calls `Uncompact` right after `Compact`, so nothing is lost. After later turns, `Uncompact` rewinds past them: q1 to q3, `Compact`, q4 and q5, then `Uncompact` leaves the context `[q1 a1 q2 a2 q3 a3]`. To get the later turns back, take `leaf := s.Leaf()` before the undo and call `s.Branch(ctx, leaf)`: the context is again the summary, `a3`, and q4 to a5.
- **A preview is a dry run.** It may run while a turn is in flight, since it reads a snapshot, but applying it fails at once with `ErrBusy` until the turn ends; it does not wait. A tail that fits inside `KeepRecent` is `ErrNothingToCompact`, not an empty plan.
- **`ApplyCompaction` validates the plan against the leaf's path**, whatever happened since it was computed. `FirstKept` must be an entry on the path (`ErrNoEntry` when the session does not hold it, `ErrInvalidCompaction` when it is on another branch), at or after the previous summary's boundary. The same boundary twice is `ErrNothingToCompact`. A plan without a summary must be a trim with its record. An empty `Reason` is recorded as `manual`. You can hand it your own plan: `&thread.Compaction{Summary: "…", FirstKept: id}` ([`ExampleSession_ApplyCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.ApplyCompaction)).
- **A pin does not hold the cut back.** Compactions summarize past a pinned entry, record its id in `Pinned`, and the context re-includes it raw after the summary. Only an entry that contributes a message can be pinned (a message, a `custom_message` or a `branch_summary`); anything else is `ErrNotPinnable`, an unknown id `ErrNoEntry`. A pin is read when a compaction is computed, so a pin on an entry already below the boundary takes effect at the next one. The pin is a reserved custom entry, kind `weft/pin` ([`ExampleSession_Pin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Pin)).

The package examples are [`ExampleSession_Compact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Compact) and [`ExampleSession_PreviewCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.PreviewCompaction).

## Configure compaction

Every part of the algorithm is replaceable, in five layers (ADR 0020 §3): knobs, the summary, swapped implementations, hooks, and provider-native compaction. All are [`thread.SessionOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionOption) values passed to `Create` or `Open`. Every function or implementation you supply runs without the session lock and may call the session; the write after a hook re-validates against the tree as it is then. An `Estimator` that called back into the session used to deadlock; since thread 0.2.0 it runs outside the lock like the rest.

### Options

| Option | Default | Effect |
|---|---|---|
| [`ContextWindow(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ContextWindow) | unknown: no automatic compaction | The window the trigger budgets against, in tokens. Zero or negative is ignored. |
| [`ModelWindows(map)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ModelWindows) | none | Per-model windows keyed by `weft.ModelInfo`; the agent's model is looked up once, at `Create` or `Open`, and overrides `ContextWindow`. A run that swaps its model with `weft.UseModel` keeps the agent's window. |
| [`ModelReserves(map)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ModelReserves) | none | Per-model `Reserve`, resolved the same way. |
| [`Reserve(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reserve) | 16,384 | The headroom: fire before the context is within `n` tokens of the window. Also sizes the summary cap (0.8 × `n`). |
| [`KeepRecent(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#KeepRecent) | 20,000 | Roughly how many estimated tokens of the tail stay raw. |
| [`TriggerFunc(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TriggerFunc) | `LastInput + Estimated > Window − Reserve` | Replaces the condition. Consulted only when a window is known and a report describes the path; a panic reads as "do not fire". |
| [`MinTurnsBetween(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MinTurnsBetween) | 0: no limit | No automatic compaction or trim within `n` turns of the last compaction on the leaf's path. |
| [`MaxPerSession(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MaxPerSession) | 0: no cap | At most `n` automatic compactions (trims included) on the leaf's path; manual `Compact` keeps working. |
| [`WithEstimator(est)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithEstimator) | a quarter of the wire bytes | Replaces the token estimator: the trigger's delta, the cut's walk, `TokensBefore`. |
| [`NoAutoCompact()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoAutoCompact) | off | No trigger, no trim, no warning. Manual calls and the overflow re-run are unaffected. |
| [`SummaryModel(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryModel) | the session's model | A cheaper model for summaries. On failure the session's model takes over; then the compaction fails. |
| [`SummaryPrompt(tmpl)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryPrompt) | the skeleton | Replaces the summarizer's system prompt whole. |
| [`SummaryFocus(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryFocus) | none | Appends a standing instruction ("keep every file path") after the prompt. |
| [`SummaryMaxTokens(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryMaxTokens) | 0.8 × `Reserve` | The summary's output cap. A summary that reaches it fails as `ErrSummaryTruncated`. |
| [`WithSummarizer(s)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithSummarizer) | a model call | Replaces text production only. `SummaryModel` and `PreferNative` do not apply; `CheckSummary` does. |
| [`WithCompactor(c)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithCompactor) | the built-in algorithm | Replaces everything past the cut; no summary layer runs. |
| [`WithTrimmer(t)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithTrimmer) | off | A custom pre-pass before summarizing, on the threshold trigger only: `Compact` and the overflow re-run always summarize. |
| [`ClearOldToolResults(keepLast)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ClearOldToolResults) | off | The built-in trimmer: stub every tool result but the newest `keepLast`. |
| [`BeforeCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BeforeCompact) | none | Sees every summary compaction before the summarizer runs and returns a `Verdict`. |
| [`AfterCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#AfterCompact) | none | Runs with the durable `CompactionEntry` after any compaction or trim lands. |
| [`CompactFailed(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactFailed) | none | Runs when a compaction that was to be written is not, with the reason it was attempted for. |
| [`CheckSummary(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CheckSummary) | none | Validates each summary; a rejection retries once, then falls back. |
| [`PreferNative()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PreferNative) | off | Use the provider's own compaction when the summary model implements `NativeCompactor`. |
| [`ReRunOnOverflow(on)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReRunOnOverflow) | on | Compact and re-run once when a turn fails with `weft.ErrContextOverflow`. |

The examples are [`ExampleSummaryModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-SummaryModel) (its cost lands in `Usage().Summaries`), [`ExampleTriggerFunc`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-TriggerFunc) and [`ExampleCheckSummary`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-CheckSummary).

**The summary chain.** With `SummaryModel` set the chain is that model, then the session's model, then no compaction. Each source gets one retry when its summary is rejected, by `CheckSummary` or as truncated at the cap; a source that errors outright is not retried. A summary with no text is a failure. When the chain is exhausted nothing is stored, the error is returned, and `CompactFailed` hears of it.

### Hook a compaction

[`thread.BeforeCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BeforeCompact) is told the reason and returns a [`thread.Verdict`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Verdict): [`thread.Proceed()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Proceed) runs the compaction with whatever the hook edited (the zero `Verdict` proceeds), [`thread.Cancel()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Cancel) stops it, and [`thread.Replace(c)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Replace) writes the hook's own compaction, recorded with reason `from_hook`:

```go title="sessions/compaction.go"
verdict := "cancel"
hook := thread.BeforeCompact(func(ctx context.Context, p *thread.Preparation) (thread.Verdict, error) {
	switch verdict {
	case "cancel":
		return thread.Cancel(), nil
	case "replace": // your own summary; recorded with Reason from_hook
		return thread.Replace(&thread.Compaction{Summary: "Order 1234: refund started.", FirstKept: p.FirstKept}), nil
	}
	for i, m := range p.Messages { // redact the range before the summarizer sees it
		p.Messages[i] = weft.Message{Role: m.Role, Content: []weft.Part{
			weft.TextPart{Text: strings.ReplaceAll(m.Text(), "ada@example.com", "[email]")},
		}}
	}
	return thread.Proceed(), nil
})
s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_hook", "a"),
	thread.KeepRecent(40), hook)
if err != nil {
	return err
}
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

The same session compacted three times, the hook's answer changed between calls:

```go title="sessions/compaction.go"
n := len(s.Entries())
err = s.Compact(ctx)
fmt.Fprintln(w, "cancel:", errors.Is(err, thread.ErrCompactCanceled), "entries written:", len(s.Entries())-n)

verdict = "replace"
if err := s.Compact(ctx); err != nil {
	return err
}
fmt.Fprintln(w, "replace:", lastCompaction(s).Reason, lastCompaction(s).Summary)

verdict = "proceed"
if err := s.Uncompact(ctx); err != nil {
	return err
}
if err := s.Compact(ctx); err != nil {
	return err
}
fed := model.Requests()[len(model.Requests())-1].Messages[0].Text()
fmt.Fprintln(w, "proceed:", lastCompaction(s).Reason, "| the summarizer saw:", fed[:len("I am [email].")])
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
cancel: true entries written: 0
replace: from_hook Order 1234: refund started.
proceed: manual | the summarizer saw: I am [email].
```

`Cancel` writes nothing and the call fails with [`thread.ErrCompactCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactCanceled); on the automatic path it stays quiet. A `Replace` plan's `FirstKept` must be an entry the session holds; `ApplyCompaction`'s rules decide the rest. A hook error or panic fails the compaction with that error. A trim never passes through the hook, since it summarizes nothing. The package example is [`ExampleBeforeCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-BeforeCompact).

The hook receives a [`*thread.Preparation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Preparation). Four fields are editable, and the compaction proceeds with the edited values; edits to the rest are ignored:

| Field | Editable | Holds |
|---|---|---|
| `Reason` | no | Why the compaction runs. |
| `Context` | no | The context the model is shown now: the previous summary, pins, the kept tail with trims applied. |
| `Messages` | yes | The range to summarize, as stored. Redact here. |
| `PrevSummary` | no | The previous summary on the path, trims skipped. |
| `FirstKept` | yes | The first entry kept raw. It must be a user or assistant message on the path, past the previous boundary, that splits no call from its result; moved alone, the range is rebuilt. |
| `TokensBefore` | no | The estimated size of `Context`. |
| `Instructions` | yes | The per-call text from `SummaryInstructions`. |
| `Pinned` | yes | The pinned ids below the cut. |

The two observers run after the fact. [`thread.AfterCompact(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#AfterCompact) gets the durable entry for every compaction however it was written (`Compact`, `ApplyCompaction`, the trigger, the overflow re-run, a trim), and the `Context` it reads already shows it. [`thread.CompactFailed(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactFailed) runs when a compaction that was to be written is not, after every fallback, including an `ApplyCompaction` that fails to validate or store. It does not run for `PreviewCompaction`, nor for the refusals that attempt nothing: `ErrNothingToCompact`, `ErrCompactCanceled`, `ErrBusy` and `ErrAwaitingApproval`. A panic in either is contained and logged. [`thread.CheckSummary(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CheckSummary) validates each [`thread.Summary`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Summary); a panic in it counts as a rejection, and a truncated summary never reaches it.

### Clear old tool results first

[`thread.ClearOldToolResults(keepLast)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ClearOldToolResults) is a cheap pre-pass: when the trigger fires, every tool result in the context except the newest `keepLast` is replaced with a stub naming the call. If that brings the estimate under `window − Reserve`, no summary is made:

```go title="sessions/compaction.go"
read := weft.Tool("read_file", "Read a file.", func(ctx context.Context, in struct {
	Path string `json:"path"`
}) (string, error) {
	return strings.Repeat(in.Path+" ", 300), nil // about 450 estimated tokens each
})
agent := weft.New(wefttest.Script(
	wefttest.ToolCalls(
		wefttest.Call{Name: "read_file", ID: "call_a", Args: `{"path":"a.go"}`},
		wefttest.Call{Name: "read_file", ID: "call_b", Args: `{"path":"b.go"}`},
	),
	wefttest.Say("Both files read.").WithUsage(weft.Usage{InputTokens: 1_900}),
), read)
s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_trim", "a"),
	thread.ContextWindow(2_000), thread.Reserve(500), thread.KeepRecent(40),
	thread.ClearOldToolResults(1)) // keep the newest result raw
if err != nil {
	return err
}
if err := send(ctx, s, "Read a.go and b.go."); err != nil {
	return err
}
c := lastCompaction(s)
fmt.Fprintln(w, "compaction:", c.Reason, "| summary empty:", c.Summary == "", "| stubs:", len(c.Trim.Stubs))
for _, m := range s.Context() {
	for _, p := range m.Content {
		if r, ok := p.(weft.ToolResultPart); ok {
			fmt.Fprintln(w, r.CallID+":", r.Content[:min(38, len(r.Content))])
		}
	}
}
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
compaction: trim | summary empty: true | stubs: 1
call_a: [cleared tool result read_file call_a]
call_b: b.go b.go b.go b.go b.go b.go b.go b.g
```

The entry has reason `trim`, no summary, and a [`thread.TrimRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimRecord) whose [`thread.TrimStub`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TrimStub) values name each stubbed result: the entry, the call id, the replacement content. The stored results are untouched. Later context builds replay the record, never the option, so reopening with another `keepLast` never changes what a recorded trim shows. A trim keeps the boundary in force; it never governs it and never feeds the summary chain. A trim that changes nothing, or does not fit, writes nothing and the summary runs ([`ExampleClearOldToolResults`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-ClearOldToolResults)).

### Swap the parts

Four interfaces replace a part of the algorithm:

- **[`thread.Summarizer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Summarizer)**, `Summarize(ctx, SummaryInput) (Summary, error)`, produces the text and nothing else; the cut, the serialization, the entry and the retry chain stay the session's. A [`thread.SummaryInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryInput) carries `Messages` (the range, serialized), `PrevSummary`, `Instructions`, `MaxTokens`, `Reason` and `SystemPrompt`, the prompt the default would send, which a custom summarizer may reuse or ignore. It returns a `thread.Summary` with `Text` (empty is a failure) and the `Usage` and `Model` it cost, zero when no model ran. One that knows it was cut short returns an error wrapping `ErrSummaryTruncated` ([`ExampleWithSummarizer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-WithSummarizer)).
- **[`thread.Compactor`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compactor)**, `Compact(ctx, Preparation) (*Compaction, error)`, is the whole algorithm past the cut, after the hook's edits. It may keep any `FirstKept` on the path past the previous boundary; a returned plan with no `Reason` takes the preparation's.
- **[`thread.Trimmer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Trimmer)**, `Trim(ctx, msgs) ([]weft.Message, error)`, edits a copy of the context. The one change the record can hold is a tool result's `Content` (and `IsError`) replaced in place; any other change fails the trim with `ErrInvalidCompaction`, reported through the logger and `CompactFailed`, and the summary runs instead. An error or panic is logged and the summary runs.
- **[`thread.Estimator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Estimator)**, `Estimate(msgs) int64`, weighs messages in tokens, called with one message during the cut's walk and with a batch otherwise. The default weighs a message's JSON, so an inline file's base64 bytes count as text ([gotcha](#best-practices--gotchas)).

A panic in a `Summarizer` or `Compactor` fails the compaction. [`thread.NativeCompactor`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NativeCompactor), `CompactNative(ctx, req, instructions)`, is what an adapter implements when its provider compacts server-side; `PreferNative` looks for it on the summary model by following `Unwrap()` through middleware. The walk compares models structurally under a depth cap of 64, so an unhashable or self-wrapping wrapper ends the walk instead of panicking or looping (since thread 0.2.0). Only the returned message's text is kept, stored like any other summary. No first-party adapter implements the interface in v0.20.2, and on a model without it, an error or an empty text, the text summary runs.

### What a compaction records

A [`thread.Compaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compaction) is the plan `PreviewCompaction` returns and `ApplyCompaction` writes, field for field:

| Field | Meaning |
|---|---|
| `Summary` | The summary text, shown behind the marker. Empty only on a trim. |
| `FirstKept` | The first entry the context still shows raw. |
| `TokensBefore` | The estimated size of the context the model was shown, the compacted view, not the raw path. |
| `Reason` | Why it ran (below). |
| `SummarizerUsage`, `SummarizerModel` | What the summary cost and which model made it. |
| `FilesRead` | The file URLs the summarized range carried, sorted and deduplicated. |
| `Pinned` | The pinned ids below `FirstKept`, re-included after the summary. |
| `RangeHash` | The SHA-256 of the serialized range the summarizer was fed. |
| `Trim` | The trim record: required on a trim, forbidden otherwise. |

The [`thread.Reason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reason) values are [`ReasonManual`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonManual) (`"manual"`: `Compact`, or `ApplyCompaction` of a preview), [`ReasonThreshold`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonThreshold) (`"threshold"`: the trigger), [`ReasonOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonOverflow) (`"overflow"`: before the re-run), [`ReasonFromHook`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonFromHook) (`"from_hook"`: a `Replace`) and [`ReasonTrim`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReasonTrim) (`"trim"`). `MaxPerSession` counts every reason but `manual` as automatic.

The trigger reads a [`thread.TriggerInput`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#TriggerInput): `LastInput`, the last step's provider-reported input plus an estimate of that step's own messages, recorded on the turn entry; `Estimated`, the tokens added since that turn; and the `Window` and `Reserve` in force.

### Errors

Match each with `errors.Is`; nothing is written on any of them.

| Error | Returned when |
|---|---|
| [`ErrNothingToCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNothingToCompact) | The tail fits inside `KeepRecent`, nothing new sits past the previous boundary, or a plan names the boundary the previous compaction left. |
| [`ErrCompactCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactCanceled) | `BeforeCompact` answered `Cancel`. |
| [`ErrSummaryTruncated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrSummaryTruncated) | The last summarizer in the chain stopped at the output cap (the chain wraps its last error); raise `SummaryMaxTokens` or `Reserve`. |
| [`ErrInvalidCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrInvalidCompaction) | A plan that cannot be written as given: `FirstKept` off the path or before the boundary, a summary-less non-trim, a bad trim record, or a `Trimmer` change the record cannot hold. |
| [`ErrCompactConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCompactConfig) | `Create` or `Open` with a known window and `Reserve` or `KeepRecent` too large for it. |
| [`ErrNotPinnable`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotPinnable) | `Pin` on an entry that contributes no message. |
| [`ErrNoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNoEntry) | `Pin` or a plan names an entry the session does not hold, or `Uncompact` finds no compaction on the path. |
| [`ErrAwaitingApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrAwaitingApproval) | `Compact` or `ApplyCompaction` while approval requests are pending. |
| `ErrBusy` | `Compact`, `ApplyCompaction` or `Uncompact` while a turn runs. |

`TrimRecord`, `TrimStub`, `Compaction.Trim` and these sentinels arrived in thread 0.9.0.

## The compaction marker

Each compaction also emits one informational OTel log record of kind `compaction` through the agent's `LoggerProvider` as it lands, filed under the id of the last run of this session that produced the compacted context. `obsdb.DB.Compactions` reads it back:

```go title="sessions/compaction.go"
p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "weft.db")), otel.NoEnv(), otel.NoGlobal())
if err != nil {
	return err
}
defer p.Shutdown(context.WithoutCancel(ctx))
agent := weft.New(wefttest.Script(
	wefttest.Say("Order 1234 shipped on Tuesday."),
	wefttest.Say("The refund for order 1234 is started."),
	wefttest.Say("The receipt is on its way."),
	wefttest.Say("Goal: refund order 1234."),
), weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_marker", "a"), thread.KeepRecent(40))
if err != nil {
	return err
}
if err := longHistory(ctx, s); err != nil {
	return err
}
if err := s.Compact(ctx); err != nil { // the marker goes out as the entry lands
	return err
}
marks, err := p.LocalDB().Compactions(ctx, "s_marker-t3") // the last run that produced the context
if err != nil {
	return err
}
for _, m := range marks {
	fmt.Fprintln(w, "marker:", m.Scope, m.Reason, "replaced", m.Replaced, "messages with", m.Entries)
}
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

```text
marker: session manual replaced 4 messages with 1
```

- **What it carries.** Counts and a hash, never messages. It has the event name `weft.compaction` and the attributes `weft.compaction.scope = session`, `weft.compaction.hash` (the SHA-256 of the entry's JSON), `weft.content = none`, `gen_ai.agent.name` and the session's run metadata (`weft.session.id`, `weft.turn`, `weft.public_id`, …), but not the `gen_ai.conversation.id` and `session.id` mirrors a run's records carry. The body is `{scope, hash, entry, reason, replaced, entries, messages_before, messages_after, tokens_before, tokens_after, summarizer_model?, summarizer_usage?, held?}` ([record contract](https://weftgo.dev/docs/reference/record-contract/#compaction)). Since 0.18.0 `summarizer_model` (`{provider, name}`) and `summarizer_usage` say what the summary cost, counts and a model id, never content; both are absent for a trim or a summarizer that ran no model.
- **Where it is filed.** Under the last run whose turn produced the context. A context no run of this session produced (entries appended by hand, a fork's copied path) holds the marker for the next run this `Session` drives. Still held at `Close`, it goes out then with `held: true` in its body, filed under no run and keyed by `weft.session.id`, as the [state log's records](https://weftgo.dev/docs/reference/record-contract/#thread) are: a store indexes it by session, and no run's `Compactions` reads it.
- **The summarizer's calls.** Since 0.18.0 every summary model call, of a compaction or a `SummarizeLeft` branch, is also a `chat` span with `weft.chat.role` `summarizer`, its model and its usage, filed under the turn in flight or the last run. It is never in that run's own usage, provider, model or metadata: [`obsdb.SessionRow.SummarizerUsage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionRow) sums it per session, apart from `Usage`, and Studio prices it at read time ([See what a run cost](https://weftgo.dev/docs/observe/studio/cost/#own-and-delegated-cost)). A failed call's span carries `error.type` `summarizer`.
- **Who reads it.** No reader applies it: the next run's input record already holds the compacted context. [`obsdb.DB.Compactions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) returns a run's run-scope compaction views first, then the session markers filed under it, scope [`obsdb.CompactionSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CompactionSession). Studio's run page draws it at the top as "session compaction · after this run", with its token line and counts.

## Complete example

`sessions/compaction.go` runs the trigger, the warning, the manual calls, the hook, a trim, an overflow and the marker, each on its own session:

```go title="sessions/compaction.go"
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"path/filepath"
	"strings"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/thread"
	"github.com/weftgo/weft/wefttest"
)

// demoCompaction is the page "Keep long sessions inside the context
// window (compaction)".
func demoCompaction(ctx context.Context, w io.Writer, dir string) error {
	steps := []func(context.Context, io.Writer, string) error{
		compactionWindow, compactionWarn, compactionManual,
		compactionHook, compactionTrim, compactionOverflow, compactionMarker,
	}
	for _, step := range steps {
		if err := step(ctx, w, dir); err != nil {
			return err
		}
	}
	return nil
}

// compactionWindow: ContextWindow arms the trigger, and a turn whose
// reported input crosses window − Reserve compacts after it ends.
func compactionWindow(ctx context.Context, w io.Writer, _ string) error {
	fmt.Fprintln(w, "== automatic")
	agent := weft.New(wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday.").WithUsage(weft.Usage{InputTokens: 300}),
		wefttest.Say("Order 5678 is still processing.").WithUsage(weft.Usage{InputTokens: 900}),
		wefttest.Say("Goal: track orders 1234 and 5678."), // the summary, made by the same model
	))
	s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_window", "a"),
		thread.ContextWindow(1_000), // arms the trigger: fire past 1,000 − Reserve
		thread.Reserve(200),         // default 16,384
		thread.KeepRecent(40))       // default 20,000: estimated tokens kept raw
	if err != nil {
		return err
	}
	for _, q := range []string{"Where is order 1234?", "And order 5678?"} {
		if err := send(ctx, s, q); err != nil { // send waits for WaitIdle: the trigger runs after the turn
			return err
		}
	}
	for _, e := range s.Entries() {
		if c, ok := e.(thread.CompactionEntry); ok {
			fmt.Fprintln(w, "compaction:", c.Reason, "first kept:", c.FirstKept, "tokens before:", c.TokensBefore)
		}
	}
	for _, m := range s.Context() {
		fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
	}
	fmt.Fprintln(w, "entries in the file:", len(s.Entries()))
	return s.Close(ctx)
}

// compactionWarn: a session with no window logs one warning and never
// compacts on its own.
func compactionWarn(ctx context.Context, w io.Writer, _ string) error {
	fmt.Fprintln(w, "== no window")
	logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
		ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				return slog.Attr{} // stable output
			}
			return a
		},
	}))
	agent := weft.New(wefttest.Script(wefttest.Say("Shipped."), wefttest.Say("Processing.")),
		weft.Logger(logger))
	s, err := thread.Create(ctx, thread.Memory(), agent) // no ContextWindow
	if err != nil {
		return err
	}
	for _, q := range []string{"Order 1234?", "Order 5678?"} {
		if err := send(ctx, s, q); err != nil {
			return err
		}
	}
	return s.Close(ctx)
}

// longHistory runs three short turns, so a manual compaction has a cut.
func longHistory(ctx context.Context, s *thread.Session) error {
	for _, q := range []string{"Where is order 1234?", "Refund it.", "Email me the receipt."} {
		if err := send(ctx, s, q); err != nil {
			return err
		}
	}
	return nil
}

// compactionManual: preview, apply, pin and undo by hand.
func compactionManual(ctx context.Context, w io.Writer, _ string) error {
	fmt.Fprintln(w, "== by hand")
	model := wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
		wefttest.Say("The refund for order 1234 is started."),
		wefttest.Say("The receipt is on its way."),
		wefttest.Say("Goal: refund order 1234 and email the receipt."), // the preview's summary
		wefttest.Say("Goal: refund order 1234."),                       // Compact's summary
	)
	s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_manual", "a"),
		thread.KeepRecent(40))
	if err != nil {
		return err
	}
	if err := longHistory(ctx, s); err != nil {
		return err
	}
	first := s.Entries()[0].(thread.MessageEntry) // "Where is order 1234?"
	if err := s.Pin(ctx, first.ID); err != nil {  // keep it raw through every compaction
		return err
	}
	before := len(s.Context())
	plan, err := s.PreviewCompaction(ctx, thread.SummaryInstructions("Keep every order number."))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "plan:", plan.Summary, "| first kept:", plan.FirstKept, "| pinned:", plan.Pinned)
	sys := model.Requests()[len(model.Requests())-1].System
	fmt.Fprintln(w, "the summarizer's prompt ends:", sys[strings.LastIndex(sys, "\n")+1:])

	if err := s.ApplyCompaction(ctx, plan); err != nil { // writes the plan as previewed
		return err
	}
	for _, m := range s.Context() {
		fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())
	}

	if err := s.Uncompact(ctx); err != nil { // a branch back: nothing deleted
		return err
	}
	fmt.Fprintln(w, "after Uncompact:", len(s.Context()), "messages, as before:", len(s.Context()) == before)

	// Preview and apply in one call; the session model summarizes again.
	if err := s.Compact(ctx); err != nil {
		return err
	}
	fmt.Fprintln(w, "after Compact:", lastCompaction(s).Summary, "|", len(s.Context()), "messages")
	return s.Close(ctx)
}

// compactionHook: BeforeCompact decides — Cancel, Replace or Proceed
// with an edited Preparation.
func compactionHook(ctx context.Context, w io.Writer, _ string) error {
	fmt.Fprintln(w, "== hook")
	model := wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
		wefttest.Say("The refund for order 1234 is started."),
		wefttest.Say("The receipt is on its way."),
		wefttest.Say("Goal: refund the order; the customer is [email]."), // the Proceed summary
	)
	verdict := "cancel"
	hook := thread.BeforeCompact(func(ctx context.Context, p *thread.Preparation) (thread.Verdict, error) {
		switch verdict {
		case "cancel":
			return thread.Cancel(), nil
		case "replace": // your own summary; recorded with Reason from_hook
			return thread.Replace(&thread.Compaction{Summary: "Order 1234: refund started.", FirstKept: p.FirstKept}), nil
		}
		for i, m := range p.Messages { // redact the range before the summarizer sees it
			p.Messages[i] = weft.Message{Role: m.Role, Content: []weft.Part{
				weft.TextPart{Text: strings.ReplaceAll(m.Text(), "ada@example.com", "[email]")},
			}}
		}
		return thread.Proceed(), nil
	})
	s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_hook", "a"),
		thread.KeepRecent(40), hook)
	if err != nil {
		return err
	}
	if err := send(ctx, s, "I am ada@example.com. Where is order 1234?"); err != nil {
		return err
	}
	if err := longHistoryFrom(ctx, s, 1); err != nil {
		return err
	}
	n := len(s.Entries())
	err = s.Compact(ctx)
	fmt.Fprintln(w, "cancel:", errors.Is(err, thread.ErrCompactCanceled), "entries written:", len(s.Entries())-n)

	verdict = "replace"
	if err := s.Compact(ctx); err != nil {
		return err
	}
	fmt.Fprintln(w, "replace:", lastCompaction(s).Reason, lastCompaction(s).Summary)

	verdict = "proceed"
	if err := s.Uncompact(ctx); err != nil {
		return err
	}
	if err := s.Compact(ctx); err != nil {
		return err
	}
	fed := model.Requests()[len(model.Requests())-1].Messages[0].Text()
	fmt.Fprintln(w, "proceed:", lastCompaction(s).Reason, "| the summarizer saw:", fed[:len("I am [email].")])
	return s.Close(ctx)
}

// longHistoryFrom runs the rest of longHistory's turns, from turn i.
func longHistoryFrom(ctx context.Context, s *thread.Session, i int) error {
	for _, q := range []string{"Where is order 1234?", "Refund it.", "Email me the receipt."}[i:] {
		if err := send(ctx, s, q); err != nil {
			return err
		}
	}
	return nil
}

// lastCompaction is the newest compaction entry on the session's path.
func lastCompaction(s *thread.Session) thread.CompactionEntry {
	var out thread.CompactionEntry
	path, _ := s.Path(s.Leaf())
	for _, e := range path {
		if c, ok := e.(thread.CompactionEntry); ok {
			out = c
		}
	}
	return out
}

// compactionTrim: ClearOldToolResults stubs old tool results first;
// when that is enough, no summary is made.
func compactionTrim(ctx context.Context, w io.Writer, _ string) error {
	fmt.Fprintln(w, "== trim")
	read := weft.Tool("read_file", "Read a file.", func(ctx context.Context, in struct {
		Path string `json:"path"`
	}) (string, error) {
		return strings.Repeat(in.Path+" ", 300), nil // about 450 estimated tokens each
	})
	agent := weft.New(wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{Name: "read_file", ID: "call_a", Args: `{"path":"a.go"}`},
			wefttest.Call{Name: "read_file", ID: "call_b", Args: `{"path":"b.go"}`},
		),
		wefttest.Say("Both files read.").WithUsage(weft.Usage{InputTokens: 1_900}),
	), read)
	s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_trim", "a"),
		thread.ContextWindow(2_000), thread.Reserve(500), thread.KeepRecent(40),
		thread.ClearOldToolResults(1)) // keep the newest result raw
	if err != nil {
		return err
	}
	if err := send(ctx, s, "Read a.go and b.go."); err != nil {
		return err
	}
	c := lastCompaction(s)
	fmt.Fprintln(w, "compaction:", c.Reason, "| summary empty:", c.Summary == "", "| stubs:", len(c.Trim.Stubs))
	for _, m := range s.Context() {
		for _, p := range m.Content {
			if r, ok := p.(weft.ToolResultPart); ok {
				fmt.Fprintln(w, r.CallID+":", r.Content[:min(38, len(r.Content))])
			}
		}
	}
	return s.Close(ctx)
}

// compactionOverflow: a turn failing with weft.ErrContextOverflow
// compacts and re-runs once.
func compactionOverflow(ctx context.Context, w io.Writer, _ string) error {
	fmt.Fprintln(w, "== overflow")
	agent := weft.New(wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
		wefttest.Fail(weft.ErrContextOverflow),    // the provider refuses the request
		wefttest.Say("Goal: track order 1234."),   // the overflow compaction's summary
		wefttest.Say("Order 5678 is processing."), // the re-run, over the shrunken path
	))
	s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_overflow", "a"),
		thread.KeepRecent(40)) // ReRunOnOverflow is on by default
	if err != nil {
		return err
	}
	if err := send(ctx, s, "Where is order 1234?"); err != nil {
		return err
	}
	turn, err := s.Send(ctx, weft.User("And order 5678?"))
	if err != nil {
		return err
	}
	res, err := turn.Wait()
	fmt.Fprintln(w, "turn:", err, "|", res.Text(), "| run:", turn.RunID())
	fmt.Fprintln(w, "compaction:", lastCompaction(s).Reason)
	return s.Close(ctx)
}

// compactionMarker: each compaction emits one session marker record,
// which obsdb reads back under the run that produced the context.
func compactionMarker(ctx context.Context, w io.Writer, dir string) error {
	fmt.Fprintln(w, "== marker")
	p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "weft.db")), otel.NoEnv(), otel.NoGlobal())
	if err != nil {
		return err
	}
	defer p.Shutdown(context.WithoutCancel(ctx))
	agent := weft.New(wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
		wefttest.Say("The refund for order 1234 is started."),
		wefttest.Say("The receipt is on its way."),
		wefttest.Say("Goal: refund order 1234."),
	), weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_marker", "a"), thread.KeepRecent(40))
	if err != nil {
		return err
	}
	if err := longHistory(ctx, s); err != nil {
		return err
	}
	if err := s.Compact(ctx); err != nil { // the marker goes out as the entry lands
		return err
	}
	marks, err := p.LocalDB().Compactions(ctx, "s_marker-t3") // the last run that produced the context
	if err != nil {
		return err
	}
	for _, m := range marks {
		fmt.Fprintln(w, "marker:", m.Scope, m.Reason, "replaced", m.Replaced, "messages with", m.Entries)
	}
	return s.Close(ctx)
}
```

[sessions/compaction.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/compaction.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`:

```sh
go run ./sessions compaction
go test ./sessions
```

```text
== automatic
compaction: threshold first kept: e_a4 tokens before: 81
user: "<weft-summary>\nGoal: track orders 1234 and 5678.\n</weft-summary>"
user: "And order 5678?"
assistant: "Order 5678 is still processing."
entries in the file: 7
== no window
level=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)"
== by hand
plan: Goal: refund order 1234 and email the receipt. | first kept: e_a7 | pinned: [e_a1]
the summarizer's prompt ends: Keep every order number.
user: "<weft-summary>\nGoal: refund order 1234 and email the receipt.\n</weft-summary>"
user: "Where is order 1234?"
user: "Email me the receipt."
assistant: "The receipt is on its way."
after Uncompact: 6 messages, as before: true
after Compact: Goal: refund order 1234. | 4 messages
== hook
cancel: true entries written: 0
replace: from_hook Order 1234: refund started.
proceed: manual | the summarizer saw: I am [email].
== trim
compaction: trim | summary empty: true | stubs: 1
call_a: [cleared tool result read_file call_a]
call_b: b.go b.go b.go b.go b.go b.go b.go b.g
== overflow
turn: <nil> | Order 5678 is processing. | run: s_overflow-t3
compaction: overflow
== marker
marker: session manual replaced 4 messages with 1
```

The other sessions log their own no-window warning and their Info lines on stderr, through `slog.Default`. `sessions/sessions_test.go` also pins that a compaction only appends, that `Uncompact` restores the context, and that `Cancel` writes nothing and calls no model.

## Best practices & gotchas

- **Set `ContextWindow` for every session that runs long.** Without it nothing compacts until a turn overflows the provider's window and pays for a failed request first. (Source: `thread/compaction.go:1306-1320`; ADR 0020 §2)
- **Compact between turns.** `Compact`, `ApplyCompaction` and `Uncompact` fail with `ErrBusy` while a turn runs; wait for the turn, or call `s.WaitIdle`. (Source: `thread/compaction.go:290-308`, 606-611)
- **Do not offer `Uncompact` as "show the full history".** It branches back to the entry before the latest compaction, so every turn sent since then leaves the model's context. With `ContextWindow` the latest compaction can be many turns back. Undo right after compacting, or keep `s.Leaf()` from before the undo and `Branch` back to it. To keep the raw history in view, read `s.Entries()` or `s.Path(leaf)` instead. (Source: `thread/compaction.go:594-635`)
- **Decide approvals before compacting.** A pending approval holds the tail raw: `Compact` fails with `ErrAwaitingApproval` and the trigger waits. (Source: `thread/compaction.go:123-126`; ADR 0021 amendment 2026-09-29)
- **Redact in `BeforeCompact`, not after.** The hook's `Preparation.Messages` is what the summarizer reads; the summary lands in the context and the file. (Source: `thread/compactopts.go:351-362`; `ExampleBeforeCompact`)
- **Wait for idle before reading what the trigger did.** The trigger runs after the turn is decided, so a caller of `turn.Wait` may read the session before the compaction lands. (Source: `thread/turn.go:1274-1276`; `ExampleClearOldToolResults`)
- **A summary costs a model call.** In a scripted test it consumes a scripted reply; in production the stored summary's call is billed under `Usage().Summaries`. (Source: ADR 0020 §4 cost ledger; `ExampleSummaryModel`)
- **Count summary spend from the provider, not from `Summaries`.** `Summaries` sums `CompactionEntry.SummarizerUsage`, the accepted summary's call alone. Rejected or truncated retries, a failed `SummaryModel` before the fallback, a compaction that failed and every `SummarizeLeft` summary are not counted. Without a `SummaryModel`, a compaction that is always rejected costs two summary calls at each trigger, and `Summaries` stays zero. (Source: `thread/compaction.go:795, 951-989`; `thread/session.go:1532-1536`)
- **Fix a compaction that keeps failing.** The trigger runs before and after every turn. A failed attempt writes no compaction entry, so `MinTurnsBetween` and `MaxPerSession` never count it. Once the gap from the last stored compaction has passed, it is retried at every trigger with no backoff. Each failure logs `thread: automatic compaction failed` at WARN; the turn itself still runs. (Source: `thread/turn.go:951, 1282`; `thread/compaction.go:1381-1385, 1398-1419, 1580-1606`)
- **Make sure the provider reports input tokens.** The trigger's signal is the final step's reported `InputTokens`. A turn that reports 0 still counts as measured, so the trigger compares only an estimate of the newest messages with the window: it never fires in practice, and nothing is logged. What still compacts: a manual `s.Compact`, a `thread.TriggerFunc` that decides on something other than the reported number (it still receives the `TriggerInput`), and the [overflow re-run](#when-a-turn-overflows) when the provider's error maps to `weft.ErrContextOverflow`. An OpenAI-compatible server without `include_usage` reports 0 ([providers](https://weftgo.dev/docs/guides/providers/#token-usage)). (Source: `thread/turn.go:1661-1671`; `thread/compaction.go:1331-1338, 1375-1380, 1424-1428`; `thread/compactopts.go:123-141`)
- **Give scripted turns usage in a compaction test.** `wefttest.Say` and `wefttest.ToolCalls` report a fixed 10 input tokens, so the signal stays at 10 however long the scripted conversation grows. Set the reported input on each turn with `Turn.WithUsage`, as `sessions/compaction.go` does: `wefttest.Say("…").WithUsage(weft.Usage{InputTokens: 900})`. (Source: `weft/core/wefttest/model.go:32-36, 124-127`)
- **Weigh inline files yourself.** The default estimate is a quarter of a message's JSON bytes, and an inline `FilePart`'s `Data` is base64 in that JSON. A 400 KiB PNG sent inline weighs about 136k estimated tokens, so the trigger before that turn can compact a session whose real input is a few thousand tokens, and pay for the summary. Send the file as a URL `FilePart`, or pass `WithEstimator` an `Estimator` that gives file parts their own weight. (Source: `thread/compaction.go:1244-1250`; `thread/compactopts.go:188-202`)
- **Raise the cap, not the retries, on `ErrSummaryTruncated`.** A cut summary is never stored; give it room with `SummaryMaxTokens` or `Reserve`. (Source: `thread/compaction.go:98-103`)

## See also

- [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/): why an open boundary holds compaction
- [Label, branch and fork a session](https://weftgo.dev/docs/sessions/tree/): `Uncompact` is a branch; `SummarizeLeft` uses the same summarizer
- [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/): the cost ledger and what the model sees
- [The session log format](https://weftgo.dev/docs/sessions/format/): the `compaction` entry and its `"v":5` trim record

Symbols used: [`thread.ContextWindow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ContextWindow) · [`thread.Reserve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Reserve) · [`thread.KeepRecent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#KeepRecent) · [`thread.NoAutoCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoAutoCompact) · [`thread.ReRunOnOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ReRunOnOverflow) · [`thread.SummaryInstructions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SummaryInstructions) · [`thread.BeforeCompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#BeforeCompact) · [`thread.Proceed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Proceed) · [`thread.Cancel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Cancel) · [`thread.Replace`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Replace) · [`thread.ClearOldToolResults`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ClearOldToolResults) · [`thread.Preparation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Preparation) · [`thread.Compaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Compaction) · [`thread.CompactionEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CompactionEntry) · [`Session.Compact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Compact) · [`Session.PreviewCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.PreviewCompaction) · [`Session.ApplyCompaction`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ApplyCompaction) · [`Session.Uncompact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Uncompact) · [`Session.Pin`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pin) · [`Session.Context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) · [`Session.Entries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) · [`Session.Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Path) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider) · [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) · [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.Say`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Say) · [`wefttest.ToolCalls`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ToolCalls) · [`Turn.WithUsage`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2/wefttest#Turn.WithUsage) · [`weft.FilePart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#FilePart) · [`thread.Estimator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Estimator) · [`thread.WithEstimator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithEstimator)
