Skip to content

The agent that grows with you

fix(agent): evict images at the provider limit, not on a keep-newest count

Meowrasaki66a281c330c6
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.py
index 5309ba7fc93..482508ce521 100644
--- a/agent/anthropic_message_convert.py
+++ b/agent/anthropic_message_convert.py
@@ -21,6 +21,14 @@ _THINKING_TYPES = frozenset(("thinking", "redacted_thinking"))
_CACHEABLE_TYPES = frozenset(("text", "tool_use"))
_EMPTY_TEXT_PLACEHOLDER = "(empty)"
_EMPTY_SCHEMA = {"type": "object", "properties": {}}
+# Screenshot eviction mirrors the API's own per-request image limit rather than a keep-newest
+# count: 20 is the documented threshold above which Anthropic imposes a stricter per-image
+# dimension cap on every image in the request, including ones nested in tool_result content.
+# Below it nothing is rewritten, so the prompt-cache prefix survives; at it, a whole batch goes
+# at once, costing one slower turn per batch instead of one per screenshot.
+_MAX_KEEP_SCREENSHOTS = 3
+_OUTBOUND_IMAGE_LIMIT = 20
+_SCREENSHOT_EVICTION_BATCH = 8
_BEDROCK_REGION_PREFIXES = ("global.", "us.", "eu.", "apac.", "ap.", "au.", "jp.", "ca.", "sa.", "me.", "af.")
@@ -592,19 +600,30 @@ def _manage_thinking_signatures(result: List[Dict[str, Any]], base_url: str | No
def _evict_old_screenshots(result: List[Dict[str, Any]]) -> None:
- """Keep only the 3 most recent computer-use screenshots (~1,465 tokens each); older images
- become a placeholder text block. Mutates ``result`` in place."""
- image_count = 0
- for msg in reversed(result):
- content = msg.get("content")
- for block in content if isinstance(content, list) else []:
- inner = block.get("content") if _block_type(block) == "tool_result" else None
- if not isinstance(inner, list) or not _has_block_type(inner, {"image"}):
- continue
- image_count += 1
- if image_count > 3:
- placeholder = _text_block("[screenshot removed to save context]")
- block["content"] = [placeholder if b.get("type") == "image" else b for b in inner]
+ """Retire screenshot payloads once the request nears the API's per-request image limit.
+
+ Mutates ``result`` in place. Eviction is triggered by the LIMIT, not by a keep-newest
+ count: retiring an image edits a block the provider has already cached, and Anthropic
+ matches its prompt cache on an exact byte prefix, so a count-based window that retires
+ one more block per new screenshot makes every turn a full-prefix miss. Holding images
+ until the limit and then dropping a batch costs one slower turn per batch instead.
+ """
+ blocks = [
+ block
+ for msg in reversed(result)
+ for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
+ if _block_type(block) == "tool_result"
+ and isinstance(block.get("content"), list)
+ and _has_block_type(block["content"], {"image"})
+ ]
+ if len(blocks) <= _OUTBOUND_IMAGE_LIMIT:
+ return
+ retire = min(_SCREENSHOT_EVICTION_BATCH, max(len(blocks) - _MAX_KEEP_SCREENSHOTS, 0))
+ for block in blocks[-retire:]:
+ placeholder = _text_block("[screenshot removed to save context]")
+ block["content"] = [
+ placeholder if b.get("type") == "image" else b for b in block["content"]
+ ]
def _ensure_leading_user_turn(result: List[Dict[str, Any]]) -> None:
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 73e729952eb..1e8ea16f757 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -983,6 +983,21 @@ _PRESSURE_KEEP_RECENT_MESSAGES = 3
# pass 2, so they ride every later request until anti-thrash disables compression (#92699).
_MAX_KEEP_TOOL_IMAGES = 3
+# Send-path eviction thresholds. The count above is the COMPACTION keep-window; the send path
+# must not use it, because evicting at 3 images retires one more message on every new image and
+# each retirement edits a row inside the Anthropic cached prefix, re-writing the whole history.
+# Mirror the provider's own constraint instead: hold images until the request would cross a real
+# API limit, then retire a BATCH, so the cost is one slower turn per batch and zero below it.
+#
+# 20 is the documented threshold at which Anthropic applies a stricter per-image dimension cap
+# (2000 px) to EVERY image in the request, counting images nested in tool_result content. Staying
+# at or below it keeps large screenshots legal. The hard ceilings are higher (100 images per
+# request on 200K-context models, 600 otherwise) but the 32 MB request-size limit usually binds
+# first, which the byte budget below guards with headroom for the text portion of the request.
+_OUTBOUND_IMAGE_LIMIT = 20
+_OUTBOUND_IMAGE_BUDGET_BYTES = 24_000_000
+_IMAGE_EVICTION_BATCH = 8
+
# Below this window the threshold is floored (raise-only): at 50% the incompressible
# floor eats the reclaimed headroom and compaction re-fires every 1-2 turns.
_SMALL_CTX_WINDOW_LIMIT = 512_000
@@ -1227,40 +1242,88 @@ def _rewritten(msg: Dict[str, Any], content: Any) -> Dict[str, Any]:
return new_msg
-def _retire_stale_tool_result_images(result: List[Dict[str, Any]], keep_newest: int = _MAX_KEEP_TOOL_IMAGES) -> int:
+def _retire_stale_tool_result_images(
+ result: List[Dict[str, Any]],
+ keep_newest: int = _MAX_KEEP_TOOL_IMAGES,
+) -> int:
"""Replace image payloads on older tool results with text placeholders.
- Keeps the newest ``keep_newest`` image-bearing tool messages; user uploads untouched. Mutates
- ``result`` in place; returns the number of messages rewritten."""
- seen = pruned = 0
- for i in range(len(result) - 1, -1, -1):
- msg = result[i]
- if not isinstance(msg, dict) or msg.get("role") != "tool" or not _tool_content_has_images(msg.get("content")):
- continue
- seen += 1
- if seen <= max(keep_newest, 0):
- continue
- new_msg = _strip_images_from_tool_msg(msg)
+
+ Keeps the newest ``keep_newest`` image-bearing tool messages; user uploads untouched.
+ Compaction's pass: it commits the rewrite into the canonical transcript once, so it
+ reclaims every eligible byte. The SEND path must not call this — see
+ :func:`evict_stale_outbound_tool_images` for why a per-turn count-based window is
+ ruinous for the prompt cache. Mutates ``result`` in place; returns messages rewritten.
+ """
+ indexes = [
+ i
+ for i in range(len(result) - 1, -1, -1)
+ if isinstance(result[i], dict)
+ and result[i].get("role") == "tool"
+ and _tool_content_has_images(result[i].get("content"))
+ ]
+ retire = len(indexes) - max(keep_newest, 0)
+ if retire <= 0:
+ return 0
+
+ pruned = 0
+ for i in indexes[-retire:]:
+ new_msg = _strip_images_from_tool_msg(result[i])
if new_msg is not None:
result[i] = new_msg
pruned += 1
return pruned
+def _image_payload_bytes(msg: Dict[str, Any]) -> int:
+ """Serialized size of the image parts in a tool message (0 when it carries none)."""
+ content = msg.get("content")
+ inner = content.get("content") if isinstance(content, dict) and content.get("_multimodal") else content
+ if not isinstance(inner, list):
+ return 0
+ return sum(len(json.dumps(p, ensure_ascii=False)) for p in inner if _is_image_part(p))
+
+
def evict_stale_outbound_tool_images(
api_messages: List[Dict[str, Any]],
keep_newest: int = _MAX_KEEP_TOOL_IMAGES,
) -> int:
"""Drop stale screenshot/vision payloads from the per-call API copy.
- Compression's keep-newest pass only runs when prune/compress fires, and
- the Anthropic adapter's screenshot eviction only sees nested
- ``tool_result`` blocks. OpenAI-style ``image_url`` tool results
- otherwise ride every subsequent request until a 413 forces the reactive
- strip (#89286). Call this on the cloned ``api_messages`` list after
- sanitization so older frames never leave the box (#89296). Do not pass
- persisted history — the rewrite is send-path only.
+ Compression's keep-newest pass only runs when prune/compress fires, and the Anthropic
+ adapter's screenshot eviction only sees nested ``tool_result`` blocks. OpenAI-style
+ ``image_url`` tool results otherwise ride every subsequent request until a 413 forces
+ the reactive strip (#89286). Call this on the cloned ``api_messages`` list after
+ sanitization (#89296). Do not pass persisted history — the rewrite is send-path only.
+
+ Eviction is driven by the PROVIDER LIMIT, not by a keep-newest count. Retiring an image
+ edits a message the provider has already cached, and Anthropic matches its prompt cache
+ on an exact byte prefix, so every retirement re-writes the whole conversation. A count
+ of N retires one more message on each new image, making every turn a full-prefix miss.
+
+ Keeping images until the request nears the API's own per-request image and byte limits,
+ then retiring a batch, costs one slower turn per batch instead of one per image, and
+ costs nothing at all while the request is under the limits.
"""
- return _retire_stale_tool_result_images(api_messages, keep_newest=keep_newest)
+ images = [
+ (i, size)
+ for i in range(len(api_messages) - 1, -1, -1)
+ if isinstance(api_messages[i], dict)
+ and api_messages[i].get("role") == "tool"
+ and (size := _image_payload_bytes(api_messages[i])) > 0
+ ]
+ over = len(images) > _OUTBOUND_IMAGE_LIMIT or sum(s for _, s in images) > _OUTBOUND_IMAGE_BUDGET_BYTES
+ if not over:
+ return 0
+
+ # Retire a whole batch so the next several turns stay under the limit and append cleanly.
+ retire = min(_IMAGE_EVICTION_BATCH, max(len(images) - keep_newest, 0))
+ pruned = 0
+ for i, _ in images[-retire:]:
+ new_msg = _strip_images_from_tool_msg(api_messages[i])
+ if new_msg is not None:
+ api_messages[i] = new_msg
+ pruned += 1
+ return pruned
def _truncate_tool_call_args_json(args: str, head_chars: int = 200) -> str:
diff --git a/tests/agent/test_outbound_stale_vision.py b/tests/agent/test_outbound_stale_vision.py
index 1cab4234a0c..df4ea642a3a 100644
--- a/tests/agent/test_outbound_stale_vision.py
+++ b/tests/agent/test_outbound_stale_vision.py
@@ -10,7 +10,9 @@ from __future__ import annotations
from agent.agent_runtime_helpers import sanitize_api_messages
from agent.context_compressor import (
+ _IMAGE_EVICTION_BATCH,
_MAX_KEEP_TOOL_IMAGES,
+ _OUTBOUND_IMAGE_LIMIT,
_tool_content_has_images,
evict_stale_outbound_tool_images,
)
@@ -69,13 +71,23 @@ class TestOutboundStaleVisionEviction:
sanitized = sanitize_api_messages(history)
assert _image_bearing_tool_ids(sanitized) == [f"call_{i}" for i in range(5)]
- def test_eviction_keeps_only_newest_window(self):
- history = _history_with_screenshots(5)
+ def test_nothing_is_evicted_below_the_provider_limit(self):
+ """The common case must be append-only: no rewrite, so the cached prefix survives."""
+ history = _history_with_screenshots(_OUTBOUND_IMAGE_LIMIT)
+ outbound = sanitize_api_messages(history)
+ assert evict_stale_outbound_tool_images(outbound) == 0
+ assert _image_bearing_tool_ids(outbound) == [
+ f"call_{i}" for i in range(_OUTBOUND_IMAGE_LIMIT)
+ ]
+
+ def test_eviction_retires_a_batch_once_over_the_limit(self):
+ n = _OUTBOUND_IMAGE_LIMIT + 1
+ history = _history_with_screenshots(n)
outbound = sanitize_api_messages(history)
pruned = evict_stale_outbound_tool_images(outbound)
- assert pruned == 5 - _MAX_KEEP_TOOL_IMAGES
+ assert pruned == _IMAGE_EVICTION_BATCH
kept = _image_bearing_tool_ids(outbound)
- assert kept == [f"call_{i}" for i in range(5 - _MAX_KEEP_TOOL_IMAGES, 5)]
+ assert kept == [f"call_{i}" for i in range(_IMAGE_EVICTION_BATCH, n)]
oldest = next(m for m in outbound if m.get("tool_call_id") == "call_0")
assert isinstance(oldest["content"], list)
@@ -87,15 +99,39 @@ class TestOutboundStaleVisionEviction:
for part in oldest["content"]
)
+ def test_frontier_holds_between_batch_advances(self):
+ """The rewritten set must not move on every new image.
+
+ A frontier that advances one step per image edits an already-cached row each
+ turn, so Anthropic re-writes the entire prompt-cache prefix instead of reading
+ it — orders of magnitude more expensive than the image tokens reclaimed. Asserted
+ over a span wide enough that a per-image frontier cannot pass by coincidence.
+ """
+ from agent.conversation_loop import _clone_message_for_send
+
+ def first_surviving(n: int) -> str:
+ msgs = [_clone_message_for_send(m) for m in _history_with_screenshots(n)]
+ evict_stale_outbound_tool_images(msgs)
+ return _image_bearing_tool_ids(msgs)[0]
+
+ span = range(_MAX_KEEP_TOOL_IMAGES + 1, _OUTBOUND_IMAGE_LIMIT + _IMAGE_EVICTION_BATCH)
+ frontier = [first_surviving(n) for n in span]
+ held = sum(a == b for a, b in zip(frontier, frontier[1:]))
+ assert held >= len(frontier) - 3, (
+ f"eviction advanced on nearly every image (frontier={frontier}); "
+ "each advance rewrites a cached row and restarts the prefix"
+ )
+
def test_does_not_rewrite_persisted_history(self):
from agent.conversation_loop import _clone_message_for_send
- history = _history_with_screenshots(5)
+ n = _OUTBOUND_IMAGE_LIMIT + 1
+ history = _history_with_screenshots(n)
outbound = [_clone_message_for_send(m) for m in history]
evict_stale_outbound_tool_images(outbound)
- assert _image_bearing_tool_ids(history) == [f"call_{i}" for i in range(5)]
+ assert _image_bearing_tool_ids(history) == [f"call_{i}" for i in range(n)]
assert _image_bearing_tool_ids(outbound) == [
- f"call_{i}" for i in range(5 - _MAX_KEEP_TOOL_IMAGES, 5)
+ f"call_{i}" for i in range(_IMAGE_EVICTION_BATCH, n)
]
def test_user_uploads_are_not_evicted(self):
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 737a503f518..9613371d5ed 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -467,9 +467,16 @@ class TestAnthropicAdapterMultimodal:
},
}
- # Build 5 screenshots interleaved with assistant messages.
+ # Build screenshots interleaved with assistant messages. The eviction frontier
+ # advances in whole batches, so use a count that lands exactly on one advance.
+ from agent.anthropic_message_convert import (
+ _OUTBOUND_IMAGE_LIMIT,
+ _SCREENSHOT_EVICTION_BATCH,
+ )
+
+ total = _OUTBOUND_IMAGE_LIMIT + 1
messages: List[Dict[str, Any]] = [{"role": "user", "content": "start"}]
- for i in range(5):
+ for i in range(total):
messages.append({
"role": "assistant", "content": "",
"tool_calls": [{
@@ -483,8 +490,7 @@ class TestAnthropicAdapterMultimodal:
_, anthropic_msgs = convert_messages_to_anthropic(messages)
- # Walk tool_result blocks in order; the OLDEST (5 - 3) = 2 should be
- # text-only placeholders, newest 3 should still carry image blocks.
+ # One batch retires; everything newer keeps its image payload.
tool_results = []
for m in anthropic_msgs:
if m["role"] != "user" or not isinstance(m["content"], list):
@@ -493,7 +499,7 @@ class TestAnthropicAdapterMultimodal:
if b.get("type") == "tool_result":
tool_results.append(b)
- assert len(tool_results) == 5
+ assert len(tool_results) == total
with_images = [
b for b in tool_results
if isinstance(b.get("content"), list)
@@ -508,8 +514,74 @@ class TestAnthropicAdapterMultimodal:
for x in b["content"]
)
]
- assert len(with_images) == 3
- assert len(placeholders) == 2
+ assert len(placeholders) == _SCREENSHOT_EVICTION_BATCH
+ assert len(with_images) == total - _SCREENSHOT_EVICTION_BATCH
+
+ def test_eviction_frontier_holds_between_batch_advances(self):
+ """Screenshot eviction must not rewrite a new block on every capture.
+
+ The Anthropic prompt cache keys on an exact byte prefix. A frontier that
+ advances one block per screenshot edits an already-cached block every turn,
+ forcing a full-prefix re-write that costs far more than the image tokens it
+ reclaims.
+ """
+ from agent.anthropic_message_convert import (
+ _OUTBOUND_IMAGE_LIMIT,
+ _SCREENSHOT_EVICTION_BATCH,
+ convert_messages_to_anthropic,
+ )
+
+ fake_png = "iVBORw0KGgo="
+
+ def placeholder_count(n: int) -> int:
+ messages: List[Dict[str, Any]] = [{"role": "user", "content": "start"}]
+ for i in range(n):
+ messages.append({
+ "role": "assistant", "content": "",
+ "tool_calls": [{
+ "id": f"call_{i}",
+ "type": "function",
+ "function": {"name": "computer_use", "arguments": "{}"},
+ }],
+ })
+ messages.append({
+ "role": "tool",
+ "tool_call_id": f"call_{i}",
+ "content": {
+ "_multimodal": True,
+ "content": [
+ {"type": "text", "text": f"cap {i}"},
+ {"type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,{fake_png}"}},
+ ],
+ "text_summary": f"cap {i}",
+ },
+ })
+ _, out = convert_messages_to_anthropic(messages)
+ return sum(
+ 1
+ for m in out
+ if isinstance(m.get("content"), list)
+ for b in m["content"]
+ if b.get("type") == "tool_result"
+ and isinstance(b.get("content"), list)
+ and any(
+ x.get("type") == "text" and "screenshot removed" in x.get("text", "")
+ for x in b["content"]
+ )
+ )
+
+ # The frontier must hold across at least one new screenshot. Asserted as an
+ # absolute invariant rather than against the batch constant, so shrinking the
+ # batch back to a one-step frontier fails this test.
+ counts = [placeholder_count(n) for n in range(_OUTBOUND_IMAGE_LIMIT - 2,
+ _OUTBOUND_IMAGE_LIMIT + _SCREENSHOT_EVICTION_BATCH)]
+ held = [a == b for a, b in zip(counts, counts[1:])]
+ assert any(held), (
+ f"eviction rewrote a new block on every screenshot (counts={counts}); "
+ "each step invalidates the cached prefix"
+ )
+ assert counts[-1] >= counts[0], "eviction must still make progress"
# ---------------------------------------------------------------------------
# Context compressor: screenshot-aware pruning