An agent run has one hard limit: the model’s context window. Every turn resends the system prompt, the conversation, the attached files and every tool result so far. When that no longer fits, the provider refuses the request and the run dies.
So something has to decide what goes in, how much of it, and what happens when the window fills. We built that part ourselves, one careful rule at a time. Then we deleted most of it and copied what Codex and Claude Code do. The replacement took three commits in under three hours.
This essay is about why our rules were worse, using the reasons the code itself recorded.
What we had built
Over a few months the runtime gathered a set of mechanisms, each added to fix a real failure:
- A tool result cap that shrank as the window filled.
- A fixed share of the window held back for the model’s answer.
- A token count calibrated by a ratio between our estimate and the provider’s report.
- A gate that withdrew every tool from a chat that had no headroom left, later softened to keep one tool,
start_task, with a message nudging the model to use it. - An extra model turn after a failed tool, asking the model to repair or report it.
- A compaction step that declined to run when the request itself filled most of the window.
- A separate, smaller budget for files read in full, used only by long-running tasks.
Each one made sense alone. Together they made the run’s behaviour depend on numbers nobody could predict.
Count what the provider reports, estimate only the rest
We estimated tokens as characters divided by four. On the model we tested, that ran about 40% under what the provider reported. The comment that recorded it gives the reasons: Dutch prose, JSON and code tokenise denser than that, and the tool schemas were not counted at all. Compaction started only after the real prompt had already passed the window.
Our first fix was a ratio. After each model call, the reported prompt size divided by our estimate became a multiplier for every later estimate. It lasted two hours.
A ratio treats a fixed cost as a proportional one. The system prompt and tool schemas are the same size whatever the transcript holds, but the multiplier spread them over everything: a new tool result was inflated by overhead it did not have, and a transcript just shortened by compaction was still counted at the old rate.
Codex does something simpler, and we now do the same. The prompt size the provider reported for the last request is exact. Only the messages added since are estimated:
def tokens(self, messages: list[dict]) -> int:
if self.reported_tokens is None or len(messages) < self.reported_messages:
return _estimated_tokens(messages)
return self.reported_tokens + _estimated_tokens(messages[self.reported_messages :])
When masking or compaction rewrites the transcript, the report no longer describes it, so the meter forgets it and estimates the whole until the next report. The error is limited to what changed since the last call.
Hold nothing back for the answer
The old runtime reserved the model’s full output cap on every turn, whether the next turn was a one-line tool call or a long answer. On our development model, with a 262,144-token window and a 65,536-token output cap, that reserve plus a 75% compaction threshold meant a run compacted at about 194,000 tokens.
The reserve also had to agree everywhere it was counted, and it did not. A comment in the message endpoint records one case: a flat setting still reserved 1,500 tokens while the routed model reserved 32,768, so attachment fitting believed it had 31,000 tokens the agent loop already considered spoken for.
Now a run may fill 90% of the window, the same limit Codex uses, before it compacts. Each request asks for the configured output cap or whatever still fits, whichever is smaller, with a floor of 1,024 tokens because the estimate can run high. On the same model that moves compaction to about 236,000 tokens.
The price is that an answer can now be cut off. When that happens, the run continues it, up to twice, with an instruction to pick up mid-sentence without repeating anything. What already streamed stays on screen. A tool call cut off the same way gets an error telling the model to send less per call, since retrying the same call would be cut at the same place.
Give every tool a fixed cap
Each tool result used to get the smaller of its own cap and what was left of the window. The removed docstring explains the intent: handing a 120,000-character document to a 32,000-token model would push out the very question it was meant to answer.
But the budget was only as good as the headroom arithmetic, and that had a cliff. The same docstring records it: the budget shrank sensibly, to 11,750 characters and then 550, and then jumped back to the 24,000 default once the window overflowed. Reading a spreadsheet into a 32,000-token model hit that cliff, the provider answered 400, and the run died.
There is a quieter problem too. A shrinking cap means the same tool returns a different amount depending on what came before it. The model can’t tell a short document from a cut one. Neither can we, reading a run afterwards.
Now each tool has a fixed cap: its own if it declares one, otherwise 24,000 characters. In the words of the new docstring, it does not shrink as the window fills; compaction is what makes room.
Cut the middle, not the end
When a result is too long, it used to keep its start and drop the rest. The new code keeps the start and the end and cuts the middle, as Codex does, with a marker saying so. The reason is in the docstring: the end of a result is often what matters, such as the error after a long log or the line saying where a paged document continues.
The sandbox applies the same rule to command output. Its comment is blunt: a long log that kept only its start hid the traceback.
Let chats compact like tasks
Only long-running tasks compacted. A chat that filled up had a different rule: below a few thousand characters of headroom, it stopped offering tools and asked the model to answer with what it had. Without that gate, the comment says, the loop kept offering tools until the request no longer fit.
Then the gate produced its own failure. A model read attachments in chat until the window was nearly full, then wrote a 6,790-character task goal against a 2,000-character limit. The rejection left no room to retry, because a full chat withdrew every tool, so the run answered that it could not do the work.
The patch kept start_task on offer with a nudge to use it. That was a rule to rescue a rule. Two hours later we removed the gate, the nudge and its wrap-up message, and let chats compact exactly like tasks.
Compact the request too
Compaction folds older turns into a written checkpoint. Ours kept the request verbatim and refused to run when the request and earlier history were most of the context, because there was “too little to gain”.
That refusal meant a request carrying large inlined files could never be compacted. In our development setup a single message could inline up to 120,000 tokens of files. The new code’s comment states the problem: a file inlined in the request was resent with every turn and could not be condensed.
Compaction now follows Codex. It keeps the preamble (system prompt, preferences, context), the user’s most recent messages within 20,000 tokens, the request and the latest turn. Everything else, earlier answers and the work since, goes into the checkpoint. A request over 20,000 tokens has its inlined files replaced by a note naming each file and saying how to read it again. Compaction now skips only when it would condense a checkpoint into itself.
One inline budget for every run
Tasks had their own setting, 20,000 tokens of files read in full, because a task takes a hundred turns or more and every turn resends them. Chats used up to half the window.
Now one setting applies to every run: one message inlines at most a fixed budget of files in total, set to 25,000 tokens in our development configuration, the size Claude Code reads a file up to. The rest stays reachable through search and the document reader, read on demand.
That reader changed too. read_document returned pages of 120,000 characters. Its config comment says such a page filled a task’s context in a handful of reads. Pages are now 40,000 characters, about 10,000 tokens, read across several calls with a cursor.
Send the error back as the result
When a tool failed, the old runtime gave the model an extra turn. If the model then answered in prose, the runtime discarded that answer, withdrew what had streamed, and asked it to retry the failure or report it accurately. The worry was real: in the removed comment’s words, a successful sibling call can make a partial run sound complete.
But it withdrew text the reader had already watched appear, and it added an instruction the model had to answer. A related rule withdrew a tool after three identical failures. It ended a task whose script crashed on three different bugs: bash was gone, and the model reported it unavailable.
Both are gone. A failure goes back as the tool’s result, starting “The tool could not complete:”, and the tool stays on offer. The model reads the error before it writes anything else, which is when it can act on it. The turn and tool-call budgets still bound a model that keeps retrying.
What stayed ours
Copying the general shape did not remove what is specific to Summa:
- Attachments. Files arrive with a message, not from a file system the model can list. Which ones are inlined, and the note that tells the model how to read a removed one again, are ours.
- Documents. Paged reading with a cursor exists because people attach long PDFs and slide decks, not source files.
- Images. Each image counts as about 1,600 tokens, whatever its file size, because counting its base64 would make one slide look like tens of thousands.
- Chats and tasks. They now share context rules, but not budgets. A chat gets 40 model turns and 180 seconds. A task gets 200 turns, an hour, and a durable checkpoint after every tool turn so a dead worker resumes instead of starting over.
- The checkpoint itself. It is written as notes, never instructions, so text a tool returned can’t become a standing order. Skills loaded before compaction are attached again in full, because a summary of instructions is not the instructions.
- Masking first. Before compaction spends a model call, older bulky tool outputs are replaced by a stub naming what was there. The last three tool turns stay whole.
What it costs
- Answers can be cut off. Without a reserve, a long answer may hit the output cap and need a continuation. That costs a model call, and a continuation can join less smoothly than one uninterrupted answer.
- The count is rough after a rewrite. Between a compaction and the next provider report, the whole transcript is estimated at four characters a token, the same estimate that once ran 40% low.
- Compaction loses detail. A checkpoint is a summary. A file cut from the request must be read again, which costs a tool call.
- The numbers are borrowed. The 90% limit and the 20,000-token budget come from Codex, the 25,000-token inline budget from Claude Code. We did not measure them ourselves.
What we would generalise
- Before inventing a context rule, read how the agents with the most sessions behind them do it. Their simple version has met more edge cases than our careful one.
- Prefer the provider’s number to your own. Estimate only the part it has not measured yet.
- Do not reserve for the worst case on every turn. Ask for what fits, and recover when it was not enough.
- Make a tool return the same amount every time. Make room by compacting, not by shrinking results.
- Keep the end of a long output. The error is usually there.
- When a fix needs a fix, question the first one.