The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): address review findings for remote-backend launch cwd
Ben Barclay4a2bb9828e4a
diff --git a/agent/terminal_env_registry.py b/agent/terminal_env_registry.pyindex b95a5e284be..aea19baafcf 100644--- a/agent/terminal_env_registry.py+++ b/agent/terminal_env_registry.py@@ -50,13 +50,15 @@ def plugin_backend_names(*, scope: Optional[str] = None) -> list[str]:return [p.name.strip().lower() for p in _registry.list_providers(scope=scope)]-def provider_flag(name: str, attr: str, default=False):+def provider_flag(name: str, attr: str, default=False, *, scope: Optional[str] = None):"""Read a classification attribute off the provider for *name*.Fail-soft: unknown backend or a raising property returns *default* so a misbehavingplugin degrades to built-in-equivalent behavior instead of taking the terminal tool down.+ *scope* names the profile home whose registrations to consult (default: the active home);+ a caller deciding for a session bound to another profile passes that profile's home."""- provider = _registry.get_provider(name)+ provider = _registry.get_provider(name, scope=scope)if provider is None:return defaulttry:diff --git a/tests/tools/test_file_tools_cwd_resolution.py b/tests/tools/test_file_tools_cwd_resolution.pyindex 7e9ef4ec574..3b1209f5556 100644--- a/tests/tools/test_file_tools_cwd_resolution.py+++ b/tests/tools/test_file_tools_cwd_resolution.py@@ -354,10 +354,11 @@ def test_v4a_delete_and_move_act_on_a_symlink_not_its_target(assert os.readlink(workspace / dest) == "safe/base.yaml"[email protected]("live_cwd", [None, "/home/sprite"], ids=["config-default", "live-env"])[email protected]("live_cwd", [None, "/srv/project-a"], ids=["no-env", "shared-env-moved"])def test_container_relative_path_without_a_recorded_cwd_uses_the_backend_cwd(_isolated_cwd, monkeypatch, live_cwd):- """A container session with no recorded cwd resolves relative paths against the sandbox's own cwd: the- process cwd is a host directory (``/opt/data`` in the hosted image) that does not exist in the sandbox."""+ """A container session with no recorded cwd resolves relative paths against the backend's configured cwd, the+ same place its terminal commands start: never the process cwd (a host dir such as ``/opt/data`` the sandbox+ lacks), and never a shared env's live cwd (wherever ANOTHER session last ``cd``'d)."""_workspace, decoy = _isolated_cwdmonkeypatch.delenv("TERMINAL_CWD", raising=False)monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: {"env_type": "modal", "cwd": "/root"})@@ -366,7 +367,10 @@ def test_container_relative_path_without_a_recorded_cwd_uses_the_backend_cwd(_isenvs["default"] = type("ModalEnvironment", (), {"cwd": live_cwd})()monkeypatch.setattr(terminal_tool, "_active_environments", envs)- resolved = ftp._resolve_path_for_task("notes/todo.md", task_id="default")+ resolved = ftp._resolve_path_for_task("notes/todo.md", task_id="b")+ command_cwd = terminal_tool._resolve_command_cwd(+ workdir=None, default_cwd="/root", session_key="b", env_type="modal")- assert resolved == PurePosixPath(live_cwd or "/root") / "notes" / "todo.md"+ assert resolved == PurePosixPath("/root") / "notes" / "todo.md"+ assert resolved.parent.parent == PurePosixPath(command_cwd)assert not str(resolved).startswith(str(decoy))diff --git a/tests/tui_gateway/test_remote_backend_launch_cwd.py b/tests/tui_gateway/test_remote_backend_launch_cwd.pyindex 218750bad9a..12c812b620c 100644--- a/tests/tui_gateway/test_remote_backend_launch_cwd.py+++ b/tests/tui_gateway/test_remote_backend_launch_cwd.py@@ -8,8 +8,11 @@ directory`` (exit 126). The backend's own default applies instead, as on the mesfrom __future__ import annotations+import threading+import pytest+from agent.terminal_env_provider import TerminalEnvironmentProviderfrom tools import terminal_toolfrom tui_gateway import server@@ -41,6 +44,43 @@ def _fresh_session(key: str) -> dict:return {"session_key": key, "cwd": cwd, "explicit_cwd": explicit, "profile_home": None, "source": "tui"}+class _Sprites(TerminalEnvironmentProvider):+ """A plugin sandbox backend (remote, container), like hermes-plugin-sprites."""++ name = "sprites"+ is_remote = True+ is_container = True++ def is_available(self):+ return True++ def create_environment(self, **kwargs):+ raise NotImplementedError+++class _HostRunner(TerminalEnvironmentProvider):+ """A plugin backend that runs commands on this host (neither remote nor a container)."""++ name = "hostrunner"+ is_remote = False+ is_container = False++ def is_available(self):+ return True++ def create_environment(self, **kwargs):+ raise NotImplementedError+++def clean_registry():+ from agent import terminal_env_registry as registry++ registry._reset_for_tests()+ yield registry+ registry._reset_for_tests()++@pytest.mark.parametrize("backend", ["modal", "daytona", "singularity"])def test_sandbox_session_does_not_register_the_launch_dir(launch_dir, monkeypatch, backend):_backend(monkeypatch, backend)@@ -59,29 +99,42 @@ def test_sandbox_session_does_not_register_the_launch_dir(launch_dir, monkeypatcterminal_tool.clear_task_env_overrides(session["session_key"])-def test_plugin_sandbox_backend_does_not_register_the_launch_dir(launch_dir, monkeypatch):+def test_plugin_sandbox_backend_does_not_register_the_launch_dir(launch_dir, monkeypatch, clean_registry):"""A plugin backend (sprites) declaring ``is_remote``/``is_container``."""- import agent.terminal_env_registry as registry-_backend(monkeypatch, "sprites")- monkeypatch.setattr(registry, "provider_flag", lambda name, attr, default=False: name == "sprites")+ clean_registry.register_provider(_Sprites())session = _fresh_session("launch-sprites")assert server._terminal_task_cwd_with_source(session) == ("", "process")assert server._persisted_session_cwd(session) is None-def test_plugin_host_backend_keeps_the_launch_dir(launch_dir, monkeypatch):+def test_plugin_host_backend_keeps_the_launch_dir(launch_dir, monkeypatch, clean_registry):"""A plugin backend declaring neither flag runs on this host: the launch dir stays its cwd."""- import agent.terminal_env_registry as registry-_backend(monkeypatch, "hostrunner")- monkeypatch.setattr(registry, "provider_flag", lambda name, attr, default=False: False)+ clean_registry.register_provider(_HostRunner())session = _fresh_session("launch-hostrunner")assert server._terminal_task_cwd_with_source(session) == (str(launch_dir), "session")+def test_plugin_classification_reads_the_bound_profiles_registry(launch_dir, tmp_path, clean_registry):+ """A provider registered only in a named profile's scope classifies that profile's sessions, even when the+ caller (session.create) has not bound the profile's home yet."""+ profile = tmp_path / "profiles" / "runner"+ profile.mkdir(parents=True)+ (profile / "config.yaml").write_text("terminal:\n backend: hostrunner\n", encoding="utf-8")+ clean_registry.register_provider(_HostRunner(), scope=str(profile))+ session = {"session_key": "named-runner", "cwd": str(launch_dir), "explicit_cwd": False,+ "profile_home": str(profile), "source": "tui"}++ assert server._host_cwd_is_terminal_cwd(str(profile))+ assert server._terminal_task_cwd_with_source(session) == (str(launch_dir), "session")+ # Unregistered in that scope: unknown plugin, treated as remote.+ clean_registry._reset_for_tests()+ assert not server._host_cwd_is_terminal_cwd(str(profile))++def test_explicit_workspace_still_wins_on_a_sandbox_backend(launch_dir, monkeypatch, tmp_path):_backend(monkeypatch, "modal")project = tmp_path / "project"@@ -120,13 +173,88 @@ def test_docker_keeps_the_host_dir(launch_dir, monkeypatch, mount):def test_sandbox_resume_drops_a_stored_hermes_home_cwd(launch_dir, monkeypatch):- """A row persisted before the fix with the Hermes home as cwd is not re-adopted as the sandbox workspace."""- hermes_home = str(server._hermes_home)+ """A row persisted before the fix with a launch dir (the Hermes home, its subprocess home) as cwd is not+ re-adopted as the sandbox workspace."""+ hermes_home = server.get_hermes_home()+ (hermes_home / "home").mkdir(exist_ok=True)_backend(monkeypatch, "modal")- assert server._resumable_stored_cwd(hermes_home, None) == ""+ for launch in (str(hermes_home), str(hermes_home / "home")):+ assert server._resumable_stored_cwd(launch, None) == ""monkeypatch.setenv("TERMINAL_ENV", "local")- assert server._resumable_stored_cwd(hermes_home, None) == hermes_home+ assert server._resumable_stored_cwd(str(hermes_home), None) == str(hermes_home)+++def test_sandbox_resume_keeps_a_workspace_picked_under_the_hermes_root(launch_dir, monkeypatch):+ """A folder the user picked under the Hermes root is a workspace, not a launch dir: it persists and resumes."""+ picked = server.get_hermes_home() / "projects" / "chosen"+ picked.mkdir(parents=True)+ _backend(monkeypatch, "modal")+ session = {"session_key": "picked", "source": "desktop", "cwd": str(picked), "explicit_cwd": True,+ "profile_home": None}++ stored = server._persisted_session_cwd(session)+ assert stored == str(picked)+ assert server._resumable_stored_cwd(stored, None) == str(picked)+++def test_sandbox_hydrated_workspace_stays_the_terminal_cwd(launch_dir, monkeypatch, tmp_path):+ """A sandbox session hydrated from its stored workspace marks it explicit, so the terminal uses it rather than+ reading it as an unpicked launch dir."""+ from hermes_state import SessionDB++ project = tmp_path / "project"+ project.mkdir()+ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ _backend(monkeypatch, "modal")+ db.create_session("hydrated", source="tui", model="m", cwd=str(project))+ monkeypatch.setitem(server._sessions, "s-hydrated",+ {"session_key": "hydrated", "source": "tui", "cwd": str(launch_dir),+ "profile_home": None})+ monkeypatch.setattr(server, "_persist_session_cwd_and_schedule_git_meta", lambda *a, **k: None)+ server._hydrate_session_cwd("s-hydrated", "hydrated", db, None)+ session = server._sessions["s-hydrated"]++ assert session["cwd"] == str(project) and session["explicit_cwd"] is True+ assert server._terminal_task_cwd_with_source(session) == (str(project), "session")+ finally:+ db.close()+++def test_compute_host_carries_workspace_provenance(launch_dir, monkeypatch, tmp_path):+ """An isolated turn's frame carries ``explicit_cwd``, so the compute host's rebuilt session keeps a picked+ sandbox workspace as its terminal cwd."""+ import io+ import types++ from tui_gateway.compute_host import ComputeHost++ project = tmp_path / "project"+ project.mkdir()+ _backend(monkeypatch, "modal")+ parent = {"session_key": "picked", "cwd": str(project), "explicit_cwd": True, "history": [],+ "history_lock": threading.Lock(), "profile_home": None, "source": "desktop"}+ frame = server._compute_host_turn_frame("rid", "child", parent, "hi")+ assert frame["explicit_cwd"] is True++ captured = {}++ def fake_init_session(sid, key, agent, history, **kwargs):+ captured.update(kwargs)+ monkeypatch.setitem(server._sessions, sid, {"agent": agent, "session_key": key, "cwd": kwargs.get("cwd"),+ "explicit_cwd": kwargs.get("explicit_cwd", False),+ "profile_home": None})++ monkeypatch.setattr(server, "_make_agent", lambda sid, key, **kw: types.SimpleNamespace(session_id=key))+ monkeypatch.setattr(server, "_transfer_db_to_agent", lambda agent, db: False)+ monkeypatch.setattr(server, "_init_session", fake_init_session)+ server._sessions.pop("child", None)+ child = ComputeHost(stdout=io.StringIO(), heartbeat_secs=0)._build_server_session(+ server, {**frame, "sid": "child", "history": []}, "child")++ assert captured["explicit_cwd"] is True+ assert server._terminal_task_cwd_with_source(child) == (str(project), "session")def test_sandbox_path_completion_lists_the_backend_cwd(launch_dir, monkeypatch):diff --git a/tools/file_tools_paths.py b/tools/file_tools_paths.pyindex 8e3b2fa3fbc..a12e40fb50e 100644--- a/tools/file_tools_paths.py+++ b/tools/file_tools_paths.py@@ -6,6 +6,7 @@ other anchor exists (a relative/sentinel ``TERMINAL_CWD`` would silently anchoredits to the agent process cwd, e.g. the main repo during a worktree session)."""+import loggingimport osimport posixpathimport sys@@ -14,6 +15,8 @@ from pathlib import Path, PurePosixPathfrom agent.runtime_self_protection import split_entry+logger = logging.getLogger(__name__)+# ``TERMINAL_CWD`` values that mean "not configured" ("." from a stale config;# "auto"/"cwd" are wizard placeholders). gateway/run.py sanitizes the same set._TERMINAL_CWD_SENTINELS = frozenset({"", ".", "./", "auto", "cwd"})@@ -265,18 +268,19 @@ def _resolve_base_dir(def _container_default_cwd(task_id: str = "default") -> str | None:- """A container backend's own working directory when the session recorded none: the live env's cwd, else the- configured one (already sanitized to the backend default). The process cwd is a host directory (``/opt/data``- in the Docker image) the sandbox does not have, and terminal commands do not run there."""+ """A container backend's configured working directory (already sanitized to the backend default) when the+ session recorded none: the cwd its terminal commands start in (``_resolve_command_cwd``'s default). The process+ cwd is a host directory (``/opt/data`` in the Docker image) the sandbox does not have. The live env's cwd is NOT+ used: a shared env's cwd is wherever ANOTHER session last ``cd``'d."""try:from tools.terminal_tool import _get_env_config- from tools.terminal_tool_lifecycle import get_active_env- for cwd in (getattr(get_active_env(task_id), "cwd", None), _get_env_config().get("cwd")):- if isinstance(cwd, str) and posixpath.isabs(cwd):- return cwd+ cwd = _get_env_config().get("cwd")+ if isinstance(cwd, str) and posixpath.isabs(cwd):+ return cwdexcept Exception:- pass+ # Path resolution must not fail on a broken terminal config; the caller falls back to the process cwd.+ logger.debug("container default cwd unavailable for task %s", task_id, exc_info=True)return Nonediff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.pyindex 2d26604a641..e395353602b 100644--- a/tui_gateway/compute_host.py+++ b/tui_gateway/compute_host.py@@ -325,6 +325,8 @@ class ComputeHost:for key in ("cwd", "profile_home"):if frame.get(key):session[key] = str(frame[key])+ if "explicit_cwd" in frame:+ session["explicit_cwd"] = bool(frame["explicit_cwd"])else:session = self._build_server_session(server, frame, sid)if isinstance(frame.get("attached_images"), list):@@ -391,7 +393,7 @@ class ComputeHost:server._init_session(sid, key, agent, list(history), cols=int(frame.get("cols") or 80),cwd=str(frame.get("cwd") or "") or None, session_db=session_db,- source=frame.get("source"))+ source=frame.get("source"), explicit_cwd=bool(frame.get("explicit_cwd")))finally:reset_transport(token)except Exception:@@ -404,6 +406,7 @@ class ComputeHost:"created_at": time.time(), "last_active": time.time(), "running": False,"attached_images": [], "image_counter": 0,"cwd": str(frame.get("cwd") or os.getcwd()), "cols": int(frame.get("cols") or 80),+ "explicit_cwd": bool(frame.get("explicit_cwd")),"slash_worker": None, "show_reasoning": server._load_show_reasoning(),"tool_progress_mode": server._load_tool_progress_mode(), "edit_snapshots": {},"tool_started_at": {}, "model_override": frame.get("model_override"),diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.pyindex c39070ba70c..d57a0096f25 100644--- a/tui_gateway/compute_host_bridge.py+++ b/tui_gateway/compute_host_bridge.py@@ -62,6 +62,8 @@ def _compute_host_turn_frame(**({"display_metadata": display_metadata} if display_metadata else {}),"history_version": history_version, "cols": int(session.get("cols", 80) or 80),"cwd": _session_cwd(session),+ # Workspace provenance rides with the cwd: a sandbox backend registers an unpicked host cwd as nothing.+ "explicit_cwd": bool(session.get("explicit_cwd")),"context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(session),"profile_home": session.get("profile_home") or "","model_override": session.get("model_override"),diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex e4a18e4ff40..5f86ceeb84b 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1727,9 +1727,10 @@ def _hydrate_session_cwd(sid: str, key: str, session_db, profile_home: str | Nonif db is not None:row = db.get_session(key) if hasattr(db, "get_session") else Noneif row and _resumable_stored_cwd(row.get("cwd"), profile_home):- # An ssh session's stored cwd is its workspace: explicit, so the remote terminal uses it instead of- # the profile's ~. Other backends keep main's semantics (resolved outside the sessions lock: I/O).- remote = _cwd_is_remote(profile_home)+ # An ssh or sandbox session's stored cwd is its workspace: explicit, so the remote terminal uses it+ # instead of the backend default (an unpicked launch dir is never persisted for them). Host backends+ # keep main's semantics (resolved outside the sessions lock: I/O).+ remote = not _host_cwd_is_terminal_cwd(profile_home)with _sessions_lock:if sid in _sessions:_sessions[sid]["cwd"] = row["cwd"]diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 9fff545600e..df42cb60ea8 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -297,9 +297,12 @@ def _host_cwd_is_terminal_cwd(profile_home) -> bool:from tools.terminal_tool_config import _BUILTIN_BACKENDSif backend in _BUILTIN_BACKENDS:return False- # An unknown or unloaded plugin is treated as remote: sending it a host path is the failure this guards.+ # An unknown or unloaded plugin is treated as remote: sending it a host path is the failure this guards. The+ # registry is read in the session's OWN profile scope: callers (session.create) run before that home is bound.from agent.terminal_env_registry import provider_flag- return not (provider_flag(backend, "is_remote", True) or provider_flag(backend, "is_container", True))+ scope = str(profile_home) if profile_home else None+ return not (provider_flag(backend, "is_remote", True, scope=scope)+ or provider_flag(backend, "is_container", True, scope=scope))def _is_hermes_owned_cwd(cwd: str, profile_home) -> bool:@@ -320,6 +323,24 @@ def _is_hermes_owned_cwd(cwd: str, profile_home) -> bool:return any(path == root or root in path.parents for root in roots) or _is_install_tree(path)+def _is_hermes_launch_dir(cwd: str, profile_home) -> bool:+ """Whether ``cwd`` IS a directory the Hermes process is launched from: the Hermes root (``/opt/data`` in the+ Docker image), a subprocess home (``/opt/data/home``), the bound profile's home, or the install tree. Folders+ below the root and the homes are not: a user may keep a workspace there."""+ from agent.runtime_cwd import _is_install_tree+ from hermes_constants import get_default_hermes_root++ if not os.path.isabs(cwd):+ return False+ try:+ path = Path(cwd).resolve()+ home = Path(profile_home or get_hermes_home()).expanduser().resolve()+ root = get_default_hermes_root(home=home).resolve()+ except (OSError, RuntimeError):+ return False+ return path in {home, home / "home", root, root / "home"} or _is_install_tree(path)++def _is_other_profiles_cwd(cwd: str, profile_home) -> bool:"""Whether a NAMED local profile's stored cwd is a directory that belongs to another profile or to Hermes itself:the root (``/opt/data``), its subprocess home (``/opt/data/home``), a sibling profile's tree, or the install tree.@@ -341,12 +362,15 @@ def _is_other_profiles_cwd(cwd: str, profile_home) -> bool:def _resumable_stored_cwd(cwd, profile_home) -> str:- """A session row's stored cwd as a resume may adopt it: empty when the row of a session whose terminal does not- run in host directories (ssh, sandboxes) holds a path in Hermes's own host tree (a host launch directory, never a- remote workspace), or a named profile's row holds another profile's (the resume then lands in- :func:`_profile_default_cwd` and re-persists it)."""+ """A session row's stored cwd as a resume may adopt it: empty when an ssh session's row holds a path in Hermes's+ own host tree (a host launch directory, never a remote workspace), when a sandbox session's row holds one of the+ launch directories themselves (rows written before launch dirs stopped being persisted), or when a named+ profile's row holds another profile's (the resume then lands in :func:`_profile_default_cwd` and re-persists+ it). A folder a sandbox user picked under the Hermes root stays."""cwd = str(cwd or "")- if cwd and not _host_cwd_is_terminal_cwd(profile_home) and _is_hermes_owned_cwd(cwd, profile_home):+ if cwd and _cwd_is_remote(profile_home) and _is_hermes_owned_cwd(cwd, profile_home):+ return ""+ if cwd and not _host_cwd_is_terminal_cwd(profile_home) and _is_hermes_launch_dir(cwd, profile_home):return ""if cwd and _is_other_profiles_cwd(cwd, profile_home):return ""