Skip to content

The agent that grows with you

fix(cli): resolve agent container paths on the fs and managed file reads

Austin Pickett6af4dff06de5
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 6ec69f1553d..bb18911262f 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -29,7 +29,8 @@ from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
from hermes_cli.web_deps import late
from hermes_cli.web_server_files import (
- _fs_path, _hosted_fs_read_guard, _managed_file_entry, _managed_response_meta, _resolve_managed_path,
+ _agent_fs_path, _fs_path, _hosted_fs_read_guard, _managed_file_entry,
+ _managed_response_meta, _resolve_managed_path,
)
from hermes_cli.web_models import (
ChatImageUpload, FsWriteText, ManagedDirectoryCreate, ManagedFileDelete, ManagedFileUpload,
@@ -159,12 +160,26 @@ def _io_errors(denied: str, failed: str):
raise HTTPException(status_code=500, detail=f"{failed}: {exc}")
+def _fs_docker_active() -> bool:
+ """True when the gateway runs the docker terminal backend (#85238 detail)."""
+ from gateway.platforms.base import _docker_env_active
+
+ return _docker_env_active()
+
+
+def _fs_sandbox_not_found_detail(path: Path) -> str:
+ """Distinguish an untranslated agent-sandbox path from a plain missing file."""
+ if _fs_docker_active() and path.as_posix().startswith("/"):
+ return "File not found on the gateway host: the path may live inside the agent sandbox"
+ return "File not found"
+
+
def _fs_regular_file(path: Path) -> tuple[Path, os.stat_result]:
target = _fs_path(str(path))
try:
st = target.stat()
except (FileNotFoundError, NotADirectoryError):
- raise HTTPException(status_code=404, detail="File not found")
+ raise HTTPException(status_code=404, detail=_fs_sandbox_not_found_detail(target))
except PermissionError:
raise HTTPException(status_code=403, detail="File is not readable")
except OSError as exc:
@@ -537,7 +552,7 @@ def _managed_readable_file(request: Request, path: str) -> tuple[Any, Path, str,
mime_type). Callers own the live-SQLite 409 (held through the read for
/api/files/read, point-in-time for streamed responses)."""
from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES
- policy, target, display_path = _resolve_managed_path(path, request)
+ policy, target, display_path = _resolve_managed_path(path, request, for_agent_read=True)
if not target.exists():
raise HTTPException(status_code=404, detail="File not found")
if not target.is_file():
@@ -768,7 +783,7 @@ async def fs_list(path: str, request: Request, profile: Optional[str] = None):
return await asyncio.to_thread(backend.list_dir, path, _FS_READDIR_HIDDEN)
except Exception as exc:
_raise_fs_backend_error(exc)
- target = _fs_path(path)
+ target = _agent_fs_path(path)
_hosted_fs_read_guard(target, request)
try:
entries = []
@@ -813,7 +828,7 @@ async def fs_read_text(path: str, request: Request = None, profile: Optional[str
"text": data.decode("utf-8", errors="replace"),
"truncated": size > _FS_TEXT_PREVIEW_MAX_BYTES,
}
- target = _fs_path(path)
+ target = _agent_fs_path(path)
_hosted_fs_read_guard(target, request)
target, st = _fs_regular_file(target)
if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES:
@@ -897,12 +912,12 @@ async def _fs_download_path(path: str, profile: Optional[str], session_id: Optio
raise HTTPException(status_code=404, detail="Session not found")
session = await get_session_detail(session_id, profile)
# Validate ownership even for absolute paths; never trust a client cwd.
- return _fs_path(path, cwd=session.get("cwd") or "")
+ return _agent_fs_path(path, cwd=session.get("cwd") or "")
if profile is not None:
from hermes_cli.web_server_cron import _cron_profile_home
_cron_profile_home(profile)
- return _fs_path(path)
+ return _agent_fs_path(path)
@router.get("/api/fs/read-data-url")
diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.py
index da4f8a7d74f..7c3c80f577e 100644
--- a/hermes_cli/web_server_files.py
+++ b/hermes_cli/web_server_files.py
@@ -1,6 +1,7 @@
"""Managed-files policy for the dashboard file browser: root resolution, path containment, entry metadata.
"""
+import logging
import mimetypes
import os
import stat
@@ -10,6 +11,7 @@ from fastapi import HTTPException, Request
from pathlib import Path
from typing import Any, Dict, Optional
+logger = logging.getLogger(__name__)
_MANAGED_FILES_ROOT_ENV = "HERMES_DASHBOARD_FILES_ROOT"
_HOSTED_MANAGED_FILES_ROOT = Path("/opt/data")
@@ -67,6 +69,56 @@ def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = T
raise HTTPException(status_code=400, detail="Invalid path")
+def _agent_container_path(raw: str) -> Path | None:
+ """Map an agent-visible container path to its host bind mount, or None.
+
+ Docker agents emit container paths (``/workspace/...``, ``/root/...``) in
+ transcripts and MEDIA tags, while the dashboard fs routes stat the gateway
+ HOST filesystem (#85238). Reuse the gateway's MEDIA volume translator, and
+ when no terminal scope is bound (``serve --isolated`` after a failed early
+ bridge) retry once under the profile's complete terminal policy, never
+ replacing an already-bound scope or refusal (retry from #104992).
+
+ Runs on the raw string, before host normalization: on a Windows gateway
+ ``Path("/workspace/x").resolve()`` anchors to the current drive and the
+ container path is gone before translation sees it.
+ """
+ if not raw.startswith("/") or raw.startswith("//"):
+ return None
+ try:
+ from gateway.platforms.base import _translate_docker_container_media_path
+
+ candidate = Path(raw)
+ translated = _translate_docker_container_media_path(candidate)
+ if translated is not None:
+ return translated
+
+ from tools.terminal_scope import (
+ build_profile_terminal_scope, get_terminal_scope, reset_terminal_scope,
+ set_terminal_scope,
+ )
+ if get_terminal_scope() is not None:
+ return None
+ from hermes_cli.config import get_hermes_home
+
+ token = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))
+ try:
+ return _translate_docker_container_media_path(candidate)
+ finally:
+ reset_terminal_scope(token)
+ except Exception: # fail open: translation is additive, the host path still serves
+ logger.debug("agent container path translation failed for %s", raw, exc_info=True)
+ return None
+
+
+def _agent_fs_path(raw_path: str, *, cwd: str | None = None) -> Path:
+ """``_fs_path`` for agent-facing reads: container paths resolve to their host
+ mount first, so callers' boundary guards see the real host target. Fails open
+ to the plain host path — translation is additive, not a gate."""
+ translated = _agent_container_path(str(raw_path or "").strip())
+ return translated if translated is not None else _fs_path(raw_path, cwd=cwd)
+
+
def _canonical_path(path: Path, *, require_exists: bool = False) -> Path:
try:
return path.expanduser().resolve(strict=require_exists)
@@ -159,12 +211,21 @@ def _managed_files_policy(request: Optional[Request], *, create_root: bool = Tru
def _resolve_managed_path(
- raw_path: str | None, request: Request, *, for_write: bool = False
+ raw_path: str | None, request: Request, *, for_write: bool = False,
+ for_agent_read: bool = False,
) -> tuple[ManagedFilesPolicy, Path, str]:
policy = _managed_files_policy(request)
text = _path_text(raw_path)
root = policy.locked_root
+ if for_agent_read and text and not text.startswith("file:"):
+ # Agent-emitted container paths (/workspace/...) resolve to their host
+ # bind mount before the root checks, so the locked-root refusal below
+ # still governs the translated target (#85238).
+ translated = _agent_container_path(text)
+ if translated is not None:
+ text = str(translated)
+
if root is not None and (not text or text in {".", "/"}):
candidate = root
elif not text:
diff --git a/tests/hermes_cli/test_web_server_files.py b/tests/hermes_cli/test_web_server_files.py
index 011a81f84fd..864d6ec1259 100644
--- a/tests/hermes_cli/test_web_server_files.py
+++ b/tests/hermes_cli/test_web_server_files.py
@@ -1,6 +1,7 @@
"""Tests for the dashboard-managed file browser API."""
import base64
+import json
from types import SimpleNamespace
import pytest
@@ -247,6 +248,47 @@ def test_stream_rejects_non_media_active_content(forced_files_client):
assert response.status_code == 415
+def test_managed_reads_resolve_docker_mount_inside_locked_root(
+ forced_files_client, monkeypatch,
+):
+ """#85238: the managed read routes must translate a docker container path
+ through the volume translator when its host target sits inside the locked
+ managed root (the hosted /opt/data layout bind-mounts /workspace there)."""
+ client, root = forced_files_client
+ root.mkdir(parents=True, exist_ok=True)
+ (root / "report.txt").write_text("container report", encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{root}:/workspace"]))
+
+ read = client.get("/api/files/read", params={"path": "/workspace/report.txt"})
+ download = client.get("/api/files/download", params={"path": "/workspace/report.txt"})
+ stream = client.get("/api/files/stream", params={"path": "/workspace/report.txt"})
+
+ assert read.status_code == 200, read.text
+ assert base64.b64decode(read.json()["data_url"].split(",", 1)[1]) == b"container report"
+ assert download.status_code == 200, download.text
+ assert download.content == b"container report"
+ # media_only: non-streamable extension 415s — proves resolution reached the file
+ assert stream.status_code == 415
+
+
+def test_managed_reads_reject_docker_mount_outside_locked_root(
+ forced_files_client, monkeypatch, tmp_path,
+):
+ """Translation must not bypass the locked-root refusal: a container path
+ whose host target lives outside the managed root stays 403 (from #85271)."""
+ client, _root = forced_files_client
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "secret.txt").write_text("not managed", encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{outside}:/workspace"]))
+
+ for route in ("/api/files/read", "/api/files/download", "/api/files/stream"):
+ response = client.get(route, params={"path": "/workspace/secret.txt"})
+ assert response.status_code == 403, response.text
+
+
def test_query_token_does_not_authenticate_other_endpoints(forced_files_client):
client, root = forced_files_client
file_path = _seed_file(client, root)
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 1b7693c0a00..5f3a9b3809e 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -1,5 +1,6 @@
import base64
import urllib.parse
+import json
from contextlib import nullcontext
from pathlib import Path
@@ -30,6 +31,25 @@ def client(monkeypatch):
web_server.app.state.auth_required = previous_auth_required
+def docker_volumes(monkeypatch, tmp_path):
+ """Docker backend env whose ``/workspace`` is bind-mounted to a fresh host dir.
+
+ Returns the host dir; writes there are what the agent's ``/workspace/...``
+ paths must resolve to."""
+ host = tmp_path / "host-workspace"
+ host.mkdir()
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{host}:/workspace"]))
+ monkeypatch.delenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", raising=False)
+ monkeypatch.delenv("TERMINAL_CONTAINER_PERSISTENT", raising=False)
+ return host
+
+
+def _no_scope_builder(_home):
+ return {"TERMINAL_ENV": "docker", "TERMINAL_DOCKER_VOLUMES": "[]"}
+
+
def test_fs_list_sorts_and_hides_noise(client, tmp_path):
root = tmp_path / "project"
root.mkdir()
@@ -227,7 +247,7 @@ def test_fs_download_streams_ssh_files_without_preview_cap(client, monkeypatch):
response = client.get(
"/api/fs/download",
- params={"path": "/srv/repos/report.txt", "profile": "remote-dev"},
+ params={"path": "/srv/repos/project/report.txt", "profile": "remote-dev"},
)
assert response.status_code == 200
@@ -390,3 +410,135 @@ def test_fs_write_text_never_decodes_percent_path(client, tmp_path):
assert response.status_code == 200
assert sibling.read_text() == "existing"
assert (tmp_path / "report%20v2.md").read_text() == "new"
[email protected]("endpoint", ["read-text", "read-data-url", "download"])
+def test_fs_reads_translate_docker_workspace_path_to_host(
+ client, docker_volumes, monkeypatch, endpoint,
+):
+ """#85238: an agent in a docker container emits /workspace/... paths; the
+ authenticated fs API runs on the host gateway and must resolve them through
+ the same docker volume translator MEDIA delivery uses."""
+ target = docker_volumes / "generated report.txt"
+ target.write_text("container output", encoding="utf-8")
+
+ response = client.get(f"/api/fs/{endpoint}", params={"path": "/workspace/generated report.txt"})
+
+ assert response.status_code == 200
+ if endpoint == "read-text":
+ assert response.json()["text"] == "container output"
+ elif endpoint == "read-data-url":
+ expected = base64.b64encode(b"container output").decode("ascii")
+ assert response.json()["dataUrl"] == f"data:text/plain;base64,{expected}"
+ else:
+ assert response.text == "container output"
+
+
+def test_fs_reads_translate_after_binding_profile_terminal_scope(client, tmp_path, monkeypatch):
+ """`serve --isolated` reaches these routes with no terminal scope bound, so
+ the first translation attempt sees the launch env only; the retry under the
+ profile's complete terminal policy must find the mount (from #104992)."""
+ target = tmp_path / "isolated report.txt"
+ target.write_text("isolated output", encoding="utf-8")
+
+ from tools.terminal_scope import get_terminal_scope
+
+ def translate(path):
+ if path == Path("/workspace/isolated report.txt") and get_terminal_scope() is not None:
+ return target
+ return None
+
+ monkeypatch.setattr(
+ "gateway.platforms.base._translate_docker_container_media_path", translate,
+ )
+ monkeypatch.setattr("tools.terminal_scope.build_profile_terminal_scope", _no_scope_builder)
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+
+ response = client.get("/api/fs/read-text", params={"path": "/workspace/isolated report.txt"})
+
+ assert response.status_code == 200
+ assert response.json()["text"] == "isolated output"
+ assert get_terminal_scope() is None # the retry's scope never leaks
+
+
+def test_fs_read_untranslated_container_path_names_the_agent_sandbox(
+ client, docker_volumes,
+):
+ """A container-shaped path that fails translation under the docker backend
+ must 404 with the honest sandbox reason, not a bare missing-file 404."""
+ response = client.get("/api/fs/read-text", params={"path": "/workspace/never-written.txt"})
+
+ assert response.status_code == 404
+ assert "agent sandbox" in response.json()["detail"]
+
+
+def test_fs_list_translates_docker_workspace_path_to_host(client, docker_volumes):
+ (docker_volumes / "report.txt").write_text("one", encoding="utf-8")
+ (docker_volumes / "nested").mkdir()
+
+ response = client.get("/api/fs/list", params={"path": "/workspace"})
+
+ assert response.status_code == 200
+ entries = response.json()["entries"]
+ assert [(entry["name"], entry["isDirectory"]) for entry in entries] == [
+ ("nested", True), ("report.txt", False),
+ ]
+ # Children carry the host path so the browser's next read/list works.
+ assert entries[0]["path"] == str(docker_volumes / "nested")
+ assert entries[1]["path"] == str(docker_volumes / "report.txt")
+
+
+def test_fs_download_maps_root_home_to_persistent_sandbox(client, monkeypatch, tmp_path):
+ """#85238 Discord repro: a persistent docker agent writes /root/fileIwant.zip;
+ the host copy lives at <sandbox>/docker/default/home. The download click must
+ serve that file, not stat the gateway's own /root ("File is not readable")."""
+ sandbox = tmp_path / "sandboxes"
+ home = sandbox / "docker" / "default" / "home"
+ home.mkdir(parents=True)
+ (home / "fileIwant.zip").write_bytes(b"PK\x03\x04zip")
+ monkeypatch.setenv("TERMINAL_SANDBOX_DIR", str(sandbox))
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "true")
+ monkeypatch.delenv("TERMINAL_DOCKER_VOLUMES", raising=False)
+
+ response = client.get("/api/fs/download", params={"path": "/root/fileIwant.zip"})
+
+ assert response.status_code == 200
+ assert response.content == b"PK\x03\x04zip"
+
+
+def test_agent_fs_path_translates_before_host_normalization(monkeypatch, tmp_path):
+ """On a Windows gateway ``_fs_path("/workspace/x")`` anchors to the current
+ drive (``D:\\workspace\\x``) and could serve an unrelated host file; the
+ container path must reach the translator verbatim, before normalization."""
+ from hermes_cli import web_server_files
+
+ mapped = tmp_path / "x.txt"
+ seen = []
+
+ def translate(candidate, session_key=""):
+ seen.append(candidate.as_posix())
+ return mapped
+
+ monkeypatch.setattr("gateway.platforms.base._translate_docker_container_media_path", translate)
+
+ def boom(*_a, **_k):
+ raise AssertionError("_fs_path must not run when translation succeeds")
+
+ monkeypatch.setattr(web_server_files, "_fs_path", boom)
+
+ assert web_server_files._agent_fs_path("/workspace/x.txt") == mapped
+ assert seen == ["/workspace/x.txt"]
+
+
+def test_agent_fs_path_leaves_host_paths_to_fs_path(monkeypatch, tmp_path):
+ from hermes_cli import web_server_files
+
+ def translate(*_a, **_k):
+ raise AssertionError("relative/UNC/drive paths are not container paths")
+
+ monkeypatch.setattr("gateway.platforms.base._translate_docker_container_media_path", translate)
+ target = tmp_path / "note.txt"
+ target.write_text("x")
+
+ assert web_server_files._agent_fs_path("note.txt", cwd=str(tmp_path)) == target.resolve()
+ assert web_server_files._agent_container_path("//server/share/x") is None
+ assert web_server_files._agent_container_path("C:/data/x") is None