Skip to content

The agent that grows with you

fix(agent): gate the 20-image eviction trigger on the request's dimensions

salch-cred8b1ccb67d34a
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.py
index 600c9478627..39080ebf8cf 100644
--- a/agent/anthropic_message_convert.py
+++ b/agent/anthropic_message_convert.py
@@ -10,7 +10,7 @@ import logging
import re
from typing import Any, Dict, List, Optional, Tuple
-from agent.image_eviction_policy import outbound_image_retire_count
+from agent.image_eviction_policy import images_all_within_many_image_limit, outbound_image_retire_count
from agent.anthropic_thinking_policy import anthropic_thinking_route, route_replays_prior_thinking
logger = logging.getLogger(__name__)
@@ -622,32 +622,49 @@ def _manage_thinking_signatures(result: list[dict[str, Any]], base_url: str | No
m.pop("_thinking_signature_invalidated", None) # internal flag, never on the wire
+def _image_source_data(block: Any) -> Optional[str]:
+ """Base64 payload of a wire ``image`` block, or None for a URL/native source (unmeasurable)."""
+ source = block.get("source") if isinstance(block, dict) else None
+ data = source.get("data") if isinstance(source, dict) else None
+ return data if isinstance(data, str) else None
+
+
def _evict_old_screenshots(result: list[dict[str, Any]]) -> None:
"""Retire screenshot payloads once the request would cross the API's per-request image limit.
- Mutates ``result`` in place. This wire pass has no byte sizes, so it enforces the block
- ceiling only; the auxiliary Anthropic client (``agent.auxiliary_client`` via
- ``anthropic_adapter.build_anthropic_kwargs``) reaches it without the compressor's
- send-path pass, so it must hold the invariant alone. Policy: :mod:`agent.image_eviction_policy`.
+ Mutates ``result`` in place. The block ceiling is conditional on the request's actual image
+ dimensions (the strict 20 only when some image exceeds the many-image per-side cap), so this
+ pass reads the headers of the ``source.data`` payloads it already holds. The auxiliary Anthropic
+ client (``agent.auxiliary_client`` via ``anthropic_adapter.build_anthropic_kwargs``) reaches
+ this pass without the compressor's send-path pass, so it must hold the invariant alone. Policy
+ and rationale: :mod:`agent.image_eviction_policy`.
"""
- reserved = sum(
- 1
+ reserved = [
+ (block, _image_source_data(block))
for msg in result
for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
if _block_type(block) == "image"
- )
+ ]
# Parallel tool calls land as sibling tool_result blocks inside ONE user message
# (oldest first), so the inner walk must also run newest -> oldest or a batch that
# ends mid-message retires the newest frames instead of the oldest (#103217).
carriers = [
- (block, sum(1 for b in block["content"] if _block_type(b) == "image"))
+ (block, [(b, _image_source_data(b)) for b in block["content"] if _block_type(b) == "image"])
for msg in reversed(result)
for block in reversed(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"})
]
- retire = outbound_image_retire_count([n for _, n in carriers], reserved)
+ many_image_safe = images_all_within_many_image_limit(
+ [
+ *(data for _, data in reserved),
+ *(data for _, images in carriers for _, data in images),
+ ]
+ )
+ retire = outbound_image_retire_count(
+ [len(images) for _, images in carriers], len(reserved), many_image_safe=many_image_safe
+ )
for block, _ in carriers[len(carriers) - retire:]:
placeholder = _text_block("[screenshot removed to save context]")
block["content"] = [
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index b6c53a54fd7..7bf0a2b4dca 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -13,7 +13,7 @@ import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
-from agent.image_eviction_policy import outbound_image_retire_count
+from agent.image_eviction_policy import images_all_within_many_image_limit, outbound_image_retire_count
from agent.compression_marker import (
ELISION_MARKER_MAX_LEN,
_elision_marker,
@@ -1484,17 +1484,20 @@ def _retire_stale_tool_result_images(
return pruned
-def _image_payload(msg: dict[str, Any]) -> tuple[int, int]:
- """``(blocks, bytes)`` of image payload in a message.
+def _image_payload(msg: dict[str, Any]) -> tuple[int, int, list[str]]:
+ """``(blocks, bytes, sources)`` of image payload in a message.
The provider counts BLOCKS: one ``tool_result`` carrying three screenshots is three against
the per-request limit. Bytes are the data-URL / base64 length — the payload is ASCII and the
JSON framing around it is noise against a 24 MB budget, so no per-request re-serialization.
+ ``sources`` holds each image's data URL/base64 string so the caller can read dimensions from
+ headers only, without a second walk or a full decode.
"""
parts = _tool_result_parts(msg.get("content"))
if not isinstance(parts, list):
- return 0, 0
+ return 0, 0, []
blocks = payload = 0
+ sources: list[str] = []
for p in parts:
if not _is_image_part(p):
continue
@@ -1504,10 +1507,13 @@ def _image_payload(msg: dict[str, Any]) -> tuple[int, int]:
data = (
(image_url.get("url") if isinstance(image_url, dict) else image_url)
or (source.get("data") if isinstance(source, dict) else None)
- or ""
)
- payload += len(data) if isinstance(data, str) else 0
- return blocks, payload
+ if isinstance(data, str):
+ payload += len(data)
+ sources.append(data)
+ else:
+ sources.append("")
+ return blocks, payload, sources
def evict_stale_outbound_tool_images(api_messages: list[dict[str, Any]]) -> int:
@@ -1521,30 +1527,39 @@ def evict_stale_outbound_tool_images(api_messages: list[dict[str, Any]]) -> int:
Eviction is driven by the provider limit, counted in image BLOCKS, with user uploads
reserved against the ceiling but never rewritten — policy and rationale in
- :mod:`agent.image_eviction_policy`. Returns the number of messages rewritten.
+ :mod:`agent.image_eviction_policy`. The block ceiling is conditional on the request's actual
+ image dimensions: the strict 20 only when some image exceeds the many-image per-side cap, the
+ hard count otherwise, so an image-heavy run of pre-shrunk screenshots no longer pays a prefix
+ rewrite per batch. Returns the number of messages rewritten.
"""
- carriers: list[tuple[int, tuple[int, int]]] = []
+ carriers: list[tuple[int, int, int, list[str]]] = [] # (index, blocks, bytes, sources)
reserved_blocks = reserved_bytes = 0
+ reserved_sources: list[str] = []
for i in range(len(api_messages) - 1, -1, -1):
msg = api_messages[i]
if not isinstance(msg, dict):
continue
- blocks, size = _image_payload(msg)
+ blocks, size, sources = _image_payload(msg)
if not blocks:
continue
if msg.get("role") == "tool":
- carriers.append((i, (blocks, size)))
+ carriers.append((i, blocks, size, sources))
else:
reserved_blocks += blocks
reserved_bytes += size
+ reserved_sources.extend(sources)
+ many_image_safe = images_all_within_many_image_limit(
+ [*reserved_sources, *(source for _, _, _, sources in carriers for source in sources)]
+ )
retire = outbound_image_retire_count(
- [blocks for _, (blocks, _) in carriers],
+ [blocks for _, blocks, _, _ in carriers],
reserved_blocks,
- carrier_bytes_newest_first=[size for _, (_, size) in carriers],
+ carrier_bytes_newest_first=[size for _, _, size, _ in carriers],
reserved_bytes=reserved_bytes,
+ many_image_safe=many_image_safe,
)
pruned = 0
- for i, _ in carriers[len(carriers) - retire:]:
+ for i, _, _, _ in carriers[len(carriers) - retire:]:
new_msg = _strip_images_from_tool_msg(api_messages[i])
if new_msg is not None:
api_messages[i] = new_msg
diff --git a/agent/image_eviction_policy.py b/agent/image_eviction_policy.py
index cde689d3d19..adc6edf837e 100644
--- a/agent/image_eviction_policy.py
+++ b/agent/image_eviction_policy.py
@@ -14,21 +14,136 @@ full-prefix miss. Holding images until the request would cross a real API limit
retiring a batch costs one slower turn per batch and nothing below the limit.
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. 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 guards with headroom for text.
+(2000 px) to EVERY image in the request, counting images nested in tool_result content. Crossing
+it costs nothing by itself: it only matters when some image actually exceeds 2000 px on a side.
+Hermes already shrinks its own tool images far below that before they enter history
+(``vision_analyze`` and browser screenshots embed at 1568 px, ``computer_use`` at 1456 px by
+default), so the 21st screenshot of a run trips no provider constraint and a batch retire there
+buys a full prefix rewrite for nothing — and, on the preserved-thinking models, invalidates every
+later thinking block. Anthropic's own computer-use guidance now says to keep screenshots at or
+under 2000 px and NOT to prune them client-side for exactly that reason.
+
+So the block ceiling is CONDITIONAL on the request's actual dimensions: the strict 20 applies
+only when some image exceeds ``MANY_IMAGE_DIMENSION_LIMIT``, when the stricter per-side cap is
+live and the retire genuinely protects the request; otherwise the ceiling is the hard count
+``OUTBOUND_IMAGE_HARD_LIMIT``. The hard ceilings above 20 are real but distant (100 images per
+request on 200K-context models, 600 otherwise) and the 32 MB request-size limit usually binds
+first, which the byte budget guards with headroom for text. Classification reads image HEADERS
+only — never a full decode of every base64 payload per request — and treats unreadable or unknown
+dimensions as unsafe, so a payload this module cannot measure keeps today's strict trigger.
"""
from __future__ import annotations
-from typing import Optional, Sequence
+import base64
+import struct
+from typing import Iterable, Optional, Sequence
OUTBOUND_IMAGE_LIMIT = 20
+# Hard per-request image count on 200K-context Claude models; the ceiling once the many-image
+# stricter cap is provably not live (see module docstring). Deliberately not 600 — the byte
+# budget below binds first for a 200K-context transcript, and the byte ceiling needs no context
+# knowledge to be safe.
+OUTBOUND_IMAGE_HARD_LIMIT = 100
OUTBOUND_IMAGE_BUDGET_BYTES = 24_000_000
IMAGE_EVICTION_BATCH = 8
# Satisfiability floor — see outbound_image_retire_count.
OUTBOUND_IMAGE_FLOOR = 3
+# Anthropic's stricter many-image per-side cap (px): above it, every image in the request is held
+# to this limit, so an image over it keeps the strict trigger live.
+MANY_IMAGE_DIMENSION_LIMIT = 2000
+# Bytes of an embedded image to decode when reading its header. PNG IHDR ends at byte 24; a JPEG
+# SOF marker lives within the first few KB. ~32 KB of base64 is generous headroom, and only the
+# prefix is ever decoded (base64 expands 3 bytes per 4 chars).
+_DIMENSION_PROBE_CHARS = 32 * 1024
+_JPEG_SOF_MARKERS = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF})
+
+
+def image_dimensions_from_bytes(raw: bytes) -> Optional[tuple[int, int]]:
+ """(width, height) for PNG / JPEG bytes, or None when unreadable. PNG: IHDR. JPEG: walk
+ segments (skipping 0xFF fill bytes) to the first SOF marker; stop at SOS. Lives here so both
+ the send-path passes and the tool layer share one header-only reader."""
+ if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:
+ width, height = struct.unpack(">II", raw[16:24]) # cannot fail: 8 bytes are guaranteed present
+ return int(width), int(height)
+ if raw.startswith(b"\xff\xd8") and len(raw) > 4:
+ i = 2
+ while i + 9 < len(raw):
+ if raw[i] != 0xFF:
+ i += 1
+ continue
+ marker, i = raw[i + 1], i + 2
+ while marker == 0xFF and i < len(raw):
+ marker, i = raw[i], i + 1
+ if marker in {0xD8, 0xD9}:
+ continue
+ if marker == 0xDA or i + 2 > len(raw):
+ break
+ segment_len = int.from_bytes(raw[i:i + 2], "big")
+ if segment_len < 2 or i + segment_len > len(raw):
+ break
+ if marker in _JPEG_SOF_MARKERS and segment_len >= 7:
+ return int.from_bytes(raw[i + 5:i + 7], "big"), int.from_bytes(raw[i + 3:i + 5], "big")
+ i += segment_len
+ return None
+
+
+def image_max_side_from_data(data: Optional[str]) -> Optional[int]:
+ """Longest side (px) of a data-URL / bare-base64 image, or None when it cannot be read.
+
+ Decodes only the leading base64 prefix (``_DIMENSION_PROBE_CHARS``), so classifying a request
+ with dozens of images costs a few header reads, not a full decode of every payload. Accepts
+ both ``data:image/...;base64,....`` and a bare base64 string; anything else (a remote URL, an
+ unrecognized container) yields None.
+ """
+ if not data:
+ return None
+ payload = data
+ if payload.startswith("data:"):
+ _, separator, payload = payload.partition(",")
+ if not separator or ";base64" not in data[:data.index(",")]:
+ return None
+ payload = payload.strip()
+ prefix = payload[:_DIMENSION_PROBE_CHARS]
+ prefix = prefix[: len(prefix) - (len(prefix) % 4)] # decode needs a multiple-of-four length
+ if not prefix:
+ return None
+ try:
+ raw = base64.b64decode(prefix, validate=False)
+ except (ValueError, TypeError):
+ return None
+ dims = image_dimensions_from_bytes(raw)
+ return max(dims) if dims is not None else None
+
+
+def image_within_many_image_limit(data: Optional[str]) -> bool:
+ """True only when the image's longest side is known and within ``MANY_IMAGE_DIMENSION_LIMIT``.
+
+ Unknown dimensions are NOT safe: the stricter per-request cap would still be live, so the
+ caller keeps the strict trigger. See :func:`images_all_within_many_image_limit`.
+ """
+ longest = image_max_side_from_data(data)
+ return longest is not None and longest <= MANY_IMAGE_DIMENSION_LIMIT
+
+
+def images_all_within_many_image_limit(datas: Iterable[Optional[str]]) -> bool:
+ """True when EVERY image in the request is a readable image within the many-image limit.
+
+ The Anthropic rule is per request: one oversized image holds every image in the request to the
+ stricter cap, so a single unreadable or over-limit image must keep the strict block ceiling.
+ Short-circuits on the first offender, which is what keeps this cheap on image-heavy turns.
+ """
+ for data in datas:
+ if not image_within_many_image_limit(data):
+ return False
+ return True
+
+
+def outbound_image_block_limit(many_image_safe: bool) -> int:
+ """Block ceiling for a request: the strict 20 unless every image is within the many-image cap."""
+ return OUTBOUND_IMAGE_HARD_LIMIT if many_image_safe else OUTBOUND_IMAGE_LIMIT
+
def outbound_image_retire_count(
carrier_blocks_newest_first: Sequence[int],
@@ -36,7 +151,8 @@ def outbound_image_retire_count(
*,
carrier_bytes_newest_first: Optional[Sequence[int]] = None,
reserved_bytes: int = 0,
- limit: int = OUTBOUND_IMAGE_LIMIT,
+ many_image_safe: bool = False,
+ limit: Optional[int] = None,
budget: int = OUTBOUND_IMAGE_BUDGET_BYTES,
batch: int = IMAGE_EVICTION_BATCH,
floor: int = OUTBOUND_IMAGE_FLOOR,
@@ -46,7 +162,8 @@ def outbound_image_retire_count(
``carrier_blocks_newest_first`` is the image-block count per image-bearing tool result,
newest first; ``reserved_blocks`` counts images the pass must never rewrite (user
uploads). The byte dimension is active only when ``carrier_bytes_newest_first`` is
- given (the wire pass has no sizes).
+ given. ``limit`` defaults to :func:`outbound_image_block_limit` of ``many_image_safe``,
+ so both passes pick the same ceiling from the same per-request classification.
The retire count must be a STEP FUNCTION of the overshoot, because the pass is recomputed
on every request: an exact ``count - limit`` target moves the frontier on every new image,
@@ -64,6 +181,8 @@ def outbound_image_retire_count(
uploads alone breach the block ceiling (no retirement can fix that), and never under byte
pressure — the request-size limit is hard and the provider answers 413.
"""
+ if limit is None:
+ limit = outbound_image_block_limit(many_image_safe)
total = len(carrier_blocks_newest_first)
sizes = carrier_bytes_newest_first
blocks_kept = [0] * (total + 1)
diff --git a/tests/agent/test_image_eviction_policy.py b/tests/agent/test_image_eviction_policy.py
index 108ca383771..decdafab484 100644
--- a/tests/agent/test_image_eviction_policy.py
+++ b/tests/agent/test_image_eviction_policy.py
@@ -9,8 +9,12 @@ covers the numbers once.
from __future__ import annotations
+import base64
+
import pytest
+from agent.anthropic_message_convert import _evict_old_screenshots
+from agent.context_compressor import evict_stale_outbound_tool_images
from agent.image_eviction_policy import (
IMAGE_EVICTION_BATCH,
OUTBOUND_IMAGE_FLOOR,
@@ -21,6 +25,74 @@ import itertools
MB = 1_000_000
+# Anthropic's >20-images stricter per-side cap in px. Kept as a literal, not an import, so the
+# two invariants below still run (and fail) against the pre-change policy module.
+MANY_IMAGE_CAP_PX = 2000
+
+
+def _png_data_url(width: int, height: int) -> str:
+ """A data URL whose PNG IHDR declares ``width`` x ``height``.
+
+ Only the 24 bytes a header-only reader inspects are needed, which is exactly the contract
+ the policy relies on: classifying a request must not decode whole payloads.
+ """
+ ihdr = "IHDR".encode("ascii") + width.to_bytes(4, "big") + height.to_bytes(4, "big") + b"\x08\x06\x00\x00\x00"
+ raw = b"\x89PNG\r\n\x1a\n" + len(ihdr).to_bytes(4, "big") + ihdr
+ return "data:image/png;base64," + base64.b64encode(raw).decode("ascii")
+
+
+def _screenshot_tool_messages(n: int, url: str) -> list[dict]:
+ """``n`` OpenAI-shaped tool results, one image block each."""
+ messages: list[dict] = []
+ for i in range(n):
+ messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": f"call_{i}",
+ "content": [
+ {"type": "text", "text": f"shot {i}"},
+ {"type": "image_url", "image_url": {"url": url}},
+ ],
+ }
+ )
+ return messages
+
+
+def _wire_tool_results(n: int, url: str) -> list[dict]:
+ """``n`` Anthropic wire user-turns, each carrying one image ``tool_result``."""
+ data = url.split(",", 1)[1]
+ result: list[dict] = [{"role": "user", "content": [{"type": "text", "text": "start"}]}]
+ for i in range(n):
+ result.append({"role": "assistant", "content": [{"type": "text", "text": f"shot {i}"}]})
+ result.append(
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": f"t{i}",
+ "content": [
+ {
+ "type": "image",
+ "source": {"type": "base64", "media_type": "image/png", "data": data},
+ }
+ ],
+ }
+ ],
+ }
+ )
+ return result
+
+
+def _wire_image_blocks(result: list[dict]) -> int:
+ return sum(
+ 1
+ for msg in result
+ for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
+ for inner in (block.get("content") if block.get("type") == "tool_result" else [block])
+ if isinstance(inner, dict) and inner.get("type") == "image"
+ )
+
@pytest.mark.parametrize(
("blocks", "reserved", "sizes", "reserved_bytes", "expected"),
@@ -58,6 +130,80 @@ def test_retire_count(blocks, reserved, sizes, reserved_bytes, expected):
)
[email protected]("n", [OUTBOUND_IMAGE_LIMIT + 1, 30])
+def test_pre_shrunk_screenshots_do_not_trip_the_many_image_trigger(n):
+ """Invariant 1 (#133999): a request whose images are all within the many-image per-side cap
+ crosses no Anthropic constraint at image #21, so no prefix may be rewritten.
+
+ Hermes embeds its own tool images at 1568 px (vision_analyze / browser) and 1456 px
+ (computer_use), i.e. comfortably under the 2000 px cap the >20 rule would tighten. Retiring a
+ batch here buys nothing and costs a full prompt-cache rewrite per batch -- plus the cache
+ invalidation of every later thinking block on the preserved-thinking models. Red on base:
+ 8 rewrites at n=21, 16 at n=30.
+ """
+ shrunk = _png_data_url(1568, 882)
+ assert evict_stale_outbound_tool_images(_screenshot_tool_messages(n, shrunk)) == 0
+
+ # The wire pass reaches aux/MoA requests without the compressor's pass, so it must hold
+ # the same invariant alone.
+ wire = _wire_tool_results(n, shrunk)
+ _evict_old_screenshots(wire)
+ assert _wire_image_blocks(wire) == n
+
+
+def test_one_oversized_image_keeps_the_strict_trigger():
+ """Invariant 2 (#133999): the stricter cap is per request, so a single image over the cap --
+ here a native-size user upload -- must keep the strict 20-block trigger for the whole request,
+ byte-identical to the pre-#133999 behaviour."""
+ shrunk = _png_data_url(1568, 882)
+ oversized = _png_data_url(MANY_IMAGE_CAP_PX + 1, 8)
+
+ upload = {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look at this"},
+ {"type": "image_url", "image_url": {"url": oversized}},
+ ],
+ }
+ outbound = [upload, *_screenshot_tool_messages(OUTBOUND_IMAGE_LIMIT, shrunk)]
+ assert evict_stale_outbound_tool_images(outbound) == IMAGE_EVICTION_BATCH
+ # The upload itself is reserved and never rewritten.
+ assert upload["content"][1]["image_url"]["url"] == oversized
+
+ # Same request on the wire shape: 20 pre-shrunk carriers plus the oversized reserved upload.
+ wire = _wire_tool_results(OUTBOUND_IMAGE_LIMIT, shrunk)
+ wire[0]["content"].append(
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": oversized.split(",", 1)[1]}}
+ )
+ _evict_old_screenshots(wire)
+ assert _wire_image_blocks(wire) == OUTBOUND_IMAGE_LIMIT - IMAGE_EVICTION_BATCH + 1
+
+
+def test_dimension_classification_reads_headers_and_fails_closed():
+ """The ceiling may only relax on dimensions this module can actually read.
+
+ Imported inside the test so the two invariants above still exercise the pre-change module.
+ """
+ from agent.image_eviction_policy import (
+ MANY_IMAGE_DIMENSION_LIMIT,
+ image_max_side_from_data,
+ image_within_many_image_limit,
+ images_all_within_many_image_limit,
+ )
+
+ shrunk = _png_data_url(1568, 882)
+ assert MANY_IMAGE_DIMENSION_LIMIT == MANY_IMAGE_CAP_PX
+ assert image_max_side_from_data(shrunk) == 1568
+ assert image_within_many_image_limit(_png_data_url(MANY_IMAGE_CAP_PX, 1)) is True
+ assert image_within_many_image_limit(_png_data_url(MANY_IMAGE_CAP_PX + 1, 1)) is False
+ # Unreadable, absent, or non-image sources must keep the strict trigger.
+ assert image_within_many_image_limit(None) is False
+ assert image_within_many_image_limit("data:image/png;base64,not-a-png") is False
+ assert image_within_many_image_limit("https://example.com/shot.png") is False
+ assert images_all_within_many_image_limit([shrunk, shrunk]) is True
+ assert images_all_within_many_image_limit([shrunk, "https://example.com/shot.png"]) is False
+
+
def test_quantum_shrinks_to_the_fit_window_for_heavy_carriers():
"""Three-block carriers: a batch of eight is wider than the window, so the retire count
must still be a step function (hold for window - floor turns), never ``total - floor``."""
diff --git a/tools/computer_use/backend.py b/tools/computer_use/backend.py
index 02052299ea3..560c0e7b1da 100644
--- a/tools/computer_use/backend.py
+++ b/tools/computer_use/backend.py
@@ -5,7 +5,6 @@ registers (see :mod:`plugins.computer_use`); ``computer_use.backend`` selects ex
from __future__ import annotations
-import struct
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@@ -13,36 +12,6 @@ from typing import Any, Dict, List, Optional, Tuple
from agent.provider_base import ProviderBase
-_JPEG_SOF_MARKERS = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF})
-
-def image_dimensions_from_bytes(raw: bytes) -> Optional[tuple[int, int]]:
- """(width, height) for PNG / JPEG bytes, or None when unreadable. PNG: IHDR. JPEG: walk
- segments (skipping 0xFF fill bytes) to the first SOF marker; stop at SOS. Used by the
- tool layer's provider min-size guard."""
- if raw.startswith(b"\x89PNG\r\n\x1a\n") and len(raw) >= 24:
- width, height = struct.unpack(">II", raw[16:24]) # cannot fail: 8 bytes are guaranteed present
- return int(width), int(height)
- if raw.startswith(b"\xff\xd8") and len(raw) > 4:
- i = 2
- while i + 9 < len(raw):
- if raw[i] != 0xFF:
- i += 1
- continue
- marker, i = raw[i + 1], i + 2
- while marker == 0xFF and i < len(raw):
- marker, i = raw[i], i + 1
- if marker in {0xD8, 0xD9}:
- continue
- if marker == 0xDA or i + 2 > len(raw):
- break
- segment_len = int.from_bytes(raw[i:i + 2], "big")
- if segment_len < 2 or i + segment_len > len(raw):
- break
- if marker in _JPEG_SOF_MARKERS and segment_len >= 7:
- return int.from_bytes(raw[i + 5:i + 7], "big"), int.from_bytes(raw[i + 3:i + 5], "big")
- i += segment_len
- return None
-
@dataclass
class UIElement:
diff --git a/tools/computer_use/cua_backend_parse.py b/tools/computer_use/cua_backend_parse.py
index 3ac0551fc05..bb8d1e0891a 100644
--- a/tools/computer_use/cua_backend_parse.py
+++ b/tools/computer_use/cua_backend_parse.py
@@ -9,7 +9,8 @@ import json
import re
from typing import Any, Dict, List, Optional, Tuple
-from tools.computer_use.backend import ActionResult, UIElement, image_dimensions_from_bytes
+from agent.image_eviction_policy import image_dimensions_from_bytes
+from tools.computer_use.backend import ActionResult, UIElement
# Linux/X11 surfaces GNOME Shell / desktop backdrop windows ahead of real app windows with no useful z-order; they
# are targetable but capture as empty, so default capture skips them.
diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.py
index 882e238cddd..31347f13c75 100644
--- a/tools/computer_use/tool.py
+++ b/tools/computer_use/tool.py
@@ -21,7 +21,8 @@ from functools import partial
from types import SimpleNamespace
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
-from tools.computer_use.backend import ActionResult, CaptureResult, ComputerUseBackend, UIElement, image_dimensions_from_bytes
+from agent.image_eviction_policy import image_dimensions_from_bytes
+from tools.computer_use.backend import ActionResult, CaptureResult, ComputerUseBackend, UIElement
logger = logging.getLogger(__name__)