The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): follow-up turns rebuilt from the session DB see the user's image again (#136216)
Tekniumc1b4b62a49e6
diff --git a/agent/image_replay.py b/agent/image_replay.pynew file mode 100644index 00000000000..65e9859408b--- /dev/null+++ b/agent/image_replay.py@@ -0,0 +1,137 @@+"""Re-attach user images on turns whose history was rebuilt from the session DB.++The DB stores user rows as text (``session_persistence._durable_content``): an image part becomes a+trailing ``[screenshot]`` line. A turn rebuilt from the DB (every API-server request, ``--resume``,+a gateway restart) therefore showed the model that placeholder instead of the photo the user asked+about one message earlier. The bytes are not gone: every native attach path (CLI, TUI, gateway,+API server) commits them under the profile's content-addressed ``native-inputs/<sha256>/<name>``+and names that path in the same row (``[Image attached at: <path>]``, written by+``image_routing.build_native_content_parts`` / ``session_api_media.restore_api_images``).++On the WIRE COPY only, when this turn sends images natively, the ``vision.replay_recent_images``+newest images (default 3, 0 = off) go back as ``image_url`` parts. The data URL comes from the same+``_file_to_data_url`` the live turn used, so the rebuilt row is byte-identical to the request that+first sent it and the prompt-cache prefix holds. Only retained bytes under this profile's+``native-inputs`` whose digest still matches are replayed; remote URLs (they can expire and 400+every later turn), missing files and anything outside the window keep their ``[screenshot]`` text.+"""++from __future__ import annotations++import hashlib+import logging+import re+from pathlib import Path+from typing import Any, Optional++logger = logging.getLogger(__name__)++DEFAULT_REPLAY_RECENT_IMAGES = 3+SCREENSHOT_MARKER = "[screenshot]"+_HINT_RE = re.compile(r"^\[Image attached(?P<local> at)?: (?P<ref>.+)\]$")+_IMAGE_PART_TYPES = {"image", "image_url", "input_image"}+++def resolve_replay_recent_images(cfg: dict) -> int:+ """``vision.replay_recent_images`` as an int >= 0; an unusable value warns and disables replay."""+ raw = ((cfg or {}).get("vision") or {}).get("replay_recent_images", DEFAULT_REPLAY_RECENT_IMAGES)+ if raw is None:+ return DEFAULT_REPLAY_RECENT_IMAGES+ if isinstance(raw, int) and not isinstance(raw, bool) and raw >= 0:+ return raw+ logger.warning("vision.replay_recent_images=%r is not a non-negative integer (0 = off, default %d); "+ "not replaying earlier images", raw, DEFAULT_REPLAY_RECENT_IMAGES)+ return 0+++def _split_rebuilt_row(content: str) -> Optional[tuple[str, list[str]]]:+ """``(text, refs)`` for a DB-rebuilt user row whose trailing ``[screenshot]`` lines pair 1:1 with+ its ``[Image attached…]`` hints; ``None`` for anything else (a typed marker never pairs)."""+ lines = content.split("\n")+ n = 0+ while n < len(lines) and lines[len(lines) - 1 - n] == SCREENSHOT_MARKER:+ n += 1+ if not n:+ return None+ text_lines = lines[: len(lines) - n]+ refs: list[str] = []+ for line in text_lines[len(text_lines) - n:] if len(text_lines) > n else ():+ m = _HINT_RE.match(line)+ if m is None:+ return None+ refs.append(m.group("ref") if m.group("local") else "")+ return ("\n".join(text_lines), refs) if len(refs) == n else None+++def _retained_data_url(ref: str) -> Optional[str]:+ """Data URL for a retained local image this profile still holds unchanged, else ``None``."""+ if not ref:+ return None+ from agent.image_routing import _file_to_data_url+ from gateway.session_ingress_media import _media_root++ path = Path(ref)+ try:+ if path.parent.parent != _media_root() or path.is_symlink() or not path.is_file():+ return None+ if hashlib.sha256(path.read_bytes()).hexdigest() != path.parent.name:+ return None+ except OSError:+ return None+ return _file_to_data_url(path)+++def replay_recent_images(api_messages: list[dict[str, Any]], keep: int) -> int:+ """Rebuild the newest ``keep`` images in place on ``api_messages`` (wire copies); images still+ live in the conversation count toward the window. Returns the number re-attached."""+ budget, plan = keep, []+ for msg in reversed(api_messages):+ if budget <= 0:+ break+ if msg.get("role") != "user":+ continue+ content = msg.get("content")+ if isinstance(content, list):+ budget -= sum(1 for p in content if isinstance(p, dict) and p.get("type") in _IMAGE_PART_TYPES)+ continue+ split = _split_rebuilt_row(content) if isinstance(content, str) else None+ if split is None:+ continue+ text, refs = split+ urls: list[Optional[str]] = [None] * len(refs)+ for i in range(len(refs) - 1, -1, -1): # a row's latest image first+ if budget > 0 and (url := _retained_data_url(refs[i])):+ urls[i] = url+ budget -= 1+ if any(urls):+ plan.append((msg, text, urls))+ attached = 0+ for msg, text, urls in plan:+ msg["content"] = [{"type": "text", "text": text}, *(+ {"type": "image_url", "image_url": {"url": u}} if u else {"type": "text", "text": SCREENSHOT_MARKER}+ for u in urls)]+ attached += sum(1 for u in urls if u)+ return attached+++def replay_for_agent(agent: Any, api_messages: list[dict[str, Any]]) -> None:+ """``build_api_messages`` hook: replay only when this turn's model takes images natively."""+ if not any(m.get("role") == "user" and isinstance(m.get("content"), str)+ and m["content"].endswith(SCREENSHOT_MARKER) for m in api_messages):+ return+ try:+ from agent.image_routing import decide_image_input_mode+ from hermes_cli.config import load_config++ cfg = load_config()+ keep = resolve_replay_recent_images(cfg)+ if keep <= 0:+ return+ provider = (getattr(agent, "provider", "") or "").strip()+ model = (getattr(agent, "model", "") or "").strip()+ if decide_image_input_mode(provider, model, cfg) != "native":+ return+ if attached := replay_recent_images(api_messages, keep):+ logger.info("image_replay: re-attached %d earlier image(s) to the request", attached)+ except Exception:+ logger.warning("image_replay: re-attaching earlier images failed", exc_info=True)diff --git a/agent/turn_context.py b/agent/turn_context.pyindex ffad01705c6..777070790b7 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -1329,6 +1329,11 @@ def build_api_messages(# left intact for the native adapters (anthropic/bedrock rebuild signed blocks from it).api_messages.append(api_msg)+ # Rows rebuilt from the session DB carry ``[screenshot]`` lines: re-attach the newest retained+ # images on this wire copy (vision.replay_recent_images; native image input only).+ from agent.image_replay import replay_for_agent+ replay_for_agent(agent, api_messages)+# A provider-rejected Anthropic signature is suppressed outside canonical history and# survives fresh request construction / process resume via session model_config.from agent.anthropic_thinking_replay import apply_rejected_thinking_suppressiondiff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 95eaab56a46..638a2de74dd 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -895,6 +895,9 @@ prompt_caching:# # per session. Unset = 3 inside delegated subagents, unlimited for the main# # agent; a number applies everywhere; 0 = unlimited.# max_calls_per_image: 3+# # Newest user images re-sent on turns rebuilt from the session DB (API server,+# # --resume) when the model takes images natively; 0 = off.+# replay_recent_images: 3## auxiliary:# # Image analysis: vision_analyze tool + browser screenshotsdiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex d87ed644c38..d522dd9ba8d 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1246,8 +1246,7 @@ DEFAULT_CONFIG = {# instead of going to the agent. [] disables."stop_phrases": ["stop"],},- # Native vision embeds (vision_analyze / browser screenshots on vision-capable main models) ride- # conversation history and are re-sent on every later API call.+ # Native images (vision_analyze, browser screenshots, replayed user images) are re-sent on every later call."vision": {# Byte budget for one embedded image (clamped 64 KiB..4 MiB). Raise it for dense phone# screenshots of tables the model calls "unreadable" at 256 KB.@@ -1256,6 +1255,7 @@ DEFAULT_CONFIG = {# null = 3 inside delegated subagents (they run unattended), unlimited for the main agent;# an explicit number applies everywhere; 0 = unlimited."max_calls_per_image": None,+ "replay_recent_images": 3, # newest user images re-sent on turns rebuilt from state.db; 0 = off},# "Hey Hermes" hands-free wake word: always-on, on-device hotword detection that starts a fresh# voice session. Off by default; toggle with /wake.diff --git a/tests/agent/test_image_replay.py b/tests/agent/test_image_replay.pynew file mode 100644index 00000000000..0b5464e5bb1--- /dev/null+++ b/tests/agent/test_image_replay.py@@ -0,0 +1,96 @@+"""Turns rebuilt from the session DB re-attach the newest retained user images (agent/image_replay.py)."""++import json+from pathlib import Path++import pytest++from agent.image_routing import build_native_content_parts+from agent.session_persistence import _durable_content+from agent.turn_context import build_api_messages+from gateway.session_ingress_media import capture_native_media+from hermes_state import SessionDB++_PNG = bytes.fromhex(+ "89504e470d0a1a0a0000000d49484452000000010000000108020000009077"+ "53de0000000c4944415408d763f8cfc0f00f00050201ff2ecf3ca10000000049454e44ae426082")+++class _Agent:+ api_mode = "chat_completions"+ provider, model = "custom", "fake-vision"+ ephemeral_system_prompt = None+ _compression_warning = None+ _current_turn_timestamp = 10_000.0++ @staticmethod+ def _copy_reasoning_content_for_api(_source, _target):+ return None++ @staticmethod+ def _should_sanitize_tool_calls():+ return False+++def _config(**vision):+ from hermes_constants import get_hermes_home # sandboxed per test by conftest+ cfg = {"agent": {"image_input_mode": vision.pop("mode", "native")}, "vision": vision}+ (get_hermes_home() / "config.yaml").write_text(json.dumps(cfg), encoding="utf-8") # JSON is valid YAML+++def _live_turn(tmp_path, name, text, data=_PNG):+ """A native user turn exactly as the CLI/gateway/API server build it: bytes retained under+ native-inputs, then ``build_native_content_parts`` on the retained path."""+ staged = tmp_path / name+ staged.write_bytes(data)+ path = capture_native_media([staged])[0]["path"]+ parts, skipped = build_native_content_parts(text, [path])+ assert not skipped+ return {"role": "user", "content": parts}, Path(path)+++def _rebuilt_request(tmp_path, live_turns):+ """Persist ``live_turns`` through the DB projection, reload as the API server does, send a follow-up."""+ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session(session_id="s", source="api_server")+ for i, turn in enumerate(live_turns):+ db.append_message("s", role="user", content=_durable_content(turn["content"]), timestamp=1000.0 + 2 * i)+ db.append_message("s", role="assistant", content=f"reply {i}", timestamp=1001.0 + 2 * i)+ history = db.get_messages_as_conversation("s") + [{"role": "user", "content": "and the expiry date?"}]+ request, _ = build_api_messages(+ _Agent(), history, current_turn_user_idx=len(history) - 1,+ ext_prefetch_cache="", plugin_user_context="", moa_config=None, active_system_prompt="")+ return [m for m in request if m["role"] == "user"]++[email protected]("mode,replayed", [("native", True), ("text", False)])+def test_rebuilt_turn_resends_the_image_byte_identical_only_for_native_input(tmp_path, mode, replayed):+ _config(mode=mode)+ live, _ = _live_turn(tmp_path, "label.png", "What is on this label?")++ users = _rebuilt_request(tmp_path, [live])++ assert users[-1]["content"] == "and the expiry date?"+ if replayed:+ # Same bytes as the request that first sent it: the prompt-cache prefix holds.+ assert users[0]["content"] == live["content"]+ else:+ assert isinstance(users[0]["content"], str) and users[0]["content"].endswith("\n[screenshot]")+++def test_replay_window_skips_untrusted_bytes_and_typed_markers(tmp_path):+ _config(replay_recent_images=2)+ oldest, _ = _live_turn(tmp_path, "oldest.png", "first photo")+ older, _ = _live_turn(tmp_path, "older.png", "second photo")+ typed = {"role": "user", "content": "I literally typed\n[screenshot]"} # no attachment hint: never paired+ changed, changed_path = _live_turn(tmp_path, "changed.png", "third photo", data=_PNG + b"\x00")+ newest, _ = _live_turn(tmp_path, "new.png", "fourth photo")+ changed_path.write_bytes(b"tampered") # retained bytes no longer match their digest++ users = _rebuilt_request(tmp_path, [oldest, older, typed, changed, newest])++ assert users[4]["content"] == newest["content"]+ assert users[3]["content"].endswith("\n[screenshot]") # tampered bytes are never replayed+ assert users[2]["content"] == "I literally typed\n[screenshot]"+ assert users[1]["content"] == older["content"]+ assert users[0]["content"].endswith("\n[screenshot]") # outside the 2-image windowdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 3c9b7560eb9..6bd160996f8 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1664,7 +1664,7 @@ Each entry supports the same three knobs as any auxiliary task config:### Native vision embed budgets (top-level `vision:`)-Separate from `auxiliary.vision` (which picks the describer model): when the *main* model is vision-capable, `vision_analyze` and browser screenshots embed real pixels into tool results that are re-sent every later turn. `vision.embed_target_bytes` (default `262144`, clamped 64 KiB..4 MiB) sizes one embed; `vision.max_calls_per_image` caps how often the same image may be embedded per session (unset = 3 inside delegated subagents, unlimited for the main agent; `0` = unlimited). See [Vision → Native embeds ride the session](./features/vision.md#native-embeds-ride-the-session-visionembed_target_bytes-and-visionmax_calls_per_image).+Separate from `auxiliary.vision` (which picks the describer model): when the *main* model is vision-capable, `vision_analyze` and browser screenshots embed real pixels into tool results that are re-sent every later turn. `vision.embed_target_bytes` (default `262144`, clamped 64 KiB..4 MiB) sizes one embed; `vision.max_calls_per_image` caps how often the same image may be embedded per session (unset = 3 inside delegated subagents, unlimited for the main agent; `0` = unlimited); `vision.replay_recent_images` (default `3`, `0` = off) re-sends the newest user images on turns rebuilt from the session database (API server, `--resume`). See [Vision → Native embeds ride the session](./features/vision.md#native-embeds-ride-the-session-visionembed_target_bytes-and-visionmax_calls_per_image).### Limiting auxiliary concurrencydiff --git a/website/docs/user-guide/features/vision.md b/website/docs/user-guide/features/vision.mdindex bff7b1dfa0f..27bb55b94fb 100644--- a/website/docs/user-guide/features/vision.md+++ b/website/docs/user-guide/features/vision.md@@ -241,3 +241,19 @@ vision:- **`embed_target_bytes`** — images above the budget (or wider than 1568 px) are downscaled to a JPEG that fits. 256 KB keeps ordinary screenshots cheap; dense phone screenshots of tables can come out unreadable at that size, so raise it (say `1048576`) when the model keeps calling figures "unreadable". Browser screenshots delivered natively use the same budget.- **`max_calls_per_image`** — how often the *same* image (region crops of it included; local paths compare by resolved path) may be embedded per session. Once the cap is hit the tool returns `"vision_analyze refused: this image has already been loaded into context N time(s) …"` instead of another embed, so the model answers from what it already sees. Left unset, only delegated `delegate_task` subagents are capped (at 3): they run unattended and cannot be steered mid-loop from the CLI, and a re-load loop there once burned 158 calls on five files. Set a number to cap every session, or `0` for unlimited everywhere.++### Images in follow-up turns: `vision.replay_recent_images`++The session database stores user messages as text, with one `[screenshot]` line per attached image. A turn whose history is rebuilt from the database (every request to the [API server](api-server.md) that continues a session with `X-Hermes-Session-Id`, `hermes chat --resume`, a gateway restart) used to show the model that placeholder, so a follow-up question about a photo sent one message earlier got a guess.++When the model takes images natively (see [Image Routing](#image-routing-vision-capable-vs-text-only-models)), Hermes now sends the most recent images again, in their original message:++```yaml+vision:+ replay_recent_images: 3 # default; 0 = never re-send earlier images+```++- The bytes come from the copy Hermes already keeps for every attached image under `cache/documents/native-inputs/` in the profile. Nothing new is stored, and the database and session messages API stay text only.+- A re-sent message is byte-identical to the request that first carried the image, so the provider's prompt cache stays valid. The request changes only when a newer image pushes one out of the window.+- Images outside the window, images sent as remote URLs (they can expire, which would fail every later turn), and retained files that are missing or changed keep the `[screenshot]` text.+- With `agent.image_input_mode: text`, or a model without native vision, nothing is re-sent. A value that is not a non-negative integer logs a warning and disables the replay.