bots-garden/mini-mepublic Fork
⑂ v2.2.1
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP
context-compression.md · 52 lines · 11.3 KBmarkdown
Blame HistoryOpen raw

Context compression — explanation

What is this about?

Nothing in an agent loop ever shortens the history. Measured against a fake engine, the messages sent to the model grew 2 → 5 → 7 → 9 over four requests, and every bash output, up to maxOutput characters, and every loaded skill stay until /quit. On a local model the context window is fixed when the server loads, and the whole history is re-read at every turn on the laptop's hardware. A long session therefore first shows up as a false watchdog stall, then as an error from the server.

The compact package replaces the old question turns by one summary written by the model itself, and keeps the last few turns raw.

Why it is designed this way

A hybrid: summary plus raw recent turns. The recent turns are where the model is working; summarising them makes it re-run what it just did. The default keeps three question turns, enough for "do X", "now fix it", "and test it". Everything older becomes a pair of messages inserted right after the system prompt: a user message carrying the notes, and a short model acknowledgement.

The cut falls on a turn boundary. A tool call and its result must never be split; reusing whole turns guarantees it.

A turn starts at a question the user asked, not at every user message. mm writes some messages in the user's role itself: the notes it hands the model ([mm: your last tool call was not run…], a reply cut at the token limit, a failed edit, a loop) and the messages the user types while a turn runs. Each of them used to open a turn of its own, so keepLastTurns: 3 could keep one real question and a hundred messages around it — about 20k tokens of a 16k window, in one observed session — with nothing old left to summarise. These messages now carry a marker and stay in the turn they were added to. Sessions saved before the marker existed are split as they used to be.

Two triggers, because the window is not always known. The primary trigger is a share of the context window, 75 % by default, leaving a quarter for the next question, its tool outputs and the answer. The server's own input-token count from the last call is preferred to the local estimate when it is larger, because it sees the tools' JSON and the chat template. When the window is unknown, Docker Model Runner tells nothing and contextWindow may be 0, only the message-count trigger can fire, and the agent says so at start-up.

One key for the window. The banner and the trigger read the same contextWindow; two keys for the same number would drift apart.

Earlier summaries are merged, not re-summarised. The two inserted messages carry a marker; a later compression recognises them and folds the new old turns into the existing summary, because summarising a summary loses detail exponentially.

A fixed-shape summary. The built-in prompt asks for seven sections with exact paths, command lines and error messages, and forbids quoting file contents: a file may have changed since it was read, and the system prompt already forbids stating what a command in this answer did not return. The summary request replaces the agent's own system prompt with a note-taker's, because "you are a coding agent, run commands" sent with a history full of tool calls invites the model to keep acting.

Failure costs nothing. If the summary request fails, server down, watchdog, empty result, the history is left untouched and the next question goes out as before. The compression exists to keep the next question possible; it must never cost one.

The watchdog is twice as patient here. The summary is the longest prefill of the session and nothing streams while it is written.

/compact skips the threshold, not the boundary. It still keeps the last turns and says so when nothing is older. This compression, the summary of old question turns, only ever runs between two generations, because Genkit holds its own copy of the conversation while a turn runs.

Inside a long turn, a second, lighter compression (context.compressInTurn, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to write_file) keeping its first line — scene.go: created, 516 line(s) — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for enabled: a turn that outgrows the window fails whatever the between-questions setting says.

When the history before the turn is too big already, one summary per turn. The summary inside a turn can only work on the turn's own exchanges; the earlier turns and the question are its floor. When that floor alone passes the threshold, no summary can get the history back under it, and summarising before every call only makes the model lose its oldest reads and do them again — observed: 3.5 hours, about thirty identical read cycles, no progress. So in that case the turn is summarised once, the 🗜️ line says why it will not be again (it is shown even when showStats is off, because the user can act on it and the model cannot), and the later calls only shrink. The next question then goes through the between-questions compression, which can reach the earlier turns.

Sizes are calibrated on the server's count. The estimate counts 3.5 characters per token, which holds for English prose. Code and HTML are denser — about 1.8 characters per token with Inkling-2-Mini on Go, HTML and shell output — and the request also carries the tools' schemas. Observed: mm estimated 8.3k tokens where the server read 17.2k. The compression fired on the server's count but judged its own work with the estimate, found it under the threshold, never summarised, shrank one exchange per call, broke the prompt cache every time, and sent 17k tokens to a 16k window until the server stopped answering. So every in-turn decision now scales the estimate by the ratio of the server's last count to the estimate of that same request. The ratio describes the tokenizer and the kind of text, so it outlives a compression, unlike the count. Two consequences follow. When the last four exchanges alone pass the threshold, the summary keeps fewer of them, because a summary that cannot get under the threshold would run again before the next call. And a request that is still larger than the window once compressed is not sent: an honest error that ends the turn beats a prompt the server reads for minutes, or never answers.

When the files do not fit the window, the model must not read them in circles. A model that needs two 500-line files to write a front end reads them in chunks; by the time it reaches the end, the first chunks were shrunk away and it starts again. Observed: 40 tool calls, all reads, the same sed -n ranges four times, no file written. Three changes break that circle. A shrunk result that holds code keeps its outline — the declarations, the routes, the JSON fields — instead of its first line, which for a Go file was package server: the model keeps the map of the code and reads a body only when it needs that body. The in-turn notes keep the same kind of facts; they used to be forbidden to quote file contents, a rule that suits the between-questions summary (a file may change between two questions) but threw away exactly what the next step of the same task needed. And when the model runs again a call whose result was dropped, the new result says so and suggests writing notes or starting the change: the loop detector cannot see this, because it is a cycle of different commands, not one command repeated. The note is part of the tool result, never a user message, which would start a turn of its own for the compaction. A first test showed that this was not enough: the outlines were there, the notes held all twenty routes, six gentle notes were sent — and the model kept reading, because mm's own wrapper around the notes told it to "re-read a file or re-run a command before relying on it", and the notes ended with "Remaining: read full type definitions … before editing". Both now point at the next change instead, and from the second re-read of a turn the note says plainly to stop reading and write a first version. A second test showed that a model can read such a note and still go on reading; so past rereadLimit re-reads of the same call (one by default), mm does not run it at all and answers with the reason instead. A call repeated after a write_file or edit_file is never counted: running the tests again after a fix is the opposite of reading in circles.

A compression must last. The in-turn compression fires at the threshold; if it only gets back just under it, the next tool result passes it again, and the turn is compressed before nearly every call. Each compression rewrites the prompt, and a server that reuses what it already read (llama.cpp, razorbill) then reads it all again: measured on Inkling-2-Mini, ~98 s for such a call against ~13 s for one that hits the cache — 29.5 minutes of a 34.5-minute run. So the compression aims lower than it triggers (inTurnTarget, two thirds of the threshold by default): the older exchanges are shrunk, then summarised — keeping fewer exchanges raw when needed — and only then, as a last resort, the kept ones are shrunk too, never the last one. Summary before shrinking, because notes keep what a shrunk result loses. The price is that the model keeps less of what it just read; a target equal to the threshold restores the old behaviour. The notes themselves start with the next change to make, and a summary cut at summaryMaxTokens loses its unfinished line and says so: five summaries of six were cut in the same session, and the line asked for at the end never got written.

Rejected alternatives

  • Truncating the oldest messages. Rejected: it would drop tool results whose calls remain, and lose the goal of the session.
  • Summarising everything, recent turns included. Rejected: the model then redoes its last steps.
  • A separate context.contextWindow key. Rejected in favour of the single top-level key.
  • Inside a turn, summarising at once, or a summary pair in the middle of the turn. Rejected: shrinking costs no model call and is often enough; and a pair of messages between two tool exchanges breaks the alternation some chat templates check (Gemma's raises an error).

How it relates to the rest

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Context compression — explanation

## What is this about?

Nothing in an agent loop ever shortens the history. Measured against a fake engine, the messages sent to the model grew 2 → 5 → 7 → 9 over four requests, and every `bash` output, up to `maxOutput` characters, and every loaded skill stay until `/quit`. On a local model the context window is fixed when the server loads, and the whole history is re-read at every turn on the laptop's hardware. A long session therefore first shows up as a false watchdog stall, then as an error from the server.

The `compact` package replaces the old question turns by one summary written by the model itself, and keeps the last few turns raw.

## Why it is designed this way

**A hybrid: summary plus raw recent turns.** The recent turns are where the model is working; summarising them makes it re-run what it just did. The default keeps three question turns, enough for "do X", "now fix it", "and test it". Everything older becomes a pair of messages inserted right after the system prompt: a user message carrying the notes, and a short model acknowledgement.

**The cut falls on a turn boundary.** A tool call and its result must never be split; reusing whole turns guarantees it.

**A turn starts at a question the user asked, not at every user message.** mm writes some messages in the user's role itself: the notes it hands the model (`[mm: your last tool call was not run…]`, a reply cut at the token limit, a failed edit, a loop) and the messages the user types while a turn runs. Each of them used to open a turn of its own, so `keepLastTurns: 3` could keep one real question and a hundred messages around it — about 20k tokens of a 16k window, in one observed session — with nothing old left to summarise. These messages now carry a marker and stay in the turn they were added to. Sessions saved before the marker existed are split as they used to be.

**Two triggers, because the window is not always known.** The primary trigger is a share of the context window, 75 % by default, leaving a quarter for the next question, its tool outputs and the answer. The server's own input-token count from the last call is preferred to the local estimate when it is larger, because it sees the tools' JSON and the chat template. When the window is unknown, Docker Model Runner tells nothing and `contextWindow` may be `0`, only the message-count trigger can fire, and the agent says so at start-up.

**One key for the window.** The banner and the trigger read the same `contextWindow`; two keys for the same number would drift apart.

**Earlier summaries are merged, not re-summarised.** The two inserted messages carry a marker; a later compression recognises them and folds the new old turns into the existing summary, because summarising a summary loses detail exponentially.

**A fixed-shape summary.** The built-in prompt asks for seven sections with exact paths, command lines and error messages, and forbids quoting file contents: a file may have changed since it was read, and the system prompt already forbids stating what a command in this answer did not return. The summary request replaces the agent's own system prompt with a note-taker's, because "you are a coding agent, run commands" sent with a history full of tool calls invites the model to keep acting.

**Failure costs nothing.** If the summary request fails, server down, watchdog, empty result, the history is left untouched and the next question goes out as before. The compression exists to keep the next question possible; it must never cost one.

**The watchdog is twice as patient here.** The summary is the longest prefill of the session and nothing streams while it is written.

**`/compact` skips the threshold, not the boundary.** It still keeps the last turns and says so when nothing is older. This compression, the summary of old question turns, only ever runs between two generations, because Genkit holds its own copy of the conversation while a turn runs.

**Inside a long turn, a second, lighter compression** (`context.compressInTurn`, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to `write_file`) keeping its first line — `scene.go: created, 516 line(s)` — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for `enabled`: a turn that outgrows the window fails whatever the between-questions setting says.

**When the history before the turn is too big already, one summary per turn.** The summary inside a turn can only work on the turn's own exchanges; the earlier turns and the question are its floor. When that floor alone passes the threshold, no summary can get the history back under it, and summarising before every call only makes the model lose its oldest reads and do them again — observed: 3.5 hours, about thirty identical read cycles, no progress. So in that case the turn is summarised once, the `🗜️` line says why it will not be again (it is shown even when `showStats` is off, because the user can act on it and the model cannot), and the later calls only shrink. The next question then goes through the between-questions compression, which can reach the earlier turns.

**Sizes are calibrated on the server's count.** The estimate counts 3.5 characters per token, which holds for English prose. Code and HTML are denser — about 1.8 characters per token with Inkling-2-Mini on Go, HTML and shell output — and the request also carries the tools' schemas. Observed: mm estimated 8.3k tokens where the server read 17.2k. The compression fired on the server's count but judged its own work with the estimate, found it under the threshold, never summarised, shrank one exchange per call, broke the prompt cache every time, and sent 17k tokens to a 16k window until the server stopped answering. So every in-turn decision now scales the estimate by the ratio of the server's last count to the estimate of that same request. The ratio describes the tokenizer and the kind of text, so it outlives a compression, unlike the count. Two consequences follow. When the last four exchanges alone pass the threshold, the summary keeps fewer of them, because a summary that cannot get under the threshold would run again before the next call. And a request that is still larger than the window once compressed is not sent: an honest error that ends the turn beats a prompt the server reads for minutes, or never answers.

**When the files do not fit the window, the model must not read them in circles.** A model that needs two 500-line files to write a front end reads them in chunks; by the time it reaches the end, the first chunks were shrunk away and it starts again. Observed: 40 tool calls, all reads, the same `sed -n` ranges four times, no file written. Three changes break that circle. A shrunk result that holds code keeps its outline — the declarations, the routes, the JSON fields — instead of its first line, which for a Go file was `package server`: the model keeps the map of the code and reads a body only when it needs that body. The in-turn notes keep the same kind of facts; they used to be forbidden to quote file contents, a rule that suits the between-questions summary (a file may change between two questions) but threw away exactly what the next step of the same task needed. And when the model runs again a call whose result was dropped, the new result says so and suggests writing notes or starting the change: the loop detector cannot see this, because it is a cycle of different commands, not one command repeated. The note is part of the tool result, never a user message, which would start a turn of its own for the compaction. A first test showed that this was not enough: the outlines were there, the notes held all twenty routes, six gentle notes were sent — and the model kept reading, because mm's own wrapper around the notes told it to "re-read a file or re-run a command before relying on it", and the notes ended with "Remaining: read full type definitions … before editing". Both now point at the next change instead, and from the second re-read of a turn the note says plainly to stop reading and write a first version. A second test showed that a model can read such a note and still go on reading; so past `rereadLimit` re-reads of the same call (one by default), mm does not run it at all and answers with the reason instead. A call repeated after a `write_file` or `edit_file` is never counted: running the tests again after a fix is the opposite of reading in circles.

**A compression must last.** The in-turn compression fires at the threshold; if it only gets back just under it, the next tool result passes it again, and the turn is compressed before nearly every call. Each compression rewrites the prompt, and a server that reuses what it already read (llama.cpp, razorbill) then reads it all again: measured on Inkling-2-Mini, ~98 s for such a call against ~13 s for one that hits the cache — 29.5 minutes of a 34.5-minute run. So the compression aims lower than it triggers (`inTurnTarget`, two thirds of the threshold by default): the older exchanges are shrunk, then summarised — keeping fewer exchanges raw when needed — and only then, as a last resort, the kept ones are shrunk too, never the last one. Summary before shrinking, because notes keep what a shrunk result loses. The price is that the model keeps less of what it just read; a target equal to the threshold restores the old behaviour. The notes themselves start with the next change to make, and a summary cut at `summaryMaxTokens` loses its unfinished line and says so: five summaries of six were cut in the same session, and the line asked for at the end never got written.

## Rejected alternatives

- **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.
- **Summarising everything, recent turns included.** Rejected: the model then redoes its last steps.
- **A separate `context.contextWindow` key.** Rejected in favour of the single top-level key.
- **Inside a turn, summarising at once, or a summary pair in the middle of the turn.** Rejected: shrinking costs no model call and is often enough; and a pair of messages between two tool exchanges breaks the alternation some chat templates check (Gemma's raises an error).

## How it relates to the rest

- Turning it on and reading the report: [how to keep a long session inside the context window](../how-to/manage-the-context-window.md).
- The `context.*` keys: [configuration reference](../reference/configuration.md).
- Where the window comes from: [providers](providers.md).