The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): latch retired screenshots per session across replay-window rollover
Teknium837213a0548e
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 01c26afe7a5..752c97e6a7c 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2201,8 +2201,8 @@ def _iteration_summary_api_messages(agent, messages: list) -> list:# Compression/resume can orphan a tool result whose parent tool_call was summarized away.api_messages = agent._sanitize_api_messages(api_messages)# Same send-path vision eviction as the main loop (#89296).- from agent.context_compressor import evict_stale_outbound_tool_images- evict_stale_outbound_tool_images(api_messages)+ from agent.context_compressor import evict_stale_outbound_tool_images, outbound_retired_image_ids+ evict_stale_outbound_tool_images(api_messages, outbound_retired_image_ids(agent))# Same per-model image strip as turn_api_request.build_api_request: this path builds# api_messages by hand and calls _build_api_kwargs directly, so a model recorded in# agent._image_rejecting_models would otherwise get images here → 4xx → no summary.diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 31dbdd97a36..0b08f41cdec 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -13,7 +13,7 @@ import timefrom dataclasses import dataclassfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple-from agent.image_eviction_policy import images_all_within_many_image_limit, outbound_image_retire_count+from agent.image_eviction_policy import images_all_within_many_image_limit, latched_retire_count, outbound_image_retire_count, outbound_retired_image_idsfrom agent.compression_marker import (ELISION_MARKER_MAX_LEN,_elision_marker,@@ -1509,7 +1509,7 @@ def _image_payload(msg: dict[str, Any]) -> list[str]:return sources-def evict_stale_outbound_tool_images(api_messages: list[dict[str, Any]]) -> int:+def evict_stale_outbound_tool_images(api_messages: list[dict[str, Any]], retired_ids: Optional[set[str]] = None) -> 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@@ -1522,6 +1522,7 @@ def evict_stale_outbound_tool_images(api_messages: list[dict[str, Any]]) -> int:reserved against the ceiling but never rewritten; the block ceiling depends on therequest's image dimensions — policy and rationale in :mod:`agent.image_eviction_policy`.Returns the number of messages rewritten.+ ``retired_ids`` latches the frontier per session: see :func:`latched_retire_count`."""carriers: list[tuple[int, list[str]]] = [] # (index, image sources), newest firstreserved: list[str] = []@@ -1539,6 +1540,7 @@ def evict_stale_outbound_tool_images(api_messages: list[dict[str, Any]]) -> int:reserved_bytes=sum(map(len, reserved)),many_image_safe=images_all_within_many_image_limit([*reserved, *(x for _, ss in carriers for x in ss)]),)+ retire = latched_retire_count(retire, [api_messages[i].get("tool_call_id") for i, _ in carriers], retired_ids)pruned = 0for i, _ in carriers[len(carriers) - retire:]:new_msg = _strip_images_from_tool_msg(api_messages[i])diff --git a/agent/turn_request_assembly.py b/agent/turn_request_assembly.pyindex be7436e72fc..cc75648461b 100644--- a/agent/turn_request_assembly.py+++ b/agent/turn_request_assembly.py@@ -160,8 +160,9 @@ def assemble_api_request(# OpenAI-style tool-result image_url parts. The per-call clone is rewritten in# place; persisted history is untouched.from agent.context_compressor import evict_stale_outbound_tool_images+ from agent.image_eviction_policy import outbound_retired_image_ids- evict_stale_outbound_tool_images(api_messages)+ evict_stale_outbound_tool_images(api_messages, outbound_retired_image_ids(agent))# One-time repeated-heal notice goes out via the status/warning callback, NEVER# appended to messages: the cached prompt prefix stays byte-identical.diff --git a/tests/agent/test_image_eviction_policy.py b/tests/agent/test_image_eviction_policy.pyindex 9ddd705a6e0..99f0f1246cb 100644--- a/tests/agent/test_image_eviction_policy.py+++ b/tests/agent/test_image_eviction_policy.py@@ -267,3 +267,77 @@ def test_unfixable_upload_breach_under_byte_pressure_fits_and_still_steps():# bytes allow 6 carriers, floor is 3 -> a 4-carrier quantum, so at most one move per 4 imagesmoves = sum(a != b for a, b in itertools.pairwise(counts))assert moves <= -(-(len(span) - OUTBOUND_IMAGE_FLOOR) // 4)+++def _mixed_tool_history(sizes: list[int], uploads: int) -> list[dict]:+ """Uploads (unreadable headers -> strict ceiling) plus one screenshot tool round per size."""+ rows: list[dict] = [+ {"role": "user", "content": [{"type": "text", "text": "look"}]+ + [{"type": "image_url", "image_url": {"url": "data:image/png;base64," + "U" * 285_000}}] * uploads}+ ]+ for i, size in enumerate(sizes):+ rows.append({"role": "assistant", "content": "shot", "tool_calls": [+ {"id": f"c{i}", "type": "function", "function": {"name": "vision_analyze", "arguments": "{}"}}]})+ rows.append({"role": "tool", "tool_call_id": f"c{i}", "content": [+ {"type": "text", "text": f"shot {i}"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64," + "Q" * size}}]})+ return rows+++def test_a_small_new_screenshot_never_restores_retired_ones():+ """#133999 review: appending a small screenshot after large ones widened the byte-derived+ quantum, so the retire count fell (8 -> 5) and three retired screenshots came back inside+ already-sent history. Retirement must only grow as the conversation does, on both passes."""+ from agent.anthropic_adapter import build_anthropic_kwargs++ def retired(sizes: list[int]) -> tuple[set[str], set[str]]:+ rows = _mixed_tool_history(sizes, uploads=OUTBOUND_IMAGE_LIMIT + 1)+ outbound = [dict(m) for m in rows]+ evict_stale_outbound_tool_images(outbound)+ kept = {m["tool_call_id"] for m in outbound if m["role"] == "tool"+ and any(p.get("type") == "image_url" for p in m["content"])}+ wire = build_anthropic_kwargs(model="claude-sonnet-4-5", messages=rows, tools=None,+ max_tokens=None, reasoning_config=None)["messages"]+ wire_kept = {b["tool_use_id"] for m in wire if isinstance(m["content"], list) for b in m["content"]+ if b.get("type") == "tool_result" and isinstance(b.get("content"), list)+ and any(x.get("type") == "image" for x in b["content"])}+ ids = {f"c{i}" for i in range(len(sizes))}+ return ids - kept, ids - wire_kept++ previous = (set(), set())+ for extra in range(4):+ now = retired([2_900_000] * 11 + [100_000] * extra)+ assert now[0] >= previous[0] and now[1] >= previous[1], (extra, previous, now)+ previous = now+ assert len(previous[0]) >= IMAGE_EVICTION_BATCH+++def test_retirement_is_latched_when_an_upload_leaves_the_request(tmp_path, monkeypatch):+ """#133999 x #136216 review: once the replay window drops an oversized upload, the request+ relaxes to the 100-image ceiling and a from-scratch decision restored all eight retired+ screenshots into already-sent history. Driven through the agent's request builder."""+ from agent.chat_completion_helpers import _iteration_summary_api_messages+ from run_agent import AIAgent++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ agent = AIAgent(api_key="k", base_url="https://api.anthropic.com", provider="anthropic",+ model="claude-sonnet-4-5", quiet_mode=True, skip_context_files=True, skip_memory=True)+ agent._cached_system_prompt = "SYS"+ shrunk, oversized = _png_data_url(1568, 882), _png_data_url(MANY_IMAGE_CAP_PX + 400, 8)+ tools = [m for i in range(OUTBOUND_IMAGE_LIMIT) for m in (+ {"role": "assistant", "content": "shot", "tool_calls": [+ {"id": f"c{i}", "type": "function", "function": {"name": "vision_analyze", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": f"c{i}", "content": [+ {"type": "text", "text": f"shot {i}"}, {"type": "image_url", "image_url": {"url": shrunk}}]})]++ def kept(upload_url: str | None) -> list[str]:+ upload = [{"type": "text", "text": "photo"}]+ if upload_url:+ upload.append({"type": "image_url", "image_url": {"url": upload_url}})+ history = [{"role": "user", "content": upload}, *tools, {"role": "user", "content": "next"}]+ return [m["tool_call_id"] for m in _iteration_summary_api_messages(agent, history)+ if m.get("role") == "tool" and any(p.get("type") == "image_url" for p in m["content"])]++ before = kept(oversized)+ assert len(before) == OUTBOUND_IMAGE_LIMIT - IMAGE_EVICTION_BATCH+ assert kept(None) == beforediff --git a/website/docs/user-guide/features/computer-use.md b/website/docs/user-guide/features/computer-use.mdindex 6b746c2cf2f..d54fd618791 100644--- a/website/docs/user-guide/features/computer-use.md+++ b/website/docs/user-guide/features/computer-use.md@@ -405,7 +405,10 @@ Screenshots are expensive. Hermes applies four layers of optimisation:prompt-cache prefix survives; at it, one slower turn per batch instead ofone per screenshot. Images you attach yourself count against the limitbut are never removed; when they alone exceed it, screenshots are still- retired in whole batches, never one per new image.+ retired in whole batches, never one per new image. A retired screenshot+ stays retired for the rest of the session, even when a later request+ would have room for it again (a smaller new screenshot, or an attached+ image that has dropped out of the request).- **Client-side compression pruning** — the context compressor detectsmultimodal tool results and strips image parts from old ones.- **Image-aware token estimation** — each image is counted as ~1500