Choose when a long agent session compacts its history
Your task
Your coding agent sends its whole history on every model call. A long session pays for the same tokens again and again, and can outgrow the context window. Compacting swaps the history for a short summary, but a compaction is a model call too, and it reads everything.
Write least_tokens(turns, system, summary, window) that returns the fewest tokens a session can spend.
Input and output:
turns: up to 1,000 whole numbers from 1 to 100,000. Turniaddsturns[i]tokens to the history.system: the tokens of the system prompt, 0 to 100,000.summary: the tokens of a compaction's summary, 0 to 100,000.window: the most tokens one model call may read, 1 to 100,000,000.- Return a whole number: the fewest tokens, or -1 when no plan keeps every call within the window.
Rules:
- The history starts empty. Each turn adds its tokens to the history, then makes one model call that reads
systemplus the whole history. - After any turn, the agent may compact. Compacting is one model call that reads
systemplus the whole history and writessummarytokens. The summary then replaces the history. - No model call may read more than
windowtokens. - A session spends every token any call reads, plus
summarytokens for each compaction.
Examples
least_tokens(turns: list[int], system: int, summary: int, window: int) -> intExample 1
Input
least_tokens([100, 200, 300], 50, 40, 10000)Output
1150Example 2
Input
least_tokens([300, 300, 300], 50, 50, 700)Output
1850Example 3
Input
least_tokens([500, 600], 100, 0, 650)Output
-1