The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(browser): an owned daemon costs one pid-file read per command; the harness pid file has one resolver
kshitijk4poor4c6bc6d1ed26
diff --git a/tests/tools/test_browser_use_cli_owned_daemon.py b/tests/tools/test_browser_use_cli_owned_daemon.pyindex 0db28f82eef..4f33c4093da 100644--- a/tests/tools/test_browser_use_cli_owned_daemon.py+++ b/tests/tools/test_browser_use_cli_owned_daemon.py@@ -79,6 +79,25 @@ def test_the_driven_daemon_is_handed_to_the_supervisor_once(fake_daemon, registeassert registered == [("register", [proc.pid])]+def test_an_owned_harness_daemon_is_not_re_verified_and_a_replacement_releases_the_old_group(+ fake_daemon, registered, monkeypatch):+ proc, runtime = fake_daemon+ _publish(runtime, "bu", proc.pid)+ env = {"BH_RUNTIME_DIR": str(runtime), "BU_NAME": "work"}+ browser_use_cli._own_harness_daemon(env)++ def _never(*_a):+ raise AssertionError("an already-owned daemon was re-verified")+ monkeypatch.setattr(browser_use_cli, "spawned_by_this_process", _never)+ browser_use_cli._own_harness_daemon(env) # steady state: one pid-file read+ assert registered == [("register", [proc.pid])]++ browser_use_cli._owned_daemon_groups[browser_use_cli.daemon_identity(env)] = 4242 # an earlier daemon+ monkeypatch.setattr(browser_use_cli, "spawned_by_this_process", lambda pid: True)+ browser_use_cli._own_harness_daemon(env)+ assert registered[1:] == [("register", [proc.pid]), ("unregister", [4242])]++def test_a_pid_file_naming_something_else_is_never_registered(tmp_path, registered):runtime = tmp_path / "runtime"runtime.mkdir()diff --git a/tools/browser_harness_dirs.py b/tools/browser_harness_dirs.pyindex 1c5df011f86..f50b2d4dd9e 100644--- a/tools/browser_harness_dirs.py+++ b/tools/browser_harness_dirs.py@@ -59,6 +59,16 @@ def fits_socket_budget(resolved_dir: str, budget: Optional[int]) -> bool:return budget is None or len(resolved_dir.encode()) <= budget+def harness_pid_file(env: dict) -> Path:+ """Where the harness publishes the pid of the daemon a call with ``env`` drives+ (browser_harness ``_ipc``): ``<runtime dir>/bu-<BU_NAME>.pid``, or ``bu.pid`` in an isolated+ runtime dir that is not shared between names."""+ isolated = env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR")+ runtime = Path(isolated).expanduser() if isolated else Path(_harness_home(env)) / "runtime"+ shared = not isolated or env.get("BH_RUNTIME_DIR_SHARED") == "1"+ return runtime / (f"bu-{env.get('BU_NAME', 'default')}.pid" if shared else "bu.pid")++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."""diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 9ddf7eb6d1c..64368bd93ea 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -26,7 +26,7 @@ from typing import Any, Callable, Dict, List, NamedTuple, Optionalfrom hermes_cli.process_identity import (own_process_groups, register_child, release_process_group_once_empty, spawn_env, spawned_by_this_process)from hermes_constants import get_hermes_home, hermes_home_key-from tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir,+from tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir, harness_pid_file,namespace_harness_dirs)from utils import is_truthy_value@@ -673,29 +673,22 @@ _owned_daemon_groups_lock = threading.Lock()def _own_harness_daemon(env: dict) -> None:"""Hand the daemon behind ``env``'s BU_NAME to the owner-death supervisor.- The harness publishes its daemon pid in ``<runtime dir>/bu-<name>.pid`` (JSON ``{"pid", "started"}``- or a bare pid). The daemon is accepted only while it is this user's live ``browser_harness.daemon``- leading its own session, so a stale or planted pid file can never hand a stranger's group to the- supervisor."""+ The harness publishes its daemon pid in its runtime dir (``harness_pid_file``: JSON+ ``{"pid", "started"}`` or a bare pid). The daemon is accepted only while it is this user's live+ ``browser_harness.daemon`` leading its own session and its spawn tag names this process, so a+ stale or planted pid file, or a daemon another Hermes started, never reaches the supervisor.+ Runs after every browser_exec: a pid already owned for this daemon costs one file read."""if os.name != "posix":return # Windows: the harness daemon is outside this process's job; nothing to register.import psutil- # Where the daemon's pid file lives, resolved from the env the CLI ran with (a profile scope can- # differ from os.environ) the way browser_harness.paths / _ipc resolve it.- name = env.get("BU_NAME", "default")- isolated = env.get("BH_RUNTIME_DIR") or env.get("BH_TMP_DIR")- home = env.get("BH_HOME") or env.get("BROWSER_HARNESS_HOME")- if isolated:- runtime = Path(isolated).expanduser()- elif home:- runtime = Path(home).expanduser() / "runtime"- else:- runtime = Path(env.get("XDG_CONFIG_HOME") or Path.home() / ".config").expanduser() / "browser-harness" / "runtime"- stem = "bu" if isolated and env.get("BH_RUNTIME_DIR_SHARED") != "1" else f"bu-{name}"+ daemon = daemon_identity(env)try:- raw = (runtime / f"{stem}.pid").read_text(encoding="utf-8-sig").strip()+ raw = harness_pid_file(env).read_text(encoding="utf-8-sig").strip()pid = int(json.loads(raw)["pid"]) if raw.startswith("{") else int(raw.split()[0])+ with _owned_daemon_groups_lock:+ if _owned_daemon_groups.get(daemon) == pid:+ returnproc = psutil.Process(pid)argv = proc.cmdline()if (os.getsid(pid) != pid or proc.uids().real != os.getuid() # windows-footgun: ok — posix-only, returned above@@ -704,15 +697,15 @@ def _own_harness_daemon(env: dict) -> None:if not spawned_by_this_process(pid):return # another Hermes on the same BU_NAME started it: that Hermes owns itexcept (OSError, ValueError, KeyError, TypeError, IndexError, psutil.Error) as exc:- logger.debug("browser_exec: no harness daemon to supervise for %s: %s", name, exc)+ logger.debug("browser_exec: no harness daemon to supervise for %s: %s", daemon[-1], exc)return- daemon = daemon_identity(env)with _owned_daemon_groups_lock:- if _owned_daemon_groups.get(daemon) == pid:- return+ replaced = _owned_daemon_groups.get(daemon)_owned_daemon_groups[daemon] = pidown_process_groups([pid])register_child(pid, "browser-harness-daemon")+ if replaced is not None:+ release_process_group_once_empty(replaced, timeout=0) # the daemon it replaced; a survivor stays covereddef _route_exec(env: dict, session: str, task_id: Optional[str], local: bool, local_sidecar: bool,