The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(browser): real-profile browsing via agent-browser copy + browser-use CDP
Teknium1f4d095fd8f2
diff --git a/apps/desktop/src/app/settings/constants.ts b/apps/desktop/src/app/settings/constants.tsindex 13d71393445..ee841452ea1 100644--- a/apps/desktop/src/app/settings/constants.ts+++ b/apps/desktop/src/app/settings/constants.ts@@ -558,7 +558,7 @@ export const FIELD_DESCRIPTIONS: Record<string, string> = defineFieldCopy({timezone: 'IANA timezone identifier. Blank uses the system timezone.',browser: {useRealProfile:- "Local browser use drives your real default browser profile — its logins, cookies, and history. Backend-independent: applies whenever a local Chromium is used, and lets the agent choose a local real-profile session even under a cloud backend. Only Chromium browsers (Chrome, Edge, Brave, Chromium) are supported; a non-Chromium default fails with a clear message. Off by default."+ "Local browsing uses your real logins. Hermes copies your default browser's profile (cookies, logins, preferences) into a managed snapshot and drives it with its packaged Chromium — your live profile is never opened directly, and the copy is refreshed from it on each run. Also lets the agent open a local real-profile session on request even when a cloud browser backend is configured. Only Chromium browsers (Chrome, Edge, Brave, Chromium) are supported; a non-Chromium default fails with a clear message. Off by default."},agent: {imageInputMode: 'Controls how image attachments are sent to the model.',diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 0d0b786ad6d..28720c4d622 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -378,6 +378,157 @@ def detect_default_chromium(system: str | None = None) -> str | None:return _detect_default_linux()+# ---------------------------------------------------------------------------+# Real-profile SNAPSHOT launch+#+# The consent path (``browser.use_real_profile``) never drives the live+# default user-data-dir. Chromium ≥136 (Google-branded builds) refuses+# remote debugging on the default dir no matter who launches it, and the+# live dir is usually held by the user's running browser (SingletonLock).+# Instead we snapshot the real profile into ``~/.hermes/browser-profile/``+# — a non-default dir Chrome will happily debug, that never contends with+# the user's browser — launch the user's real binary on the copy with a+# devtools port, and hand the CDP URL to whichever browser lane is active+# (Browser Use CLI or the built-in tools). We launch the browser ourselves+# precisely so NO mock-keychain/basic-store switches are added: cookies+# encrypted with the OS keyring (gnome-keyring / kwallet / macOS Keychain)+# decrypt exactly like they do in the user's own browser.+# ---------------------------------------------------------------------------++# Directory names excluded from the profile snapshot: caches/telemetry AND the+# heavy, replay-prone state that hangs a fresh Chromium's renderer (extensions+# and their service workers spin up on launch and wedge JS eval; IndexedDB /+# GPUCache add hundreds of MB for nothing). We keep ONLY auth/login state+# (cookies, Login Data, Web Data, Preferences, Local State) — the point of the+# feature — which turns a multi-hundred-MB profile into a few MB.+_SNAPSHOT_IGNORES = (+ "*Cache*", # Cache, Code Cache, GPUCache, GrShaderCache, ShaderCache, GraphiteDawnCache, component_crx_cache, ...+ "Extensions", # wallets/etc.: 100s of MB, and hang the renderer headless+ "Extension*", # Extension State, Extension Rules, Extension Scripts+ "Local Extension Settings",+ "Service Worker", # replays on launch → wedges the renderer+ "IndexedDB",+ "Crash Reports",+ "Crashpad",+ "BrowserMetrics*",+ "Snapshots",+ "OptimizationGuide*",+ "optimization_guide_model_store",+ "Safe Browsing",+ "SafetyTips",+ "OnDeviceHeadSuggestModel",+ "segmentation_platform",+ "Sync Data",+ "Shared Dictionary",+ "History*", # large; not needed for auth+ "Favicons*",+ "Singleton*", # live-instance symlinks; never valid in a copy+ "RunningChromeVersion",+ "SingletonSocket",+ "*.tmp",+ "BrowserMetrics-spare.pma",+)++# Small, auth-bearing files re-synced from the live profile on EVERY consented+# launch (the full tree is only copied when the snapshot doesn't exist yet).+# Paths are relative to the user-data-dir; <profile> expands per profile dir.+_AUTH_REFRESH_FILES = (+ "Local State",+ "<profile>/Cookies",+ "<profile>/Cookies-journal",+ "<profile>/Network/Cookies",+ "<profile>/Network/Cookies-journal",+ "<profile>/Login Data",+ "<profile>/Login Data-journal",+ "<profile>/Login Data For Account",+ "<profile>/Web Data",+ "<profile>/Web Data-journal",+ "<profile>/Preferences",+)++def real_profile_copy_dir(browser: str) -> str:+ """Return the hermes-owned snapshot dir for ``browser``'s real profile."""+ return str(get_hermes_home() / "browser-profile" / browser)+++def _profile_subdirs(src: str) -> list[str]:+ """Names of per-profile dirs (Default, Profile 1, ...) inside a data dir."""+ out = []+ try:+ for name in os.listdir(src):+ if name == "Default" or name.startswith("Profile "):+ if os.path.isdir(os.path.join(src, name)):+ out.append(name)+ except OSError:+ pass+ return out or ["Default"]+++def snapshot_real_profile(browser: str, src: str | None = None) -> tuple[str | None, str | None]:+ """Snapshot ``browser``'s real profile into the hermes copy dir.++ Full copy (minus caches) when the copy doesn't exist; otherwise only the+ auth-bearing files (cookies, login data, preferences) are re-synced so+ fresh logins from the user's own browsing show up in the agent session.+ Locked-file copy errors are tolerated best-effort: SQLite journals make a+ mid-write copy readable, and a stale cookie jar beats a failed launch.++ Returns ``(copy_dir, None)`` on success, ``(None, error)`` on failure.+ """+ src = src or real_profile_data_dir(browser)+ if not src or not os.path.isdir(src):+ return None, (+ f"profile directory for '{browser}' was not found ({src!r}). "+ "Launch that browser at least once, or turn browser.use_real_profile off."+ )+ dst = real_profile_copy_dir(browser)+ fresh = not os.path.isdir(os.path.join(dst, "Default"))+ try:+ if fresh:+ os.makedirs(dst, exist_ok=True)+ try:+ shutil.copytree(+ src,+ dst,+ dirs_exist_ok=True,+ symlinks=False,+ ignore=shutil.ignore_patterns(*_SNAPSHOT_IGNORES),+ ignore_dangling_symlinks=True,+ )+ except shutil.Error as multi:+ # Per-file failures (browser mid-write) are non-fatal.+ logger.info(+ "real-profile snapshot: %d file(s) skipped while copying %s",+ len(multi.args[0]) if multi.args else 0, src,+ )+ else:+ profiles = _profile_subdirs(src)+ for rel in _AUTH_REFRESH_FILES:+ rels = (+ [rel.replace("<profile>", p) for p in profiles]+ if "<profile>" in rel else [rel]+ )+ for r in rels:+ s = os.path.join(src, r)+ if not os.path.isfile(s):+ continue+ d = os.path.join(dst, r)+ try:+ os.makedirs(os.path.dirname(d), exist_ok=True)+ shutil.copy2(s, d)+ except OSError as e:+ logger.debug("real-profile refresh: skipped %s: %s", r, e)+ # Never carry live-instance leftovers into the copy.+ for leftover in ("SingletonLock", "SingletonSocket", "SingletonCookie"):+ try:+ os.unlink(os.path.join(dst, leftover))+ except OSError:+ pass+ except OSError as e:+ return None, f"could not snapshot the '{browser}' profile into {dst}: {e}"+ return dst, None++def get_chrome_debug_candidates(system: str) -> list[str]:candidates: list[str] = []seen: set[str] = set()diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex f09068eca09..eee52189bc3 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -575,16 +575,19 @@ DEFAULT_CONFIG = {"engine": "auto","auto_local_for_private_urls": True, # When a cloud provider is set, auto-spawn local Chromium for LAN/localhost URLs instead of sending them to the cloud"cdp_url": "", # Optional persistent CDP endpoint for attaching to an existing Chromium/Chrome- # Consent to drive the user's REAL default-Chromium profile in local- # mode. When true, any local Chromium launch (built-in tools, or a- # local sidecar spawned under a cloud backend) uses the default- # browser's real user-data-dir — exposing that profile's live logins,- # cookies, and history to automation. Backend-independent. Only- # Chromium-family default browsers are supported (Chrome, Edge, Brave,- # Chromium); a non-Chromium default (e.g. Firefox) fails closed with a- # clear message. Default false. Also gates the browser tools'- # ``local_browser`` argument. Toggle in the desktop Settings → Browser- # section.+ # Consent to browse with the user's REAL logins for local browsing.+ # When true, local browsing (the Browser Use CLI, or the built-in+ # browser tools) runs on a Hermes-managed SNAPSHOT of the user's+ # default-Chromium profile — cookies, logins and preferences copied in,+ # re-synced from the real profile on each launch — driven by Hermes'+ # packaged Chromium. The snapshot is a non-default dir, so it sidesteps+ # Chrome 136+'s block on debugging the default profile and never+ # contends with the user's running browser. Only Chromium-family+ # default browsers are supported (Chrome, Edge, Brave, Chromium); a+ # non-Chromium default (e.g. Firefox) fails closed with a clear+ # message. Default false. Also gates the browser_exec ``local``+ # argument, which forces a real-profile local session even under a+ # cloud browser backend. Toggle in the desktop Settings → Browser section."use_real_profile": False,"allow_unsafe_evaluate": False, # Legacy override: when true, browser_console(expression=...) bypasses the restrict_evaluate denylist entirely"restrict_evaluate": False, # Opt-in denylist blocking sensitive JS primitives (cookies/storage/clipboard/network/form values) in browser_console(expression=...)diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex 66f2f3fe18a..5cf447027ac 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -1,4 +1,12 @@-"""Tests for real-profile local browser resolution + routing."""+"""Tests for real-profile browsing: resolvers, snapshot, launch routing, consent.++The consent path never drives the live default profile: it snapshots into+``~/.hermes/browser-profile/<browser>/`` and launches the user's real binary+on the copy with a devtools port (see hermes_cli.browser_connect). These tests+exercise the real functions with real file I/O wherever possible — the mocks+are limited to OS detection and process launch.+"""+import jsonimport osimport ntpathfrom unittest.mock import Mock, patch@@ -41,123 +49,344 @@ class TestRealProfileResolvers:assert bc.detect_default_chromium("Linux") is None-class TestRealProfileLaunchArgs:+class TestSnapshotRealProfile:+ """Real file I/O: the snapshot copier against a synthetic profile tree."""++ def _make_profile(self, root):+ """Build a minimal real-looking Chromium user-data-dir."""+ (root / "Default" / "Network").mkdir(parents=True)+ (root / "Default" / "Cache" / "Cache_Data").mkdir(parents=True)+ (root / "Code Cache" / "js").mkdir(parents=True)+ (root / "Crashpad").mkdir()+ (root / "Local State").write_text('{"os_crypt": {}}')+ (root / "Default" / "Cookies").write_text("sqlite-cookies")+ (root / "Default" / "Network" / "Cookies").write_text("sqlite-net-cookies")+ (root / "Default" / "Login Data").write_text("sqlite-logins")+ (root / "Default" / "Preferences").write_text("{}")+ (root / "Default" / "Cache" / "Cache_Data" / "big").write_text("x" * 1000)+ (root / "Code Cache" / "js" / "blob").write_text("y" * 1000)+ (root / "Crashpad" / "dump").write_text("z")+ # Live-instance leftovers that must never reach the copy+ os.symlink("dead-target-1", root / "SingletonLock")+ return root++ def test_fresh_snapshot_copies_auth_and_skips_caches(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ src = self._make_profile(tmp_path / "real")+ home = tmp_path / "hermes-home"+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)++ dst, err = bc.snapshot_real_profile("chrome", src=str(src))+ assert err is None+ assert dst == str(home / "browser-profile" / "chrome")+ # Auth files present+ assert (home / "browser-profile" / "chrome" / "Default" / "Cookies").read_text() == "sqlite-cookies"+ assert (home / "browser-profile" / "chrome" / "Default" / "Network" / "Cookies").exists()+ assert (home / "browser-profile" / "chrome" / "Default" / "Login Data").exists()+ assert (home / "browser-profile" / "chrome" / "Local State").exists()+ # Caches, crash dirs, singleton leftovers excluded+ assert not (home / "browser-profile" / "chrome" / "Default" / "Cache").exists()+ assert not (home / "browser-profile" / "chrome" / "Code Cache").exists()+ assert not (home / "browser-profile" / "chrome" / "Crashpad").exists()+ assert not (home / "browser-profile" / "chrome" / "SingletonLock").exists()++ def test_existing_snapshot_refreshes_auth_files_only(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ src = self._make_profile(tmp_path / "real")+ home = tmp_path / "hermes-home"+ monkeypatch.setattr(bc, "get_hermes_home", lambda: home)++ dst, err = bc.snapshot_real_profile("chrome", src=str(src))+ assert err is None+ # Simulate: user logs into a new site in their own browser, and the+ # copy has drifted state that must survive (History not in refresh set).+ (src / "Default" / "Cookies").write_text("sqlite-cookies-v2")+ copy_history = home / "browser-profile" / "chrome" / "Default" / "History"+ copy_history.write_text("agent-session-history")++ dst2, err2 = bc.snapshot_real_profile("chrome", src=str(src))+ assert err2 is None and dst2 == dst+ assert (home / "browser-profile" / "chrome" / "Default" / "Cookies").read_text() == "sqlite-cookies-v2"+ assert copy_history.read_text() == "agent-session-history"++ def test_missing_source_fails_closed(self, tmp_path, monkeypatch):+ import hermes_cli.browser_connect as bc+ monkeypatch.setattr(bc, "get_hermes_home", lambda: tmp_path / "hh")+ dst, err = bc.snapshot_real_profile("chrome", src=str(tmp_path / "nope"))+ assert dst is None+ assert err and "was not found" in err+++class TestRealProfileCdpLaunch:+ """The agent-browser-based launcher in browser_tool._real_profile_cdp."""+def _reset(self):import tools.browser_tool as bt- bt._use_real_profile_resolved = False- bt._cached_use_real_profile = False+ bt._real_profile_cdp_cache.clear()def test_consent_off_is_noop(self):import tools.browser_tool as btself._reset()with patch.object(bt, "_use_real_profile", return_value=False):- args, err = bt._real_profile_launch_args()- assert args == [] and err is None+ cdp, err = bt._real_profile_cdp()+ assert cdp is None and err is Nonedef test_non_chromium_default_fails_closed(self):import tools.browser_tool as btself._reset()with patch.object(bt, "_use_real_profile", return_value=True), \patch("hermes_cli.browser_connect.detect_default_chromium", return_value=None):- args, err = bt._real_profile_launch_args()- assert args == []+ cdp, err = bt._real_profile_cdp()+ assert cdp is Noneassert err and "not a supported Chromium" in err- def test_chromium_default_injects_profile(self, tmp_path):+ def test_snapshot_failure_fails_closed(self):import tools.browser_tool as btself._reset()- data_dir = tmp_path / "chrome-user-data"- data_dir.mkdir()with patch.object(bt, "_use_real_profile", return_value=True), \patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \- patch("hermes_cli.browser_connect.real_profile_data_dir", return_value=str(data_dir)), \- patch("hermes_cli.browser_connect.chromium_executable", return_value="/usr/bin/google-chrome"):- args, err = bt._real_profile_launch_args()+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(None, "boom")):+ cdp, err = bt._real_profile_cdp()+ assert cdp is None+ assert err and "boom" in err++ def test_launch_returns_http_cdp(self, tmp_path):+ import tools.browser_tool as bt+ self._reset()+ proc = Mock(returncode=0, stdout="", stderr="")+ with patch.object(bt, "_use_real_profile", return_value=True), \+ patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(str(tmp_path), None)), \+ patch.object(bt, "_agent_browser_get_cdp",+ side_effect=[None, "http://127.0.0.1:41000"]), \+ patch.object(bt, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \+ patch.object(bt.subprocess, "run", return_value=proc), \+ patch.object(bt, "_is_headed_mode", return_value=False):+ cdp, err = bt._real_profile_cdp()assert err is None- assert "--profile" in args and str(data_dir) in args- assert "--executable-path" in args and "/usr/bin/google-chrome" in args+ assert cdp == "http://127.0.0.1:41000"+ self._reset()- def test_missing_profile_dir_fails_closed(self, tmp_path):+ def test_launch_never_passes_headless(self, tmp_path):+ """--headless would use a separate cookie store → 0 real cookies."""import tools.browser_tool as btself._reset()+ proc = Mock(returncode=0, stdout="", stderr="")+ captured = {}++ def fake_run(argv, **kw):+ captured["argv"] = argv+ return proc+with patch.object(bt, "_use_real_profile", return_value=True), \patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \- patch("hermes_cli.browser_connect.real_profile_data_dir", return_value=str(tmp_path / "nope")):- args, err = bt._real_profile_launch_args()- assert args == []- assert err and "profile directory was not found" in err+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(str(tmp_path), None)), \+ patch.object(bt, "_agent_browser_get_cdp",+ side_effect=[None, "http://127.0.0.1:41000"]), \+ patch.object(bt, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \+ patch.object(bt.subprocess, "run", side_effect=fake_run), \+ patch.object(bt, "_is_headed_mode", return_value=False):+ bt._real_profile_cdp()+ assert "--headless" not in captured["argv"]+ assert "--profile" in captured["argv"]+ assert str(tmp_path) in captured["argv"]+ self._reset()+ def test_reuses_only_session_on_our_copy_dir(self, tmp_path):+ """A live session on a DIFFERENT dir (stale/throwaway) is closed, not reused."""+ import tools.browser_tool as bt+ self._reset()+ proc = Mock(returncode=0, stdout="", stderr="")+ closed = {"n": 0}+ with patch.object(bt, "_use_real_profile", return_value=True), \+ patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(str(tmp_path), None)), \+ patch.object(bt, "_agent_browser_get_cdp",+ side_effect=["http://127.0.0.1:5000", "http://127.0.0.1:41000"]), \+ patch.object(bt, "_cdp_http_ready", return_value=True), \+ patch.object(bt, "_cdp_on_data_dir", return_value=False), \+ patch.object(bt, "_agent_browser_close_session",+ side_effect=lambda s: closed.__setitem__("n", closed["n"] + 1)), \+ patch.object(bt, "_find_agent_browser", return_value="/usr/bin/agent-browser"), \+ patch.object(bt.subprocess, "run", return_value=proc), \+ patch.object(bt, "_is_headed_mode", return_value=False):+ cdp, err = bt._real_profile_cdp()+ assert closed["n"] == 1 # stale wrong-dir session was closed+ assert cdp == "http://127.0.0.1:41000"+ self._reset()-class TestLocalBrowserRouting:- def _reset(self):+ def test_cdp_on_data_dir_matches_devtoolsactiveport(self, tmp_path):import tools.browser_tool as bt- bt._use_real_profile_resolved = False- bt._cached_use_real_profile = False+ (tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n")+ assert bt._cdp_on_data_dir("http://127.0.0.1:41000", str(tmp_path))+ assert not bt._cdp_on_data_dir("http://127.0.0.1:9999", str(tmp_path))+++class TestConsentConfigRead:+ """Unmocked config read: _use_real_profile against a real config.yaml."""- def test_local_browser_forces_sidecar_with_consent(self):+ def test_consent_read_from_config(self, tmp_path, monkeypatch):import tools.browser_tool as bt- self._reset()- with patch.object(bt, "_get_cdp_override_raw", return_value=""), \- patch.object(bt, "_is_camofox_mode", return_value=False), \- patch.object(bt, "_get_cloud_provider", return_value=Mock()), \- patch.object(bt, "_url_is_private", return_value=False), \- patch.object(bt, "_use_real_profile", return_value=True):- key = bt._navigation_session_key("t1", "https://example.com", local_browser=True)- assert key == "t1::local"+ cfg = tmp_path / "config.yaml"+ cfg.write_text("browser:\n use_real_profile: true\n")+ with patch("hermes_cli.config.read_raw_config",+ return_value={"browser": {"use_real_profile": True}}):+ assert bt._use_real_profile() is True- def test_local_browser_without_cloud_provider_keeps_bare_session(self):- """Pure local backend: the bare session already is the (real-profile)- local Chromium; a second ``::local`` session would fight it for the- same user-data-dir."""+ def test_consent_default_off(self):import tools.browser_tool as bt- self._reset()- with patch.object(bt, "_get_cdp_override_raw", return_value=""), \- patch.object(bt, "_is_camofox_mode", return_value=False), \- patch.object(bt, "_get_cloud_provider", return_value=None), \- patch.object(bt, "_use_real_profile", return_value=True):- key = bt._navigation_session_key("t1", "https://example.com", local_browser=True)- assert key == "t1"+ with patch("hermes_cli.config.read_raw_config", return_value={}):+ assert bt._use_real_profile() is False- def test_local_browser_respects_private_url_opt_out(self):- """auto_local_for_private_urls: false is the user's LAN routing- decision; a model-supplied flag must not override it."""+ def test_consent_revocation_takes_effect_immediately(self):+ """No process-lifetime caching: consent is a per-use read."""import tools.browser_tool as bt- self._reset()- with patch.object(bt, "_get_cdp_override_raw", return_value=""), \- patch.object(bt, "_is_camofox_mode", return_value=False), \- patch.object(bt, "_get_cloud_provider", return_value=Mock()), \- patch.object(bt, "_url_is_private", return_value=True), \- patch.object(bt, "_auto_local_for_private_urls", return_value=False), \- patch.object(bt, "_use_real_profile", return_value=True):- key = bt._navigation_session_key("t1", "http://192.168.1.1/admin", local_browser=True)- assert key == "t1"+ with patch("hermes_cli.config.read_raw_config",+ return_value={"browser": {"use_real_profile": True}}):+ assert bt._use_real_profile() is True+ with patch("hermes_cli.config.read_raw_config",+ return_value={"browser": {"use_real_profile": False}}):+ assert bt._use_real_profile() is False- def test_local_browser_private_url_follows_auto_local_when_allowed(self):++class TestLocalSessionRealProfile:+ def test_local_session_attaches_to_real_profile_cdp(self):+ import tools.browser_tool as bt+ with patch.object(bt, "_real_profile_cdp",+ return_value=("http://127.0.0.1:9251", None)), \+ patch.object(bt, "_resolve_cdp_override", side_effect=lambda u: u):+ info = bt._create_local_session("t1")+ assert info["cdp_url"] == "http://127.0.0.1:9251"+ assert info["features"]["real_profile"] is True+ assert info["session_name"].startswith("rp_")++ def test_local_session_fails_closed_on_error(self):+ import tools.browser_tool as bt+ with patch.object(bt, "_real_profile_cdp", return_value=(None, "no chromium")):+ with pytest.raises(RuntimeError, match="no chromium"):+ bt._create_local_session("t1")++ def test_local_session_without_consent_is_throwaway(self):+ import tools.browser_tool as bt+ with patch.object(bt, "_real_profile_cdp", return_value=(None, None)):+ info = bt._create_local_session("t1")+ assert info["cdp_url"] is None+ assert "real_profile" not in info["features"]+ assert info["session_name"].startswith("h_")+++class TestBrowserExecLocalArg:+ def _env(self):+ return {}++ def test_local_forces_real_profile_under_cloud_backend(self):+ import tools.browser_use_cli as bu+ env = self._env()+ with patch.object(bu, "_real_profile_consented", return_value=True), \+ patch("tools.browser_tool._get_cdp_override_raw", return_value=""), \+ patch("tools.browser_tool._get_cloud_provider", return_value=Mock()), \+ patch("tools.browser_tool._real_profile_cdp",+ return_value=("http://127.0.0.1:9251", None)):+ err = bu._resolve_real_profile_cdp(env, force_local=True)+ assert err is None+ assert env.get("BU_CDP_URL") == "http://127.0.0.1:9251"++ def test_no_force_keeps_cloud_backend(self):+ import tools.browser_use_cli as bu+ env = self._env()+ with patch.object(bu, "_real_profile_consented", return_value=True), \+ patch("tools.browser_tool._get_cdp_override_raw", return_value=""), \+ patch("tools.browser_tool._get_cloud_provider", return_value=Mock()):+ err = bu._resolve_real_profile_cdp(env, force_local=False)+ assert err is None+ assert "BU_CDP_URL" not in env and "BU_CDP_WS" not in env++ def test_local_backend_upgrades_without_force(self):+ import tools.browser_use_cli as bu+ env = self._env()+ with patch.object(bu, "_real_profile_consented", return_value=True), \+ patch.object(bu, "_read_browser_cfg", return_value={}), \+ patch("tools.browser_tool._get_cdp_override_raw", return_value=""), \+ patch("tools.browser_tool._get_cloud_provider", return_value=None), \+ patch("tools.browser_tool._real_profile_cdp",+ return_value=("http://127.0.0.1:9251", None)):+ err = bu._resolve_real_profile_cdp(env, force_local=False)+ assert err is None+ assert env.get("BU_CDP_URL") == "http://127.0.0.1:9251"++ def test_consent_off_is_inert(self):+ import tools.browser_use_cli as bu+ env = self._env()+ with patch.object(bu, "_real_profile_consented", return_value=False):+ err = bu._resolve_real_profile_cdp(env, force_local=True)+ assert err is None and env == {}++ def test_launch_failure_fails_closed(self):+ import tools.browser_use_cli as bu+ env = self._env()+ with patch.object(bu, "_real_profile_consented", return_value=True), \+ patch("tools.browser_tool._get_cdp_override_raw", return_value=""), \+ patch("tools.browser_tool._real_profile_cdp",+ return_value=(None, "chrome exited")):+ err = bu._resolve_real_profile_cdp(env, force_local=True)+ assert err == "chrome exited"+ assert "BU_CDP_URL" not in env++ def test_explicit_bu_env_override_wins(self):+ import tools.browser_use_cli as bu+ env = {"BU_CDP_WS": "ws://operator-override"}+ with patch.object(bu, "_real_profile_consented", return_value=True):+ err = bu._resolve_real_profile_cdp(env, force_local=True)+ assert err is None+ assert env["BU_CDP_WS"] == "ws://operator-override"+ assert "BU_CDP_URL" not in env++ def test_operator_cdp_override_wins(self):+ import tools.browser_use_cli as bu+ env = self._env()+ with patch.object(bu, "_real_profile_consented", return_value=True), \+ patch("tools.browser_tool._get_cdp_override_raw", return_value="ws://connect"):+ err = bu._resolve_real_profile_cdp(env, force_local=True)+ assert err is None and env == {}+++class TestBrowserExecSchemaGating:+ def test_local_arg_absent_without_consent(self):+ import tools.browser_use_cli as bu+ with patch.object(bu, "_real_profile_consented", return_value=False):+ overrides = bu._dynamic_schema_overrides()+ assert "parameters" not in overrides+ assert "local" not in bu.BROWSER_EXEC_SCHEMA["parameters"]["properties"]++ def test_local_arg_present_with_consent(self):+ import tools.browser_use_cli as bu+ with patch.object(bu, "_real_profile_consented", return_value=True):+ overrides = bu._dynamic_schema_overrides()+ props = overrides["parameters"]["properties"]+ assert "local" in props+ assert props["local"]["type"] == "boolean"+ # Static schema must stay untouched (override is a copy).+ assert "local" not in bu.BROWSER_EXEC_SCHEMA["parameters"]["properties"]+ # 'local' must not be required — pure opt-in.+ assert "local" not in overrides["parameters"].get("required", [])+++class TestNavigationRouting:+ def test_private_url_routing_unchanged(self):import tools.browser_tool as bt- self._reset()with patch.object(bt, "_get_cdp_override_raw", return_value=""), \patch.object(bt, "_is_camofox_mode", return_value=False), \patch.object(bt, "_get_cloud_provider", return_value=Mock()), \- patch.object(bt, "_url_is_private", return_value=True), \patch.object(bt, "_auto_local_for_private_urls", return_value=True), \- patch.object(bt, "_use_real_profile", return_value=True):- key = bt._navigation_session_key("t1", "http://192.168.1.1/admin", local_browser=True)+ patch.object(bt, "_url_is_private", return_value=True):+ key = bt._navigation_session_key("t1", "http://192.168.1.1/x")assert key == "t1::local"- def test_local_browser_ignored_without_consent(self):+ def test_public_url_stays_on_cloud(self):import tools.browser_tool as bt- self._reset()with patch.object(bt, "_get_cdp_override_raw", return_value=""), \patch.object(bt, "_is_camofox_mode", return_value=False), \- patch.object(bt, "_use_real_profile", return_value=False), \- patch.object(bt, "_get_cloud_provider", return_value=None):- key = bt._navigation_session_key("t1", "https://example.com", local_browser=True)- assert key == "t1"-- def test_cdp_override_still_wins_over_local_browser(self):- import tools.browser_tool as bt- self._reset()- with patch.object(bt, "_get_cdp_override_raw", return_value="ws://x"), \- patch.object(bt, "_use_real_profile", return_value=True):- key = bt._navigation_session_key("t1", "https://example.com", local_browser=True)+ patch.object(bt, "_get_cloud_provider", return_value=Mock()), \+ patch.object(bt, "_url_is_private", return_value=False):+ key = bt._navigation_session_key("t1", "https://example.com")assert key == "t1"diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 0b6ce0b0204..98cb0334526 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -1025,9 +1025,6 @@ def _is_local_backend() -> bool:_auto_local_for_private_urls_resolved = False_cached_auto_local_for_private_urls: bool = True-_use_real_profile_resolved = False-_cached_use_real_profile: bool = False-def _get_browser_engine() -> str:"""Return the configured browser engine (``auto``, ``lightpanda``, or ``chrome``).@@ -1433,65 +1430,220 @@ def _auto_local_for_private_urls() -> bool:def _use_real_profile() -> bool:"""Return whether the user consented to real-profile local browsing.- Reads ``browser.use_real_profile`` (default False) once and caches it. When- True, local Chromium launches point agent-browser at the user's REAL- default-browser profile, and the browser tools' ``local_browser`` argument- is honored.+ Reads ``browser.use_real_profile`` (default False) on EVERY call — it is a+ consent switch, so flipping it off must take effect without a restart, and+ in a multiplexed gateway each profile's config must decide for itself.+ The read is one YAML load per local session creation (not per command),+ so there is no hot-path cost to keeping it uncached."""- global _use_real_profile_resolved, _cached_use_real_profile- if _use_real_profile_resolved:- return _cached_use_real_profile-- _use_real_profile_resolved = Truetry:from hermes_cli.config import read_raw_configcfg = read_raw_config()browser_cfg = cfg.get("browser", {})- if isinstance(browser_cfg, dict) and "use_real_profile" in browser_cfg:- _cached_use_real_profile = bool(browser_cfg.get("use_real_profile"))+ if isinstance(browser_cfg, dict):+ return bool(browser_cfg.get("use_real_profile", False))except Exception as e:logger.debug("Could not read use_real_profile from config: %s", e)- return _cached_use_real_profile+ return False+++# Session name for the single shared real-profile copy-browser. All consented+# local browsing attaches to this one agent-browser session so concurrent+# tasks reuse the same copy-browser instead of each launching a rival Chromium+# on the same copied user-data-dir.+_REAL_PROFILE_SESSION = "hermes-real-profile"+_real_profile_cdp_lock = threading.Lock()+_real_profile_cdp_cache: dict = {}+++def _agent_browser_argv(browser_cmd: str) -> list:+ """Command prefix to invoke agent-browser (binary or npx sentinel)."""+ if _is_npx_agent_browser_sentinel(browser_cmd):+ _npx_bin = _resolve_npx_bin() or "npx"+ return [_npx_bin, "--ignore-scripts", "--prefer-offline", "-y", AGENT_BROWSER_NPX_SPEC]+ return [browser_cmd]+++def _cdp_http_ready(http_cdp: str) -> bool:+ """True when an ``http://host:port`` CDP discovery root answers."""+ try:+ from hermes_cli.browser_connect import is_browser_debug_ready++ return is_browser_debug_ready(http_cdp, timeout=1.0)+ except Exception:+ return False+++def _agent_browser_get_cdp(session_name: str) -> Optional[str]:+ """Return the HTTP CDP endpoint of an agent-browser session, or None.++ agent-browser prints ``ws://127.0.0.1:<port>/devtools/browser/<id>`` for+ ``get cdp-url``; the browser-use harness wants the HTTP discovery root+ (``http://127.0.0.1:<port>``), so we convert. None when the session isn't+ running or the port can't be parsed.+ """+ try:+ browser_cmd = _find_agent_browser()+ except FileNotFoundError:+ return None+ try:+ proc = subprocess.run(+ [*_agent_browser_argv(browser_cmd), "--session", session_name, "get", "cdp-url"],+ capture_output=True, text=True, timeout=15, env=_build_browser_env(),+ )+ except (subprocess.SubprocessError, OSError) as e:+ logger.debug("real-profile get cdp-url failed: %s", e)+ return None+ out = (proc.stdout or "").strip()+ m = re.search(r"ws://127\.0\.0\.1:(\d+)/", out)+ if not m:+ return None+ return f"http://127.0.0.1:{m.group(1)}"+++def _cdp_on_data_dir(http_cdp: str, data_dir: str) -> bool:+ """True when the CDP endpoint's browser is running on ``data_dir``.++ agent-browser's launched Chrome writes ``DevToolsActivePort`` into its+ user-data-dir with the live debug port on the first line. Matching that+ port against the CDP endpoint's port confirms the running browser is our+ profile copy — not a throwaway temp dir a raced/stale launch fell back to.+ """+ m = re.search(r":(\d+)", http_cdp or "")+ if not m:+ return False+ try:+ with open(os.path.join(data_dir, "DevToolsActivePort"), encoding="utf-8") as fh:+ port_line = fh.readline().strip()+ return port_line == m.group(1)+ except OSError:+ return False-def _real_profile_launch_args() -> tuple:- """Resolve (profile_args, error) for a real-profile local launch.+def _agent_browser_close_session(session_name: str) -> None:+ """Best-effort close of an agent-browser session (stale/wrong-dir cleanup)."""+ try:+ browser_cmd = _find_agent_browser()+ except FileNotFoundError:+ return+ try:+ subprocess.run(+ [*_agent_browser_argv(browser_cmd), "--session", session_name, "close"],+ capture_output=True, text=True, timeout=15, env=_build_browser_env(),+ )+ except (subprocess.SubprocessError, OSError) as e:+ logger.debug("real-profile session close failed: %s", e)+++def _real_profile_cdp() -> tuple:+ """Resolve ``(cdp_url, error)`` for consented real-profile browsing.- Returns ``(["--profile", <data_dir>, "--executable-path", <bin>], None)``- when consent is on and the default browser is a resolvable Chromium.- Returns ``([], <message>)`` when the default browser is non-Chromium or its- profile/binary cannot be located, so the caller can fail closed with a- clear reason. Returns ``([], None)`` when consent is off (no-op).+ Snapshots the user's default-Chromium profile into a hermes-owned copy+ (auth/login state only), then has agent-browser launch its packaged+ Chromium on that copy and returns the HTTP CDP endpoint for the browser-use+ harness to attach to. The copy is a non-default dir, so it sidesteps the+ Chrome ≥136 default-profile remote-debugging block and never contends with+ the user's running browser; agent-browser launches the packaged Chromium+ with no mock-keychain switches, so keyring-encrypted cookies decrypt.++ A single shared agent-browser session is reused across calls (its CDP URL+ is cached and re-validated). Returns ``(None, message)`` fail-closed when+ the default browser is non-Chromium or the snapshot/launch fails;+ ``(None, None)`` when consent is off."""if not _use_real_profile():- return [], None+ return None, None+from hermes_cli.browser_connect import (- chromium_executable,detect_default_chromium,- real_profile_data_dir,+ snapshot_real_profile,)- browser = detect_default_chromium()- if browser is None:- return [], (- "browser.use_real_profile is on, but your default browser is not a "- "supported Chromium browser (Chrome, Edge, Brave, Chromium). "- "Real-profile browsing requires a Chromium default; set one or turn "- "the toggle off."- )- data_dir = real_profile_data_dir(browser)- if not data_dir or not os.path.isdir(data_dir):- return [], (- f"browser.use_real_profile is on and your default browser is "- f"'{browser}', but its profile directory was not found "- f"({data_dir!r}). Launch that browser at least once, or turn the "- "toggle off."- )- args = ["--profile", data_dir]- exe = chromium_executable(browser)- if exe:- args += ["--executable-path", exe]- return args, None+ with _real_profile_cdp_lock:+ # Reuse a live copy-browser from an earlier call this process made.+ cached = _real_profile_cdp_cache.get("cdp")+ if cached and _cdp_http_ready(cached):+ return cached, None+ _real_profile_cdp_cache.pop("cdp", None)++ browser = detect_default_chromium()+ if browser is None:+ return None, (+ "browser.use_real_profile is on, but your default browser is not a "+ "supported Chromium browser (Chrome, Edge, Brave, Chromium). "+ "Real-profile browsing requires a Chromium default; set one or turn "+ "the toggle off."+ )+ copy_dir, err = snapshot_real_profile(browser)+ if err or not copy_dir:+ return None, f"browser.use_real_profile is on, but {err}"++ # A shared session may already be up from a previous hermes process,+ # but ONLY reuse it when it is actually driving our copy dir — a stale+ # session from an earlier/failed launch can be attached to a throwaway+ # temp profile (agent-browser falls back to one when a launch races),+ # which would serve zero real cookies. Verify, else close and relaunch.+ existing = _agent_browser_get_cdp(_REAL_PROFILE_SESSION)+ if existing and _cdp_http_ready(existing) and _cdp_on_data_dir(existing, copy_dir):+ _real_profile_cdp_cache["cdp"] = existing+ return existing, None+ if existing:+ _agent_browser_close_session(_REAL_PROFILE_SESSION)++ # Launch agent-browser's packaged Chromium on the profile COPY. This is+ # the same launch path Hermes' built-in local browsing already uses,+ # just pointed at the copied user-data-dir — no bespoke Chrome launch.+ try:+ browser_cmd = _find_agent_browser()+ except FileNotFoundError as e:+ return None, (+ "browser.use_real_profile is on, but the local browser engine "+ f"(agent-browser) is not installed: {e}"+ )+ argv = [+ *_agent_browser_argv(browser_cmd),+ "--session", _REAL_PROFILE_SESSION,+ "--profile", copy_dir,+ ]+ # Do NOT pass agent-browser's ``--headless``: it maps to Chrome's legacy+ # headless mode, which uses a SEPARATE cookie store and loads none of the+ # copied profile's cookies (verified: --headless → 0 cookies, default →+ # full jar). agent-browser's default already runs windowless on a+ # server (no DISPLAY) while reading the real cookie store, which is+ # exactly what real-profile browsing needs. Headed mode is a superset+ # (visible window) and equally fine, so no flag either way.+ argv += ["open", "about:blank"]+ try:+ proc = subprocess.run(+ argv, capture_output=True, text=True,+ timeout=_get_open_command_timeout(first_open=True),+ env=_build_browser_env(),+ )+ except subprocess.TimeoutExpired:+ return None, (+ "browser.use_real_profile is on, but the real-profile browser "+ "took too long to start. Retry, or turn the toggle off."+ )+ except (subprocess.SubprocessError, OSError) as e:+ return None, f"browser.use_real_profile is on, but the launch failed: {e}"+ if proc.returncode != 0:+ tail = (proc.stderr or proc.stdout or "").strip().splitlines()+ reason = tail[-1] if tail else f"exit {proc.returncode}"+ return None, (+ f"browser.use_real_profile is on, but the real-profile browser "+ f"failed to start: {reason}"+ )++ cdp = _agent_browser_get_cdp(_REAL_PROFILE_SESSION)+ if not cdp:+ return None, (+ "browser.use_real_profile is on, but the real-profile browser "+ "started without exposing a devtools endpoint. Retry, or turn "+ "the toggle off."+ )+ _real_profile_cdp_cache["cdp"] = cdp+ logger.info("real-profile browser ready for %s at %s (%s)", browser, cdp, copy_dir)+ return cdp, Nonedef _url_is_private(url: str) -> bool:@@ -1557,7 +1709,7 @@ def _url_is_private(url: str) -> bool:return False-def _navigation_session_key(task_id: str, url: str, local_browser: bool = False) -> str:+def _navigation_session_key(task_id: str, url: str) -> str:"""Pick the session key that should handle ``url`` for ``task_id``.Returns the bare task_id unless ALL of these are true:@@ -1570,17 +1722,11 @@ def _navigation_session_key(task_id: str, url: str, local_browser: bool = False)When all are true, returns ``f"{task_id}::local"`` so the hybrid-routingpath spawns a local Chromium sidecar while the cloud session (if any)- continues to serve public URLs.-- ``local_browser=True`` (the model-facing arg) forces the ``::local`` sidecar- for the backend choice — but ONLY when the user consented to real-profile- browsing (``browser.use_real_profile``). Without consent the flag is ignored- (the caller surfaces a note); it never silently routes to the real profile.- It does not override the private-URL policy: a private URL is still routed- exactly as ``browser.auto_local_for_private_urls`` says. Without a cloud- provider the bare session is already local (and already carries the real- profile when consented), so the flag adds nothing there. A CDP override or- Camofox mode still owns the session and is not overridden.+ continues to serve public URLs. With ``browser.use_real_profile`` consent,+ local sessions (bare or sidecar) attach to the user's real-profile+ copy-browser via ``_create_local_session``; forcing a local session from+ the model side is the Browser Use lane's ``local`` argument, not a+ built-in-tools argument."""if task_id is None:task_id = "default"@@ -1589,17 +1735,7 @@ def _navigation_session_key(task_id: str, url: str, local_browser: bool = False)if _is_camofox_mode():return task_idif _get_cloud_provider() is None:- # Already local. A second ``::local`` session for the same task would- # contend with the bare one for the same user-data-dir.return task_id- if local_browser and _use_real_profile():- # Every private-URL gate in browser_navigate keys off the sidecar- # key, so honouring the flag for a private URL while the user opted- # out of auto-local routing would turn a model-supplied argument- # into a LAN policy override.- if _url_is_private(url) and not _auto_local_for_private_urls():- return task_id- return f"{task_id}{_LOCAL_SUFFIX}"if not _auto_local_for_private_urls():return task_idif not _url_is_private(url):@@ -2284,11 +2420,6 @@ BROWSER_TOOL_SCHEMAS = ["url": {"type": "string","description": "The URL to navigate to (e.g., 'https://example.com')"- },- "local_browser": {- "type": "boolean",- "description": "Use the user's real local browser profile (their logins/cookies) via a local Chromium session, even if a cloud backend is configured. Only honored when the user has consented (browser.use_real_profile); otherwise ignored.",- "default": False}},"required": ["url"]@@ -2435,6 +2566,27 @@ BROWSER_TOOL_SCHEMAS = [def _create_local_session(task_id: str) -> Dict[str, str]:import uuid++ # Real-profile consent: instead of an agent-browser-managed throwaway+ # Chromium, attach this local session (via CDP) to the user's default+ # browser running on a hermes-owned SNAPSHOT of their real profile —+ # live logins/cookies included. Fail closed on resolver/launch errors:+ # a consented user must never be silently downgraded to a throwaway.+ cdp_url, err = _real_profile_cdp()+ if err:+ raise RuntimeError(err)+ if cdp_url:+ session_name = f"rp_{uuid.uuid4().hex[:10]}"+ logger.info(+ "Created real-profile local session %s for task %s", session_name, task_id+ )+ return {+ "session_name": session_name,+ "bb_session_id": None,+ "cdp_url": _resolve_cdp_override(cdp_url),+ "features": {"local": True, "real_profile": True},+ }+session_name = f"h_{uuid.uuid4().hex[:10]}"logger.info("Created local browser session %s for task %s",session_name, task_id)@@ -3004,15 +3156,6 @@ def _run_browser_command(backend_args = ["--session", session_info["session_name"]]if _is_headed_mode():backend_args.append("--headed")- # Real-profile consent: point agent-browser at the user's real default- # Chromium profile so their live logins/cookies are available. Fails- # closed (returns an error) if the default browser is non-Chromium or- # its profile can't be located, rather than silently using a throwaway.- _profile_args, _profile_err = _real_profile_launch_args()- if _profile_err:- return {"success": False, "error": _profile_err}- if _profile_args:- backend_args += _profile_args# Lightpanda engine injection (local mode only, agent-browser v0.25.3+).# Use the resolved session backend rather than global cloud-provider state:@@ -3408,17 +3551,13 @@ def evaluate_url_safety(url: str) -> Optional[dict]:return None-def browser_navigate(url: str, task_id: Optional[str] = None, local_browser: bool = False) -> str:+def browser_navigate(url: str, task_id: Optional[str] = None) -> str:"""Navigate to a URL in the browser.Args:url: The URL to navigate totask_id: Task identifier for session isolation- local_browser: Force a local Chromium session using the user's real- default-browser profile, even when a cloud backend is configured.- Honored only if the user consented via ``browser.use_real_profile``;- ignored (with a note) otherwise.Returns:JSON string with navigation result (includes stealth features info on first nav)@@ -3454,18 +3593,7 @@ def browser_navigate(url: str, task_id: Optional[str] = None, local_browser: boo# cloud provider never sees the URL in that case. Can also be opted# out globally via ``browser.allow_private_urls`` in config.effective_task_id = task_id or "default"- # local_browser is honored only with real-profile consent; note when the- # agent asked for it but consent is off so the behavior isn't silently lost.- real_profile_note = None- if local_browser and not _use_real_profile():- real_profile_note = (- "local_browser was requested but browser.use_real_profile is off; "- "using the default browser backend. Enable real-profile browsing in "- "Settings → Browser to honor this."- )- nav_session_key = _navigation_session_key(- effective_task_id, url, local_browser=local_browser- )+ nav_session_key = _navigation_session_key(effective_task_id, url)auto_local_this_nav = _is_local_sidecar_key(nav_session_key)sensitive_query_key = _sensitive_query_param_name(url)@@ -3589,8 +3717,13 @@ def browser_navigate(url: str, task_id: Optional[str] = None, local_browser: boo"url": final_url,"title": title}- if real_profile_note:- response["note"] = real_profile_note+ # Auditability: stamp navigations that ran on the user's real-profile+ # copy-browser so usage is visible in the tool result.+ try:+ if (session_info.get("features") or {}).get("real_profile"):+ response["used_real_profile"] = True+ except Exception:+ pass# Remember only a successful, non-blocked navigation as the task owner.# Failed opens and blocked redirects must not retarget follow-up clicks# or snapshots to a newly-created but irrelevant session.@@ -5593,7 +5726,7 @@ registry.register(handler=lambda args, **kw: routed_browser_handler("browser_navigate",args,- fallback=lambda: browser_navigate(url=args.get("url", ""), task_id=kw.get("task_id"), local_browser=bool(args.get("local_browser", False))),+ fallback=lambda: browser_navigate(url=args.get("url", ""), task_id=kw.get("task_id")),**_browser_router_kw(kw),),check_fn=check_browser_navigate_requirements,diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 257ba2c945b..23dbd24bed2 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -599,11 +599,87 @@ def _resolve_backend_cdp(return None+def _real_profile_consented() -> bool:+ """Whether the user opted in to real-profile local browsing (config read)."""+ try:+ from tools.browser_tool import _use_real_profile++ return _use_real_profile()+ except Exception as e: # pragma: no cover — stubbed browser_tool in tests+ logger.debug("real-profile consent lookup failed: %s", e)+ return False+++def _resolve_real_profile_cdp(env: dict, force_local: bool) -> Optional[str]:+ """Point the harness at the user's real-profile copy-browser when consented.++ With ``browser.use_real_profile`` on, local browsing must mean the user's+ default Chromium with their logins — a browser Hermes launches on a+ SNAPSHOT of their real profile (see hermes_cli.browser_connect). Two ways+ in:++ - the effective backend is already local (no cloud provider, no CDP+ override, no legacy Browser Use cloud config): every local attach+ upgrades to the real profile, silently — this is requirement one; or+ - ``force_local`` (the consent-gated ``local`` tool arg): the model was+ asked to drive the user's actual browser even though a cloud backend+ is configured. The cloud backend keeps serving everything else.++ Explicit operator overrides (BU_CDP_WS/BU_CDP_URL env, /browser connect,+ ``browser.cdp_url``) own the session either way, matching the built-in+ lane's precedence.++ Sets BU_CDP_URL/BU_CDP_WS on success. Returns an error string when the+ real-profile launch fails (fail closed — a consented user is never+ silently downgraded to a throwaway browser), else None.+ """+ if not _real_profile_consented():+ return None+ if env.get("BU_CDP_WS") or env.get("BU_CDP_URL"):+ return None++ try:+ from tools.browser_tool import (+ _get_cdp_override_raw,+ _get_cloud_provider,+ _real_profile_cdp,+ )+ except Exception as e: # pragma: no cover — stubbed browser_tool in tests+ logger.debug("real-profile backend resolution unavailable: %s", e)+ return None++ try:+ if _get_cdp_override_raw():+ return None+ except Exception:+ pass++ if not force_local:+ # Only auto-upgrade genuinely-local attaches; any cloud path (provider+ # or legacy Browser Use cloud config) stays on its backend unless the+ # model passes local=true.+ try:+ if _get_cloud_provider() is not None:+ return None+ except Exception:+ return None+ if is_legacy_browser_use_cloud_config(_read_browser_cfg()):+ return None++ cdp, err = _real_profile_cdp()+ if err:+ return err+ if cdp:+ env["BU_CDP_URL" if cdp.startswith(("http://", "https://")) else "BU_CDP_WS"] = cdp+ return None++def browser_exec(code: str,session: str = "",timeout_s: int = _DEFAULT_TIMEOUT_S,task_id: Optional[str] = None,+ local: bool = False,):"""Run Python code through the browser-use CLI, and return its output"""from tools.registry import tool_error, tool_result@@ -632,6 +708,24 @@ def browser_exec("dashes, or underscores (e.g. 'r7k2').")env["BU_NAME"] = session+ # Real-profile consent: on a local backend this upgrades the attach to+ # the user's default browser (profile snapshot, logins included); with+ # local=True it forces that even under a cloud backend. Runs BEFORE+ # provider resolution so a real-profile hit short-circuits the cloud+ # path via the BU_CDP_* env contract.+ rp_err = _resolve_real_profile_cdp(env, force_local=bool(local))+ if rp_err:+ return tool_error(rp_err)+ if local and not (env.get("BU_CDP_URL") or env.get("BU_CDP_WS")):+ # local=True is only served by the real-profile route; anything else+ # (consent off — schema normally hidden, but be explicit; or an+ # operator CDP override owning the session) must not pretend.+ if not _real_profile_consented():+ return tool_error(+ "local=true was requested but browser.use_real_profile is off. "+ "Enable it in config.yaml (browser.use_real_profile: true) or "+ "the desktop Settings → Browser section, then retry."+ )# Route through the configured browser backend (Browserbase, Firecrawl,# Nous gateway, CDP override, local Chrome, …). Named sessions compose# with the backend: BU_NAME namespaces the harness daemon (its IPC@@ -831,7 +925,28 @@ def _cli_skill_text() -> str:def _dynamic_schema_overrides() -> dict:- return {"description": _description_header() + _HELPERS_DIGEST}+ overrides: dict = {"description": _description_header() + _HELPERS_DIGEST}+ # The ``local`` argument exists ONLY when the user consented to+ # real-profile browsing — everyone else's schema carries zero extra+ # surface. get_definitions() applies this at schema-build time, and the+ # caller memoizes on config.yaml mtime, so toggling consent changes the+ # schema on the next session rather than mid-conversation.+ if _real_profile_consented():+ props = dict(BROWSER_EXEC_SCHEMA["parameters"]["properties"])+ props["local"] = {+ "type": "boolean",+ "description": (+ "Drive the user's own local browser (a Hermes-managed copy of "+ "their real default-Chromium profile, logins/cookies included) "+ "instead of the configured cloud browser backend. Use when the "+ "user asks to act as themselves — their accounts, their "+ "sessions. No-op when the backend is already local. Default "+ "false."+ ),+ "default": False,+ }+ overrides["parameters"] = {**BROWSER_EXEC_SCHEMA["parameters"], "properties": props}+ return overridesBROWSER_EXEC_SCHEMA = {@@ -879,6 +994,7 @@ registry.register(session=args.get("session", "") or "",timeout_s=args.get("timeout_s", _DEFAULT_TIMEOUT_S),task_id=kw.get("task_id"),+ local=bool(args.get("local", False)),),check_fn=is_browser_use_cli_mode,dynamic_schema_overrides=_dynamic_schema_overrides,diff --git a/website/docs/user-guide/features/browser.md b/website/docs/user-guide/features/browser.mdindex 9ca1f368637..1403518ac35 100644--- a/website/docs/user-guide/features/browser.md+++ b/website/docs/user-guide/features/browser.md@@ -158,6 +158,41 @@ auto-installs it). Post-navigation redirects from a public URL onto a privateaddress are still blocked (you can't use a redirect-to-internal trick to reachyour LAN through the public path).+### Real profile browsing (use your own logins)++By default, local browsing runs in a clean, throwaway profile — the agent is+logged into nothing. Turn on **real profile browsing** to let the agent browse+as *you*, with your existing logins and cookies:++```yaml+# ~/.hermes/config.yaml+browser:+ use_real_profile: true+```++When enabled, Hermes copies your default browser's profile — cookies, saved+logins, and preferences — into a managed snapshot under+`~/.hermes/browser-profile/<browser>/`, then drives that snapshot with its+packaged Chromium. Your live browser profile is **never opened directly**: the+snapshot is a separate directory, so it doesn't fight your running browser for+the profile lock and it sidesteps Chrome 136+'s block on remote-debugging the+default profile directory. The auth files (cookies/logins/preferences) are+re-synced from your real profile on every launch, so logins you do in your own+browser show up in the agent's session.++- **Supported browsers:** Chrome, Edge, Brave, Chromium (whichever is your OS+ default). A non-Chromium default (e.g. Firefox) fails closed with a clear+ message rather than guessing.+- **Works on any backend.** On a local backend it's automatic once the toggle+ is on. Under a **cloud** browser backend, the agent can still open a+ real-profile local session on demand via the `browser_exec` tool's `local`+ argument (the tool only exposes that argument when this toggle is on) — the+ cloud backend keeps serving everything else.+- **Security framing:** this is a consent-gated convenience, not an isolation+ boundary. A page the agent visits runs with your real logins, so only enable+ it when you want the agent acting as you. Off by default.+- **Desktop:** toggle it in **Settings → Browser → Use My Real Browser Profile**.+### Camofox local mode[Camofox](https://github.com/jo-inc/camofox-browser) is a self-hosted Node.js server wrapping Camoufox (a Firefox fork with C++ fingerprint spoofing). It provides local anti-detection browsing without cloud dependencies.