Skip to content

The agent that grows with you

fix(gateway): re-home inbound attachments into the routed profile's cache (#101134, salvage #101369)

teknium100771ffce96b
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index e59789add43..1cbcb8969ba 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -1490,14 +1490,17 @@ async def cache_document_from_bytes_async(data: bytes, filename: str) -> str:
@dataclass
class CachedMedia:
"""Result of caching one attachment's bytes."""
- path: str # absolute cache path, agent-visible (sandbox-translated)
+ path: str # absolute HOST cache path (same coordinate system as cache_*_from_bytes)
media_type: str # MIME type recorded on the MessageEvent
kind: str # "image" | "video" | "audio" | "document"
display_name: str # human-readable name for transcript notes
def context_note(self) -> str:
- """One-line transcript annotation pointing the agent at the file."""
- return f"[{self.kind} '{self.display_name}' saved at: {self.path}]"
+ """One-line transcript annotation pointing the agent at the file (sandbox-translated at
+ render time, never baked into ``path``: ``event.media_urls`` must hold one coordinate
+ system so the routed turn can re-home and translate every entry alike, #101134)."""
+ from tools.credential_files import to_agent_visible_cache_path
+ return f"[{self.kind} '{self.display_name}' saved at: {to_agent_visible_cache_path(self.path)}]"
# MIME -> extension reverse lookup; FIRST match across image, video, document tables wins
@@ -1519,7 +1522,6 @@ def cache_media_bytes(data: bytes, *, filename: str = "", mime_type: str = "",
"""Classify and cache raw attachment bytes -> CachedMedia (None only for images failing
validation). ``default_kind`` biases ambiguous ext/MIME (Telegram native photo, no name);
anything not image/video/audio is a document."""
- from tools.credential_files import to_agent_visible_cache_path
ext = _resolve_media_ext(filename, mime_type)
mime = (mime_type or "").lower()
display = re.sub(r"[^\w.\- ]", "_", filename) if filename else (ext.lstrip(".") or "file")
@@ -1538,13 +1540,13 @@ def cache_media_bytes(data: bytes, *, filename: str = "", mime_type: str = "",
raise
return None
out_mime = mime if passthrough and mime.startswith(f"{kind}/") else table[kind_ext]
- return CachedMedia(to_agent_visible_cache_path(path), out_mime, kind, display)
+ return CachedMedia(path, out_mime, kind, display)
# Any other type is cached and surfaced as a path — an authorized user's uploads must never be
# silently dropped. Unknown types get octet-stream so the agent reaches for terminal tools.
fallback_name = filename or (f"document{ext}" if ext else "document.bin")
path = cache_document_from_bytes(data, fallback_name)
out_mime = SUPPORTED_DOCUMENT_TYPES.get(ext) or mime or "application/octet-stream"
- return CachedMedia(to_agent_visible_cache_path(path), out_mime, "document", display or fallback_name)
+ return CachedMedia(path, out_mime, "document", display or fallback_name)
async def cache_media_bytes_async(
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index f84b9e87968..e7647ceb5b2 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -15,8 +15,11 @@ import dataclasses
import json
import os
import re
+import shutil
import time
from contextlib import suppress
+from pathlib import Path
+
from gateway.config import Platform
from gateway.platforms.base import EphemeralReply
from gateway.platforms.event import MessageEvent, MessageType
@@ -40,6 +43,45 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
logger = logging.getLogger("gateway.run")
+def rehome_inbound_media(event: MessageEvent) -> None:
+ """Move adapter-cached attachments into the ACTIVE profile's ``cache/`` and repoint the event.
+
+ Adapters download and cache an attachment BEFORE the gateway routes the event to a profile, so
+ on a multiplexed gateway the file lands under the launch home while the routed turn's sandbox
+ mounts (``get_cache_directory_mounts``) and vision's ``_media_cache_roots`` resolve the routed
+ profile's ``cache/`` — the agent is handed a mounted, empty directory (#101134). Runs inside the
+ routed scope at the shared preprocessing choke point (every adapter, every media kind); a no-op
+ when the active home is the launch home, and idempotent (a moved entry is no longer under it).
+ """
+ if not event.media_urls:
+ return
+ from hermes_constants import get_hermes_home, get_routing_process_hermes_home, hermes_home_key
+ active, launch = Path(get_hermes_home()), Path(get_routing_process_hermes_home())
+ if hermes_home_key(active) == hermes_home_key(launch):
+ return
+ from tools.credential_files import to_agent_visible_cache_path
+ rewritten = list(event.media_urls)
+ for i, raw in enumerate(event.media_urls):
+ src = Path(raw)
+ try:
+ rel = src.relative_to(launch / "cache")
+ except ValueError:
+ continue
+ dest = active / "cache" / rel
+ try:
+ if not src.is_file():
+ continue
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(src), str(dest))
+ except OSError:
+ logger.warning("Could not move inbound attachment %s into the routed profile's cache", raw, exc_info=True)
+ continue
+ rewritten[i] = str(dest)
+ if event.text and raw in event.text: # note an adapter already baked in (observed/replied media)
+ event.text = event.text.replace(raw, to_agent_visible_cache_path(str(dest)))
+ event.media_urls = rewritten
+
+
def discord_triggering_note(message_id: Any) -> str:
"""Model-facing routing note for a Discord turn (rides the API-bound user message only)."""
return (
@@ -1702,6 +1744,7 @@ class GatewayInboundMixin:
follow-up paths so attribution, image enrichment, STT, document notes, reply context and
@ references behave the same. Side effect: buffers per-session native image paths when the
model supports native vision; the caller consumes that buffer at ``run_conversation``."""
+ rehome_inbound_media(event) # before any consumer (vision, STT, document notes) reads media_urls
_pending_stt_prepared = hasattr(event, "_gateway_pending_stt_text")
message_text = (event._gateway_pending_stt_text if _pending_stt_prepared else event.text) or ""
# Prefer the caller's resolved session key so this write key matches the consume key at the
diff --git a/tests/gateway/test_inbound_media_profile_scope.py b/tests/gateway/test_inbound_media_profile_scope.py
new file mode 100644
index 00000000000..05b506499fb
--- /dev/null
+++ b/tests/gateway/test_inbound_media_profile_scope.py
@@ -0,0 +1,84 @@
+"""Inbound attachments on a multiplexed gateway live in the ROUTED profile's cache (#101134).
+
+Adapters cache an attachment before the event is routed, so the bytes land under the launch home
+while the routed profile's sandbox mounts point at ``profiles/<p>/cache/<kind>`` — a mounted, empty
+directory. Real temp homes A (launch) and B (routed), real ``_profile_runtime_scope``, multiplex on.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import hermes_yaml as yaml
+
+from agent import secret_scope as ss
+from gateway.platforms.base import cache_media_bytes
+from gateway.platforms.event import MessageEvent, MessageType
+from gateway.run import _profile_runtime_scope
+from gateway.run_inbound import GatewayInboundMixin, rehome_inbound_media
+from tools.credential_files import from_agent_visible_cache_path, get_cache_directory_mounts
+
+
+def two_homes(tmp_path, monkeypatch):
+ """Launch home A (HERMES_HOME, local backend) and routed profile B (docker backend)."""
+ a = tmp_path / ".hermes"
+ b = a / "profiles" / "b"
+ b.mkdir(parents=True)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(a))
+ for name, home in (("a", a), ("b", b)):
+ (home / "config.yaml").write_text(
+ yaml.safe_dump({"terminal": {"backend": "local" if name == "a" else "docker"}}), encoding="utf-8")
+ ss.set_multiplex_active(True)
+ yield a, b
+ ss.set_multiplex_active(False)
+
+
+def _adapter_cached(home: Path, kind: str, name: str) -> str:
+ """What an adapter leaves behind: a file under ``<home>/cache/<kind>`` (host path)."""
+ path = home / "cache" / kind / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"%PDF-1.4 x" if kind == "documents" else b"\xff\xd8\xff\xe0 jpeg")
+ return str(path)
+
+
+def test_routed_turn_rehomes_adapter_cached_attachments_a_b_a(two_homes):
+ a, b = two_homes
+ doc, img = _adapter_cached(a, "documents", "doc_0123456789ab_report.pdf"), _adapter_cached(a, "images", "img_1.jpg")
+ event = MessageEvent(text=f"[document 'report.pdf' saved at: {doc}]", message_type=MessageType.DOCUMENT,
+ source=None, media_urls=[doc, img], media_types=["application/pdf", "image/jpeg"])
+
+ with _profile_runtime_scope(b): # routed turn: B's mounts, B's cache roots
+ rehome_inbound_media(event)
+ note = GatewayInboundMixin._prepend_inbound_document_notes(event, "")
+ assert "/root/.hermes/cache/documents/doc_0123456789ab_report.pdf" in note # sandbox form
+ # The sandbox path names a file B's container actually mounts.
+ host = Path(from_agent_visible_cache_path("/root/.hermes/cache/documents/doc_0123456789ab_report.pdf"))
+ assert host.is_file() and host == b / "cache" / "documents" / "doc_0123456789ab_report.pdf"
+ assert {Path(m["host_path"]) for m in get_cache_directory_mounts()} >= {host.parent, (b / "cache" / "images")}
+ assert "/root/.hermes/cache/documents/doc_0123456789ab_report.pdf" in event.text # baked note repointed
+ assert event.media_urls == [str(b / "cache" / "documents" / "doc_0123456789ab_report.pdf"),
+ str(b / "cache" / "images" / "img_1.jpg")]
+ assert not Path(doc).exists() and not Path(img).exists() # moved, not copied: A holds nothing of B's
+ assert (b / "cache" / "images" / "img_1.jpg").is_file()
+
+ # A→B→A: a launch-profile turn keeps its own files where they are (no-op, no bleed into B).
+ doc_a = _adapter_cached(a, "documents", "doc_aaaaaaaaaaaa_own.pdf")
+ own = MessageEvent(text="", message_type=MessageType.DOCUMENT, source=None,
+ media_urls=[doc_a], media_types=["application/pdf"])
+ with _profile_runtime_scope(a):
+ rehome_inbound_media(own)
+ assert own.media_urls == [doc_a] and Path(doc_a).is_file()
+ assert not (b / "cache" / "documents" / "doc_aaaaaaaaaaaa_own.pdf").exists()
+
+
+def test_cache_media_bytes_returns_host_path_and_translates_in_note(two_homes):
+ """``media_urls`` holds ONE coordinate system (host paths, like ``cache_image_from_bytes``); the
+ sandbox translation happens at render time under the scope that owns the turn."""
+ _, b = two_homes
+ with _profile_runtime_scope(b): # docker backend
+ cached = cache_media_bytes(b"%PDF-1.4 x", filename="report.pdf", mime_type="application/pdf")
+ assert Path(cached.path).is_file() and Path(cached.path).parent == b / "cache" / "documents"
+ assert cached.context_note().startswith("[document 'report.pdf' saved at: /root/.hermes/cache/documents/doc_")