Skip to content

The agent that grows with you

fix(compression): retire stale vision tool images in the protected tail

HexLab987ff2fe8bc9fe
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 2a0b5dc4a44..aa3d7a78460 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1220,6 +1220,13 @@ _FEASIBILITY_SKIP_MIDDLE_FRACTION = 0.10
# protected region — but always keep this many trailing messages verbatim so
# the active user ask / latest tool pair remain readable. Issue #61932.
_PRESSURE_KEEP_RECENT_MESSAGES = 3
+# Native vision_analyze / computer_use screenshots that sit inside the
+# protected tail cannot be demoted by pass 2, so they ride every later
+# request until anti-thrash disables compression (#92699). Keep this many
+# newest image-bearing tool results verbatim; retire older image payloads
+# even when they fall inside ``protect_last_n``. Matches the Anthropic
+# adapter's outbound keep-window.
+_MAX_KEEP_TOOL_IMAGES = 3
# Models with context windows below this get their compression threshold
# floored at ``_SMALL_CTX_THRESHOLD_PERCENT`` (raise-only — an explicitly
@@ -1560,6 +1567,60 @@ def _strip_image_parts_from_parts(parts: Any) -> Any:
return out if had_image else None
+def _tool_content_has_images(content: Any) -> bool:
+ """True when a tool-result body carries embedded image bytes.
+
+ Handles both unwrapped OpenAI-style part lists and the native
+ ``{_multimodal: True, content: [...]}`` envelope vision_analyze returns.
+ """
+ if isinstance(content, dict) and content.get("_multimodal"):
+ return _content_has_images(content.get("content"))
+ return _content_has_images(content)
+
+
+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.
+
+ Walks newest-first, keeps the most recent ``keep_newest`` image-bearing
+ tool messages intact (follow-up screenshot QA still sees the latest
+ frames), and retires the rest. User-role uploads are not touched.
+
+ Mutates ``result`` in place. Returns the number of messages rewritten.
+ """
+ if keep_newest < 0:
+ keep_newest = 0
+ seen = 0
+ pruned = 0
+ for i in range(len(result) - 1, -1, -1):
+ msg = result[i]
+ if not isinstance(msg, dict) or msg.get("role") != "tool":
+ continue
+ content = msg.get("content")
+ if not _tool_content_has_images(content):
+ continue
+ seen += 1
+ if seen <= keep_newest:
+ continue
+ if isinstance(content, dict) and content.get("_multimodal"):
+ summary = content.get("text_summary") or "[screenshot removed to save context]"
+ new_msg = {**msg, "content": f"[screenshot removed] {summary[:200]}"}
+ drop_stale_api_content(new_msg)
+ result[i] = new_msg
+ pruned += 1
+ continue
+ stripped = _strip_image_parts_from_parts(content)
+ if stripped is None:
+ continue
+ new_msg = {**msg, "content": stripped}
+ drop_stale_api_content(new_msg)
+ result[i] = new_msg
+ pruned += 1
+ return pruned
+
+
def _truncate_tool_call_args_json(args: str, head_chars: int = 200) -> str:
"""Shrink long string values inside a tool-call arguments JSON blob while
preserving JSON validity.
@@ -3779,6 +3840,13 @@ class ContextCompressor(ContextEngine):
for i in range(max(0, prune_boundary)):
_truncate_tool_call_args_at(i)
+ # Pass 3.5 (#92699): retire image payloads that pass 2 cannot reach
+ # because they sit inside the protected tail. Native vision_analyze
+ # embeds re-sent on every turn otherwise make compression look
+ # ineffective (savings < 10%) and anti-thrash disables it. Newest
+ # frames stay live for follow-up QA; older ones become placeholders.
+ pruned += _retire_stale_tool_result_images(result)
+
# Pass 4 (issue #61932): protected-tail pressure demotion.
# After multiple in-place compactions the transcript can be short
# enough that nearly every remaining message sits inside the
diff --git a/tests/agent/test_compressor_stale_tool_images.py b/tests/agent/test_compressor_stale_tool_images.py
new file mode 100644
index 00000000000..a6972b397a2
--- /dev/null
+++ b/tests/agent/test_compressor_stale_tool_images.py
@@ -0,0 +1,140 @@
+"""Retire stale vision_analyze / screenshot tool images inside the protected tail.
+
+Issue #92699: native embeds sitting in protect_last_n ride every later
+request, compression savings stay tiny, and anti-thrash disables further
+compaction. Pass 2 of ``_prune_old_tool_results`` only strips images
+*outside* the tail; this suite pins the extra keep-newest pass.
+"""
+
+from __future__ import annotations
+
+from agent.context_compressor import (
+ ContextCompressor,
+ _MAX_KEEP_TOOL_IMAGES,
+ _content_has_images,
+ _tool_content_has_images,
+)
+
+
+def _compressor() -> ContextCompressor:
+ c = ContextCompressor.__new__(ContextCompressor)
+ c.quiet_mode = True
+ return c
+
+
+def _image_tool(i: int, *, blob: str = "A" * 400) -> list[dict]:
+ return [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": f"call_{i}",
+ "type": "function",
+ "function": {
+ "name": "vision_analyze",
+ "arguments": f'{{"image_url":"shot{i}.png"}}',
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": f"call_{i}",
+ "content": [
+ {"type": "text", "text": f"Image attached natively shot {i}"},
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,{blob}{i}"},
+ },
+ ],
+ },
+ ]
+
+
+def _image_bearing_tools(messages: list[dict]) -> list[dict]:
+ return [
+ m
+ for m in messages
+ if m.get("role") == "tool" and _tool_content_has_images(m.get("content"))
+ ]
+
+
+class TestRetireStaleToolImagesInProtectedTail:
+ def test_keep_newest_images_inside_a_large_protect_window(self):
+ """Five native embeds all fit in protect_last_n=20; only newest N stay."""
+ msgs: list[dict] = [{"role": "user", "content": "screenshot QA"}]
+ for i in range(5):
+ msgs.extend(_image_tool(i))
+ msgs.append({"role": "user", "content": "compare the last few"})
+
+ out, pruned = _compressor()._prune_old_tool_results(
+ msgs, protect_tail_count=20,
+ )
+ assert pruned >= 5 - _MAX_KEEP_TOOL_IMAGES
+ kept = _image_bearing_tools(out)
+ assert len(kept) == _MAX_KEEP_TOOL_IMAGES
+ kept_ids = [m["tool_call_id"] for m in kept]
+ assert kept_ids == [f"call_{i}" for i in range(5 - _MAX_KEEP_TOOL_IMAGES, 5)]
+
+ def test_multimodal_envelopes_outside_keep_window_become_text(self):
+ msgs: list[dict] = [{"role": "user", "content": "go"}]
+ for i in range(_MAX_KEEP_TOOL_IMAGES + 1):
+ msgs.append({
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{
+ "id": f"env_{i}",
+ "type": "function",
+ "function": {"name": "vision_analyze", "arguments": "{}"},
+ }],
+ })
+ msgs.append({
+ "role": "tool",
+ "tool_call_id": f"env_{i}",
+ "content": {
+ "_multimodal": True,
+ "content": [
+ {"type": "text", "text": f"shot {i}"},
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,XYZ{i}"},
+ },
+ ],
+ "text_summary": f"native shot {i}",
+ },
+ })
+
+ out, _ = _compressor()._prune_old_tool_results(
+ msgs, protect_tail_count=20,
+ )
+ oldest = next(m for m in out if m.get("tool_call_id") == "env_0")
+ assert isinstance(oldest["content"], str)
+ assert "screenshot removed" in oldest["content"]
+ assert "native shot 0" in oldest["content"]
+ newest = next(
+ m for m in out
+ if m.get("tool_call_id") == f"env_{_MAX_KEEP_TOOL_IMAGES}"
+ )
+ assert _tool_content_has_images(newest["content"])
+
+ def test_user_uploads_are_not_retired(self):
+ user_img = {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,USERUPLOAD"},
+ },
+ ],
+ }
+ msgs = [user_img]
+ for i in range(_MAX_KEEP_TOOL_IMAGES + 2):
+ msgs.extend(_image_tool(i))
+
+ out, _ = _compressor()._prune_old_tool_results(
+ msgs, protect_tail_count=20,
+ )
+ assert _content_has_images(out[0]["content"])
+ assert out[0]["content"][1]["image_url"]["url"].endswith("USERUPLOAD")