An agent solves a task in a loop: the model writes a tool call, the harness runs the tool and appends its output to the conversation, and the model reads everything again before the next call. The conversation is the model's context, and it has a fixed size in tokens. Tool outputs (file contents, test logs) fill it quickly. Compaction rewrites the history so that it fits a token budget while keeping what the model needs: the task, and the most recent work in full.
A trajectory is a list of messages {"role": ..., "content": ...} with role "system", "user", "assistant" or "tool", oldest first. The starter code provides count_tokens(message) (the number of whitespace-separated words in the content) and two strings, PLACEHOLDER and NOTE.
split_trajectory(messages)
"assistant" message (the system prompt and the task). A step is one "assistant" message together with every message after it up to, but not including, the next "assistant" message (normally its tool outputs).(head, steps): a list of messages and a list of steps, each step a list of messages. With no assistant message, everything is head and steps is [].compact_trajectory(messages, budget, keep_last=2)
keep_last steps are protected and are never changed. The steps before them are the old steps. The size of a trajectory is the sum of count_tokens over its messages.size <= budget), nothing is changed. Otherwise apply two stages, stopping as soon as the size is within the budget:
"tool" message with more than 2 tokens, replace its content by PLACEHOLDER (2 tokens). Check the size after every replacement.k >= 1 steps have been removed, one message {"role": "user", "content": NOTE.format(k=k)} sits directly after the head (4 tokens, counted in the size). Check the size after every removal."messages" (the new list), "tokens" (its size), "cleared" (the number of cleared tool outputs still present in "messages"), "dropped" (the number of removed steps) and "fits" (tokens <= budget)."role" and "content". keep_last < 0 raises ValueError. keep_last = 0 protects only the head.