The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): keep the spawn PATH's dirs a login profile resets out of the snapshot
Teknium6fa171ce5423
diff --git a/Dockerfile b/Dockerfileindex 32441d3ff6c..c5fd7f509dc 100644--- a/Dockerfile+++ b/Dockerfile@@ -527,6 +527,8 @@ COPY --chmod=0755 docker/entrypoint-dispatch.sh /opt/hermes/docker/entrypoint-di# binary by absolute path, so this PATH ordering is transparent to# every other consumer.ENV PATH="/opt/hermes/bin:/opt/hermes/.venv/bin:/opt/data/.local/bin:${PATH}"+# Login shells re-read /etc/profile, which resets PATH; this re-adds the dirs above.+COPY --chmod=0644 docker/profile-hermes-path.sh /etc/profile.d/hermes.sh# PM's atomic writer creates private facts for source installs. In the# image these are shared, non-secret package metadata, read by UID 10000.# uv's environment locks are build-only and may be world-writable. Removediff --git a/docker/profile-hermes-path.sh b/docker/profile-hermes-path.shnew file mode 100644index 00000000000..bccddb5151d--- /dev/null+++ b/docker/profile-hermes-path.sh@@ -0,0 +1,13 @@+# Installed as /etc/profile.d/hermes.sh. Debian's /etc/profile resets PATH for+# every login shell (`bash -l`, `docker exec <c> bash -l`, ssh, the terminal+# tool's background `bash -lic`), dropping the image's ENV PATH dirs, so bare+# `hermes` exits 127 there. Put them back in the ENV PATH order; dirs a login+# PATH already lists keep their position.+for __hermes_p in /opt/data/.local/bin /opt/hermes/.venv/bin /opt/hermes/bin; do+ case ":$PATH:" in+ *":$__hermes_p:"*) ;;+ *) PATH="$__hermes_p:$PATH" ;;+ esac+done+unset __hermes_p+export PATHdiff --git a/tests/docker/test_login_shell_path.py b/tests/docker/test_login_shell_path.pynew file mode 100644index 00000000000..be9d51e99cb--- /dev/null+++ b/tests/docker/test_login_shell_path.py@@ -0,0 +1,24 @@+"""Login shells in the image keep Hermes' own dirs on PATH.++Debian's ``/etc/profile`` resets PATH for every login shell, so without+``/etc/profile.d/hermes.sh`` a ``bash -l`` (``docker exec <c> bash -l``, ssh, the+terminal tool's background ``bash -lic``) lost ``/opt/hermes/bin`` and bare+``hermes`` exited 127 (#56634).+"""+from __future__ import annotations++import subprocess+++def test_login_shell_resolves_hermes_to_the_image_shim(built_image: str) -> None:+ r = subprocess.run(+ ["docker", "run", "--rm", "-u", "hermes", "--entrypoint", "bash", built_image,+ "-lc", "command -v hermes; echo \"$PATH\""],+ capture_output=True, text=True, timeout=60, check=False,+ )+ assert r.returncode == 0, r.stderr+ resolved, path = r.stdout.splitlines()[-2:]+ assert resolved == "/opt/hermes/bin/hermes"+ entries = path.split(":")+ assert entries.index("/opt/hermes/bin") < entries.index("/opt/hermes/.venv/bin")+ assert entries.count("/opt/hermes/bin") == 1diff --git a/tests/tools/test_login_shell_path_preservation.py b/tests/tools/test_login_shell_path_preservation.pyindex 7eac41e2afe..be2bd1b6754 100644--- a/tests/tools/test_login_shell_path_preservation.py+++ b/tests/tools/test_login_shell_path_preservation.py@@ -17,7 +17,7 @@ import pytestfrom tools.environments.local import LocalEnvironment-_PATH_LINE = re.compile(r'^(?:declare -x|export) PATH="(.*)"$', re.M)+_PATH_LINE = re.compile(r'^(?:declare -x|export) PATH="(.*)"$', re.MULTILINE)def _managed_setup(tmp_path, monkeypatch, *, profile_body: str):@@ -34,7 +34,7 @@ def _managed_setup(tmp_path, monkeypatch, *, profile_body: str):"tools.environments.local._resolve_hermes_bin_dir", lambda: str(managed))monkeypatch.setattr(- "tools.environments.local._managed_runtime_path_entries", lambda: []+ "tools.environments.local._managed_runtime_path_entries", list)return managed@@ -101,3 +101,34 @@ class TestLoginShellPathPreservation:assert str(managed) in out.split(":")finally:env.cleanup()+++def _exe(directory, name: str):+ tool = directory / name+ tool.write_text(f"#!/bin/sh\necho {directory.name}\n")+ tool.chmod(0o755)++[email protected]("posix")+def test_dropped_spawn_path_dirs_return_after_the_login_path(tmp_path, monkeypatch):+ """Any spawn-env dir a resetting profile dropped (not only Hermes' own: the gateway's+ pm runtime, a ``docker run -e PATH=`` addition) comes back in parent order AFTER the+ login PATH, so a command the login PATH resolves keeps resolving to the same binary."""+ user_bin, extra_a, extra_b = (tmp_path / n for n in ("user-bin", "extra-a", "extra-b"))+ for d in (user_bin, extra_a, extra_b):+ d.mkdir()+ _exe(user_bin, "shared-tool")+ _exe(extra_a, "shared-tool")+ _exe(extra_b, "only-in-parent")+ _managed_setup(tmp_path, monkeypatch,+ profile_body=f'PATH="/usr/local/bin:/usr/bin:/bin"\nPATH="{user_bin}:$PATH"\n')+ env = LocalEnvironment(cwd=str(tmp_path), env={"PATH": f"{extra_a}:{extra_b}:/usr/bin:/bin"})+ try:+ entries = _snapshot_path_value(env)+ assert entries.index(str(user_bin)) < entries.index("/usr/bin") < entries.index(str(extra_a)) \+ < entries.index(str(extra_b))+ assert entries.count("/usr/bin") == 1+ out = env.execute("only-in-parent; shared-tool")["output"].split()+ assert out == ["extra-b", "user-bin"]+ finally:+ env.cleanup()diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 5a93248b190..00eac61b500 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -6,6 +6,7 @@ import ntpathimport osimport platformimport re+import shleximport shutilimport signalimport subprocess@@ -861,23 +862,25 @@ def _prepend_shell_init(cmd_string: str, files: list[str]) -> str:return "\n".join(prelude) + "\n" + cmd_string-def _prepend_managed_path_restore(cmd_string: str) -> str:- """Prepend idempotent PATH-restore lines for Hermes-managed dirs.+def _append_dropped_path_entries(cmd_string: str, parent_path: str) -> str:+ """Prepend a line that re-appends *parent_path* dirs the login profile dropped.- Login profiles can reset PATH outright — Debian's ``/etc/profile`` does so- for non-root shells, dropping the venv dir the process env put there- (#56634). Sits between the init-file prelude and the command (the env- snapshot's ``export -p``), so restored entries survive into the snapshot.- Each ``case`` guard re-adds its dir only when absent, keeping reruns and- profiles that kept the entries duplicate-free."""+ A login profile can reset PATH outright (Debian's ``/etc/profile``, so every+ Debian/Ubuntu image and host), and the snapshot's ``export -p`` then pins the reset+ PATH over the spawn env for every later command: in the Docker image that loses+ ``/opt/hermes/bin`` and bare ``hermes`` exits 127 (#56634). Dropped dirs go AFTER+ the login PATH in parent order, so a command that resolved before still resolves+ to the same binary (the user's nvm/pyenv keep precedence); only commands that had+ no match gain one. Present entries are never duplicated; missing dirs are skipped."""if _IS_WINDOWS:return cmd_string # native PATH stays ``;``-joined; bash sees a converted copy- entries = [d for d in (_resolve_hermes_bin_dir(), *_managed_runtime_path_entries())- if d and '"' not in d]+ entries = [d for d in dict.fromkeys(parent_path.split(":")) if d and os.path.isdir(d)]if not entries:return cmd_string- lines = [f'case ":$PATH:" in *":{d}:"*) ;; *) PATH="{d}:$PATH" ;; esac' for d in entries]- return "\n".join(lines) + "\n" + cmd_string+ restore = (f"for __hermes_p in {' '.join(shlex.quote(d) for d in entries)}; do "+ 'case ":$PATH:" in *":$__hermes_p:"*) ;; *) PATH="${PATH:+$PATH:}$__hermes_p" ;; esac; '+ "done; unset __hermes_p; export PATH")+ return restore + "\n" + cmd_string# --- Process-group teardown (POSIX) ---@@ -1125,18 +1128,17 @@ class LocalEnvironment(BaseEnvironment):def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,stdin_data: str | None = None) -> subprocess.Popen:bash = _find_bash()+ run_env = _make_run_env(self.env)# Login invocations (init_session's env snapshot) source the user's rc /- # custom init files so nvm/asdf/pyenv land on PATH in the snapshot; the- # managed-dir restore runs after that prelude so a profile that resets- # PATH (Debian's /etc/profile) can't drop Hermes' own dirs from the- # snapshot (#56634).+ # custom init files so nvm/asdf/pyenv land on PATH in the snapshot; then the+ # spawn env's dirs a resetting profile dropped are re-appended (#56634).if login:- cmd_string = _prepend_managed_path_restore(cmd_string)+ cmd_string = _append_dropped_path_entries(cmd_string, run_env.get("PATH", ""))cmd_string = _prepend_shell_init(cmd_string, _resolve_shell_init_files())args = [bash, *(["-l"] if login else []), "-c", cmd_string]self._recover_cwd()proc = subprocess.Popen(- args, text=True, env=_make_run_env(self.env), encoding="utf-8", errors="replace",+ args, text=True, env=run_env, encoding="utf-8", errors="replace",stdout=subprocess.PIPE, stderr=subprocess.STDOUT,stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL,start_new_session=True, cwd=self.cwd,