Skip to content

The agent that grows with you

fix(cli): classify unmapped container paths in the requested profile's scope

Austin Pickett5c7615824f63
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 8d86c9032f3..5605dd1b93b 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -160,17 +160,18 @@ def _io_errors(denied: str, failed: str):
raise HTTPException(status_code=500, detail=f"{failed}: {exc}")
-def _fs_sandbox_not_found_detail(path: Path) -> str:
+def _fs_sandbox_not_found_detail(path: Path, profile_home: Optional[Path] = None) -> str:
"""Distinguish an untranslated agent-sandbox path from a plain missing file."""
- return SANDBOX_NOT_FOUND if _is_unmapped_container_path(path.as_posix()) else "File not found"
+ unmapped = _is_unmapped_container_path(path.as_posix(), profile_home=profile_home)
+ return SANDBOX_NOT_FOUND if unmapped else "File not found"
-def _fs_regular_file(path: Path) -> tuple[Path, os.stat_result]:
+def _fs_regular_file(path: Path, profile_home: Optional[Path] = None) -> tuple[Path, os.stat_result]:
target = _fs_path(str(path))
try:
st = target.stat()
except (FileNotFoundError, NotADirectoryError):
- raise HTTPException(status_code=404, detail=_fs_sandbox_not_found_detail(target))
+ raise HTTPException(status_code=404, detail=_fs_sandbox_not_found_detail(target, profile_home))
except PermissionError:
raise HTTPException(status_code=403, detail="File is not readable")
except OSError as exc:
@@ -819,9 +820,10 @@ 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 = _agent_fs_path(path, profile_home=_fs_profile_home(profile))
+ profile_home = _fs_profile_home(profile)
+ target = _agent_fs_path(path, profile_home=profile_home)
_hosted_fs_read_guard(target, request)
- target, st = _fs_regular_file(target)
+ target, st = _fs_regular_file(target, profile_home)
if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
data = await asyncio.to_thread(
@@ -938,7 +940,7 @@ async def fs_read_data_url(
return {"dataUrl": f"data:{_fs_mime_type(Path(target))};base64,{encoded}"}
target = await _fs_download_path(path, profile, session_id)
_hosted_fs_read_guard(target, request)
- target, st = _fs_regular_file(target)
+ target, st = _fs_regular_file(target, _fs_profile_home(profile))
if st.st_size > _FS_DATA_URL_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
encoded = await asyncio.to_thread(
@@ -968,7 +970,7 @@ async def fs_download(
)
target = await _fs_download_path(path, profile, session_id)
_hosted_fs_read_guard(target, request)
- target, _st = _fs_regular_file(target)
+ target, _st = _fs_regular_file(target, _fs_profile_home(profile))
await asyncio.to_thread(_refuse_live_database, target)
return FileResponse(
path=str(target),
diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.py
index ba975816f0e..b759412bd16 100644
--- a/hermes_cli/web_server_files.py
+++ b/hermes_cli/web_server_files.py
@@ -6,10 +6,11 @@ import mimetypes
import os
import stat
import urllib.request
+from contextlib import contextmanager
from dataclasses import dataclass
from fastapi import HTTPException, Request
from pathlib import Path
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Iterator, Optional
logger = logging.getLogger(__name__)
@@ -84,19 +85,51 @@ def _translate_agent_path(candidate: Path) -> Path | None:
return _translate_docker_container_media_path(candidate, quiet=True)
+@contextmanager
+def _agent_path_scope(profile_home: Path | None = None) -> Iterator[None]:
+ """Bind the profile whose sandbox a container path names: its home and its terminal policy.
+
+ A requested ``profile_home`` other than the current home binds that home and its complete
+ terminal policy, as MEDIA delivery does (#109024). A home already bound by the caller (a
+ native profile ticket's override) gets its own terminal policy when no scope is bound, so
+ translation never reads the launch profile's ambient ``TERMINAL_DOCKER_VOLUMES``. An
+ override naming the launch home keeps the ambient env, which may carry env-only policy.
+ Translation and the unmapped-path classification both run inside this scope, so they
+ agree about the backend.
+ """
+ from hermes_cli.config import get_hermes_home
+ from hermes_constants import (
+ get_hermes_home_override, get_process_hermes_home, reset_hermes_home_override,
+ set_hermes_home_override,
+ )
+ from tools.terminal_scope import get_terminal_scope, install_profile_terminal_scope, reset_terminal_scope
+
+ home_token = scope_token = None
+ if profile_home is not None and Path(profile_home).resolve() != get_hermes_home().resolve():
+ home_token = set_hermes_home_override(str(profile_home))
+ try:
+ foreign_override = (get_hermes_home_override() is not None
+ and get_hermes_home().resolve() != get_process_hermes_home().resolve())
+ if home_token is not None or (foreign_override and get_terminal_scope() is None):
+ scope_token = install_profile_terminal_scope(get_hermes_home())
+ yield
+ finally:
+ if scope_token is not None:
+ reset_terminal_scope(scope_token)
+ if home_token is not None:
+ reset_hermes_home_override(home_token)
+
+
def _agent_container_path(raw: str, *, profile_home: Path | None = None) -> 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.
-
- ``profile_home`` (a request's ``profile``) binds that profile's home and
- terminal policy, as MEDIA delivery does (#109024), so its sandbox and mounts
- are used rather than the active profile's. Without one, when no terminal
- scope is bound (``serve --isolated`` after a failed early bridge), retry once
- under the active profile's complete terminal policy, never replacing an
- already-bound scope or refusal (retry from #104992).
+ HOST filesystem (#85238). Reuse the gateway's MEDIA volume translator inside
+ ``_agent_path_scope(profile_home)``. When no terminal scope is bound even
+ then (``serve --isolated`` after a failed early bridge), retry once under the
+ current 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
@@ -107,29 +140,20 @@ def _agent_container_path(raw: str, *, profile_home: Path | None = None) -> Path
return None
try:
from hermes_cli.config import get_hermes_home
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
from tools.terminal_scope import (
- build_profile_terminal_scope, get_terminal_scope, install_and_reset_profile_terminal_scope,
- reset_terminal_scope, set_terminal_scope,
+ build_profile_terminal_scope, get_terminal_scope, reset_terminal_scope, set_terminal_scope,
)
candidate = Path(raw)
- if profile_home is not None and Path(profile_home).resolve() != get_hermes_home().resolve():
- home_token = set_hermes_home_override(str(profile_home))
+ with _agent_path_scope(profile_home):
+ translated = _translate_agent_path(candidate)
+ if translated is not None or get_terminal_scope() is not None:
+ return translated
+ token = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))
try:
- with install_and_reset_profile_terminal_scope(profile_home):
- return _translate_agent_path(candidate)
+ return _translate_agent_path(candidate)
finally:
- reset_hermes_home_override(home_token)
-
- translated = _translate_agent_path(candidate)
- if translated is not None or get_terminal_scope() is not None:
- return translated
- token = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))
- try:
- return _translate_agent_path(candidate)
- finally:
- reset_terminal_scope(token)
+ 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
@@ -159,23 +183,25 @@ def _agent_fs_path(
translated = _agent_container_path(raw, profile_home=profile_home)
if translated is not None:
return translated
- if _is_unmapped_container_path(raw):
+ if _is_unmapped_container_path(raw, profile_home=profile_home):
raise HTTPException(status_code=404, detail=SANDBOX_NOT_FOUND)
return _fs_path(raw_path, cwd=cwd)
-def _is_unmapped_container_path(raw: str) -> bool:
+def _is_unmapped_container_path(raw: str, *, profile_home: Path | None = None) -> bool:
"""A docker-backend container path (``/workspace``, ``/root`` or a configured
- volume target) rather than a host path or a typo elsewhere on the host."""
+ volume target) rather than a host path or a typo elsewhere on the host. Reads
+ the backend and volumes in the same profile scope translation used."""
if not raw.startswith("/") or raw.startswith("//"):
return False
try:
from gateway.platforms.base import _docker_env_active, _parse_docker_volume_mounts
from tools.environments.local import _msys_to_windows_path
- if not _docker_env_active() or _msys_to_windows_path(raw) != raw:
- return False
- roots = {"/workspace", "/root", *(c.as_posix() for _, c in _parse_docker_volume_mounts())}
+ with _agent_path_scope(profile_home):
+ if not _docker_env_active() or _msys_to_windows_path(raw) != raw:
+ return False
+ roots = {"/workspace", "/root", *(c.as_posix() for _, c in _parse_docker_volume_mounts())}
except Exception: # a refusal scope or import failure: just skip the hint
logger.debug("container path classification failed for %s", raw, exc_info=True)
return False
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 5cf693e1d2c..2a7cb7872d7 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -634,6 +634,71 @@ def test_fs_reads_accept_profile_current_for_host_files(client, tmp_path):
assert listing.status_code == 200, (selector, listing.text)
+def _two_profile_homes(monkeypatch, tmp_path, *, active_backend, work_backend):
+ """Default + ``work`` homes with their own ``terminal.backend``; returns (default, work)."""
+ from hermes_cli import profiles
+
+ default_home = tmp_path / "default-home"
+ work_home = default_home / "profiles" / "work"
+ for home, backend in ((default_home, active_backend), (work_home, work_backend)):
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(
+ f"terminal:\n backend: {backend}\n container_persistent: false\n", encoding="utf-8")
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
+ monkeypatch.setenv("HERMES_HOME", str(default_home))
+ monkeypatch.setenv("TERMINAL_ENV", active_backend)
+ monkeypatch.delenv("TERMINAL_DOCKER_VOLUMES", raising=False)
+ return default_home, work_home
+
+
[email protected](("active", "work", "expected"), [
+ ("local", "docker", True), # requested docker profile: a miss is a sandbox path
+ ("docker", "local", False), # requested local profile: never the sandbox 404
+])
+def test_unmapped_classification_uses_requested_profiles_backend(
+ monkeypatch, tmp_path, active, work, expected,
+):
+ """The Windows 404-or-drive decision and the sandbox hint read the same profile
+ translation used, in both mixed-backend directions."""
+ from hermes_cli import web_server_files
+
+ _default, work_home = _two_profile_homes(
+ monkeypatch, tmp_path, active_backend=active, work_backend=work)
+
+ assert web_server_files._is_unmapped_container_path(
+ "/workspace/x.txt", profile_home=work_home) is expected
+ assert web_server_files._is_unmapped_container_path("/workspace/x.txt") is (active == "docker")
+
+
+def test_native_home_override_translates_with_that_profiles_volumes(monkeypatch, tmp_path):
+ """A native ticket binds the profile's home before the route runs; translation must
+ install that profile's terminal policy, not read the launch env's volumes."""
+ from hermes_cli import web_server_files
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ _default, work_home = _two_profile_homes(
+ monkeypatch, tmp_path, active_backend="docker", work_backend="docker")
+ launch_mount = tmp_path / "launch-mount"
+ work_mount = tmp_path / "work-mount"
+ for mount, label in ((launch_mount, "LAUNCH"), (work_mount, "WORK")):
+ mount.mkdir()
+ (mount / "native.txt").write_text(label, encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{launch_mount}:/workspace"]))
+ (work_home / "config.yaml").write_text(
+ "terminal:\n backend: docker\n container_persistent: false\n"
+ f" docker_volumes:\n - {work_mount}:/workspace\n", encoding="utf-8")
+
+ token = set_hermes_home_override(str(work_home))
+ try:
+ translated = web_server_files._agent_container_path("/workspace/native.txt")
+ finally:
+ reset_hermes_home_override(token)
+
+ assert translated == (work_mount / "native.txt").resolve()
+ assert web_server_files._agent_container_path("/workspace/native.txt") == (
+ launch_mount / "native.txt").resolve()
+
+
def test_fs_read_plain_host_path_logs_no_docker_media_warning(client, docker_volumes, tmp_path, caplog):
"""fs routes see ordinary host paths constantly; misses are not MEDIA warnings."""
plain = tmp_path / "plain.txt"