From 13137718d454fc1be1735cfe4aeab4a395182697 Mon Sep 17 00:00:00 2001 From: mintaka Date: Sun, 22 Nov 2026 21:49:00 -0500 Subject: [PATCH] feat(hermes): sandbox macOS local terminal away from secret files (RIG-11734) Known limits: tmux, launchd and other unsandboxed IPC services can execute outside the sandbox. vault_secret shell spawns are not sandboxed. Hard-link denial requires a macOS live check. Co-authored-by: Matt Wilkinson --- forks/hermes-agent/hermes_cli/auth.py | 4 + .../hermes_cli/config_defaults.py | 2 + forks/hermes-agent/hermes_cli/env_loader.py | 11 +- .../test_auth_store_read_failure.py | 13 ++ .../hermes_cli/test_env_loader_unreadable.py | 44 ++++ .../tools/test_local_macos_secret_sandbox.py | 221 ++++++++++++++++++ forks/hermes-agent/tools/code_kernel.py | 4 +- .../hermes-agent/tools/environments/local.py | 57 ++++- forks/hermes-agent/tools/process_registry.py | 5 +- 9 files changed, 355 insertions(+), 6 deletions(-) create mode 100644 forks/hermes-agent/tests/tools/test_local_macos_secret_sandbox.py diff --git a/forks/hermes-agent/hermes_cli/auth.py b/forks/hermes-agent/hermes_cli/auth.py index 74f6e7e37..fb4d96441 100644 --- a/forks/hermes-agent/hermes_cli/auth.py +++ b/forks/hermes-agent/hermes_cli/auth.py @@ -769,6 +769,10 @@ def _load_auth_store(auth_file: Optional[Path] = None) -> dict[str, Any]: return _empty_auth_store() try: raw = json.loads(auth_file.read_text(encoding="utf-8-sig")) + except PermissionError as exc: + if exc.errno == errno.EPERM and os.environ.get("HERMES_SECRET_SANDBOX") == "1": + return _empty_auth_store() + raise except OSError: # Exists but unreadable (EMFILE, EACCES, EIO, stalled mount): contents are not bad, and this # module read-modify-writes everywhere, so an empty store here is one _save_auth_store() diff --git a/forks/hermes-agent/hermes_cli/config_defaults.py b/forks/hermes-agent/hermes_cli/config_defaults.py index eb0d3acb7..4c11dbc0f 100644 --- a/forks/hermes-agent/hermes_cli/config_defaults.py +++ b/forks/hermes-agent/hermes_cli/config_defaults.py @@ -331,6 +331,8 @@ # go first because n/nvm/asdf write PATH exports there without an interactivity guard. Turn # off if an rc file misbehaves when sourced non-interactively (exits on TTY check). "auto_source_bashrc": True, + # Hide local macOS terminal commands from Hermes credential files when sandbox-exec exists. + "sandbox_macos_secrets": True, # The default sandbox for every container backend: the nikolaik/python-nodejs base # (Python 3.13 / Node 26) plus a display stack, so Bot Screen, computer_use and the # bot's browser run INSIDE the sandbox and the pane can watch them (see bot_desktop). diff --git a/forks/hermes-agent/hermes_cli/env_loader.py b/forks/hermes-agent/hermes_cli/env_loader.py index fa153d6f0..acda0a52b 100644 --- a/forks/hermes-agent/hermes_cli/env_loader.py +++ b/forks/hermes-agent/hermes_cli/env_loader.py @@ -3,6 +3,7 @@ from __future__ import annotations import codecs +import errno import io import itertools import logging @@ -637,7 +638,9 @@ def _load_user_dotenv(path: Path, *, load_pass: int) -> bool: be the only place the backend is set, and skipping it would run terminal commands on the host.""" try: _load_dotenv_with_fallback(path, override=True, load_pass=load_pass) - except PermissionError: + except PermissionError as exc: + if exc.errno == errno.EPERM and os.environ.get("HERMES_SECRET_SANDBOX") == "1": + return False from hermes_cli import managed_scope if managed_scope.pinned_terminal_backend() is None: @@ -722,7 +725,11 @@ def load_hermes_dotenv( # the committed .env. override=False lets a systemd `EnvironmentFile=-…/.op.env` token win. op_env = home_path / ".op.env" if op_env.exists() and not os.environ.get("OP_SERVICE_ACCOUNT_TOKEN"): - _load_dotenv_with_fallback(op_env, override=False, load_pass=load_pass) + try: + _load_dotenv_with_fallback(op_env, override=False, load_pass=load_pass) + except PermissionError as exc: + if exc.errno != errno.EPERM or os.environ.get("HERMES_SECRET_SANDBOX") != "1": + raise if project_env_path and project_env_path.exists(): _load_dotenv_with_fallback(project_env_path, override=not user_env.exists(), load_pass=load_pass) diff --git a/forks/hermes-agent/tests/hermes_cli/test_auth_store_read_failure.py b/forks/hermes-agent/tests/hermes_cli/test_auth_store_read_failure.py index c9e575f41..b4b741a08 100644 --- a/forks/hermes-agent/tests/hermes_cli/test_auth_store_read_failure.py +++ b/forks/hermes-agent/tests/hermes_cli/test_auth_store_read_failure.py @@ -67,3 +67,16 @@ def test_unparseable_json_still_degrades_and_preserves_a_copy(store_file): def test_healthy_store_is_returned_unchanged(store_file): result = auth._load_auth_store(store_file) assert result["providers"]["nous"]["api_key"] == "secret" + + +@pytest.mark.parametrize("error", [errno.EPERM, errno.EACCES]) +def test_sandboxed_auth_permission_error_returns_empty_only_for_eperm(store_file, monkeypatch, error): + from pathlib import Path + + monkeypatch.setenv("HERMES_SECRET_SANDBOX", "1") + monkeypatch.setattr(Path, "read_text", _fail_read(PermissionError(error, "denied"))) + if error == errno.EPERM: + assert auth._load_auth_store(store_file) == {"version": auth.AUTH_STORE_VERSION, "providers": {}} + else: + with pytest.raises(PermissionError): + auth._load_auth_store(store_file) diff --git a/forks/hermes-agent/tests/hermes_cli/test_env_loader_unreadable.py b/forks/hermes-agent/tests/hermes_cli/test_env_loader_unreadable.py index f34f02607..7c33082c5 100644 --- a/forks/hermes-agent/tests/hermes_cli/test_env_loader_unreadable.py +++ b/forks/hermes-agent/tests/hermes_cli/test_env_loader_unreadable.py @@ -7,6 +7,7 @@ """ import builtins +import errno import io import logging import os @@ -132,3 +133,46 @@ def test_reload_still_removes_keys_a_readable_env_dropped(monkeypatch): assert reload_env() == 2 assert "OPENAI_API_KEY" not in os.environ assert os.environ["ANTHROPIC_API_KEY"] == "from-file" + + +@pytest.mark.parametrize("sandboxed,error,ignored", [(True, errno.EPERM, True), (True, errno.EACCES, False), + (False, errno.EPERM, False)]) +def test_sandboxed_user_dotenv_permission_error(monkeypatch, tmp_path, sandboxed, error, ignored): + from hermes_cli import env_loader + + def deny(*args, **kwargs): + raise PermissionError(error, "denied") + monkeypatch.setattr(env_loader, "_load_dotenv_with_fallback", deny) + monkeypatch.setattr(managed_scope, "pinned_terminal_backend", lambda: None) + if sandboxed: + monkeypatch.setenv("HERMES_SECRET_SANDBOX", "1") + else: + monkeypatch.delenv("HERMES_SECRET_SANDBOX", raising=False) + if ignored: + assert env_loader._load_user_dotenv(tmp_path / ".env", load_pass=1) is False + else: + with pytest.raises(PermissionError): + env_loader._load_user_dotenv(tmp_path / ".env", load_pass=1) + + +@pytest.mark.parametrize("sandboxed,error,ignored", [(True, errno.EPERM, True), (True, errno.EACCES, False), + (False, errno.EPERM, False)]) +def test_sandboxed_op_dotenv_permission_error(monkeypatch, tmp_path, sandboxed, error, ignored): + from hermes_cli import env_loader + + op_env = tmp_path / ".op.env" + op_env.touch() + monkeypatch.delenv("OP_SERVICE_ACCOUNT_TOKEN", raising=False) + if sandboxed: + monkeypatch.setenv("HERMES_SECRET_SANDBOX", "1") + else: + monkeypatch.delenv("HERMES_SECRET_SANDBOX", raising=False) + def deny(path, **kwargs): + if path == op_env: + raise PermissionError(error, "denied") + monkeypatch.setattr(env_loader, "_load_dotenv_with_fallback", deny) + if ignored: + load_hermes_dotenv(hermes_home=tmp_path, load_external_secrets=False) + else: + with pytest.raises(PermissionError): + load_hermes_dotenv(hermes_home=tmp_path, load_external_secrets=False) diff --git a/forks/hermes-agent/tests/tools/test_local_macos_secret_sandbox.py b/forks/hermes-agent/tests/tools/test_local_macos_secret_sandbox.py new file mode 100644 index 000000000..b61c3d84a --- /dev/null +++ b/forks/hermes-agent/tests/tools/test_local_macos_secret_sandbox.py @@ -0,0 +1,221 @@ +"""Local macOS terminal sandboxing hides only the Hermes credential files.""" + +from unittest.mock import patch + +import pytest + +from tools.environments import local + + +def test_profile_denies_each_secret_file_but_not_logs(tmp_path, monkeypatch): + home = tmp_path / ".hermes" + monkeypatch.setenv("HERMES_HOME", str(home)) + + profile = local._local_macos_secret_profile() + + for name in (".env", "auth.json", ".rr-token"): + assert f'(deny file-read* file-write* file-link (literal "{(home / name).resolve()}"))' in profile + assert "(allow default)" in profile + assert str((home / "logs").resolve()) not in profile + + +def test_profile_denies_symlink_and_resolved_paths(tmp_path, monkeypatch): + real_home = tmp_path / "real" + real_home.mkdir() + home = tmp_path / "link" + home.symlink_to(real_home, target_is_directory=True) + monkeypatch.setenv("HERMES_HOME", str(home)) + + profile = local._local_macos_secret_profile() + + for name in (".env", "auth.json", ".rr-token"): + for path in (home / name, real_home / name): + assert f'(deny file-read* file-write* file-link (literal "{path}"))' in profile + assert str(home / "logs") not in profile + assert str(real_home / "logs") not in profile + + +def test_wraps_argv_on_darwin_when_sandbox_exec_exists(monkeypatch): + monkeypatch.setattr(local.sys, "platform", "darwin") + original = ["/bin/bash", "-c", "echo hi"] + monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec") + monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile") + with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}): + wrapped = local._sandbox_local_macos_argv(original) + + assert wrapped == ["/usr/bin/sandbox-exec", "-p", "profile", "/usr/bin/env", "HERMES_SECRET_SANDBOX=1", *original] + + +def test_leaves_argv_unchanged_on_other_platform(monkeypatch): + monkeypatch.setattr(local.sys, "platform", "linux") + original = ["/bin/bash", "-c", "echo hi"] + + assert local._sandbox_local_macos_argv(original) is original + + +def test_leaves_argv_unchanged_when_sandbox_exec_is_missing(monkeypatch, caplog): + monkeypatch.setattr(local.sys, "platform", "darwin") + monkeypatch.setattr(local, "_sandbox_missing_warned", False) + original = ["/bin/bash", "-c", "echo hi"] + monkeypatch.setattr(local.os.path, "exists", lambda path: False) + with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}): + wrapped = local._sandbox_local_macos_argv(original) + local._sandbox_local_macos_argv(original) + + assert wrapped is original + assert "sandbox-exec is unavailable" in caplog.text + assert caplog.text.count("sandbox-exec is unavailable") == 1 + + +def test_leaves_argv_unchanged_when_config_disables_sandbox(monkeypatch): + monkeypatch.setattr(local.sys, "platform", "darwin") + original = ["/bin/bash", "-c", "echo hi"] + monkeypatch.setattr(local.os.path, "exists", lambda path: True) + with patch("hermes_cli.config_effective.load_user_config_effective", return_value={ + "terminal": {"sandbox_macos_secrets": False}, + }): + wrapped = local._sandbox_local_macos_argv(original) + + assert wrapped is original + + +def test_sandbox_setting_defaults_on(): + from hermes_cli.config_defaults import DEFAULT_CONFIG + + assert DEFAULT_CONFIG["terminal"]["sandbox_macos_secrets"] is True + + +def test_local_environment_spawn_uses_sandbox_wrapper(monkeypatch, tmp_path): + monkeypatch.setattr(local.sys, "platform", "darwin") + env = local.LocalEnvironment.__new__(local.LocalEnvironment) + env.cwd = str(tmp_path) + env.env = {} + captured = {} + + monkeypatch.setattr(local, "_find_bash", lambda: "/bin/bash") + monkeypatch.setattr(local, "_make_run_env", lambda _env: {}) + monkeypatch.setattr(env, "_recover_cwd", lambda: None) + + def fake_popen(args, **kwargs): + captured["args"] = args + class FakeProcess: + pid = 1 + return FakeProcess() + + monkeypatch.setattr(local.subprocess, "Popen", fake_popen) + monkeypatch.setattr(local, "own_process_groups", lambda _groups: None) + monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec") + with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}): + with patch("gateway.status.get_process_start_time", return_value=None): + env._run_bash("echo hi") + + assert captured["args"][:2] == ["/usr/bin/sandbox-exec", "-p"] + assert captured["args"][-3:] == ["/bin/bash", "-c", "echo hi"] + + +@pytest.mark.parametrize("platform", ["darwin", "linux"]) +@pytest.mark.parametrize("use_pty", [False, True]) +def test_background_spawn_sandbox(platform, use_pty, monkeypatch, tmp_path): + from types import SimpleNamespace + from tools import process_registry as pr + + registry = pr.ProcessRegistry() + session = pr.ProcessSession(id="proc_test", command="echo hi", task_id="test", cwd=str(tmp_path)) + captured = {} + monkeypatch.setattr(local.sys, "platform", platform) + monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec") + monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile") + monkeypatch.setattr(pr, "_find_shell", lambda: "/bin/bash") + monkeypatch.setattr(pr, "_IS_LINUX", False) + monkeypatch.setattr(pr, "worker_output_log", lambda _id: None) + monkeypatch.setattr(registry, "_spawn_env", lambda _env: {}) + monkeypatch.setattr(registry, "_track_started", lambda *args: None) + monkeypatch.setattr(registry, "_safe_host_start_time", lambda _pid: None) + monkeypatch.setattr(registry, "_own_pty_job", lambda *_args: None) + + def capture(argv, **kwargs): + captured["argv"] = argv + return SimpleNamespace(pid=1234) + + monkeypatch.setattr(registry, "_spawn_job", lambda _session, argv, _persist, **kwargs: capture(argv, **kwargs)) + with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}): + with patch("ptyprocess.PtyProcess.spawn", side_effect=capture): + registry._spawn_local_admitted(session, "echo hi", {}, use_pty, False) + + shell = ["/bin/bash", "-lic", "set +m; echo hi"] + expected = (["/usr/bin/sandbox-exec", "-p", "profile", "/usr/bin/env", "HERMES_SECRET_SANDBOX=1", *shell] + if platform == "darwin" else shell) + assert captured["argv"] == expected + + +def test_profile_covers_shared_credentials_root_and_writes(tmp_path, monkeypatch): + import json + from agent.file_safety import _CREDENTIAL_FILE_NAMES + + root = tmp_path / 'José " space' + home = root / "profiles" / "nemo" + monkeypatch.setenv("HERMES_HOME", str(home)) + profile = local._local_macos_secret_profile() + for path in [*(home / name for name in _CREDENTIAL_FILE_NAMES), home / ".op.env", + home / ".rr-token", root / "auth.json"]: + literal = json.dumps(str(path), ensure_ascii=False) + assert f"(deny file-read* file-write* file-link (literal {literal}))" in profile + for path in (home, *home.parents, home / "config.yaml"): + assert f"(deny file-write* (literal {json.dumps(str(path), ensure_ascii=False)}))" in profile + assert str(home / "logs") not in profile + + +def test_profile_denies_secret_directories_and_symlink_ancestors(tmp_path, monkeypatch): + real = tmp_path / "real" + real.mkdir() + alias = tmp_path / "alias" + alias.symlink_to(real, target_is_directory=True) + home = alias / "profiles" / "nemo" + monkeypatch.setenv("HERMES_HOME", str(home)) + profile = local._local_macos_secret_profile() + for path in (home, *home.parents): + for spelling in (path, path.resolve()): + assert f'(deny file-write* (literal "{spelling}"))' in profile + for name in ("mcp-tokens", "vault", "browser-profile", "webapp"): + for path in (home / name, (home / name).resolve()): + assert f'(deny file-read* file-write* file-link (subpath "{path}"))' in profile + + +def test_profile_rejects_control_characters(tmp_path, monkeypatch): + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "bad\x01home")) + with pytest.raises(ValueError, match="control characters"): + local._local_macos_secret_profile() + + +def test_config_error_still_wraps(monkeypatch): + monkeypatch.setattr(local.sys, "platform", "darwin") + monkeypatch.setattr(local.os.path, "exists", lambda path: True) + monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile") + with patch("hermes_cli.config_effective.load_user_config_effective", side_effect=OSError): + assert local._sandbox_local_macos_argv(["shell"])[0:2] == ["/usr/bin/sandbox-exec", "-p"] + + +def test_kernel_spawn_uses_sandbox(monkeypatch, tmp_path): + from types import SimpleNamespace + from tools import code_kernel + + monkeypatch.setattr(local.sys, "platform", "darwin") + monkeypatch.setattr(local.os.path, "exists", lambda path: path == "/usr/bin/sandbox-exec") + monkeypatch.setattr(local, "_local_macos_secret_profile", lambda: "profile") + monkeypatch.setattr(code_kernel.tempfile, "mkdtemp", lambda **kwargs: str(tmp_path)) + monkeypatch.setattr(code_kernel, "_bind_rpc_socket", lambda kernel: "socket") + monkeypatch.setattr(code_kernel, "_ensure_background_reaper", lambda: None) + monkeypatch.setattr(code_kernel.threading, "Thread", lambda **kwargs: SimpleNamespace(start=lambda: None)) + captured = {} + def spawn(argv, **kwargs): + captured["argv"] = argv + return SimpleNamespace(pid=1234) + monkeypatch.setattr("hermes_cli.process_identity.spawn_owned", spawn) + monkeypatch.setattr("tools.code_execution_env._build_child_env", lambda **kwargs: {}) + monkeypatch.setattr("tools.code_execution_tool.generate_hermes_tools_module", lambda tools: "") + with patch("hermes_cli.config_effective.load_user_config_effective", return_value={"terminal": {}}): + code_kernel._spawn(code_kernel.SessionKernel(("test",)), child_python="/bin/python", child_cwd="", + sandbox_tools=frozenset(), max_tool_calls=1) + assert captured["argv"] == ["/usr/bin/sandbox-exec", "-p", "profile", "/usr/bin/env", + "HERMES_SECRET_SANDBOX=1", "/bin/python", str(tmp_path / "hermes_kernel_runner.py")] + diff --git a/forks/hermes-agent/tools/code_kernel.py b/forks/hermes-agent/tools/code_kernel.py index a36de8686..565540074 100644 --- a/forks/hermes-agent/tools/code_kernel.py +++ b/forks/hermes-agent/tools/code_kernel.py @@ -573,6 +573,7 @@ def _parent_process_handle(child_env: dict[str, str]): def _spawn(kernel: SessionKernel, *, child_python: str, child_cwd: str, sandbox_tools: frozenset, max_tool_calls: int, task_id: str = "") -> None: from tools.code_execution_env import _build_child_env + from tools.environments.local import _sandbox_local_macos_argv from tools.code_execution_tool import generate_hermes_tools_module kernel.tmpdir = tempfile.mkdtemp(prefix="hermes_kernel_") kernel.rpc_token = secrets.token_urlsafe(32) @@ -596,7 +597,8 @@ def _spawn(kernel: SessionKernel, *, child_python: str, child_cwd: str, from hermes_cli.process_identity import spawn_owned try: kernel.proc = spawn_owned( - [child_python, os.path.join(kernel.tmpdir, "hermes_kernel_runner.py")], purpose="code-kernel", + _sandbox_local_macos_argv([child_python, os.path.join(kernel.tmpdir, "hermes_kernel_runner.py")]), + purpose="code-kernel", # Strict mode passes an empty cwd: the kernel's staging dir plays the per-call tmpdir's role. cwd=child_cwd or kernel.tmpdir, env=child_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, diff --git a/forks/hermes-agent/tools/environments/local.py b/forks/hermes-agent/tools/environments/local.py index 4a17717fd..d580b7d38 100644 --- a/forks/hermes-agent/tools/environments/local.py +++ b/forks/hermes-agent/tools/environments/local.py @@ -1,6 +1,7 @@ """Local execution environment — spawn-per-call with session snapshot.""" import contextlib +import json import logging import ntpath import os @@ -17,7 +18,7 @@ from collections.abc import Mapping from pathlib import Path -from hermes_constants import get_process_hermes_home +from hermes_constants import get_hermes_home, get_process_hermes_home from tools.environments.base import BaseEnvironment from tools.environments.base_output import _pipe_stdin from hermes_cli._subprocess_compat import windows_hide_flags @@ -844,6 +845,59 @@ def _read_terminal_shell_init_config() -> tuple[list[str], bool]: return [], True +def _local_macos_secret_profile() -> str: + """Protect credential files; IPC to unsandboxed services remains outside this sandbox.""" + from agent.file_safety import _CREDENTIAL_FILE_NAMES, _READ_DENIED_DIRS + from hermes_constants import get_default_hermes_root + + home = get_hermes_home().absolute() + root = get_default_hermes_root(home=home).absolute() + secrets = [home / name for name in (*_CREDENTIAL_FILE_NAMES, ".op.env", ".rr-token")] + secrets.append(root / "auth.json") + + def aliases(paths): + return dict.fromkeys(alias for path in paths for alias in (path, path.resolve())) + + def literal(path): + value = str(path) + if any(ord(char) < 32 or ord(char) == 127 for char in value): + raise ValueError("sandbox paths cannot contain control characters") + return json.dumps(value, ensure_ascii=False) + + rules = [f"(deny file-read* file-write* file-link (literal {literal(path)}))" + for path in aliases(secrets)] + rules.extend(f"(deny file-read* file-write* file-link (subpath {literal(path)}))" + for path in aliases(home / name for name, _, _ in _READ_DENIED_DIRS)) + rules.extend(f"(deny file-write* (literal {literal(path)}))" + for path in aliases((home / "config.yaml", home, *home.parents))) + return "\n".join(["(version 1)", "(allow default)", *rules]) + + +_sandbox_missing_warned = False + + +def _sandbox_local_macos_argv(args: list[str]) -> list[str]: + """Hide Hermes secrets from local macOS terminal shells when sandbox-exec is available.""" + global _sandbox_missing_warned + if sys.platform != "darwin": + return args + try: + from hermes_cli.config_effective import load_user_config_effective + terminal_cfg = (load_user_config_effective() or {}).get("terminal") or {} + if terminal_cfg.get("sandbox_macos_secrets", True) is False: + return args + except Exception: + pass # An unreadable config must not prevent terminal execution. + sandbox_exec = "/usr/bin/sandbox-exec" + if not os.path.exists(sandbox_exec): + if not _sandbox_missing_warned: + _sandbox_missing_warned = True + logger.warning( + "sandbox-exec is unavailable; running local macOS terminal command without secret-file sandboxing") + return args + return [sandbox_exec, "-p", _local_macos_secret_profile(), "/usr/bin/env", "HERMES_SECRET_SANDBOX=1", *args] + + def _resolve_shell_init_files() -> list[str]: """Files to source before the login-shell snapshot (``~``/``${VAR}`` expanded, missing dropped). ``auto_source_bashrc`` applies only without an explicit list: @@ -1157,6 +1211,7 @@ def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120, 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] + args = _sandbox_local_macos_argv(args) self._recover_cwd() # Not spawn_owned: an awaited command needs no spawn-ledger entry; own_process_groups below hands # its group to the owner-death supervisor and _wait_for_process releases it. diff --git a/forks/hermes-agent/tools/process_registry.py b/forks/hermes-agent/tools/process_registry.py index 0289e41ee..36b597109 100644 --- a/forks/hermes-agent/tools/process_registry.py +++ b/forks/hermes-agent/tools/process_registry.py @@ -25,7 +25,8 @@ # (not merely "not Windows") so macOS and other POSIX platforms never touch systemd. # See #70716. _IS_LINUX = platform.system() == "Linux" -from tools.environments.local import _append_dropped_path_entries, _find_shell, _resolve_safe_cwd, _sanitize_subprocess_env, _terminal_env +from tools.environments.local import (_append_dropped_path_entries, _find_shell, _resolve_safe_cwd, + _sandbox_local_macos_argv, _sanitize_subprocess_env, _terminal_env) from hermes_cli._subprocess_compat import windows_hide_flags from dataclasses import dataclass, field from typing import Any, Dict, List, Literal, NamedTuple, Optional @@ -1138,7 +1139,7 @@ def _scope_argv(self, session: ProcessSession, safe_command: str, unit_suffix: s sourced, user tools on PATH), wrapped in a transient systemd scope when we are the supervised gateway (own cgroup: an OOM kills only the worker, not the gateway and its messaging control plane).""" - argv = [_find_shell(), "-lic", f"set +m; {safe_command}"] + argv = _sandbox_local_macos_argv([_find_shell(), "-lic", f"set +m; {safe_command}"]) # This applies to both pipe mode and the PTY path above. See #70716. in_supervised_gateway = _IS_LINUX and _is_supervised_gateway_process() if in_supervised_gateway and _systemd_run_user_scope_available():