The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): harness dir policy in its own module; socket length judged on the resolved path
Teknium0d067c91f9a6
diff --git a/tests/tools/conftest.py b/tests/tools/conftest.pyindex 41afea411ca..796e3a9775e 100644--- a/tests/tools/conftest.py+++ b/tests/tools/conftest.py@@ -41,11 +41,11 @@ def _no_shared_temp_socket_dirs():in the shared temp root (sun_path budget). Unit tests never claim one there: fake CLIs wouldleave latch files behind. The dir keeps its long path; tests of the claim restore the real one."""try:- import tools.browser_use_cli as bu_cli+ import tools.browser_harness_dirs as harness_dirsexcept Exception:yieldreturn- with patch.object(bu_cli, "_claim_private_dir", lambda path: False):+ with patch.object(harness_dirs, "claim_private_dir", lambda path: False):yielddiff --git a/tests/tools/test_browser_profile_scope_edges.py b/tests/tools/test_browser_profile_scope_edges.pyindex 413a5904630..1e0c651c17f 100644--- a/tests/tools/test_browser_profile_scope_edges.py+++ b/tests/tools/test_browser_profile_scope_edges.py@@ -12,7 +12,8 @@ from agent import secret_scopefrom gateway.run import _profile_runtime_scopefrom hermes_constants import get_hermes_home, hermes_home_keyfrom tools import browser_tool_cdp as bt_cdp-from tools.browser_use_cli import _claim_private_dir as _REAL_CLAIM # conftest stubs it per test+from tools import browser_harness_dirs as harness_dirs+from tools.browser_harness_dirs import claim_private_dir as _REAL_CLAIM # conftest stubs it per test@pytest.fixture@@ -78,26 +79,22 @@ def test_installed_harness_names_a_shared_dir_socket_bu_name_sock(tmp_path):assert out == f"{rt.resolve()}/bu-{_LONGEST_NAME}.sock"-def test_a_served_profiles_harness_socket_fits_macos_sun_path_on_a_default_home(profiles, monkeypatch):- """macOS ``sun_path`` is 104 bytes (103 + NUL). Under ``~/.config/browser-harness/runtime/p-<hash>``- a served profile's socket left room for only ~31-character session names on a 9-letter account."""- import os- import sys- from tools import browser_use_cli as bu_cli- a, _b = profiles- real = os.path.realpath- # os-marker: ok — computed length on a fixed macOS-shaped HOME; the real branch runs in the macOS test below- monkeypatch.setattr(sys, "platform", "darwin")- monkeypatch.setattr(os.path, "realpath", # no-tmp: ok — macOS resolves the /tmp alias- lambda p, *args, **kw: "/private/tmp" if p == "/tmp" else real(p, *args, **kw))- claimed = []- monkeypatch.setattr(bu_cli, "_claim_private_dir", lambda path: claimed.append(path) or True, raising=False)- env = {"HOME": "/Users/alexander"}- with _profile_runtime_scope(a, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)- assert env["BH_RUNTIME_DIR_SHARED"] == "1"- assert _sock_len(env["BH_RUNTIME_DIR"]) <= 103, env["BH_RUNTIME_DIR"]- assert claimed == [env["BH_RUNTIME_DIR"]][email protected](("platform", "budget"), [("darwin", 103 - 73), ("linux", 107 - 73), ("win32", None)])+def test_the_socket_dir_budget_is_sun_path_minus_a_64_char_session_socket(platform, budget):+ """macOS ``sun_path`` is 104 bytes (103 + NUL), Linux 108; Windows serves over loopback TCP."""+ assert harness_dirs.socket_dir_budget(platform) == budget+++def test_a_default_macos_home_does_not_fit_and_the_short_temp_dir_does():+ """Pure length rule with macOS data (no host platform involved): under+ ``~/.config/browser-harness/runtime/p-<hash>`` a 9-letter account left room for ~31-character+ session names; ``/private/tmp/hbh-<12 hex>`` fits a 64-character one."""+ budget = harness_dirs.socket_dir_budget("darwin")+ home = "/Users/alexander/.config/browser-harness/runtime/p-0123456789ab"+ short = "/private/tmp/hbh-0123456789ab" # no-tmp: ok — a macOS path as data, nothing is written+ assert not harness_dirs.fits_socket_budget(home, budget)+ assert harness_dirs.fits_socket_budget(short, budget) and _sock_len(short) <= 103+ assert harness_dirs.fits_socket_budget("x" * 500, None) # no sun_path limit@pytest.mark.platforms("macos")@@ -107,10 +104,10 @@ def test_on_macos_a_served_profile_binds_a_64_char_session_socket(profiles, tmp_import socketfrom tools import browser_use_cli as bu_clia, _b = profiles- monkeypatch.setattr(bu_cli, "_claim_private_dir", _REAL_CLAIM) # the real claim, real short root+ monkeypatch.setattr(harness_dirs, "claim_private_dir", _REAL_CLAIM) # the real claim, real short rootenv = {"HOME": str(tmp_path / ("u" * 40))}with _profile_runtime_scope(a, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())path = f"{os.path.realpath(env['BH_RUNTIME_DIR'])}/bu-{_LONGEST_NAME}.sock"assert len(path.encode()) <= 103s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)@@ -150,10 +147,10 @@ def test_on_linux_a_served_profiles_64_char_session_socket_fits_sun_path(profilefrom tools import browser_use_cli as bu_clia, _b = profilesclaimed = []- monkeypatch.setattr(bu_cli, "_claim_private_dir", lambda path: claimed.append(path) or True)+ monkeypatch.setattr(harness_dirs, "claim_private_dir", lambda path: claimed.append(path) or True)env = {"HOME": user_home}with _profile_runtime_scope(a, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())sock = f"{env['BH_RUNTIME_DIR']}/bu-{_LONGEST_NAME}.sock"assert claimed == [env["BH_RUNTIME_DIR"]]assert _sock_len(env["BH_RUNTIME_DIR"]) <= 107 and _kernel_accepts_sun_path(sock), sock@@ -165,18 +162,47 @@ def test_on_linux_a_runtime_dir_that_already_fits_is_kept_and_an_unclaimable_onefrom tools import browser_use_cli as bu_clia, _b = profilesclaimed = []- monkeypatch.setattr(bu_cli, "_claim_private_dir", lambda path: claimed.append(path) or True)+ monkeypatch.setattr(harness_dirs, "claim_private_dir", lambda path: claimed.append(path) or True)env = {"BH_HOME": "/b"}with _profile_runtime_scope(a, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())assert env["BH_RUNTIME_DIR"].startswith("/b/runtime/p-") and claimed == []- monkeypatch.setattr(bu_cli, "_claim_private_dir", lambda path: False) # squatted / not ours+ monkeypatch.setattr(harness_dirs, "claim_private_dir", lambda path: False) # squatted / not oursenv = {"HOME": "/home/teknium"}with _profile_runtime_scope(a, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())assert env["BH_RUNTIME_DIR"].startswith("/home/teknium/.config/browser-harness/runtime/p-")[email protected]("linux")[email protected]("via", ["relative", "symlink"])+def test_on_linux_a_short_spelling_of_a_long_runtime_dir_is_measured_resolved(profiles, monkeypatch, tmp_path, via):+ """The harness binds ``Path(BH_RUNTIME_DIR).expanduser().resolve()``: a short relative or symlinked+ spelling of a deep dir still gives an overlong socket, so the length is judged on the resolved path."""+ import os+ from tools import browser_use_cli as bu_cli+ a, _b = profiles+ deep = tmp_path / ("d" * 60)+ deep.mkdir()+ if via == "relative": # BH_RUNTIME_DIR=rt from a deep working directory+ monkeypatch.chdir(deep)+ base = "rt"+ else: # a short symlink to a deep dir+ link = tmp_path / "l"+ link.symlink_to(deep)+ monkeypatch.chdir(tmp_path)+ base = "l"+ claimed = []+ monkeypatch.setattr(harness_dirs, "claim_private_dir", lambda path: claimed.append(path) or True)+ env = {"BH_RUNTIME_DIR": base}+ with _profile_runtime_scope(a, hydrate_secrets=False):+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())+ resolved = os.path.realpath(env["BH_RUNTIME_DIR"])+ assert _sock_len(resolved) <= 107, resolved+ assert _kernel_accepts_sun_path(f"{resolved}/bu-{_LONGEST_NAME}.sock")+ assert claimed == [env["BH_RUNTIME_DIR"]]++def test_the_short_socket_dir_is_claimed_only_when_private_and_ours(tmp_path):"""The short dir sits in a world-writable root: a symlink or another user's/open dir is refused."""fresh = tmp_path / "hbh-fresh"@@ -203,13 +229,13 @@ def test_each_served_profile_gets_its_own_harness_tmp_dir(profiles, tmp_path):for home in (a, b):env = {"BH_HOME": str(tmp_path / "bh")}with _profile_runtime_scope(home, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())assert env.get("BH_TMP_DIR_SHARED") == "1" # several BU_NAMEs share it: keep bu-<name>.log stemsseen[home] = env.get("BH_TMP_DIR")assert seen[a] and seen[b] and seen[a] != seen[b]assert all(str(p).startswith(str(tmp_path / "bh" / "tmp")) for p in seen.values())unscoped = {"BH_HOME": str(tmp_path / "bh")}- bu_cli._namespace_harness_daemons(unscoped)+ harness_dirs.namespace_harness_dirs(unscoped, bu_cli._served_profile_tag())assert unscoped == {"BH_HOME": str(tmp_path / "bh")} # single-profile: unchanged@@ -218,7 +244,7 @@ def test_a_served_profile_under_an_inherited_tmp_dir_nests_inside_it(profiles, ta, _b = profilesenv = {"BH_TMP_DIR": str(tmp_path / "shared-tmp")}with _profile_runtime_scope(a, hydrate_secrets=False):- bu_cli._namespace_harness_daemons(env)+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())assert env["BH_TMP_DIR"].startswith(str(tmp_path / "shared-tmp") + "/p-")# The runtime dir still derives from the inherited BH_TMP_DIR (harness fallback), not the new one.assert env["BH_RUNTIME_DIR"].startswith(str(tmp_path / "shared-tmp") + "/p-")@@ -231,8 +257,8 @@ def test_an_unscoped_shutdown_reload_reaches_the_daemon_with_its_own_tmp_dir(proa, _b = profileswith _profile_runtime_scope(a, hydrate_secrets=False):env = {"HOME": "/home/u"}- bu_cli._namespace_harness_daemons(env)- key = (*(env.get(k, "") for k in bu_cli._HARNESS_DIR_KEYS), "s1")+ harness_dirs.namespace_harness_dirs(env, bu_cli._served_profile_tag())+ key = harness_dirs.daemon_identity({**env, "BU_NAME": "s1"})monkeypatch.setattr(bu_cli, "_driven_daemons", {key: hermes_home_key(a)})monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["browser-harness"])seen = []@@ -359,7 +385,7 @@ def test_a_browser_exec_that_routed_to_the_old_endpoint_during_a_connect_reloadsdef run(cmd, code, env, timeout):import subprocess- ident = (*(env.get(k, "") for k in bu_cli._HARNESS_DIR_KEYS), env.get("BU_NAME", "default"))+ ident = harness_dirs.daemon_identity(env)if cmd[-1] == "--reload":latched.pop(ident, None)else:@@ -403,7 +429,7 @@ def test_a_connect_that_lands_while_browser_exec_spawns_its_daemon_reloads_it(prlatched, connects = {}, []def run(cmd, code, env, timeout):- ident = (*(env.get(k, "") for k in bu_cli._HARNESS_DIR_KEYS), env.get("BU_NAME", "default"))+ ident = harness_dirs.daemon_identity(env)if cmd[-1] == "--reload":latched.pop(ident, None)return subprocess.CompletedProcess(cmd, 0, "", "")diff --git a/tools/browser_harness_dirs.py b/tools/browser_harness_dirs.pynew file mode 100644index 00000000000..49671e220d6--- /dev/null+++ b/tools/browser_harness_dirs.py@@ -0,0 +1,119 @@+"""Per-profile runtime and tmp dirs for browser-harness daemons (Browser Use mode).++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 (daemon+sockets) 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.++``browser_use_cli._base_subprocess_env`` applies the result through ``namespace_harness_dirs``.+"""+from __future__ import annotations++import hashlib+import os+import stat+import sys+from pathlib import Path+from typing import Optional++# browser_harness/_ipc.py: a shared runtime dir names a daemon socket ``<dir>/bu-<BU_NAME>.sock`` and+# BU_NAME may be 64 characters, so the dir gets sun_path (macOS 104 bytes, Linux 108, with the NUL)+# minus 73 (`/bu-` + 64 + `.sock`).+_MACOS_SOCKET_DIR_BUDGET = 103 - len("/bu-.sock") - 64+_LINUX_SOCKET_DIR_BUDGET = 107 - len("/bu-.sock") - 64+++# The env keys that, with BU_NAME, identify one harness daemon (a served profile's dirs are its own).+HARNESS_DIR_KEYS = ("BH_RUNTIME_DIR", "BH_RUNTIME_DIR_SHARED", "BH_TMP_DIR", "BH_TMP_DIR_SHARED")+++def daemon_identity(env: dict) -> tuple[str, ...]:+ """``(*HARNESS_DIR_KEYS values, BU_NAME)`` of the daemon a call with ``env`` drives."""+ return (*(env.get(k, "") for k in HARNESS_DIR_KEYS), env.get("BU_NAME", "default"))+++def daemon_env(env: dict, identity: tuple[str, ...]) -> dict:+ """``env`` re-pointed at the daemon ``identity`` names (its own dirs and BU_NAME)."""+ *dirs, name = identity+ target = {k: v for k, v in env.items() if k not in HARNESS_DIR_KEYS}+ target.update((k, v) for k, v in zip(HARNESS_DIR_KEYS, dirs) if v)+ return {**target, "BU_NAME": name}+++def socket_dir_budget(platform: str) -> Optional[int]:+ """The runtime-dir byte budget on ``platform`` (a ``sys.platform`` value) where the harness binds+ AF_UNIX sockets, else None."""+ if platform == "darwin":+ return _MACOS_SOCKET_DIR_BUDGET+ if platform.startswith("linux"):+ return _LINUX_SOCKET_DIR_BUDGET+ return None # Windows: the harness serves over loopback TCP (port files), no sun_path+++def fits_socket_budget(resolved_dir: str, budget: Optional[int]) -> bool:+ """Whether a 64-character session's socket under ``resolved_dir`` (the absolute, symlink-resolved+ path the harness binds) fits ``budget``; no budget means no sun_path limit."""+ return budget is None or len(resolved_dir.encode()) <= budget+++def namespace_harness_dirs(env: dict, tag: str) -> None:+ """Give served profile ``tag`` its own harness runtime and tmp dirs in the child ``env``. An empty+ ``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())+ 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)+ env["BH_RUNTIME_DIR"] = socket_fit_runtime_dir(runtime, base, tag)+ env["BH_RUNTIME_DIR_SHARED"] = "1" # several BU_NAMEs share the dir: keep bu-<name> stems+ # Screenshots, debug overlays and daemon logs (paths.tmp_dir): the profile's own, never shared.+ env["BH_TMP_DIR"] = str(Path(env.get("BH_TMP_DIR") or str(Path(root) / "tmp")) / leaf)+ env["BH_TMP_DIR_SHARED"] = "1"+++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-character+ session. The harness binds ``Path(BH_RUNTIME_DIR).expanduser().resolve()``, so the length is+ judged 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)."""+ budget = socket_dir_budget(sys.platform)+ if fits_socket_budget(str(Path(runtime).expanduser().resolve()), budget):+ return runtime+ from hermes_constants import socket_safe_tmpdir+ getuid = getattr(os, "getuid", lambda: 0)+ digest = hashlib.sha256(f"{getuid()}\0{base}\0{tag}".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+ for 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+++def claim_private_dir(path: str) -> bool:+ """Create ``path`` 0700, or accept an existing one only when it is a real directory (not a+ symlink) owned by this uid and closed to group/other: the temp root is world-writable, and the+ harness resolves symlinks and only chmods a dir it created itself."""+ try:+ os.mkdir(path, 0o700)+ return True+ except FileExistsError:+ pass+ except OSError:+ return False+ try:+ st = os.lstat(path)+ except OSError:+ return False+ return (stat.S_ISDIR(st.st_mode) and st.st_uid == getattr(os, "getuid", lambda: -1)()+ and not st.st_mode & 0o077)diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 619d24bb5ba..59f900d65b8 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -5,7 +5,7 @@ instead of default browser tools"""import contextlib-import hashlib+import functoolsimport importlibimport importlib.utilimport json@@ -21,6 +21,7 @@ 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_dirsfrom utils import is_truthy_valuelogger = logging.getLogger(__name__)@@ -178,92 +179,10 @@ def _base_subprocess_env() -> dict:env.pop("PYTHONPATH", None)env["PATH"] = _floor_subprocess_path(env.get("PATH", ""))env.setdefault("ANONYMIZED_TELEMETRY", "false")- _namespace_harness_daemons(env)+ namespace_harness_dirs(env, _served_profile_tag()) # a served profile's own harness runtime/tmp dirsreturn env-def _namespace_harness_daemons(env: dict) -> None:- """A served profile's harness daemons live in their own runtime and tmp dirs. The harness names a- daemon by ``BU_NAME`` alone (unnamed calls are ``default``) and reuses any live one, so with one- shared dir a profile's exec drove another profile's browser; one shared tmp dir mixed their- screenshots and logs. Outside a served-profile scope nothing changes."""- tag = _served_profile_tag()- 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())- 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)- env["BH_RUNTIME_DIR"] = _socket_fit_runtime_dir(runtime, base, tag)- env["BH_RUNTIME_DIR_SHARED"] = "1" # several BU_NAMEs share the dir: keep bu-<name> stems- # Screenshots, debug overlays and daemon logs (paths.tmp_dir): the profile's own, never shared.- env["BH_TMP_DIR"] = str(Path(env.get("BH_TMP_DIR") or str(Path(root) / "tmp")) / leaf)- env["BH_TMP_DIR_SHARED"] = "1"---# browser_harness/_ipc.py: a shared runtime dir names a daemon socket ``<dir>/bu-<BU_NAME>.sock`` and-# BU_NAME may be 64 characters, so the dir gets sun_path (macOS 104 bytes, Linux 108, with the NUL)-# minus 72.-_MACOS_SOCKET_DIR_BUDGET = 103 - len("/bu-.sock") - 64-_LINUX_SOCKET_DIR_BUDGET = 107 - len("/bu-.sock") - 64---def _socket_dir_budget() -> Optional[int]:- """The runtime-dir byte budget on platforms where the harness binds AF_UNIX sockets, else None."""- if sys.platform == "darwin":- return _MACOS_SOCKET_DIR_BUDGET- if sys.platform.startswith("linux"):- return _LINUX_SOCKET_DIR_BUDGET- return None # Windows: the harness serves over loopback TCP (port files), no sun_path---def _socket_fit_runtime_dir(runtime: str, base: str, tag: str) -> str:- """``runtime`` unless it is too long for a 64-character session's socket (macOS: the default- ``~/.config/browser-harness/runtime`` alone exceeds it; Linux: anything past a 34-byte dir). Then- the served profile gets a private dir under the short socket temp root (``hbh-<12 hex>``), keyed by- uid, root and profile; if none fits or can be claimed safely the long path stays (shorter names- only)."""- budget = _socket_dir_budget()- if budget is None or len(runtime.encode()) <= budget:- return runtime- from hermes_constants import socket_safe_tmpdir- getuid = getattr(os, "getuid", lambda: 0)- digest = hashlib.sha256(f"{getuid()}\0{base}\0{tag}".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- for root in roots:- short = os.path.join(root, f"hbh-{digest}")- if len(short.encode()) <= budget and _claim_private_dir(short):- return short- return runtime---def _claim_private_dir(path: str) -> bool:- """Create ``path`` 0700, or accept an existing one only when it is a real directory (not a- symlink) owned by this uid and closed to group/other: the temp root is world-writable, and the- harness resolves symlinks and only chmods a dir it created itself."""- import stat- try:- os.mkdir(path, 0o700)- return True- except FileExistsError:- pass- except OSError:- return False- try:- st = os.lstat(path)- except OSError:- return False- return (stat.S_ISDIR(st.st_mode) and st.st_uid == getattr(os, "getuid", lambda: -1)()- and not st.st_mode & 0o077)--def _floor_subprocess_path(path: str) -> str:"""Keep system commands reachable from profile workers with a minimal PATH.@@ -774,14 +693,12 @@ def _run_cli_killing_process_group(cmd, code, env, timeout):return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr)-# Harness daemons this process has driven. The daemon reads BU_CDP_* once, at start, and outlives-# every call, so a backend swap (/browser connect|disconnect) that only changes the resolved endpoint-# leaves later browser_exec calls in the old browser until these are stopped. Keyed by the daemon's-# identity (its _HARNESS_DIR_KEYS values plus BU_NAME): a served profile's runtime and tmp dirs are its own,-# so no other profile can take over the entry.-_HARNESS_DIR_KEYS = ("BH_RUNTIME_DIR", "BH_RUNTIME_DIR_SHARED", "BH_TMP_DIR", "BH_TMP_DIR_SHARED")-_driven_daemons: dict[tuple[str, ...], str] = {} # (*_HARNESS_DIR_KEYS values, BU_NAME) -> home+# Harness daemons this process drove: each latches BU_CDP_* at start and outlives every call, so a backend+# swap (/browser connect|disconnect) leaves later calls in the old browser until these are stopped.+_driven_daemons: dict[tuple[str, ...], str] = {} # daemon identity -> home_driven_daemons_lock = threading.Lock()+_live_generation = functools.partial(_lazy_call, "tools.browser_tool_cdp", "live_cdp_generation", 0,+ "live CDP generation lookup failed") # this profile's publish count# Route cache key -> whether its last browser_exec ran on the hybrid local sidecar._exec_route_is_sidecar: dict[str, bool] = {}# Route cache key -> the note from its real-profile fallback; that route stays on the fallback browser.@@ -800,22 +717,14 @@ def stop_harness_daemons(home_key: Optional[str] = None) -> None:_reload_daemons(daemons)-def _reload_daemons(daemons) -> None:- """``--reload`` each ``(*_HARNESS_DIR_KEYS values, BU_NAME)`` daemon with its own dirs."""+def _reload_daemons(daemons) -> None: # each ``daemon_identity`` daemon, with its own dirscmd = _find_cli() if daemons else Noneif not cmd:returnenv = _base_subprocess_env()- for *dirs, name in daemons:- target = {k: v for k, v in env.items() if k not in _HARNESS_DIR_KEYS}- target.update((k, v) for k, v in zip(_HARNESS_DIR_KEYS, dirs) if v)+ for daemon in daemons:with contextlib.suppress(OSError, subprocess.SubprocessError):- _run_cli_killing_process_group([*cmd, "--reload"], "", {**target, "BU_NAME": name}, 15)---def _live_generation() -> int:- from tools.browser_tool_cdp import live_cdp_generation- return _quiet(live_cdp_generation, 0, "live CDP generation lookup failed")+ _run_cli_killing_process_group([*cmd, "--reload"], "", daemon_env(env, daemon), 15)def _route_exec(env: dict, session: str, task_id: Optional[str], local: bool, local_sidecar: bool,@@ -833,11 +742,8 @@ def _route_exec(env: dict, session: str, task_id: Optional[str], local: bool, lodef _route_exec_current(env: dict, session: str, task_id: Optional[str], local: bool,local_sidecar: bool, route_key: str) -> tuple[dict, Optional[str], bool, int]:- """``_route_exec`` on a copy of ``env``; returns ``(routed env, error, sidecar, generation)``.-- A /browser connect that publishes while this call routes or spawns its daemon reaps nothing (the- daemon isn't recorded yet), and the daemon latches the endpoint resolved here: re-route (at most 3- attempts) when the profile published during routing; ``_reload_if_republished`` covers dispatch."""+ """``_route_exec`` on a copy of ``env`` -> ``(routed env, error, sidecar, generation)``, re-routed (at+ most 3 tries) when /browser connect published meanwhile; ``_reload_if_republished`` covers dispatch."""for _attempt in range(3):routed = dict(env)generation = _live_generation()@@ -848,11 +754,10 @@ def _route_exec_current(env: dict, session: str, task_id: Optional[str], local:def _reload_if_republished(env: dict, generation: int) -> None:- """The profile published a new endpoint while this call's daemon spawned on the old one: stop it- so the next call respawns it on the current endpoint."""+ """Stop this call's daemon if the profile published a new endpoint while it spawned on the old one."""if _live_generation() == generation:return- daemon = (*(env.get(k, "") for k in _HARNESS_DIR_KEYS), env.get("BU_NAME", "default"))+ daemon = daemon_identity(env)with _driven_daemons_lock:_driven_daemons.pop(daemon, None)_reload_daemons([daemon])@@ -925,7 +830,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTdef dispatch() -> dict[str, Any]:_attach_vault_supervisor(env, task_id)with _driven_daemons_lock:- daemon = (*(env.get(k, "") for k in _HARNESS_DIR_KEYS), env.get("BU_NAME", "default"))+ daemon = daemon_identity(env)_driven_daemons[daemon] = hermes_home_key()try:return {"proc": _run_cli_killing_process_group(cmd, code, env, timeout)}