The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(native-compaction): retain image-only user content
Andrex Ibiza, MBA532b2d8874b9
diff --git a/agent/native_compaction.py b/agent/native_compaction.pyindex b1e4d2b3355..ba98ea2a48d 100644--- a/agent/native_compaction.py+++ b/agent/native_compaction.py@@ -207,10 +207,11 @@ def _approx_tokens(text: str) -> int:def _extract_item_text(item: Any) -> Optional[str]:- """Extract measurable text from string, list content, output_text, or nested metadata text.+ """Extract measurable text from message content and fallback fields.- Returns None when the item carries no measurable text.- Handles string content, multipart lists (input_text/text/output_text), and fallback keys.+ Returns None when the item carries no measurable text. Handles string+ content, multipart lists (input_text/text/output_text), and nested+ metadata text."""if not isinstance(item, dict):return None@@ -242,6 +243,30 @@ def _extract_item_text(item: Any) -> Optional[str]:return None+def _has_retainable_image_content(item: Any) -> bool:+ """Return True for a converted Responses message with a valid image part.++ The pruning boundary receives normalized Responses items, so only the+ adapter-owned ``input_image`` shape is authority here. Unknown, malformed,+ or empty multipart placeholders must not become durable history merely+ because their list is non-empty.+ """+ if not isinstance(item, dict):+ return False+ content = item.get("content")+ if not isinstance(content, list):+ return False+ for part in content:+ if not isinstance(part, dict):+ continue+ if str(part.get("type") or "").strip().lower() != "input_image":+ continue+ image_url = part.get("image_url")+ if isinstance(image_url, str) and image_url.strip():+ return True+ return False++def _is_summary_item(item: Any) -> bool:"""True when *item* is a canonical Hermes compression-summary message.@@ -286,7 +311,8 @@ def prune_pre_checkpoint_items(- Retained user messages are kept verbatim within``retained_user_token_budget``; the boundary message is head-truncatedwhen it only partially fits (string content only) — goals are usually- stated up front, so the head is the valuable end.+ stated up front, so the head is the valuable end. A recognized+ image-only user message is retained whole at one-token cost.- Compression summary messages (``_is_summary_item``, the canonical``agent.context_compressor`` provenance check) are retained wholewithin ``retained_summary_token_budget``. A summary is never@@ -397,14 +423,11 @@ def prune_pre_checkpoint_items(continuetext = _extract_item_text(item)- if text is None:- continue- # Image-only user messages have empty text but non-empty content —- # main retains them at 1-token cost (images count as zero, matching- # Codex's retention accounting). Don't skip them just because text- # is falsy.- if not text and not is_user:+ has_retainable_image = is_user and _has_retainable_image_content(item)+ if text is None and not has_retainable_image:continue+ if text is None:+ text = ""if is_summary:result = _try_retain_summary(text)diff --git a/tests/run_agent/test_native_compaction_nontext_retention.py b/tests/run_agent/test_native_compaction_nontext_retention.pynew file mode 100644index 00000000000..3ac259b7530--- /dev/null+++ b/tests/run_agent/test_native_compaction_nontext_retention.py@@ -0,0 +1,83 @@+"""Regression coverage for image-only user content across native compaction."""++from agent.codex_responses_adapter import _chat_messages_to_responses_input+from agent.native_compaction import _extract_item_text, prune_pre_checkpoint_items+++_IMAGE_URL = "data:image/png;base64,AAAA"+_CHAT_IMAGE_PART = {"type": "image_url", "image_url": {"url": _IMAGE_URL}}+_RESPONSES_IMAGE_PART = {"type": "input_image", "image_url": _IMAGE_URL}+_CHECKPOINT = {"type": "compaction", "encrypted_content": "blob_cp"}+++def test_extract_item_text_remains_text_only_for_image_content():+ image_only = {"content": [_RESPONSES_IMAGE_PART]}++ assert _extract_item_text(image_only) is None+ assert _extract_item_text({"content": []}) is None+++def test_image_only_user_message_survives_pre_checkpoint_pruning_verbatim():+ image_only = {"role": "user", "content": [_RESPONSES_IMAGE_PART]}+ items = [+ image_only,+ _CHECKPOINT,+ {"role": "user", "content": "after checkpoint"},+ ]++ pruned = prune_pre_checkpoint_items(items, retained_user_token_budget=1)++ assert pruned == [+ _CHECKPOINT,+ image_only,+ {"role": "user", "content": "after checkpoint"},+ ]+ assert pruned[1] is image_only+++def test_image_only_user_message_still_obeys_retention_budget():+ image_only = {"role": "user", "content": [_RESPONSES_IMAGE_PART]}++ assert prune_pre_checkpoint_items(+ [image_only, _CHECKPOINT],+ retained_user_token_budget=0,+ ) == [_CHECKPOINT]+++def test_malformed_or_unknown_multipart_is_not_retained():+ invalid_contents = [+ [{}],+ [{"type": "input_image", "image_url": ""}],+ [{"type": "unknown", "value": "not an attachment"}],+ ]++ for content in invalid_contents:+ malformed = {"role": "user", "content": content}+ assert prune_pre_checkpoint_items(+ [malformed, _CHECKPOINT],+ retained_user_token_budget=1,+ ) == [_CHECKPOINT]+++def test_adapter_preserves_image_only_user_message_across_checkpoint():+ messages = [+ {"role": "user", "content": [_CHAT_IMAGE_PART]},+ {+ "role": "assistant",+ "content": "checkpoint turn",+ "codex_reasoning_items": [_CHECKPOINT],+ },+ {"role": "user", "content": "after checkpoint"},+ ]++ converted = _chat_messages_to_responses_input(+ messages,+ native_compaction_eligible=True,+ )++ assert converted == [+ _CHECKPOINT,+ {"role": "user", "content": [_RESPONSES_IMAGE_PART]},+ {"role": "assistant", "content": "checkpoint turn"},+ {"role": "user", "content": "after checkpoint"},+ ]