Compact an agent's message history under a token budget

HardAgentsPro

Why it matters Claude Code, Codex and other long-running agents compact context like this when the window fills up.

When an agent's context fills up, old turns are replaced by a summary while recent turns and the system prompt stay.

Write compact_history(messages, budget, summarize). messages is a list of dicts {"role", "content"}; tokens of a message = len(content.split()). messages[0] is the system prompt and always stays. If the total fits the budget, return messages unchanged. Otherwise keep the longest suffix of the remaining messages whose tokens plus the system prompt plus a summary fit: build the summary of the dropped middle with summarize(list_of_dropped) (returns a string), and insert {"role": "system", "content": "Summary: " + text} after the system prompt. Never split a tool result from the assistant message just before it: if the first kept message has role "tool", drop it into the summary too. Return the new list.

Signaturedef compact_history(messages, budget, summarize)

Example

if everything fits, the output equals the input.

Understand the idea

When an agent's history gets too long for its context, old turns are squeezed into a short summary. The system prompt always stays, the most recent turns stay, and everything in between is replaced by one summary message. The summary counts toward the budget. A tool result must never appear without the assistant call before it. Worked example: tokens are word counts. System prompt 3 tokens, then user 10, assistant 10, tool 10, user 4: total 37, budget 25. Suppose the summary message is 4 tokens. Keeping [user 4] costs 3 + 4 + 4 = 11, fine. Keeping [tool 10, user 4] costs 21, fine. Adding the assistant gives 31, too much. The longest fitting tail starts with a tool message, which would be orphaned, so the tool joins the dropped part. Result: [system, summary, user 4]. Rule: if the total fits, return messages unchanged; else find the longest suffix of messages[1:] such that system + summary + suffix fits; if its first message has role 'tool', move it into the dropped list; summary = {'role': 'system', 'content': 'Summary: ' + summarize(dropped)}; return [system, summary] + kept. Used in: long-running coding and chat agents.

Shapes and data flow

[system | m1 m2 m3 m4 m5]
-> [system | Summary(m1 m2) | m3 m4 m5]
kept tail never starts with a tool message
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecompact_history(_M[:2], 100, _sum) == _M[:2]
  • Sample 2: compactscompact_history(_M, 20, _sum)