The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): deliver MEDIA files that live inside a remote terminal sandbox (#466)
Tarek Belkahia70a64db53243
diff --git a/gateway/media_fetch.py b/gateway/media_fetch.pynew file mode 100644index 00000000000..52a44b65211--- /dev/null+++ b/gateway/media_fetch.py@@ -0,0 +1,109 @@+"""Deliver ``MEDIA:<path>`` files that live inside a remote terminal sandbox (#466).++``validate_media_delivery_path`` only accepts files on the gateway host. When the terminal backend+is ssh / modal / daytona / singularity / vercel (or a docker path outside its bind mounts), the+agent's artifact is on another filesystem, so the tag was silently dropped. This module pulls the+file through the active environment's ``fetch_file`` into the document cache (already an+allowlisted delivery root) and hands back the host copy.++The remote path is screened against the same denylist as local deliveries BEFORE any bytes move,+and again after ``readlink -f`` — a remote fetch must never become a bypass of the host denylist.+"""++from __future__ import annotations++import logging+import os+import posixpath+import uuid+from pathlib import Path, PurePosixPath+from typing import Optional++logger = logging.getLogger(__name__)++# Telegram bot uploads cap at 50 MB; the other platforms are in the same range. Mirrors+# tools.image_source._MAX_INGEST_BYTES.+_FETCH_MAX_BYTES = 50 * 1024 * 1024+++def remote_path_is_denied(path: str, remote_home: Optional[str]) -> bool:+ """Pure string check (the remote fs can't be stat'd from here) applying the host denylist to a+ sandbox path: system prefixes, credential dirs under the sandbox home, Hermes credential stores.+ Unknown home ⇒ home-relative entries match ANY path component (conservative)."""+ from gateway.platforms.base import (+ _MEDIA_DELIVERY_DENIED_HOME_SUBPATHS, _MEDIA_DELIVERY_DENIED_PREFIXES, _ROOT_CREDENTIAL_PATHS)++ target = PurePosixPath(posixpath.normpath(path))+ if not target.is_absolute():+ return True+ home = PurePosixPath(posixpath.normpath(remote_home)) if remote_home else None++ def _under(root: PurePosixPath) -> bool:+ return target == root or root in target.parents++ # The sandbox's own home may be a denied system prefix (/root); its credential subpaths are+ # separate, more specific entries — same exception as _path_under_denied_prefix.+ if any(_under(PurePosixPath(p)) for p in _MEDIA_DELIVERY_DENIED_PREFIXES if PurePosixPath(p) != home):+ return True+ home_relative = [PurePosixPath(s) for s in _MEDIA_DELIVERY_DENIED_HOME_SUBPATHS]+ home_relative += [PurePosixPath(".hermes", *PurePosixPath(rel.replace(os.sep, "/")).parts) for rel in _ROOT_CREDENTIAL_PATHS]+ if home is not None:+ return any(_under(home / rel) for rel in home_relative)+ parts = target.parts+ return any(parts[i:i + len(rel.parts)] == rel.parts+ for rel in home_relative for i in range(len(parts) - len(rel.parts) + 1))+++def _active_remote_env():+ """The live remote BaseEnvironment for the current session, or None (local backend / no env yet)."""+ from agent.prompt_builder import _REMOTE_TERMINAL_BACKENDS, _plugin_backend_is_remote+ from gateway.platforms.base import _tenv+ backend = _tenv("TERMINAL_ENV", "local").strip().lower()+ if backend not in _REMOTE_TERMINAL_BACKENDS and not _plugin_backend_is_remote(backend):+ return None+ try:+ from tools.terminal_tool import _current_session_key+ from tools.terminal_tool_lifecycle import get_active_env+ return get_active_env(_current_session_key() or "default")+ except Exception as exc:+ logger.debug("Remote media fetch: no active env: %s", exc)+ return None+++def fetch_remote_media(path: str) -> Optional[str]:+ """Host path of a validated copy of sandbox file ``path``, or None (never raises). Only fires+ when a remote backend is active; the caller has already failed local validation."""+ env = _active_remote_env()+ if env is None:+ return None+ from gateway.platforms.base import DOCUMENT_CACHE_DIR, _log_safe_path, validate_media_delivery_path+ from tools.environments.base import FileFetchError++ remote_home = getattr(env, "_remote_home", None)+ candidate = posixpath.normpath(str(path).strip())+ if candidate == "~" or candidate.startswith("~/"):+ if not remote_home:+ return None+ candidate = posixpath.normpath(posixpath.join(remote_home, candidate[2:]))+ if not candidate.startswith("/") or remote_path_is_denied(candidate, remote_home):+ return None+ try:+ resolved = env.fetch_realpath(candidate) or candidate+ if remote_path_is_denied(resolved, remote_home):+ return None+ basename = "".join(c for c in posixpath.basename(resolved) if c.isprintable() and c not in '/\\:*?"<>|') or "file"+ dest = Path(DOCUMENT_CACHE_DIR) / f"remote_{uuid.uuid4().hex[:12]}_{basename}"+ dest.parent.mkdir(parents=True, exist_ok=True)+ env.fetch_file(resolved, dest, max_bytes=_FETCH_MAX_BYTES)+ except FileFetchError as exc:+ logger.warning("Remote media fetch of %s skipped: %s", _log_safe_path(candidate), exc)+ return None+ except Exception:+ logger.warning("Remote media fetch of %s failed", _log_safe_path(candidate), exc_info=True)+ return None+ validated = validate_media_delivery_path(str(dest))+ if not validated:+ dest.unlink(missing_ok=True)+ return None+ logger.info("Fetched remote media %s from the %s sandbox", _log_safe_path(candidate), type(env).__name__)+ return validateddiff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 6365d5fedc2..f001a9a0b49 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -1132,9 +1132,13 @@ def _log_safe_path(path: str) -> str:def _validated_delivery_path(raw_path, session_key: str, label: str) -> Optional[str]:- """``validate_media_delivery_path`` plus the shared "Skipping unsafe ..." warning."""+ """``validate_media_delivery_path`` plus the shared "Skipping unsafe ..." warning. A path the+ host cannot see is retried against the active remote sandbox (ssh/modal/...; #466)."""raw = str(raw_path)safe_path = validate_media_delivery_path(raw, session_key=session_key)+ if not safe_path:+ from gateway.media_fetch import fetch_remote_media+ safe_path = fetch_remote_media(raw)if not safe_path:logger.warning("Skipping unsafe %s: %s", label, _log_safe_path(raw))return safe_pathdiff --git a/tools/environments/base.py b/tools/environments/base.pyindex 52650a973e4..3a19d63246e 100644--- a/tools/environments/base.py+++ b/tools/environments/base.py@@ -52,6 +52,14 @@ if _DEBUG_INTERRUPT:_activity_callback_local = threading.local()+class FileFetchError(RuntimeError):+ """A file could not be extracted from the backend filesystem."""+++# Pulling a large artifact over a slow exec channel can outlast the per-command terminal timeout.+_FETCH_TIMEOUT_SECONDS = 300++class EnvironmentConnectionError(RuntimeError):"""Infrastructure/connection-class failure of a terminal backend (SSH host down, Dockerdaemon not running, remote sync on a dead link) — never a command that merely exited@@ -183,6 +191,44 @@ class BaseEnvironment(ABC):"""Release backend resources (container, instance, connection)."""...+ # --- File extraction (backend -> host) ---+ def fetch_file(self, remote_path: str, local_dest: Path, *, max_bytes: int) -> None:+ """Copy a regular file out of the backend filesystem to ``local_dest`` on the host.++ One transport for every backend: base64 over the exec channel, bounded INSIDE the sandbox+ (``head -c max+1`` so /dev/zero can't stream unbounded data into host memory — the same+ shape ``tools.image_source`` uses to read sandbox images). The payload is fenced between+ unique markers so login-shell noise in the merged stdout/stderr can't corrupt the decode.+ Raises :class:`FileFetchError` on a missing/unreadable/oversized file.+ """+ import base64+ import binascii+ marker = f"__HERMES_FETCH_{uuid.uuid4().hex[:12]}__"+ quoted = shlex.quote(remote_path)+ # ``[ -f ]`` follows symlinks, so a link to a denied host file is judged by the CALLER on+ # ``readlink -f`` output before any bytes move.+ result = self.execute(+ f"[ -f {quoted} ] && echo {marker} && head -c {max_bytes + 1} < {quoted} | base64 && echo {marker}",+ timeout=_FETCH_TIMEOUT_SECONDS, rewrite_compound_background=False)+ output = result.get("output") or ""+ first, last = output.find(marker), output.rfind(marker)+ if int(result.get("returncode") or 0) != 0 or first == -1 or last <= first:+ raise FileFetchError(f"could not read {remote_path!r} in the sandbox (missing, not a regular file, or unreadable)")+ try:+ data = base64.b64decode("".join(output[first + len(marker):last].split()), validate=True)+ except (ValueError, binascii.Error) as exc:+ raise FileFetchError(f"transfer of {remote_path!r} was corrupted in transit: {exc}") from exc+ if len(data) > max_bytes:+ raise FileFetchError(f"{remote_path!r} exceeds the {max_bytes // (1024 * 1024)} MB delivery limit")+ Path(local_dest).write_bytes(data)++ def fetch_realpath(self, remote_path: str) -> str | None:+ """``readlink -f`` inside the backend, or None when it cannot be resolved."""+ result = self.execute(f"readlink -f {shlex.quote(remote_path)} 2>/dev/null", rewrite_compound_background=False)+ if int(result.get("returncode") or 0) != 0:+ return None+ return next((ln.strip() for ln in reversed((result.get("output") or "").splitlines()) if ln.strip().startswith("/")), None)+# --- Session snapshot (init_session) ---def _additional_profile_scoped_passthrough_names(self) -> Iterable[str]:"""Return backend-specific names that must not persist in snapshots."""