Skip to content

The agent that grows with you

fix(gateway): deliver and bound-sync generated media in cache/generated

kshitijk4poor266499524ef2
diff --git a/agent/image_gen_provider.py b/agent/image_gen_provider.py
index 23911c4efc9..00046756e4d 100644
--- a/agent/image_gen_provider.py
+++ b/agent/image_gen_provider.py
@@ -75,10 +75,7 @@ def normalize_reference_images(value: Any) -> Optional[List[str]]:
return [item.strip() for item in value if isinstance(item, str) and item.strip()] or None
-# Generated deliverables live in ``cache/generated/<media>/``, OUTSIDE the
-# transient inbound caches the gateway housekeeping sweeps after 24h (#126445):
-# for base64-returning providers the cached file is the ONLY copy of the image.
-_GENERATED_IMAGE_KIND = "generated/images"
+_GENERATED_IMAGE_KIND = f"{provider_media.GENERATED_SUBDIR}/images"
def save_b64_image(b64_data: str, *, prefix: str = "image", extension: str = "png") -> Path:
diff --git a/agent/pet/generate/orchestrate.py b/agent/pet/generate/orchestrate.py
index 9175064edec..073ed9d94a3 100644
--- a/agent/pet/generate/orchestrate.py
+++ b/agent/pet/generate/orchestrate.py
@@ -75,7 +75,7 @@ def _harden_transparency(path: Path) -> Path:
out = path if path.suffix.lower() == ".png" else path.with_suffix(".png")
keyed.save(out, format="PNG")
if out != path:
- _unlink_quietly(path) # nothing else prunes cache/generated/images outside the gateway loop
+ _unlink_quietly(path) # nothing prunes cache/generated/images, so drop it now
return out
except Exception as exc: # noqa: BLE001 - cosmetic; fall back to the raw image
logger.debug("base draft transparency hardening failed for %s: %s", path, exc)
@@ -199,7 +199,7 @@ def _generate_row(spec: tuple[str, int, int], *, base: Path, label: str, style:
logger.warning("pet hatch %r: row %r attempt %d/%d failed: %s", slug, state, attempt + 1, _ROW_GEN_ATTEMPTS, exc)
finally:
# Strips are intermediates already decoded into memory; nothing
- # prunes cache/generated/images outside the gateway loop, so drop them now.
+ # prunes cache/generated/images, so drop them now.
for strip in strips:
_unlink_quietly(Path(strip))
logger.warning("pet hatch %r: row %r gave up after %.1fs: %s", slug, state, time.monotonic() - t0, last_exc)
diff --git a/agent/provider_media.py b/agent/provider_media.py
index 866ee68f78f..8fc5aa80256 100644
--- a/agent/provider_media.py
+++ b/agent/provider_media.py
@@ -16,6 +16,14 @@ from pathlib import Path
from typing import Dict, Optional, Tuple
from urllib.parse import urljoin
+# Generated deliverables live in ``cache/generated/<media>/``, OUTSIDE the transient
+# inbound caches the gateway housekeeping sweeps (#126445): for base64-returning
+# providers the cached file is the ONLY copy of the output.
+GENERATED_SUBDIR = "generated"
+# Age (hours) past which the gateway sweeps transient media caches; remote sync of the
+# unswept ``cache/generated`` tree uses the same window so it stays bounded.
+MEDIA_CACHE_MAX_AGE_HOURS = 24
+
_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}
_MAX_SAVE_URL_REDIRECTS = 5
diff --git a/agent/video_gen_provider.py b/agent/video_gen_provider.py
index dfe18adf6e8..25b64a8e9bf 100644
--- a/agent/video_gen_provider.py
+++ b/agent/video_gen_provider.py
@@ -69,10 +69,7 @@ class VideoGenProvider(CatalogProviderBase):
pass; providers that honor it report ``upscaled: True`` in ``extra``."""
-# Generated deliverables live in ``cache/generated/<media>/``, OUTSIDE the
-# transient inbound caches the gateway housekeeping sweeps after 24h (#126445):
-# for base64-returning providers the cached file is the ONLY copy of the video.
-_GENERATED_VIDEO_KIND = "generated/videos"
+_GENERATED_VIDEO_KIND = f"{provider_media.GENERATED_SUBDIR}/videos"
def save_b64_video(b64_data: str,*, prefix: str="video", extension: str="mp4") -> Path:
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 8d7950cc2e8..5e2adf5bd67 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -434,6 +434,7 @@ from hermes_cli.observability.shared_metrics_gateway import records_delivery, st
from gateway.session import SessionSource, build_session_key
from gateway.session_transcript import TranscriptReadError
from hermes_constants import get_default_hermes_root, get_hermes_dir, get_hermes_home
+from agent.provider_media import GENERATED_SUBDIR, MEDIA_CACHE_MAX_AGE_HOURS
if TYPE_CHECKING:
from agent.display import ToolPreview
@@ -599,7 +600,7 @@ def _cache_dir_accessors(kind: str, constant_name: str, new_subpath: str, old_na
_secure_media_cache_dir(d)
return d
- def cleanup(max_age_hours: int = 24) -> int:
+ def cleanup(max_age_hours: int = MEDIA_CACHE_MAX_AGE_HOURS) -> int:
return _cleanup_cache_dir(get_dir(), max_age_hours)
get_dir.__name__ = get_dir.__qualname__ = f"get_{kind}_cache_dir"
cleanup.__name__ = cleanup.__qualname__ = f"cleanup_{kind}_cache"
@@ -810,7 +811,8 @@ MEDIA_DELIVERY_TRUST_RECENT_SECONDS_ENV = "HERMES_MEDIA_TRUST_RECENT_SECONDS"
# credential / system paths). Set true on public-facing gateways.
MEDIA_DELIVERY_STRICT_ENV = "HERMES_MEDIA_DELIVERY_STRICT"
# Canonical cache subdirs of deliverable artifacts; also enumerates per-profile cache roots.
-_MEDIA_DELIVERY_CACHE_SUBDIRS = ("images", "audio", "videos", "documents", "screenshots")
+_MEDIA_DELIVERY_CACHE_SUBDIRS = (
+ "images", "audio", "videos", "documents", "screenshots", GENERATED_SUBDIR)
MEDIA_DELIVERY_SAFE_ROOTS = (
IMAGE_CACHE_DIR, AUDIO_CACHE_DIR, VIDEO_CACHE_DIR, DOCUMENT_CACHE_DIR, SCREENSHOT_CACHE_DIR,
*(_HERMES_HOME / d for d in (
diff --git a/tests/agent/test_generated_media_durable.py b/tests/agent/test_generated_media_durable.py
index d2bea97ea6c..bf502cb1718 100644
--- a/tests/agent/test_generated_media_durable.py
+++ b/tests/agent/test_generated_media_durable.py
@@ -25,6 +25,10 @@ from pathlib import Path
import pytest
+from agent.image_gen_provider import save_b64_image
+from agent.video_gen_provider import save_b64_video
+from gateway.platforms import base
+
PNG_1PX = bytes.fromhex(
"89504e470d0a1a0a0000000d49484452000000010000000108020000009077"
"53de00000010494441547801635c0e000000feff03000006000557bfabd400"
@@ -38,32 +42,33 @@ def _backdate_hours(path, hours: float = 25.0) -> None:
@pytest.mark.parametrize(
- "writer, sweeper",
- [
- ("agent.image_gen_provider:save_b64_image", "cleanup_image_cache"),
- ("agent.video_gen_provider:save_b64_video", "cleanup_video_cache"),
- ],
+ "save, sweeper",
+ [(save_b64_image, base.cleanup_image_cache), (save_b64_video, base.cleanup_video_cache)],
ids=["image", "video"],
)
-def test_old_generated_media_is_not_swept(tmp_path, monkeypatch, writer, sweeper):
- import importlib
-
- from gateway.platforms import base
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- mod, fn = writer.split(":")
- save = getattr(importlib.import_module(mod), fn)
+def test_old_generated_media_is_not_swept(tmp_path, monkeypatch, save, sweeper):
+ # Profile home so the check-time per-profile cache roots (built from
+ # _MEDIA_DELIVERY_CACHE_SUBDIRS) cover it; the import-time roots do not.
+ home = tmp_path / "profiles" / "p"
+ home.mkdir(parents=True)
+ monkeypatch.setattr(base, "_HERMES_ROOT", tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
path = save(base64.b64encode(PNG_1PX).decode(), prefix="red_test")
_backdate_hours(path)
- removed = getattr(base, sweeper)(max_age_hours=24)
+ removed = sweeper(max_age_hours=24)
assert path.exists(), f"25h-old generated media was swept ({removed} removed): {path}"
+ # Still deliverable on a strict gateway with recency trust off: only the
+ # cache allowlist can vouch for a day-old file.
+ monkeypatch.setenv("HERMES_MEDIA_DELIVERY_STRICT", "1")
+ monkeypatch.setenv("HERMES_MEDIA_TRUST_RECENT_FILES", "0")
+ assert base.validate_media_delivery_path(str(path)) == str(path.resolve())
+
def test_generated_dir_is_mounted_from_the_writers_location(tmp_path, monkeypatch):
"""Out-of-sweep is only half the job: remote backends must still see the file."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- from agent.image_gen_provider import save_b64_image
from tools.credential_files import get_cache_directory_mounts
path = save_b64_image(base64.b64encode(PNG_1PX).decode(), prefix="red_test")
diff --git a/tests/tools/test_credential_files.py b/tests/tools/test_credential_files.py
index 63bb3854a15..992147c2f5d 100644
--- a/tests/tools/test_credential_files.py
+++ b/tests/tools/test_credential_files.py
@@ -1,6 +1,7 @@
"""Tests for credential file passthrough and skills directory mounting."""
import os
+import time
from pathlib import Path
from unittest.mock import patch
@@ -581,12 +582,20 @@ class TestIterCacheFiles:
doc_dir.mkdir(parents=True)
(doc_dir / "upload.zip").write_bytes(b"PK\x03\x04")
(doc_dir / "report.pdf").write_bytes(b"%PDF-1.4")
+ old = time.time() - 25 * 3600
+ os.utime(doc_dir / "report.pdf", (old, old))
+ # cache/generated is never swept: sync only its last-24h files (#126445).
+ gen_dir = hermes_home / "cache" / "generated" / "images"
+ gen_dir.mkdir(parents=True)
+ (gen_dir / "fresh.png").write_bytes(b"\x89PNG")
+ (gen_dir / "stale.png").write_bytes(b"\x89PNG")
+ os.utime(gen_dir / "stale.png", (old, old))
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
entries = iter_cache_files()
names = {Path(e["container_path"]).name for e in entries}
- assert "upload.zip" in names
- assert "report.pdf" in names
+ assert {"upload.zip", "report.pdf", "fresh.png"} <= names
+ assert "stale.png" not in names
@pytest.mark.require_symlinks
def test_skips_symlinks(self, tmp_path, monkeypatch):
diff --git a/tools/credential_files.py b/tools/credential_files.py
index 66b256a1522..fedd79f806d 100644
--- a/tools/credential_files.py
+++ b/tools/credential_files.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import logging
import os
import posixpath
+import time
from contextvars import ContextVar
from pathlib import Path
from typing import Callable, Dict, Iterator, List, Optional, Tuple
@@ -17,6 +18,7 @@ from typing import Callable, Dict, Iterator, List, Optional, Tuple
from hermes_cli.config import cfg_get
from hermes_constants import get_hermes_dir, get_hermes_home
+from agent.provider_media import GENERATED_SUBDIR, MEDIA_CACHE_MAX_AGE_HOURS
from agent.skill_utils import EXCLUDED_SKILL_DIRS
try: # pragma: no cover - exercised via the fail-closed test below
@@ -241,6 +243,7 @@ def iter_skills_files(container_base: str = "/root/.hermes") -> List[Dict[str, s
# --- Cache directory mounts (documents, images, audio, videos, screenshots) ---
# (new_subpath, old_name) pairs matching hermes_constants.get_hermes_dir().
+_GENERATED_CACHE = f"cache/{GENERATED_SUBDIR}"
_CACHE_DIRS: list[tuple[str, str]] = [
("cache/documents", "document_cache"),
("cache/images", "image_cache"),
@@ -250,12 +253,9 @@ _CACHE_DIRS: list[tuple[str, str]] = [
("cache/web", "web_cache"),
("cache/delegation", "delegation_cache"),
("cache/spillover", "cache/spillover"), # oversized tool results; host side is canonical
- # Generated image/video deliverables (#126445). They are deliberately kept
- # out of the swept inbound caches above, so they need their own mount/sync
- # entry — without it Docker/SSH/Modal backends never see the file and the
- # provider result loses ``agent_visible_image``. No legacy alias exists, so
- # both tuple slots match. Parent entry: covers every generated media kind.
- ("cache/generated", "cache/generated"),
+ # Unswept generated image/video deliverables (#126445) need their own mount/sync
+ # entry or remote backends never see them. No legacy alias exists.
+ (_GENERATED_CACHE, _GENERATED_CACHE),
# Flat top-level desktop staging dirs (tui_gateway attach RPCs; no legacy alias),
# mounted so vision/file tools in sandboxes reach uploads and dropped files.
# Mount it so vision can reach uploads inside sandbox containers (#69575). No legacy alias exists, so
@@ -385,11 +385,23 @@ def to_agent_visible_cache_path(host_path: str, container_base: str = "/root/.he
return mapped if mapped is not None else host_path
+def _recent_enough(item: Path, cutoff: Optional[float]) -> bool:
+ try:
+ return cutoff is None or item.stat().st_mtime >= cutoff
+ except OSError:
+ return False
+
+
def iter_cache_files(container_base: str = "/root/.hermes") -> List[Dict[str, str]]:
- """Per-file cache entries (Modal upload/resync); skips symlinks."""
+ """Per-file cache entries (Modal upload/resync); skips symlinks. ``cache/generated`` is
+ never swept, so only its files from the last ``MEDIA_CACHE_MAX_AGE_HOURS`` are synced —
+ otherwise every remote sync would re-walk and upload the whole generation history."""
+ generated_cutoff = time.time() - MEDIA_CACHE_MAX_AGE_HOURS * 3600
+ base = container_base.rstrip("/")
return [_mount(item, f"{root}/{item.relative_to(host_dir)}")
for host_dir, root in _cache_dir_roots(container_base, create_missing=False)
- for item in host_dir.rglob("*") if not item.is_symlink() and item.is_file()]
+ for item in host_dir.rglob("*") if not item.is_symlink() and item.is_file()
+ and _recent_enough(item, generated_cutoff if root == f"{base}/{_GENERATED_CACHE}" else None)]
def clear_credential_files() -> None: