The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a shared daemon is owned only by the Hermes whose command started it
kshitijk4poore8ccfffc0b51
diff --git a/hermes_cli/process_identity.py b/hermes_cli/process_identity.pyindex 0739923e0ff..ed076fbb5f4 100644--- a/hermes_cli/process_identity.py+++ b/hermes_cli/process_identity.py@@ -212,6 +212,25 @@ def parse_spawn_tag(raw: object) -> Optional[SpawnTag]:return SpawnTag(install, purpose, pid, create) if pid > 0 else None+def spawned_by_this_process(pid: int) -> bool:+ """True when ``pid`` carries a spawn tag naming THIS process (pid and create time).++ A shared daemon (one session or pid file every Hermes of this user can reach) is owned only by+ the Hermes whose command actually started it: the CLI it ran was given ``spawn_env`` and the+ daemon inherited it. A pid file proves what a process is, not who started it. Fails closed:+ an unreadable environment (another user, a race) is not ours."""+ try:+ import psutil++ tag = parse_spawn_tag(psutil.Process(int(pid)).environ().get(SPAWN_ENV_VAR))+ except Exception:+ return False+ if tag is None or tag.spawner_pid != os.getpid():+ return False+ mine = _process_create_time()+ return tag.spawner_create is None or mine is None or abs(tag.spawner_create - mine) < 2.0++# Layer 2 — spawn ledgerdiff --git a/tests/tools/test_browser_use_cli_owned_daemon.py b/tests/tools/test_browser_use_cli_owned_daemon.pyindex 96874c2c852..be7d2f02554 100644--- a/tests/tools/test_browser_use_cli_owned_daemon.py+++ b/tests/tools/test_browser_use_cli_owned_daemon.py@@ -40,7 +40,8 @@ def fake_daemon(tmp_path):(pkg / "__init__.py").write_text("", encoding="utf-8")(pkg / "daemon.py").write_text("import time\ntime.sleep(300)\n", encoding="utf-8")proc = subprocess.Popen([sys.executable, "-m", "browser_harness.daemon"], cwd=str(tmp_path / "pkgroot"),- stdin=subprocess.DEVNULL, start_new_session=True)+ stdin=subprocess.DEVNULL, start_new_session=True,+ env={**os.environ, **process_identity.spawn_env("browser-harness-daemon")})runtime = tmp_path / "runtime"runtime.mkdir()yield proc, runtime@@ -123,7 +124,7 @@ def test_a_sigkilled_owner_takes_its_harness_daemon_with_it(tmp_path):"import json, os, subprocess, sys, time\n""from tools import browser_use_cli\n"f"d = subprocess.Popen([sys.executable, '-m', 'browser_harness.daemon'], cwd={str(tmp_path / 'pkgroot')!r},"- " stdin=subprocess.DEVNULL, start_new_session=True)\n"+ " stdin=subprocess.DEVNULL, start_new_session=True, env=browser_use_cli._base_subprocess_env())\n"f"open({str(runtime / 'bu.pid')!r}, 'w', encoding='utf-8').write(json.dumps({{'pid': d.pid}}))\n" # windows-footgun: ok — a writef"browser_use_cli._own_harness_daemon({{'BH_RUNTIME_DIR': {str(runtime)!r}}})\n""print(d.pid, flush=True)\n"@@ -149,3 +150,30 @@ def test_a_sigkilled_owner_takes_its_harness_daemon_with_it(tmp_path):owner.kill()owner.wait(timeout=10)process_identity._supervised_pgids.clear()+++def test_a_daemon_another_live_hermes_started_on_the_same_name_is_never_registered(tmp_path, registered):+ """Two Hermes processes on the default BU_NAME read the same bu-default.pid. The daemon belongs+ to the one whose CLI started it: the other must not hand it to its supervisor, or that Hermes+ dying would kill a browser session the first still uses."""+ pkg = tmp_path / "pkgroot" / "browser_harness"+ pkg.mkdir(parents=True)+ (pkg / "__init__.py").write_text("", encoding="utf-8")+ (pkg / "daemon.py").write_text("import time\ntime.sleep(300)\n", encoding="utf-8")+ runtime = tmp_path / "runtime"+ runtime.mkdir()+ other_hermes = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE)+ tag = process_identity.spawn_env("browser-harness-daemon")+ tag[process_identity.SPAWN_ENV_VAR] = tag[process_identity.SPAWN_ENV_VAR].replace(+ f":{os.getpid()}:", f":{other_hermes.pid}:")+ daemon = subprocess.Popen([sys.executable, "-m", "browser_harness.daemon"], cwd=str(tmp_path / "pkgroot"),+ stdin=subprocess.DEVNULL, start_new_session=True, env={**os.environ, **tag})+ try:+ _publish(runtime, "bu-default", daemon.pid)+ browser_use_cli._own_harness_daemon({"BH_HOME": str(runtime.parent)})+ assert registered == []+ finally:+ daemon.kill()+ daemon.wait(timeout=10)+ other_hermes.stdin.close()+ other_hermes.wait(timeout=10)diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 5a0c348cf23..1f42730a52a 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -23,7 +23,8 @@ import timefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, NamedTuple, Optional-from hermes_cli.process_identity import own_process_groups, register_child, release_process_group_once_empty+from 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_keyfrom tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir,namespace_harness_dirs)@@ -196,6 +197,8 @@ def _base_subprocess_env() -> dict:env["PATH"] = _floor_subprocess_path(env.get("PATH", ""))env.setdefault("ANONYMIZED_TELEMETRY", "false")namespace_harness_dirs(env, _served_profile_tag()) # a served profile's own harness runtime/tmp dirs+ # A daemon the CLI starts inherits this tag; _own_harness_daemon owns only one that names us.+ env.update(spawn_env("browser-harness-daemon"))return env@@ -686,6 +689,8 @@ def _own_harness_daemon(env: dict) -> None:if (os.getsid(pid) != pid or proc.uids().real != os.getuid() # windows-footgun: ok — posix-only, returned aboveor argv[argv.index("-m") + 1] != "browser_harness.daemon"):return+ 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)return