Open History to see the last commit
1---
2title: Compact a harness session
3id: harness-compaction
4order: 4
5description: "Keep a long harness session under the context limit. The compaction goes into the session log, so a session that opens again sees the same context."
6keywords:
7 - tanstack ai
8 - harness
9 - compaction
10 - context window
11 - projectCompaction
12 - compactNext
13 - session log
14---
15
16A harness session can run for days. Its transcript grows until a model call passes the context limit. [Compaction](../advanced/compaction) shrinks what the model sees. In a durable harness, the result must also survive a restart. A session that opens again must see the same context as before.
17
18Set `durable: true`. Compaction then writes a `tanstack.compaction` record into the session log. The host folds that record into the messages with `projectCompaction`, live and when the session opens again.
19
20## Add compaction to a harness
21
221. Create the compaction middleware with `durable: true`.
232. Add it to `middleware` in `defineHarness`.
243. Give the harness `projectCompaction` in its `durability.addRecordsToModelContext` option.
25
26```ts group=harness-compaction
27import { createHarnessHost, defineHarness } from '@tanstack/ai-harness'
28import { memoryPersistence } from '@tanstack/ai-persistence'
29import { openaiText } from '@tanstack/ai-openai'
30import {
31 conversationSummarizer,
32 projectCompaction,
33 summarizeOldest,
34 withCompaction,
35} from '@tanstack/ai-compaction'
36
37const compaction = withCompaction({
38 maxTokens: 180_000,
39 contextWindow: 200_000,
40 countTokens: 'usage',
41 durable: true,
42 strategy: summarizeOldest({
43 cut: 'turn',
44 keepRecentTokens: 8_000,
45 summarize: conversationSummarizer({ adapter: openaiText('gpt-6.1-sol') }),
46 }),
47})
48
49const assistant = defineHarness({
50 name: 'acme/assistant',
51 adapter: openaiText('gpt-6.1-sol'),
52 middleware: [compaction],
53 durability: { addRecordsToModelContext: { version: 'v1', record: projectCompaction } },
54})
55
56const host = createHarnessHost({ persistence: memoryPersistence() })
57```
58
59- Compaction runs before a model call when the count passes `maxTokens`. If the usage of the last model call of a turn passed `maxTokens` or `contextWindow`, compaction also runs right after that call. This check needs `countTokens: 'usage'`.
60- The log only grows, so the original messages stay in the store. The fold that the model gets starts with the summary.
61- Readers still get every message. `session.transcript()`, `GET transcript`, and the chat hydration show the full history, not the summary.
62- A thread can change its model. To give each model its own limit, pass a function, like `maxTokens: ({ model }) => ...`. See [A limit for each model](../advanced/compaction-advanced#a-limit-for-each-model).
63
64## Prepare the summary in the background
65
66A summary call takes time. When compaction runs at `maxTokens`, the user waits for that call before the model answers. Set `background` to prepare the summary earlier, while the session goes on:
67
68```ts group=harness-compaction
69const earlyCompaction = withCompaction({
70 maxTokens: 180_000,
71 contextWindow: 200_000,
72 countTokens: 'usage',
73 durable: true,
74 background: { atTokens: 150_000 },
75 strategy: summarizeOldest({
76 cut: 'turn',
77 keepRecentTokens: 8_000,
78 summarize: conversationSummarizer({ adapter: openaiText('gpt-6.1-sol') }),
79 }),
80})
81```
82
83- `atTokens` must be below `maxTokens`. If it is not, `withCompaction` throws.
84- When the count at a model call passes `atTokens`, the summary starts beside the turn. The turn does not wait for it.
85- The summary applies at the first model call of the next run, never in the middle of a run. It goes into the log as a `tanstack.compaction` record with `reason: 'background'`.
86- A model call over `maxTokens` while the summary runs waits for it and applies it. It compacts inline only when the messages are still over `maxTokens`.
87- If you cancel the run during that wait, the wait stops. The summary continues and applies at the next run.
88
89Sometimes a summary does not apply:
90
91- A newer compaction cut past the message that the summary keeps. The summary is dropped. `onCompact` and `compaction:ended` report it with `stale: true`.
92- The next run calls another model than the one that started the summary. The summary is dropped and reported with `stale: true`.
93- The summary call failed. Nothing applies. `onCompact` and `compaction:ended` report it with `error`. The next model call past `atTokens` starts a new summary.
94
95## Fold your own records too
96
97If your harness already folds records of its own, call `projectCompaction` first:
98
99```ts group=harness-compaction
100import type { ProjectOptions } from '@tanstack/ai-harness'
101
102const project: ProjectOptions = {
103 version: 'v2',
104 record: (input) => {
105 const compacted = projectCompaction(input)
106 if (compacted) return compacted
107 const { record, messages } = input
108 if (record.type === 'app.signal' && typeof record.text === 'string') {
109 return [...messages, { role: 'user', content: record.text }]
110 }
111 return undefined
112 },
113}
114```
115
116Change `version` when you change the function. A log snapshot with another version is not used, so the host folds the log again from the first record.
117
118## Retry after a context overflow
119
120A model call can still fail because the context is too long. `withCompaction` handles it for you. When a call fails with `CONTEXT_OVERFLOW_CODE` (`'context_overflow'`), the middleware compacts and calls the model again, inside the `chat()` call of the turn. That compaction also writes its record to the log.
121
122- It retries once per model call. This also works with `auto: false`.
123- `turn.onModelError` sees the overflow only when the compacted call is still too long. Then `error.code` is `'context_overflow'`, and the turn fails unless your hook returns `'retry'`.
124- To compact the next call yourself, for example before you switch the thread to a model with a smaller context window, call `compaction.compactNext(session.threadId)`.
125
126For a strategy that always finds something to cut on the retry, see [Give the retry something to cut](../advanced/compaction#give-the-retry-something-to-cut).
127
128## What you have now
129
130- A session that compacts before it passes the context limit, counted with the real usage of each call.
131- The same context after a restart, because the compaction is in the log.
132- With `background`, a summary that is ready before the session reaches `maxTokens`.
133- One retry after an overflow, with a compaction first, and no code of your own.