Choose when a long agent session compacts its history

Agent buildMedium30 min

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. Turn i adds turns[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 system plus the whole history.
  • After any turn, the agent may compact. Compacting is one model call that reads system plus the whole history and writes summary tokens. The summary then replaces the history.
  • No model call may read more than window tokens.
  • A session spends every token any call reads, plus summary tokens for each compaction.

Examples

least_tokens(turns: list[int], system: int, summary: int, window: int) -> int
Example 1
Inputleast_tokens([100, 200, 300], 50, 40, 10000)
Output1150
Example 2
Inputleast_tokens([300, 300, 300], 50, 50, 700)
Output1850
Example 3
Inputleast_tokens([500, 600], 100, 0, 650)
Output-1