Skip to content

The agent that grows with you

fix(agent): deliver pre_llm_call/memory context on multimodal turns (#71998)

PRATHAMESH75b8b519c39887
diff --git a/agent/turn_context.py b/agent/turn_context.py
index c655e1d11ca..86e20b89548 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -78,22 +78,74 @@ def _agent_stale_thinking_on_wire(agent: Any) -> bool:
return True
+def _context_injection_parts(
+ ext_prefetch_cache: str,
+ plugin_user_context: str,
+) -> list[str]:
+ """The ephemeral context pieces (memory prefetch + ``pre_llm_call``).
+
+ Shared by the string sidecar (:func:`compose_user_api_content`) and the
+ multimodal text-part (:func:`compose_multimodal_context_part`) paths so
+ both inject byte-identical context regardless of the turn's content shape.
+ """
+ injections: list[str] = []
+ if ext_prefetch_cache:
+ fenced = build_memory_context_block(ext_prefetch_cache)
+ if fenced:
+ injections.append(fenced)
+ if plugin_user_context:
+ injections.append(plugin_user_context)
+ return injections
+
+
def compose_user_api_content(
content: Any, ext_prefetch_cache: str, plugin_user_context: str
) -> Optional[str]:
"""Compose the API-bound content of the current turn's user message.
- Single source for the ``api_content`` sidecar and the wire bytes so they never drift
- (what turn N sends is what turn N+1 replays). ``None`` when nothing is injected."""
+ Sources: memory-manager prefetch + ``pre_llm_call`` plugin context with
+ target="user_message" (the default). Both are appended to the *API copy*
+ of the user message only — the stored content stays clean.
+
+ This is the single source of that composition. The prologue stamps the
+ result onto the live message as ``api_content`` (persisted alongside the
+ clean content) and the ``api_messages`` build in ``conversation_loop``
+ sends the same helper's output, so the persisted sidecar can never drift
+ from the bytes on the wire — which is the whole prompt-cache invariant:
+ what turn N sends must be what turn N+1 replays.
+
+ Returns ``None`` when nothing is injected (multimodal/non-string content,
+ or no ephemeral context), meaning the message is sent as-is. Multimodal
+ (list) turns take the injection via :func:`compose_multimodal_context_part`
+ instead, since the string sidecar can't ride on list content.
+ """
if not isinstance(content, str):
return None
- fenced = build_memory_context_block(ext_prefetch_cache) if ext_prefetch_cache else ""
- injections = [part for part in (fenced, plugin_user_context) if part]
+ injections = _context_injection_parts(ext_prefetch_cache, plugin_user_context)
if not injections:
return None
return content + "\n\n" + "\n\n".join(injections)
+def compose_multimodal_context_part(
+ ext_prefetch_cache: str,
+ plugin_user_context: str,
+) -> Optional[str]:
+ """The memory-prefetch + ``pre_llm_call`` context as a single text part.
+
+ :func:`compose_user_api_content` returns ``None`` for multimodal (list)
+ turns, so the string ``api_content`` sidecar can't carry this context and
+ it would silently drop on image/attachment turns (#71998). Callers append
+ the returned text as a durable content part instead — the same channel the
+ gateway must-deliver notes use (:func:`append_notes_to_multimodal_content`)
+ — so an image-only turn still reaches the model with the injected context.
+
+ Returns ``None`` when nothing is injected.
+ """
+ injections = _context_injection_parts(ext_prefetch_cache, plugin_user_context)
+ return "\n\n".join(injections) if injections else None
+
+
def substitute_api_content(api_msg: Dict[str, Any]) -> Optional[str]:
"""Pop the ``api_content`` sidecar and substitute it into ``content`` (keeps the
prompt-cache prefix byte-stable). Returns the popped sidecar, or ``None``."""
@@ -867,9 +919,26 @@ def _stamp_api_content_sidecar(
plugin_user_context: str, *, preflight_compressed: bool,
) -> None:
"""api_content sidecar — persist what you send: injected context lives only in the
- API copy, so stamp the exact sent bytes on the live dict for replay."""
+ API copy, so stamp the exact sent bytes on the live dict for replay.
+
+ Multimodal (list) turns can't carry the string ``api_content`` sidecar —
+ :func:`compose_user_api_content` returns ``None`` for them — so the memory/
+ plugin context would silently drop on an image-only turn (#71998). For those,
+ deliver the context as a durable text part instead (the same channel the
+ gateway must-deliver notes use), keeping the wire byte-identical to what is
+ persisted and replayed."""
_turn_user_msg = messages[current_turn_user_idx]
live_content = _turn_user_msg.get("content")
+ # Multimodal (list) turns can't carry the string ``api_content`` sidecar —
+ # :func:`compose_user_api_content` returns ``None`` for them — so the memory/
+ # plugin context would silently drop on an image-only turn (#71998). Deliver it
+ # as a durable text part instead (the same channel the gateway must-deliver notes
+ # use), which is persisted and replayed as ordinary content — no sidecar needed.
+ if isinstance(live_content, list):
+ _mm_ctx = compose_multimodal_context_part(ext_prefetch_cache, plugin_user_context)
+ if _mm_ctx:
+ append_notes_to_multimodal_content(live_content, _mm_ctx)
+ return
from agent.session_persistence import _persist_lock, durable_user_row_content
# Match the row the flush wrote (persist override = clean transcript), not the live bytes.
durable_content, _api_content = durable_user_row_content(
diff --git a/tests/agent/test_api_content_sidecar.py b/tests/agent/test_api_content_sidecar.py
index 2f65df5c1be..1f46b1449e4 100644
--- a/tests/agent/test_api_content_sidecar.py
+++ b/tests/agent/test_api_content_sidecar.py
@@ -30,7 +30,11 @@ from unittest.mock import MagicMock, patch
import pytest
from agent.memory_manager import build_memory_context_block
-from agent.turn_context import build_turn_context, compose_user_api_content
+from agent.turn_context import (
+ build_turn_context,
+ compose_multimodal_context_part,
+ compose_user_api_content,
+)
from hermes_state import SessionDB
@@ -51,6 +55,29 @@ class TestComposeUserApiContent:
+class TestComposeMultimodalContextPart:
+ """#71998: the injection composed as a standalone text part for the
+ multimodal (list) content path, mirroring the string sidecar's sources."""
+
+ def test_none_when_nothing_to_inject(self):
+ assert compose_multimodal_context_part("", "") is None
+
+ def test_plugin_context_only(self):
+ assert compose_multimodal_context_part("", "CTX") == "CTX"
+
+ def test_memory_block_and_plugin_context(self):
+ out = compose_multimodal_context_part("likes tea", "CTX")
+ fenced = build_memory_context_block("likes tea")
+ assert out == fenced + "\n\n" + "CTX"
+
+ def test_matches_string_sidecar_injection_tail(self):
+ # The multimodal part is exactly the string sidecar minus the leading
+ # content + separator, so both paths inject byte-identical context.
+ sidecar = compose_user_api_content("hello", "likes tea", "CTX")
+ part = compose_multimodal_context_part("likes tea", "CTX")
+ assert sidecar == "hello\n\n" + part
+
+
# ---------------------------------------------------------------------------
# SessionDB: schema, round-trip, verbatim replay
# ---------------------------------------------------------------------------
@@ -281,6 +308,46 @@ class TestPrologueStamping:
ctx = _build(agent)
assert "api_content" not in ctx.messages[ctx.current_turn_user_idx]
+ def test_appends_context_part_for_multimodal_turn(self):
+ """#71998: pre_llm_call context must reach an image-only (multimodal)
+ turn as a durable text part, not silently drop.
+
+ The string api_content sidecar can't ride on list content, so the
+ context is appended to the content list (the gateway must-deliver-note
+ channel) — durable, so wire == persisted == replay."""
+ agent = _FakeAgent()
+ blocks = [{"type": "image_url", "image_url": {"url": "data:img"}}]
+ with patch(
+ "hermes_cli.plugins.invoke_hook",
+ return_value=[{"context": "PLUGIN-CTX"}],
+ ):
+ ctx = _build(
+ agent,
+ user_message=blocks,
+ summarize_user_message_for_log=lambda _m: "[image]",
+ )
+ content = ctx.messages[ctx.current_turn_user_idx]["content"]
+ assert isinstance(content, list)
+ # Original image part preserved; plugin context appended as a text part.
+ assert content[0] == {"type": "image_url", "image_url": {"url": "data:img"}}
+ assert content[-1] == {"type": "text", "text": "PLUGIN-CTX"}
+ # Multimodal turns carry the context durably, not via the string sidecar.
+ assert "api_content" not in ctx.messages[ctx.current_turn_user_idx]
+
+ def test_no_context_part_for_multimodal_without_injections(self):
+ """A multimodal turn with no ephemeral context is left untouched."""
+ agent = _FakeAgent()
+ blocks = [{"type": "image_url", "image_url": {"url": "data:img"}}]
+ with patch("hermes_cli.plugins.invoke_hook", return_value=[]):
+ ctx = _build(
+ agent,
+ user_message=blocks,
+ summarize_user_message_for_log=lambda _m: "[image]",
+ )
+ content = ctx.messages[ctx.current_turn_user_idx]["content"]
+ assert content == blocks # no stray text part appended
+ assert "api_content" not in ctx.messages[ctx.current_turn_user_idx]
+
# ---------------------------------------------------------------------------
# Flush: persist-override rows keep the sent bytes in the sidecar (#48677)