R476 · Agent architecture › Context economics and caching

An eviction policy cannot evict its own recovery path: a harness context-management implementation in its own source

Read the original

context-economicsagent-harnessopen-sourceclaim-hygiene

Source: the langchain-ai/deepagents repository — README.md, libs/deepagents/deepagents/backends/utils.py, and libs/deepagents/deepagents/middleware/filesystem.py, as published in the repository itself. The occasion was a vendor summary of the harness's context management; the two numbers in that summary are checked against the code below, and one of them is wrong by a factor of ten.

The problem the mechanism solves

An agent that can run tools will eventually run one whose output does not fit. A repository-wide grep, a large JSON response, a log dump: any of them can be larger than the remaining context window, and an agent that pastes it into the conversation has spent its budget on data it will mostly not use.

Deep Agents answers this with two distinct mechanisms, both keyed off the same number, and the distinction between them is where the interesting engineering lives.

Mechanism one: truncation

In backends/utils.py:

MAX_LINE_LENGTH = 5000
TOOL_RESULT_TOKEN_LIMIT = 20000  # Same threshold as eviction
TRUNCATION_GUIDANCE = "... [results truncated, try being more specific with your parameters]"

truncate_if_too_long compares against TOOL_RESULT_TOKEN_LIMIT * 4 and cuts the overflow, appending the guidance string. The overflow is discarded. For a list result it walks items accounting len(repr(item)) + 2 each, because "callers render the list with str()" — the budget is spent on the rendered form, not the logical content.

Truncation is lossy on purpose. The guidance tells the model to narrow its query rather than to go and fetch the rest.

Mechanism two: eviction

In middleware/filesystem.py, FilesystemMiddleware.__init__ takes:

tool_token_limit_before_evict: int | None = 20000,
human_message_token_limit_before_evict: int | None = 50000,

When a tool message exceeds the threshold, _process_large_message writes the content through the configured backend under {root}/large_tool_results/{sanitized_tool_call_id} and replaces the message with a head-and-tail preview plus the path, marking the omitted middle as ... [N lines truncated] .... The agent can then page through the file with read_file's offset and limit.

Eviction is lossless. Nothing is thrown away; it moves from the conversation to storage and the conversation keeps a pointer.

Note that human_message_token_limit_before_evict applies the same treatment to oversized user messages, at a separate and higher threshold. A pasted log is handled the same way as a tool result.

The threshold is characters, not tokens

This is the detail most worth carrying away, and it is one comment line in the source:

# Approximate number of characters per token for truncation calculations.
# Using 4 chars per token as a conservative approximation (actual ratio varies by content)
# This errs on the high side to avoid premature eviction of content that might fit
NUM_CHARS_PER_TOKEN = 4

The comparison is len(content_str) <= NUM_CHARS_PER_TOKEN * self._tool_token_limit_before_evict. So a "20,000 token" threshold is an 80,000 character threshold, and the conversion is a fixed constant rather than a tokenizer call.

The consequence is systematic, not random. Content that tokenizes better than 4 characters per token — ordinary English prose often does — passes through at well above 20,000 real tokens. Content that tokenizes worse — dense non-Latin script, base64, long machine-generated identifiers, minified JSON — gets evicted earlier than the nominal budget suggests. The code states which way it chose to be wrong, and it chose to err loose.

If you are budgeting a context window on a harness with a mechanism like this, that constant is the number you actually have to reason about. Calling a tokenizer on every tool result costs something; using a fixed ratio is a reasonable trade. Not knowing which one your harness does is not.

The exclusion list, and the rule behind it

Seven built-in tools never get evicted:

TOOLS_EXCLUDED_FROM_EVICTION = (
    "ls", "glob", "grep", "read_file", "edit_file", "write_file", "delete",
)

The source gives a reason for each group, and they are not the same reason.

Tools with their own truncation (ls, glob, grep). These "truncate their own output when it becomes too large", and the comment makes an argument about what a large result means: when these tools overflow "it typically indicates the query needs refinement rather than full result preservation", so "the truncated matches are potentially more like noise and the LLM should be prompted to narrow its search criteria instead." Preserving ten thousand grep hits is not helping the agent; telling it to grep better is.

Tools that return confirmations (edit_file, write_file). They "return minimal confirmation messages and are never expected to produce output large enough to exceed token limits, so checking them would be unnecessary." This one is pure cost avoidance.

And then read_file, which is the interesting one:

read_file is tricky to handle as the failure mode here is single long lines (e.g., imagine a jsonl file with very long payloads on each line). If we try to truncate the result of read_file, the agent may then attempt to re-read the truncated file using read_file again, which won't help.

Read that against the eviction design. Eviction's whole recovery path is: write the content to a file, hand the agent the path, let it page through with read_file. If read_file were itself subject to eviction, then paging through an evicted result could evict again, and the agent's recovery action would produce another pointer to chase. The mechanism would feed itself.

Stated as a general rule, which is how it is worth remembering:

An eviction policy must exempt the tool used to read evicted content, or the policy's recovery path becomes a source of new evictions.

That holds for any offload-and-pointer design: a summarizer that can summarize its own summaries, a cache that can spill its own spill file, a retry wrapper around the fetch that retries. The specific instance here is a JSONL file with long lines, but the shape is generic, and the comment is the only place it is written down.

What read_file does instead

Since it cannot be evicted, read_file carries its own bounded window and its own guidance. The default is:

DEFAULT_READ_OFFSET = 0
DEFAULT_READ_LIMIT = 1000

1,000 lines, interpolated into the tool's own description: "By default, it reads up to 1000 lines starting from the beginning of the file." A vendor summary of this harness stated the default as "about 100 lines at a time", which is off by a factor of ten. The likeliest origin is an example sentence inside a deprecated prompt string, _LEGACY_TOO_LARGE_TOOL_MSG, marked "available until deepagents==0.9.0": "For example, to read the first 100 lines, you can use the read_file tool with offset=0 and limit=100." A number from an illustrative example in a legacy string, reported as the configured behaviour.

When read_file does overflow, its message is unusually constructive — it names the fix rather than just the failure:

Output was truncated due to size limits. The file content is very large. Consider reformatting the file to make it easier to navigate. For example, if this is JSON, use execute(command='jq . {file_path}') to pretty-print it with line breaks.

That is a good pattern on its own: an error that tells the agent which tool call would make the next attempt succeed. Note the dependency it creates — the advice only works if the backend provides execute, which only some backends do.

Where "a file" actually is

"Offloads to a file" is doing more work than it looks. Storage is pluggable:

So the same eviction can mean "kept in the agent's own state for this run", "written to a durable per-user store", or "written to a container's disk", depending on configuration. The context-window benefit is identical in all three; the durability, the blast radius and the privacy properties are not. A design review of a mechanism like this should ask which backend is configured before asking whether the threshold is right.

One security note worth copying

normalize_read_bounds clamps offset and limit to non-negative integers, and the docstring explains why the int() coercion is not redundant with the type annotations:

The int() coercion is deliberate and load-bearing, not redundant with the annotations: offset and limit originate from model-supplied tool arguments, and the sandbox backend interpolates them into the source of a script it executes (_READ_COMMAND_TEMPLATE). Do not remove it.

Model-controlled values reaching a shell script template, defended by a cast, with a comment telling the next reader not to delete the defence. Two things to take from it: annotations are documentation and not validation at a trust boundary, and a defence whose necessity is non-obvious needs the comment or it will be refactored away.

Other bounds in the same file

The pattern across all of them is the same: a default that bounds the common case, a per-call override for the model, and a way for the operator to turn it off.

Review checklist for an offload mechanism

If you are building or reviewing one of these, the source above suggests the questions:

  1. Lossy or lossless? Truncation and eviction are different contracts. Which tools get which, and does the caller know?

  2. What unit is the threshold in? If it converts characters to tokens by a constant, which direction does it err, and on what content does that bite?

  3. Which tools are exempt, and why each? "Has its own truncation", "returns confirmations" and "is the recovery path" are three distinct reasons that happen to produce one list.

  4. Can the recovery path trigger the mechanism? If yes, you have a loop. This is the one that is easy to miss and hard to debug.

  5. Where does the offloaded content live, and for how long? Ephemeral state, durable store and sandbox disk have different privacy and durability properties under the same code path.

  6. Does the overflow message tell the agent what to do next? Naming the remediation tool call turns a dead end into a retry.

  7. Is the threshold measured against anything? None of the numbers above is justified by an experiment in what is covered here. They are defaults chosen to be safe, which is reasonable, and is not the same as being right.

That last point is the honest limit of this summary. The capability is documented, the implementation is careful and well-commented, and nothing in the repository says how much context the offload actually saves, how often eviction fires in practice, or what it costs in extra paging round-trips. The mechanism is sound engineering with unmeasured parameters — which is the normal state of most context-management code, and worth naming rather than assuming.

Connections

See R476 on the knowledge map

Part of the Research notes on nowucca.com. Figures and claims are the source's own unless the summary says otherwise.