The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): browser_exec binds its daemon socket under a deep HOME
Teknium92e8a6398d8c
diff --git a/tests/tools/test_browser_harness_default_socket.py b/tests/tools/test_browser_harness_default_socket.pynew file mode 100644index 00000000000..8f12212b776--- /dev/null+++ b/tests/tools/test_browser_harness_default_socket.py@@ -0,0 +1,94 @@+"""browser_exec outside a served profile: the harness daemon socket must bind under a deep HOME.++browser-harness binds ``<home>/.config/browser-harness/runtime/bu-<BU_NAME>.sock`` unless+``BH_RUNTIME_DIR`` says otherwise. A container's profile home (``$HERMES_HOME/home``) or a long+account home overflowed sun_path and every call died with ``AF_UNIX path too long``.+"""+import json+import os+import socket+import stat+from pathlib import Path++import pytest++import tools.browser_use_cli as bu_cli+from tools import browser_harness_dirs as harness_dirs+from tools import browser_session as bs+++def harness_env(tmp_path, monkeypatch):+ """A fake harness CLI that echoes the env it was launched with; returns a driver."""+ for key in ("BU_NAME", "BH_HOME", "BROWSER_HARNESS_HOME", "XDG_CONFIG_HOME", "BH_RUNTIME_DIR",+ "BH_TMP_DIR", "BROWSER_USE_API_KEY", "BROWSER_CDP_URL"):+ monkeypatch.delenv(key, raising=False)+ monkeypatch.setattr(bs, "get_session_info", lambda key: {+ "cdp_url": "ws://127.0.0.1:47000/devtools/browser/x", "features": {"local": True}})+ from tools import browser_supervisor++ class _Registry:+ def get_or_start(self, *a, **kw):+ return None++ def get(self, task_id):+ return None++ monkeypatch.setattr(browser_supervisor, "SUPERVISOR_REGISTRY", _Registry())+ monkeypatch.setattr("hermes_cli.config_effective.load_user_config_effective", lambda: {"browser": {}})+ monkeypatch.setattr("tools.browser_session_cdp.resolve_cdp_override", lambda url: url)+ cli = tmp_path / "browser-harness"+ cli.write_text('#!/bin/sh\ncat > /dev/null\necho "{\\"home\\": \\"$HOME\\", \\"runtime\\": \\"$BH_RUNTIME_DIR\\", '+ '\\"shared\\": \\"$BH_RUNTIME_DIR_SHARED\\", \\"name\\": \\"${BU_NAME:-default}\\"}"\n',+ encoding="utf-8")+ cli.chmod(cli.stat().st_mode | stat.S_IXUSR)+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: [str(cli)])+ claimed = [] # conftest keeps unit tests out of the shared temp root; record the claim instead+ monkeypatch.setattr(harness_dirs, "claim_private_dir", lambda path: claimed.append(path) or True)++ def drive(home: str, session: str = "") -> tuple[dict, list]:+ monkeypatch.setenv("HOME", home)+ result = json.loads(bu_cli.browser_exec("print(1)", session=session, task_id="t-sock"))+ assert result["success"] is True, result+ return json.loads(result["output"]), claimed++ return drive+++def _bound_socket(seen: dict) -> str:+ """The socket browser_harness/_ipc.py binds for that env: ``bu-<NAME>.sock`` under the resolved+ BH_RUNTIME_DIR (shared stems), else under ``<home>/.config/browser-harness/runtime``."""+ runtime = seen["runtime"] or f"{seen['home']}/.config/browser-harness/runtime"+ return f"{Path(runtime).resolve()}/bu-{seen['name']}.sock"+++def _kernel_accepts(path: str) -> bool:+ """An unbound dir answers ENOENT; an overlong path answers "AF_UNIX path too long" first."""+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ try:+ s.bind(path)+ except OSError as e:+ return "too long" not in str(e)+ else:+ os.unlink(path)+ return True+ finally:+ s.close()++[email protected]("linux")+def test_a_deep_home_gets_a_daemon_socket_the_kernel_accepts(harness_env, tmp_path):+ deep_home = str(tmp_path / "profiles" / ("research-assistant-" * 3) / "home")+ seen, claimed = harness_env(deep_home)+ assert seen["shared"] == "1" and claimed == [seen["runtime"]] # keeps bu-<name> stems, private dir+ assert _kernel_accepts(_bound_socket(seen)), _bound_socket(seen)++[email protected]("linux")+def test_a_socket_that_already_binds_keeps_its_path_and_a_long_name_is_judged_by_its_own_length(harness_env):+ """The default name under an ordinary home binds today: its daemon (and live socket) stay put.+ A 64-character session under the same home overflows, so that call moves."""+ seen, claimed = harness_env("/home/alexander.smith")+ assert seen["runtime"] == "" and claimed == []+ seen, claimed = harness_env("/home/alexander.smith", session="n" * 64)+ assert seen["runtime"] and _kernel_accepts(_bound_socket(seen)), _bound_socket(seen)diff --git a/tools/browser_harness_dirs.py b/tools/browser_harness_dirs.pyindex 49671e220d6..1c5df011f86 100644--- a/tools/browser_harness_dirs.py+++ b/tools/browser_harness_dirs.py@@ -3,9 +3,12 @@A multiplexed gateway serves every profile from one process. The harness names a daemon by``BU_NAME`` alone and reuses any live one, so each served profile gets its own runtime dir (daemonsockets) and tmp dir (screenshots, debug overlays, logs). A runtime dir too long for a 64-character-session's AF_UNIX socket moves to a private short dir under the socket temp root.+session's AF_UNIX socket moves to a private short dir under ``$XDG_RUNTIME_DIR`` or the socket temp+root; outside a served profile, so does a default runtime dir whose socket for the call's own+``BU_NAME`` would overflow (a deep HOME).-``browser_use_cli._base_subprocess_env`` applies the result through ``namespace_harness_dirs``.+``browser_use_cli._base_subprocess_env`` applies the result through ``namespace_harness_dirs``, and+``browser_exec`` calls ``fit_default_socket_dir`` once the call's ``BU_NAME`` is final."""from __future__ import annotations@@ -61,12 +64,7 @@ def namespace_harness_dirs(env: dict, tag: str) -> None:``tag`` (outside a served-profile scope) leaves ``env`` unchanged."""if not tag:return- root = env.get("BH_HOME") or env.get("BROWSER_HARNESS_HOME")- if not root: # browser-harness paths.home_dir(), resolved against the child's env- xdg = env.get("XDG_CONFIG_HOME")- root = str(Path(xdg) / "browser-harness") if xdg else str(- Path(env.get("HOME") or Path.home()) / ".config" / "browser-harness")- root = str(Path(root).expanduser())+ root = _harness_home(env)leaf = f"p-{hashlib.sha256(tag.encode()).hexdigest()[:12]}"base = env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR") or str(Path(root) / "runtime")runtime = str(Path(base) / leaf)@@ -77,27 +75,86 @@ def namespace_harness_dirs(env: dict, tag: str) -> None:env["BH_TMP_DIR_SHARED"] = "1"+def _harness_home(env: dict) -> str:+ """browser-harness ``paths.home_dir()``, resolved against the child's env."""+ root = env.get("BH_HOME") or env.get("BROWSER_HARNESS_HOME")+ if not root:+ xdg = env.get("XDG_CONFIG_HOME")+ root = str(Path(xdg) / "browser-harness") if xdg else str(+ Path(env.get("HOME") or Path.home()) / ".config" / "browser-harness")+ return str(Path(root).expanduser())+++def fit_default_socket_dir(env: dict) -> None:+ """Outside a served profile the harness binds ``<home>/runtime/bu-<BU_NAME>.sock``. Under a deep+ HOME (a container's profile home ``$HERMES_HOME/home``, a long account home) that path overflows+ sun_path and every call dies with ``AF_UNIX path too long``; such a call's runtime dir moves to a+ private short dir. Judged on the call's own BU_NAME so a socket that already binds keeps its+ path (and its live daemon). A runtime/tmp dir already set (a served profile's, or exported by+ the user) is left alone."""+ if env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR"):+ return+ budget = socket_dir_budget(sys.platform)+ if budget is None:+ return+ root = _harness_home(env)+ stem_budget = budget + 64 - len(env.get("BU_NAME") or "default") # budget assumes a 64-char name+ if fits_socket_budget(str((Path(root) / "runtime").resolve()), stem_budget):+ return+ short = _claim_short_dir(f"{root}\0", stem_budget)+ if short:+ env["BH_RUNTIME_DIR"] = short+ env["BH_RUNTIME_DIR_SHARED"] = "1" # several BU_NAMEs share the dir: keep bu-<name> stems++def socket_fit_runtime_dir(runtime: str, base: str, tag: str) -> str:"""``runtime`` unless the socket the harness binds under it would be too long for a 64-charactersession. The harness binds ``Path(BH_RUNTIME_DIR).expanduser().resolve()``, so the length isjudged on that path (a short relative or symlinked spelling can still resolve deep); a dir that- fits is returned as given. Otherwise the served profile gets a private dir under the short socket- temp root (``hbh-<12 hex>``), keyed by uid, base and profile; if none fits or can be claimed safely- the long path stays (shorter names only)."""+ fits is returned as given. Otherwise the served profile gets a private short dir+ (``_claim_short_dir``) keyed by base and profile; if none fits or can be claimed safely the long+ path stays (shorter names only)."""budget = socket_dir_budget(sys.platform)if fits_socket_budget(str(Path(runtime).expanduser().resolve()), budget):return runtime+ return _claim_short_dir(f"{base}\0{tag}", budget) or runtime+++def _claim_short_dir(key: str, budget: Optional[int]) -> Optional[str]:+ """A private ``hbh-<12 hex>`` dir (keyed by uid and ``key``) that fits ``budget``: under the+ user's private ``$XDG_RUNTIME_DIR`` first, else the short socket temp root; None when no+ candidate fits or can be claimed safely."""from hermes_constants import socket_safe_tmpdirgetuid = getattr(os, "getuid", lambda: 0)- digest = hashlib.sha256(f"{getuid()}\0{base}\0{tag}".encode()).hexdigest()[:12]+ digest = hashlib.sha256(f"{getuid()}\0{key}".encode()).hexdigest()[:12]# socket_safe_tmpdir() caps the root at 50 bytes for Chrome's longer socket names; ours needs a- # root of at most 17, which a Hermes scratch TMPDIR exceeds, so the sticky system root follows.- roots = dict.fromkeys(os.path.realpath(r) for r in (socket_safe_tmpdir(), "/tmp")) # no-tmp: ok — AF_UNIX sun_path budget; dir claimed 0700 and ownership-checked+ # root of at most 17-21, which a Hermes scratch TMPDIR exceeds, so the sticky system root follows.+ # A container or macOS has no XDG_RUNTIME_DIR, which is why the shared roots stay as fallbacks.+ xdg = [xdg_dir] if (xdg_dir := private_user_runtime_dir()) else []+ roots = dict.fromkeys(os.path.realpath(r) for r in (*xdg, socket_safe_tmpdir(), "/tmp")) # no-tmp: ok — AF_UNIX sun_path budget; dir claimed 0700 and ownership-checkedfor root in roots:short = os.path.join(root, f"hbh-{digest}")if fits_socket_budget(short, budget) and claim_private_dir(short):return short- return runtime+ return None+++def private_user_runtime_dir() -> Optional[str]:+ """``$XDG_RUNTIME_DIR`` (a system-unit gateway has none: ``/run/user/<uid>`` then) when it is+ what the spec promises: an absolute real directory owned by this uid with no group/other access,+ so no other user can pre-create a name inside it."""+ getuid = getattr(os, "getuid", None)+ if getuid is None:+ return None+ raw = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{getuid()}"+ if not os.path.isabs(raw):+ return None+ try:+ st = os.lstat(raw)+ except OSError:+ return None+ ours = stat.S_ISDIR(st.st_mode) and st.st_uid == getuid()+ return raw if ours and not st.st_mode & 0o077 else Nonedef claim_private_dir(path: str) -> bool:diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 5f09da97ca7..fa450229bb1 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -24,7 +24,8 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, List, NamedTuple, Optionalfrom hermes_constants import get_hermes_home, hermes_home_key-from tools.browser_harness_dirs import daemon_env, daemon_identity, namespace_harness_dirs+from tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir,+ namespace_harness_dirs)from utils import is_truthy_valuelogger = logging.getLogger(__name__)@@ -718,6 +719,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTreturn tool_error(route_err)if local_sidecar:env["BU_NAME"] = _sidecar_daemon_name(session)+ fit_default_socket_dir(env) # BU_NAME is final: a deep HOME's socket would overflow sun_path_exec_route_is_sidecar[route_key] = local_sidecarlocal_engine = env.pop(_BOT_DESKTOP_BROWSER_SENTINEL, None)bot_desktop_browser = bool(local_engine)