The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): resolve a cwd-mounted session's /workspace in its own workspace
unsupportedpastelscdf1091ffc15
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex a2e679c96cb..6ec8dfb8737 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -1004,13 +1004,13 @@ def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: strdef _translate_docker_container_media_path(- candidate: Path, session_key: str = "", workspace_key: str = "", *, quiet: bool = False,+ candidate: Path, session_key: str = "", workspace_key: str = "", *, quiet: bool = False, workspace_cwd: str = "",) -> Optional[Path]:"""Container-absolute path -> host path via longest-prefix match over ``docker_volumes``, theauto-mounted cache dirs (``/root/.hermes/...``), persistent ``/workspace`` and ``/root``.- ``workspace_key`` is the 16-hex digest of one session's host cwd. It selects that- session's ``<base>:ws:<digest>`` sandbox and is empty for MEDIA delivery.+ ``workspace_key`` is the 16-hex digest of one session's host cwd ``workspace_cwd`` (its cwd+ mount). It selects that session's ``<base>:ws:<digest>`` sandbox and is empty for MEDIA delivery."""if not candidate.as_posix().startswith("/"): # POSIX even on Windows gateways (not is_absolute)return None@@ -1029,7 +1029,7 @@ def _translate_docker_container_media_path(if "/workspace" not in mounted:mounts.extend((root, Path("/workspace"))- for root in _default_docker_workspace_host_roots(session_key, workspace_key))+ for root in _default_docker_workspace_host_roots(session_key, workspace_key, workspace_cwd))# Synthetic /root mounts catch stray home writes (/root/out.png; cache mounts are longer# prefixes). /root/.hermes/* that missed a cache mount is the container's credential surface —# translating it via the home mount would dodge the host denylist.diff --git a/gateway/platforms/docker_media_paths.py b/gateway/platforms/docker_media_paths.pyindex 0cdf8f7be26..2034a397541 100644--- a/gateway/platforms/docker_media_paths.py+++ b/gateway/platforms/docker_media_paths.py@@ -75,9 +75,9 @@ def _docker_persistent_sandbox_roots(return []-def _mounted_workspace_cwd() -> list[Path]:+def _mounted_workspace_cwd(workspace_cwd: str = "") -> list[Path]:tenv, _truthy, _persistent = _scope()- cwd = tenv("TERMINAL_CWD") or os.getcwd()+ cwd = workspace_cwd or tenv("TERMINAL_CWD") or os.getcwd()try:host = Path(os.path.expanduser(cwd)).resolve(strict=False)except (OSError, RuntimeError, ValueError):@@ -85,15 +85,35 @@ def _mounted_workspace_cwd() -> list[Path]:return [host] if host.is_dir() else []+def _session_mounted_workspace(workspace_key: str, workspace_cwd: str) -> list[Path]:+ """The host dir a session bound to a workspace mounts at ``/workspace``, or nothing.++ A gateway turn runs with the session's own cwd as ``TERMINAL_CWD``+ (``gateway.session_policy.build_policy``), and that cwd is also what+ ``bind_turn_workspace`` registers and hashes into ``workspace_key``. So the+ mount is that cwd, never the profile's ``terminal.cwd``. A cwd whose digest+ is not ``workspace_key`` names some other container's mount: no root.+ """+ from tools.terminal_tool import workspace_key_for++ cwd = (workspace_cwd or "").strip()+ if not cwd or "\0" in cwd or not os.path.isabs(os.path.expanduser(cwd)):+ return []+ if workspace_key_for(cwd) != workspace_key:+ return []+ return _mounted_workspace_cwd(cwd)++def _default_docker_workspace_host_roots(- session_key: str = "", workspace_key: str = "",+ session_key: str = "", workspace_key: str = "", workspace_cwd: str = "",) -> list[Path]:"""Host dirs that stand in for ``/workspace``.A cwd mount is tried first. With no workspace digest that mount is the- only candidate, so MEDIA delivery (which has no session) stays cwd-only.- A download that names a digest also tries that session's sandbox after- the mount: the container key can be ``default:ws:<digest>`` while+ profile's cwd and the only candidate, so MEDIA delivery (which has no+ session) stays cwd-only. A download that names a digest mounts that+ session's own cwd (``workspace_cwd``) instead, then tries that session's+ sandbox: the container key can be ``default:ws:<digest>`` while``/workspace`` is still the sandbox directory, because the host cwd wasnot bind-mounted when the container was created."""@@ -103,9 +123,9 @@ def _default_docker_workspace_host_roots(roots: list[Path] = []mounted = tenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in truthyif mounted:- roots.extend(_mounted_workspace_cwd())if not _WORKSPACE_KEY_RE.fullmatch(workspace_key or ""):- return roots+ return _mounted_workspace_cwd()+ roots.extend(_session_mounted_workspace(workspace_key, workspace_cwd))for root in _docker_persistent_sandbox_roots(session_key, "workspace", workspace_key):if root not in roots:roots.append(root)diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex e1e07bd4f42..1f015c2f21d 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -37,8 +37,9 @@ from hermes_cli.web_server_remote_media import remote_media_responsefrom hermes_cli.web_upload_limit import CHAT_IMAGE_MAX_BYTESfrom hermes_cli.web_server_surface import route_onfrom hermes_cli.web_server_files import (- SANDBOX_NOT_FOUND, _agent_fs_path, _file_url_path, _fs_path, _hosted_fs_read_guard, _is_unmapped_container_path,- _managed_file_entry, _managed_response_meta, _resolve_managed_path, _session_workspace_key,+ SANDBOX_NOT_FOUND, _agent_fs_path, _agent_path_scope, _file_url_path, _fs_path, _hosted_fs_read_guard,+ _is_unmapped_container_path, _managed_file_entry, _managed_response_meta, _resolve_managed_path,+ _session_workspace,)from hermes_cli.web_models import (ChatImageUpload, FileTicketRequest, FsWriteText, ManagedDirectoryCreate, ManagedFileDelete,@@ -1144,10 +1145,12 @@ async def _fs_download_path(session = await _fs_owned_session(session_id, profile)# Validate ownership even for absolute paths; never trust a client cwd.cwd = (session or {}).get("cwd") or ""+ # The profile's scope qualifies the key its turns registered the session's workspace under.+ with _agent_path_scope(profile_home):+ workspace_key, workspace_cwd = _session_workspace(session_id, cwd)return _agent_fs_path(- path, cwd=cwd, profile_home=profile_home,- workspace_key=_session_workspace_key(session_id, cwd), decode_fallback=decode_fallback,- own_sandbox_only=own_sandbox_only,+ path, cwd=cwd, profile_home=profile_home, workspace_key=workspace_key,+ workspace_cwd=workspace_cwd, decode_fallback=decode_fallback, own_sandbox_only=own_sandbox_only,)return _agent_fs_path(path, profile_home=profile_home, decode_fallback=decode_fallback)diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.pyindex 01757b1a084..06f07f7a687 100644--- a/hermes_cli/web_server_files.py+++ b/hermes_cli/web_server_files.py@@ -108,25 +108,28 @@ def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = T_WORKSPACE_KEY_RE = re.compile(r"^[0-9a-f]{16}$")-def _session_workspace_key(session_id: str, cwd: str | None) -> str:- """16-hex digest of this session's per-workspace Docker sandbox, or ``""``.+def _session_workspace(session_id: str, cwd: str | None) -> tuple[str, str]:+ """``(digest, host cwd)`` of this session's per-workspace Docker sandbox, or ``("", "")``.- The live override is the key the container was created under. After that- binding is gone, the session row's host cwd hashes to the same digest.- ``/workspace`` and ``/root`` are container paths, not host workspaces.+ The live override is the key the container was created under, and its cwd is the+ workspace the turn mounted. After that binding is gone, the session row's host cwd+ hashes to the same digest. ``/workspace`` and ``/root`` are container paths, not host+ workspaces. Call it in the session's profile scope, where the turn registered the key."""from tools.terminal_tool import resolve_task_overrides, workspace_key_for- key = resolve_task_overrides(session_id).get("workspace_key")+ overrides = resolve_task_overrides(session_id)+ key = overrides.get("workspace_key")if isinstance(key, str) and _WORKSPACE_KEY_RE.fullmatch(key):- return key+ bound = overrides.get("cwd")+ return key, bound if isinstance(bound, str) else ""host = (cwd or "").strip()if not host or "\0" in host or _is_container_cwd(host):- return ""+ return "", ""expanded = os.path.expanduser(host)if not os.path.isdir(expanded):- return ""- return workspace_key_for(expanded)+ return "", ""+ return workspace_key_for(expanded), expandeddef _is_container_cwd(host: str) -> bool:@@ -134,7 +137,7 @@ def _is_container_cwd(host: str) -> bool:def _translate_agent_path(- candidate: Path, workspace_key: str = "", own_sandbox_only: bool = False,+ candidate: Path, workspace_key: str = "", own_sandbox_only: bool = False, workspace_cwd: str = "",) -> Path | None:"""One translation attempt under whatever scope is bound; None off the docker backend.@@ -148,7 +151,9 @@ def _translate_agent_path(_ensure_terminal_env_bridged()if not _docker_env_active():return None- translated = _translate_docker_container_media_path(candidate, quiet=True, workspace_key=workspace_key)+ translated = _translate_docker_container_media_path(+ candidate, quiet=True, workspace_key=workspace_key, workspace_cwd=workspace_cwd,+ )if own_sandbox_only and translated is not None and _in_fallback_sandbox(translated, workspace_key):raise HTTPException(status_code=409, detail=SANDBOX_COPY_MISSING)return translated@@ -208,6 +213,7 @@ def _agent_path_scope(profile_home: Path | None = None) -> Iterator[None]:def _agent_container_path(raw: str, *, profile_home: Path | None = None, workspace_key: str = "", own_sandbox_only: bool = False,+ workspace_cwd: str = "",) -> Path | None:"""Map an agent-visible container path to its host bind mount, or None.@@ -234,12 +240,12 @@ def _agent_container_path(candidate = Path(raw)with _agent_path_scope(profile_home):- translated = _translate_agent_path(candidate, workspace_key, own_sandbox_only)+ translated = _translate_agent_path(candidate, workspace_key, own_sandbox_only, workspace_cwd)if translated is not None or get_terminal_scope() is not None:return translatedtoken = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))try:- return _translate_agent_path(candidate, workspace_key, own_sandbox_only)+ return _translate_agent_path(candidate, workspace_key, own_sandbox_only, workspace_cwd)finally:reset_terminal_scope(token)except HTTPException:@@ -255,10 +261,12 @@ SANDBOX_NOT_FOUND = "File not found on the gateway host: the path may live insiddef _agent_fs_path(raw_path: str, *, cwd: str | None = None, profile_home: Path | None = None,workspace_key: str = "", decode_fallback: bool = True, own_sandbox_only: bool = False,+ workspace_cwd: str = "",) -> Path:"""``_fs_path`` for agent-facing reads; container paths resolve to their hostmount, so callers' boundary guards see the real host target. A session's Save passes``own_sandbox_only``: a container path stays in the session's own sandbox (else 409).+ ``workspace_cwd`` is the host cwd ``workspace_key`` hashes, the session's cwd mount.POSIX: a readable host path wins, and translation only runs when the hostlookup misses, so a root-run gateway can still browse its own ``/root``.@@ -272,11 +280,12 @@ def _agent_fs_path(return hosttranslated = _agent_container_path(_file_url_container_text(raw), profile_home=profile_home, workspace_key=workspace_key,- own_sandbox_only=own_sandbox_only,+ own_sandbox_only=own_sandbox_only, workspace_cwd=workspace_cwd,)return translated if translated is not None else hosttranslated = _agent_container_path(raw, profile_home=profile_home, workspace_key=workspace_key, own_sandbox_only=own_sandbox_only,+ workspace_cwd=workspace_cwd,)if translated is not None:return translateddiff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.pyindex 42317fc7490..45d74c302f1 100644--- a/tests/hermes_cli/test_web_server_fs.py+++ b/tests/hermes_cli/test_web_server_fs.py@@ -968,7 +968,7 @@ def test_fs_reads_translate_after_binding_profile_terminal_scope(client, tmp_patfrom tools.terminal_scope import get_terminal_scope- def translate(path, session_key="", workspace_key="", *, quiet=False):+ def translate(path, session_key="", workspace_key="", *, quiet=False, workspace_cwd=""):if path == Path("/workspace/isolated report.txt") and get_terminal_scope() is not None:return targetreturn None@@ -1122,14 +1122,16 @@ def test_fs_download_maps_workspace_container_to_its_sandbox(client, monkeypatchdef test_fs_download_cwd_mount_wins_then_falls_back_to_workspace_sandbox(client, monkeypatch, tmp_path,):- """With the host cwd mounted on ``/workspace``, that directory wins when the- file is there. When the container was still created as ``default:ws:`` and+ """With the host cwd mounted on ``/workspace``, the session's own cwd is that+ mount and wins when the file is there; the profile's ``terminal.cwd`` is another+ container's mount. When the container was still created as ``default:ws:`` andthe file only exists in its sandbox workspace, the download serves that copy."""project = tmp_path / "project"project.mkdir()+ (project / "note.txt").write_bytes(b"mounted-file")mounted = tmp_path / "mounted-cwd"mounted.mkdir()- (mounted / "note.txt").write_bytes(b"mounted-file")+ (mounted / "note.txt").write_bytes(b"profile-cwd-file")sandbox = tmp_path / "sandboxes"own = _workspace_sandbox(sandbox, project)(own / "note.txt").write_bytes(b"sandbox-file")@@ -1150,7 +1152,7 @@ def test_fs_download_cwd_mount_wins_then_falls_back_to_workspace_sandbox(assert mounted_hit.status_code == 200assert mounted_hit.content == b"mounted-file"- (mounted / "note.txt").unlink()+ (project / "note.txt").unlink()sandbox_hit = client.get("/api/fs/download", params={"path": "/workspace/note.txt", "session_id": "sess-ws"},)@@ -1168,7 +1170,7 @@ def test_agent_fs_path_translates_before_host_normalization(monkeypatch, tmp_patmapped = tmp_path / "x.txt"seen = []- def translate(candidate, session_key="", workspace_key="", *, quiet=False):+ def translate(candidate, session_key="", workspace_key="", *, quiet=False, workspace_cwd=""):seen.append(candidate.as_posix())return mappeddiff --git a/tests/hermes_cli/test_web_server_fs_session_workspace.py b/tests/hermes_cli/test_web_server_fs_session_workspace.pyindex fe7fe3a1030..a7567e90c14 100644--- a/tests/hermes_cli/test_web_server_fs_session_workspace.py+++ b/tests/hermes_cli/test_web_server_fs_session_workspace.py@@ -70,6 +70,7 @@ def sandboxes(monkeypatch, tmp_path):"sess-ws": ("default", str(project)),"sess-other": ("default", str(other)),"sess-work": ("work", str(project)),+ "sess-container": ("default", "/workspace"), # no host workspace binding}lookups = []@@ -274,6 +275,74 @@ def test_save_refuses_a_session_this_profile_does_not_own(client, sandboxes, sesassert _notes(sandboxes) == {"own": "session note", "foreign": "foreign note", "shared": "shared note"}+# Part 4: docker_mount_cwd_to_workspace+++def cwd_mount(sandboxes, monkeypatch, tmp_path):+ """The cwd mount on: the profile's ``terminal.cwd`` is P (``projmount``), while ``sess-ws`` is+ bound to its own workspace W (``project``), which its container mounts at ``/workspace``."""+ profile_cwd, workspace = tmp_path / "projmount", tmp_path / "project"+ profile_cwd.mkdir()+ (profile_cwd / "note.txt").write_text("profile note", encoding="utf-8")+ (workspace / "note.txt").write_text("workspace note", encoding="utf-8")+ monkeypatch.setenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "true")+ monkeypatch.setenv("TERMINAL_CWD", str(profile_cwd))+ return {**sandboxes, "profile_cwd": profile_cwd, "workspace": workspace}++[email protected](params=["session row", "live binding"])+def bound(request, cwd_mount):+ """``sess-ws``'s workspace from its stored cwd, or from the binding its running turn registered."""+ if request.param == "session row":+ yield cwd_mount+ return+ from gateway.session_policy import unbind_turn_workspace+ from tools.terminal_tool import register_task_env_overrides, workspace_key_for++ workspace = str(cwd_mount["workspace"])+ register_task_env_overrides("sess-ws", {+ "cwd": workspace, "cwd_source": "session", "workspace_key": workspace_key_for(workspace),+ })+ try:+ yield cwd_mount+ finally:+ unbind_turn_workspace("sess-ws")+++def _mount_notes(roots):+ return {name: (roots[name] / "note.txt").read_text(encoding="utf-8") for name in ("workspace", "profile_cwd")}++[email protected]("path", ["/workspace/note.txt", "file:///workspace/note.txt"])+def test_a_cwd_mounted_session_reads_and_saves_its_own_workspace(client, bound, path):+ read = client.get("/api/fs/read-text", params={"path": path, "session_id": "sess-ws"})+ saved = client.post("/api/fs/write-text", json={"path": path, "content": "edited", "session_id": "sess-ws"})++ assert (read.status_code, read.json()["text"]) == (200, "workspace note"), read.text+ assert saved.status_code == 200, saved.text+ assert saved.json()["path"] == read.json()["path"] == str(bound["workspace"] / "note.txt")+ assert _mount_notes(bound) == {"workspace": "edited", "profile_cwd": "profile note"}+++def test_a_cwd_mounted_session_without_a_workspace_binding_keeps_the_profile_cwd(client, cwd_mount):+ for params in ({"session_id": "sess-container"}, {}):+ read = client.get("/api/fs/read-text", params={"path": "/workspace/note.txt", **params})+ assert (read.status_code, read.json()["text"]) == (200, "profile note"), (params, read.text)+ assert read.json()["path"] == str(cwd_mount["profile_cwd"] / "note.txt")++[email protected]("session_id", ["sess-work", "missing-session", " "])+def test_a_cwd_mounted_session_this_profile_does_not_own_is_refused(client, cwd_mount, session_id):+ note = {"path": "/workspace/note.txt", "session_id": session_id}++ read = client.get("/api/fs/read-text", params=note)+ saved = client.post("/api/fs/write-text", json={**note, "content": "edited"})++ assert (read.status_code, saved.status_code) == (404, 404)+ assert _mount_notes(cwd_mount) == {"workspace": "workspace note", "profile_cwd": "profile note"}++@pytest.mark.parametrize("path", ["/workspace/escape.txt","file:///workspace/escape.txt",