The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(browser): honor browser.engine=lightpanda in Browser Use mode
Adrià Arrufate3a85ae5a091
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 52a416fc936..31782deaca1 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -40,6 +40,37 @@ from hermes_cli.browser_connect import ()+def _print_lightpanda_engine_status() -> None:+ """One or two ``/browser status`` lines about ``browser.engine: lightpanda``.++ Silent unless the engine is set to lightpanda. Says whether it is in use+ (and by which driver) or which setting shadows it — the engine is the+ lowest-precedence browser knob and used to be ignored silently.+ """+ try:+ from tools.browser_tool import lightpanda_engine_status, _using_lightpanda_engine++ if not _using_lightpanda_engine():+ return+ used, reason = lightpanda_engine_status()+ except Exception:+ return+ if not used:+ print(f" ⚠ browser.engine is 'lightpanda' but it is NOT in use: {reason}")+ return+ print(f" Engine: Lightpanda — {reason} (no screenshots)")+ try:+ from tools.browser_lightpanda import LIGHTPANDA_INSTALL_HINT, find_lightpanda_binary++ lightpanda_bin = find_lightpanda_binary()+ except Exception:+ return+ if lightpanda_bin:+ print(f" Binary: {lightpanda_bin}")+ else:+ print(f" ⚠ lightpanda binary not found — {LIGHTPANDA_INSTALL_HINT}")++class CLICommandsMixin:"""Mixin holding the interactive-CLI slash-command handlers.@@ -2797,6 +2828,7 @@ class CLICommandsMixin:if _bu_mode:print("🌐 Browser: Browser Use mode (browser_exec via the Browser Use CLI 3.0)")print(" Local Chrome via CDP, or Browser Use cloud browsers")+ _print_lightpanda_engine_status()print()print(" /browser use off — revert to the built-in browser tools")print()@@ -2804,6 +2836,7 @@ class CLICommandsMixin:if current:print("🌐 Browser: connected to live Chromium-family browser via CDP")print(f" Endpoint: {current}")+ _print_lightpanda_engine_status()_port = 9222try:@@ -2828,6 +2861,7 @@ class CLICommandsMixin:if provider is not None:print(f"🌐 Browser: {provider.provider_name()} (cloud)")+ _print_lightpanda_engine_status()else:# Show engine info for local modetry:@@ -2839,6 +2873,7 @@ class CLICommandsMixin:print("🌐 Browser: local Lightpanda (agent-browser --engine lightpanda)")print(" ⚡ Lightpanda: faster navigation, no screenshot support")print(" Automatic Chromium fallback for screenshots and failed commands")+ _print_lightpanda_engine_status()elif engine == "chrome":print("🌐 Browser: local headless Chromium (agent-browser --engine chrome)")else:diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex 717ed5830fb..a958482a31c 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -2591,7 +2591,39 @@ def run_doctor(args):check_info(step)else:check_warn("Node.js not found", "(optional, needed for browser tools)")-++ # Lightpanda engine (browser.engine / AGENT_BROWSER_ENGINE). Independent+ # of Node: Browser Use mode spawns ``lightpanda serve`` itself.+ try:+ from tools.browser_tool import _using_lightpanda_engine, lightpanda_engine_status+ from tools.browser_lightpanda import LIGHTPANDA_INSTALL_HINT, find_lightpanda_binary+ except Exception:+ pass+ else:+ try:+ _lp_selected = _using_lightpanda_engine()+ except Exception:+ _lp_selected = False+ if _lp_selected:+ try:+ _lp_used, _lp_reason = lightpanda_engine_status()+ except Exception as e:+ _lp_used, _lp_reason = False, f"status check failed: {e}"+ if not _lp_used:+ check_warn("browser.engine=lightpanda is shadowed", f"({_lp_reason})")+ check_info(+ "Fix: pick Lightpanda in `hermes tools` → Browser Automation, "+ "or set browser.engine: auto"+ )+ elif find_lightpanda_binary():+ check_ok("Lightpanda", f"({_lp_reason})")+ else:+ check_warn(+ "Lightpanda selected but binary not found",+ "(browser tools will fail until it is installed)",+ )+ check_info(LIGHTPANDA_INSTALL_HINT)+# npm audit for all Node.js packages_npm_bin = _safe_which("npm")if _npm_bin:diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.pyindex 831a8ac105a..edbcf333592 100644--- a/hermes_cli/tools_config.py+++ b/hermes_cli/tools_config.py@@ -615,6 +615,10 @@ TOOL_CATEGORIES = {# fresh install — pressing Enter must land on the free, no-key local# backend, never on the paid Nous Subscription gateway row:# - "Local Browser" — non-cloud option, no CloudBrowserProvider.+ # - "Lightpanda" — local too (cloud_provider: local) but with+ # browser.engine: lightpanda; Browser Use mode spawns+ # ``lightpanda serve`` itself, the built-in tools use+ # ``agent-browser --engine lightpanda``. No Chromium needed.# - "Nous Subscription (Browser Use cloud)" — managed Browser Use# billed via Nous subscription (requires_nous_auth +# override_env_vars). Uses the browser-use plugin as the@@ -629,8 +633,18 @@ TOOL_CATEGORIES = {"tag": "Headless Chromium, no API key needed","env_vars": [],"browser_provider": "local",+ "browser_engine": "auto","post_setup": "agent_browser",},+ {+ "name": "Lightpanda",+ "badge": "free · local · no Chromium",+ "tag": "Zig headless browser spawned by Hermes, text-only (no screenshots)",+ "env_vars": [],+ "browser_provider": "local",+ "browser_engine": "lightpanda",+ "post_setup": "lightpanda",+ },{"name": "Nous Subscription (Browser Use cloud)","badge": "subscription",@@ -2029,6 +2043,28 @@ def _run_post_setup(post_setup_key: str):"""Run post-setup hooks for tools that need extra installation steps."""from hermes_constants import find_node_executable+ if post_setup_key == "lightpanda":+ # Browser Use mode drives Lightpanda directly (Hermes spawns+ # ``lightpanda serve``); the built-in tools go through agent-browser.+ # Neither needs a Chromium build.+ _ensure_browser_use_cli()+ from tools.browser_lightpanda import (+ LIGHTPANDA_INSTALL_HINT,+ find_lightpanda_binary,+ )++ lightpanda_bin = find_lightpanda_binary()+ if lightpanda_bin:+ _print_success(f" Lightpanda found: {lightpanda_bin}")+ else:+ _print_warning(+ " lightpanda binary not found on PATH, ~/.lightpanda or ~/.local/bin"+ )+ _print_info(f" {LIGHTPANDA_INSTALL_HINT}")+ if os.name == "nt":+ _print_info(" Lightpanda has no native Windows build; run Hermes under WSL2.")+ return+if post_setup_key in {"agent_browser", "browserbase"}:# Every non-Camofox browser backend drives through the Browser Use# CLI when it's runnable — install it here too, not only on the@@ -3747,10 +3783,21 @@ _POST_SETUP_READY: dict = {"agent_browser": lambda: _agent_browser_installed(),"browserbase": lambda: _cloud_agent_browser_installed(),"camofox": lambda: _camofox_installed(),+ "lightpanda": lambda: _lightpanda_installed(),"cua_driver": lambda: _cua_driver_install_ready(),}+def _lightpanda_installed() -> bool:+ """True when a lightpanda binary is on PATH or in a known install dir."""+ try:+ from tools.browser_lightpanda import find_lightpanda_binary++ return find_lightpanda_binary() is not None+ except Exception:+ return False++def _cloud_agent_browser_installed() -> bool:"""Installed-check for the ``browserbase`` hook (cloud provider rows).@@ -4159,7 +4206,15 @@ def _is_provider_active(# Browser Use mode composes with the provider (driver over the# provider's CDP endpoint) — don't deactivate the provider row.current = cfg_get(config, "browser", "cloud_provider")- return provider["browser_provider"] == current+ if provider["browser_provider"] != current:+ return False+ # Two local rows differ only by engine ("Local Browser" vs+ # "Lightpanda"): config.yaml is the picker's source of truth here,+ # the AGENT_BROWSER_ENGINE env var is not consulted.+ if provider.get("browser_engine"):+ engine = str(cfg_get(config, "browser", "engine") or "auto").strip().lower()+ return engine == provider["browser_engine"]+ return Trueif provider.get("browser_backend"):backend = cfg_get(config, "browser", "backend")if backend is False:@@ -4680,6 +4735,12 @@ def _write_provider_config(provider: dict, config: dict, *, managed_feature) ->browser_cfg = config.setdefault("browser", {})browser_cfg["backend"] = provider["browser_backend"]+ # Local engine rows ("Local Browser" resets to auto, "Lightpanda" sets+ # lightpanda). Composes with browser.backend like the provider does.+ if provider.get("browser_engine"):+ browser_cfg = config.setdefault("browser", {})+ browser_cfg["engine"] = provider["browser_engine"]+# Set web search backend in config if applicableif provider.get("web_backend"):_set_selection("web", "backend", provider["web_backend"])@@ -4875,6 +4936,9 @@ def _configure_provider(if provider.get("browser_backend"):_print_success(" Browser set to Browser Use (browser_exec via CLI 3.0)")+ if provider.get("browser_engine") and provider["browser_engine"] != "auto":+ _print_success(f" Browser engine set to: {provider['browser_engine']}")+# Set web search backend in config if applicableif provider.get("web_backend"):_print_success(f" Web backend set to: {provider['web_backend']}")@@ -5412,6 +5476,12 @@ def _reconfigure_provider(browser_cfg["backend"] = provider["browser_backend"]_print_success(" Browser set to Browser Use (browser_exec via CLI 3.0)")+ if provider.get("browser_engine"):+ browser_cfg = config.setdefault("browser", {})+ browser_cfg["engine"] = provider["browser_engine"]+ if provider["browser_engine"] != "auto":+ _print_success(f" Browser engine set to: {provider['browser_engine']}")+# Set web search backend in config if applicableif provider.get("web_backend"):web_cfg = config.setdefault("web", {})diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.pyindex 08e6a15e393..9e37dc2cc2f 100644--- a/tests/hermes_cli/test_doctor.py+++ b/tests/hermes_cli/test_doctor.py@@ -1664,3 +1664,40 @@ class TestMacOSTCCGrants:out = capsys.readouterr().outassert "could not read code-signing requirement" in outassert "stable" not in out+++def test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):+ helper = TestDoctorMemoryProviderSection()+ import tools.browser_tool as bt++ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)+ monkeypatch.setattr(+ bt, "lightpanda_engine_status",+ lambda: (False, "cloud provider Browserbase is selected"),+ )+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)+ assert "browser.engine=lightpanda is shadowed" in out+ assert "Browserbase" in out+++def test_run_doctor_reports_lightpanda_ok(monkeypatch, tmp_path):+ helper = TestDoctorMemoryProviderSection()+ import tools.browser_tool as bt++ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)+ monkeypatch.setattr(bt, "lightpanda_engine_status", lambda: (True, "Browser Use mode"))+ monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: "/opt/lightpanda")+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)+ assert "Lightpanda" in out+ assert "shadowed" not in out+++def test_run_doctor_warns_when_lightpanda_binary_missing(monkeypatch, tmp_path):+ helper = TestDoctorMemoryProviderSection()+ import tools.browser_tool as bt++ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)+ monkeypatch.setattr(bt, "lightpanda_engine_status", lambda: (True, "Browser Use mode"))+ monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: None)+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)+ assert "Lightpanda selected but binary not found" in outdiff --git a/tests/hermes_cli/test_tools_config.py b/tests/hermes_cli/test_tools_config.pyindex 0ff5e99c44d..6acef7d27e4 100644--- a/tests/hermes_cli/test_tools_config.py+++ b/tests/hermes_cli/test_tools_config.py@@ -1219,3 +1219,50 @@ def test_explicit_plugin_toolset_admitted_against_real_a2a_plugin(monkeypatch):f"plugin-provided 'a2a' toolset dropped by _get_platform_tools "f"(Layer 2 of #81163); enabled={sorted(enabled)}")+++class TestLightpandaPostSetup:+ """The Lightpanda picker row: no Chromium, just the binary check."""++ @pytest.fixture(autouse=True)+ def _stub_browser_use_install(self):+ with patch("hermes_cli.tools_config._ensure_browser_use_cli") as stub:+ yield stub++ def test_reports_binary_when_found(self, _stub_browser_use_install):+ from hermes_cli.tools_config import _run_post_setup++ with patch("tools.browser_lightpanda.find_lightpanda_binary", return_value="/opt/lightpanda"), \+ patch("hermes_cli.tools_config._print_success") as ok, \+ patch("hermes_cli.tools_config._print_warning") as warn:+ _run_post_setup("lightpanda")+ _stub_browser_use_install.assert_called_once()+ assert "/opt/lightpanda" in ok.call_args.args[0]+ warn.assert_not_called()++ def test_prints_install_hint_when_missing(self):+ from hermes_cli.tools_config import _run_post_setup+ from tools.browser_lightpanda import LIGHTPANDA_INSTALL_URL++ with patch("tools.browser_lightpanda.find_lightpanda_binary", return_value=None), \+ patch("hermes_cli.tools_config._print_warning") as warn, \+ patch("hermes_cli.tools_config._print_info") as info:+ _run_post_setup("lightpanda")+ assert "not found" in warn.call_args.args[0]+ assert any(LIGHTPANDA_INSTALL_URL in c.args[0] for c in info.call_args_list)++ def test_post_setup_key_is_valid_and_readiness_gated(self):+ from hermes_cli.tools_config import (+ _POST_SETUP_INSTALLED,+ _POST_SETUP_READY,+ valid_post_setup_keys,+ )++ assert "lightpanda" in valid_post_setup_keys()+ with patch("tools.browser_lightpanda.find_lightpanda_binary", return_value="/opt/lightpanda"):+ assert _POST_SETUP_READY["lightpanda"]() is True+ with patch("tools.browser_lightpanda.find_lightpanda_binary", return_value=None):+ assert _POST_SETUP_READY["lightpanda"]() is False+ # Not in the forced-setup gate: a missing binary must not nag every+ # user who toggles the browser toolset.+ assert "lightpanda" not in _POST_SETUP_INSTALLEDdiff --git a/tests/tools/test_browser_lightpanda.py b/tests/tools/test_browser_lightpanda.pyindex d736edb47c3..8e9d47c44a0 100644--- a/tests/tools/test_browser_lightpanda.py+++ b/tests/tools/test_browser_lightpanda.py@@ -496,3 +496,244 @@ class TestEngineOverride:assert len(captured_cmds) == 1assert "--engine" in captured_cmds[0]assert captured_cmds[0][captured_cmds[0].index("--engine") + 1] == "lightpanda"+++# ---------------------------------------------------------------------------+# lightpanda_engine_status — is the engine in effect, or shadowed?+# ---------------------------------------------------------------------------++class TestLightpandaEngineStatus:+ def _gates(self, monkeypatch, **overrides):+ import tools.browser_tool as bt++ gates = dict(+ _using_lightpanda_engine=lambda: True,+ _get_cdp_override_raw=lambda: "",+ _is_camofox_mode=lambda: False,+ _get_cloud_provider=lambda: None,+ _is_browser_use_cli_mode=lambda: True,+ _use_real_profile=lambda: False,+ )+ gates.update(overrides)+ for name, fn in gates.items():+ monkeypatch.setattr(bt, name, fn)+ monkeypatch.setattr(+ "tools.browser_use_cli.is_legacy_browser_use_cloud_config", lambda cfg: False+ )+ return bt++ def test_not_lightpanda(self, monkeypatch):+ bt = self._gates(monkeypatch, _using_lightpanda_engine=lambda: False)+ assert bt.lightpanda_engine_status() == (False, "")++ def test_used_in_browser_use_mode(self, monkeypatch):+ bt = self._gates(monkeypatch)+ used, reason = bt.lightpanda_engine_status()+ assert used is True+ assert "lightpanda serve" in reason++ def test_used_with_builtin_tools(self, monkeypatch):+ bt = self._gates(monkeypatch, _is_browser_use_cli_mode=lambda: False)+ used, reason = bt.lightpanda_engine_status()+ assert used is True+ assert "--engine lightpanda" in reason++ def test_shadowed_by_cdp_override(self, monkeypatch):+ bt = self._gates(monkeypatch, _get_cdp_override_raw=lambda: "ws://x")+ used, reason = bt.lightpanda_engine_status()+ assert used is False and "CDP override" in reason++ def test_shadowed_by_camofox(self, monkeypatch):+ bt = self._gates(monkeypatch, _is_camofox_mode=lambda: True)+ used, reason = bt.lightpanda_engine_status()+ assert used is False and "Camofox" in reason++ def test_shadowed_by_cloud_provider(self, monkeypatch):+ provider = MagicMock()+ provider.provider_name.return_value = "Browserbase"+ bt = self._gates(monkeypatch, _get_cloud_provider=lambda: provider)+ used, reason = bt.lightpanda_engine_status()+ assert used is False and "Browserbase" in reason++ def test_shadowed_by_legacy_browser_use_cloud(self, monkeypatch):+ bt = self._gates(monkeypatch)+ monkeypatch.setattr(+ "tools.browser_use_cli.is_legacy_browser_use_cloud_config", lambda cfg: True+ )+ used, reason = bt.lightpanda_engine_status()+ assert used is False and "Browser Use cloud" in reason++ def test_shadowed_by_real_profile(self, monkeypatch):+ bt = self._gates(monkeypatch, _use_real_profile=lambda: True)+ used, reason = bt.lightpanda_engine_status()+ assert used is False and "use_real_profile" in reason+++# ---------------------------------------------------------------------------+# Browser Use mode session lifecycle+# ---------------------------------------------------------------------------++class _FakeServer:+ def __init__(self, port=4321, alive=True):+ self.port = port+ self.cdp_url = f"http://127.0.0.1:{port}"+ self._alive = alive++ def is_alive(self):+ return self._alive+++class TestLightpandaSessionCreation:+ def _common(self, monkeypatch, *, bu_mode=True, local_backend=True, launch=None):+ import tools.browser_tool as bt++ calls = []++ def fake_launch(session_name, *, block_private_networks=False):+ calls.append((session_name, block_private_networks))+ if launch is not None:+ return launch+ return _FakeServer(), None++ monkeypatch.setattr(bt, "_real_profile_cdp", lambda: (None, None))+ monkeypatch.setattr(bt, "_is_browser_use_cli_mode", lambda: bu_mode)+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)+ monkeypatch.setattr(bt, "_is_local_backend", lambda: local_backend)+ monkeypatch.setattr("tools.browser_lightpanda.launch_lightpanda", fake_launch)+ return bt, calls++ def test_spawns_lightpanda_in_browser_use_mode(self, monkeypatch):+ bt, calls = self._common(monkeypatch)+ info = bt._create_local_session("task-1")+ assert info["session_name"].startswith("lp_")+ assert info["cdp_url"] == "http://127.0.0.1:4321"+ assert info["features"] == {"local": True, "lightpanda": True}+ assert info["bb_session_id"] is None+ assert calls == [(info["session_name"], False)]++ def test_blocks_private_networks_for_containerised_terminal(self, monkeypatch):+ bt, calls = self._common(monkeypatch, local_backend=False)+ bt._create_local_session("task-1")+ assert calls[0][1] is True++ def test_ignores_engine_outside_browser_use_mode(self, monkeypatch):+ bt, calls = self._common(monkeypatch, bu_mode=False)+ info = bt._create_local_session("task-1")+ assert info["features"] == {"local": True}+ assert info["cdp_url"] is None+ assert calls == []++ def test_launch_failure_raises(self, monkeypatch):+ bt, _ = self._common(monkeypatch, launch=(None, "no lightpanda binary was found"))+ with pytest.raises(RuntimeError, match="no lightpanda binary"):+ bt._create_local_session("task-1")+++class TestLightpandaSessionLifecycle:+ def setup_method(self):+ import tools.browser_tool as bt++ self.bt = bt+ self.orig_sessions = bt._active_sessions.copy()+ self.orig_activity = bt._session_last_activity.copy()+ self.orig_cleanup_done = bt._cleanup_done+ bt._active_sessions.clear()+ bt._session_last_activity.clear()++ def teardown_method(self):+ bt = self.bt+ bt._active_sessions.clear()+ bt._active_sessions.update(self.orig_sessions)+ bt._session_last_activity.clear()+ bt._session_last_activity.update(self.orig_activity)+ bt._cleanup_done = self.orig_cleanup_done++ def _seed(self, key="task-1", name="lp_dead"):+ info = {+ "session_name": name,+ "bb_session_id": None,+ "cdp_url": "http://127.0.0.1:1",+ "features": {"local": True, "lightpanda": True},+ }+ self.bt._active_sessions[key] = info+ self.bt._session_last_activity[key] = 1.0+ return info++ def test_dead_process_is_detected(self, monkeypatch):+ info = self._seed()+ monkeypatch.setattr("tools.browser_lightpanda.get_server", lambda name: None)+ assert self.bt._local_backend_process_dead(info) is True+ monkeypatch.setattr(+ "tools.browser_lightpanda.get_server", lambda name: _FakeServer(alive=False)+ )+ assert self.bt._local_backend_process_dead(info) is True+ monkeypatch.setattr("tools.browser_lightpanda.get_server", lambda name: _FakeServer())+ assert self.bt._local_backend_process_dead(info) is False+ assert self.bt._local_backend_process_dead({"features": {"local": True}}) is False++ def test_get_session_info_respawns_dead_lightpanda(self, monkeypatch):+ bt = self.bt+ stale = self._seed()+ fresh = {+ "session_name": "lp_fresh",+ "bb_session_id": None,+ "cdp_url": "http://127.0.0.1:2",+ "features": {"local": True, "lightpanda": True},+ }+ cleaned = []++ def fake_cleanup(key):+ cleaned.append(key)+ bt._active_sessions.pop(key, None)++ monkeypatch.setattr(bt, "_start_browser_cleanup_thread", lambda: None)+ monkeypatch.setattr(+ bt, "_browser_session_backend",+ lambda key: MagicMock(ensure_healthy=lambda: True),+ )+ monkeypatch.setattr("tools.browser_lightpanda.get_server", lambda name: None)+ monkeypatch.setattr(bt, "_cleanup_single_browser_session", fake_cleanup)+ monkeypatch.setattr(bt, "_get_cdp_override", lambda: "")+ monkeypatch.setattr(bt, "_get_cloud_provider", lambda: None)+ monkeypatch.setattr(bt, "_create_local_session", lambda *a, **k: fresh)+ supervised = []+ monkeypatch.setattr(bt, "_ensure_cdp_supervisor", supervised.append)++ info = bt._get_session_info("task-1")+ assert cleaned == ["task-1"]+ assert info["session_name"] == "lp_fresh"+ assert bt._active_sessions["task-1"]["session_name"] == "lp_fresh"+ assert info["session_name"] != stale["session_name"]+ # Browser Use mode hides the browser_* tools that read supervisor+ # state; a Lightpanda session never attaches one.+ assert supervised == []++ def test_cleanup_stops_lightpanda_without_agent_browser_close(self, monkeypatch):+ bt = self.bt+ self._seed()+ stopped = []+ monkeypatch.setattr("tools.browser_lightpanda.stop_lightpanda", stopped.append)+ with patch("tools.browser_tool._maybe_stop_recording"), \+ patch("tools.browser_tool._run_browser_command") as run, \+ patch("tools.browser_tool.os.path.exists", return_value=False):+ bt.cleanup_browser("task-1")+ run.assert_not_called()+ assert stopped == ["lp_dead"]+ assert "task-1" not in bt._active_sessions+ assert "task-1" not in bt._session_last_activity++ def test_emergency_cleanup_stops_all_lightpanda(self, monkeypatch):+ bt = self.bt+ bt._cleanup_done = False+ with patch("tools.browser_lightpanda.stop_all_lightpanda") as stop_all, \+ patch("tools.browser_tool._terminate_real_profile_chrome"), \+ patch("tools.browser_tool.cleanup_all_browsers"), \+ patch("tools.browser_tool._reap_orphaned_browser_sessions"):+ bt._emergency_cleanup_all_sessions()+ stop_all.assert_called_once()++ def test_orphan_reaper_sweeps_lightpanda_records(self, tmp_path):+ with patch("tools.browser_lightpanda.reap_orphaned_lightpanda") as reap, \+ patch("tools.browser_tool._socket_safe_tmpdir", return_value=str(tmp_path)):+ self.bt._reap_orphaned_browser_sessions()+ reap.assert_called_once()diff --git a/tests/tools/test_browser_lightpanda_serve.py b/tests/tools/test_browser_lightpanda_serve.pynew file mode 100644index 00000000000..73200bac14f--- /dev/null+++ b/tests/tools/test_browser_lightpanda_serve.py@@ -0,0 +1,309 @@+"""Tests for tools/browser_lightpanda.py — the ``lightpanda serve`` launcher+Browser Use mode uses when ``browser.engine`` is ``lightpanda``."""++import json+import os+import stat+import subprocess+from unittest.mock import patch++import pytest++import tools.browser_lightpanda as lp+++class FakeProc:+ def __init__(self, pid=4242, exit_code=None):+ self.pid = pid+ self._rc = exit_code+ self.terminated = False+ self.killed = False++ def poll(self):+ return self._rc++ def terminate(self):+ self.terminated = True+ self._rc = -15++ def kill(self):+ self.killed = True+ self._rc = -9++ def wait(self, timeout=None):+ return self._rc++[email protected](autouse=True)+def _isolate(tmp_path, monkeypatch):+ state = tmp_path / "state"+ state.mkdir()+ monkeypatch.setattr(lp, "_state_dir", lambda: state)+ # Never touch the developer's real ~/.local/bin/lightpanda.+ monkeypatch.setattr(lp, "_home_candidates", lambda: [])+ monkeypatch.setattr(lp, "_safe_start_time", lambda pid: 111)+ with lp._servers_lock:+ lp._servers.clear()+ yield state+ with lp._servers_lock:+ lp._servers.clear()+++def _exe(path):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ path.chmod(path.stat().st_mode | stat.S_IXUSR)+ return path+++class TestFindBinary:+ def test_prefers_path(self, tmp_path, monkeypatch):+ exe = _exe(tmp_path / "bin" / "lightpanda")+ monkeypatch.setenv("PATH", str(tmp_path / "bin"))+ monkeypatch.setattr("tools.browser_tool._merge_browser_path", lambda p: p)+ assert lp.find_lightpanda_binary() == str(exe)++ def test_falls_back_to_home_candidates(self, tmp_path, monkeypatch):+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))+ monkeypatch.setattr("tools.browser_tool._merge_browser_path", lambda p: p)+ exe = _exe(tmp_path / ".lightpanda" / "lightpanda")+ monkeypatch.setattr(lp, "_home_candidates", lambda: [exe])+ assert lp.find_lightpanda_binary() == str(exe)++ def test_none_when_absent(self, tmp_path, monkeypatch):+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))+ monkeypatch.setattr("tools.browser_tool._merge_browser_path", lambda p: p)+ assert lp.find_lightpanda_binary() is None++ def test_none_on_windows(self, monkeypatch):+ monkeypatch.setattr(lp.os, "name", "nt")+ assert lp.find_lightpanda_binary() is None+++class TestLaunch:+ def _launch(self, monkeypatch, *, proc=None, ready=True, stderr=b"", **kw):+ calls = {}++ def fake_popen(argv, **kwargs):+ calls["argv"] = argv+ calls["kwargs"] = kwargs+ if stderr:+ kwargs["stderr"].write(stderr)+ kwargs["stderr"].flush()+ return proc or FakeProc()++ monkeypatch.setattr(lp, "find_lightpanda_binary", lambda: "/opt/lightpanda")+ monkeypatch.setattr(lp, "_pick_free_loopback_port", lambda: 43111)+ monkeypatch.setattr(lp, "_cdp_ready", lambda url: ready)+ monkeypatch.setattr(lp, "_browser_env", lambda: {"PATH": "/usr/bin"})+ monkeypatch.setattr(lp.subprocess, "Popen", fake_popen)+ server, err = lp.launch_lightpanda("lp_test", **kw)+ return server, err, calls++ def test_missing_binary_returns_install_hint(self, monkeypatch):+ monkeypatch.setattr(lp, "find_lightpanda_binary", lambda: None)+ server, err = lp.launch_lightpanda("lp_test")+ assert server is None+ assert "browser.engine" in err+ assert lp.LIGHTPANDA_INSTALL_URL in err++ def test_spawns_serve_on_loopback_without_timeout_flag(self, monkeypatch, _isolate):+ server, err, calls = self._launch(monkeypatch)+ assert err is None+ assert calls["argv"] == [+ "/opt/lightpanda", "serve", "--host", "127.0.0.1", "--port", "43111",+ ]+ kw = calls["kwargs"]+ assert kw["stdin"] is subprocess.DEVNULL+ assert kw["stdout"] is subprocess.DEVNULL+ assert hasattr(kw["stderr"], "write") # a log file, never a pipe+ assert kw["env"] == {"PATH": "/usr/bin"}+ if os.name != "nt":+ assert kw["start_new_session"] is True+ assert server.cdp_url == "http://127.0.0.1:43111"+ assert server.start_time == 111+ assert lp.get_server("lp_test") is server+ record = json.loads((_isolate / "lp_test.json").read_text(encoding="utf-8"))+ assert record["pid"] == 4242+ assert record["port"] == 43111+ assert record["owner_pid"] == os.getpid()+ assert record["start_time"] == 111++ def test_block_private_networks_flag(self, monkeypatch):+ _, err, calls = self._launch(monkeypatch, block_private_networks=True)+ assert err is None+ assert calls["argv"][-1] == "--block-private-networks"++ def test_early_exit_reports_stderr_tail(self, monkeypatch):+ server, err, _ = self._launch(+ monkeypatch, proc=FakeProc(exit_code=1), ready=False,+ stderr=b"info: starting\nFATAL app : unknown argument --bogus\n",+ )+ assert server is None+ assert "exited with code 1" in err+ assert "unknown argument --bogus" in err+ assert lp.get_server("lp_test") is None++ def test_ready_timeout_terminates_child(self, monkeypatch, _isolate):+ monkeypatch.setattr(lp, "_READY_TIMEOUT_S", 0.05)+ monkeypatch.setattr(lp, "_POLL_INTERVAL_S", 0.01)+ proc = FakeProc()+ server, err, _ = self._launch(monkeypatch, proc=proc, ready=False)+ assert server is None+ assert "did not expose" in err+ assert proc.terminated is True+ assert not (_isolate / "lp_test.json").exists()+ assert lp.get_server("lp_test") is None++ def test_spawn_failure_is_reported(self, monkeypatch):+ monkeypatch.setattr(lp, "find_lightpanda_binary", lambda: "/opt/lightpanda")+ monkeypatch.setattr(lp, "_pick_free_loopback_port", lambda: 1)+ monkeypatch.setattr(lp, "_browser_env", lambda: {})++ def boom(*a, **k):+ raise OSError("exec format error")++ monkeypatch.setattr(lp.subprocess, "Popen", boom)+ server, err = lp.launch_lightpanda("lp_test")+ assert server is None+ assert "exec format error" in err+++class TestStop:+ def _seed(self, _isolate, name="lp_test", alive=True):+ proc = FakeProc(pid=777, exit_code=None if alive else 0)+ server = lp.LightpandaServer(name, 43111, proc, str(_isolate / f"{name}.log"), 111)+ lp._write_record(server)+ with lp._servers_lock:+ lp._servers[name] = server+ return server++ def test_stop_uses_tree_kill_with_expected_start_and_removes_record(self, _isolate):+ server = self._seed(_isolate)+ killed = []+ with patch(+ "tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=lambda pid, expected_start=None: killed.append((pid, expected_start)),+ ):+ lp.stop_lightpanda("lp_test")+ assert killed == [(777, 111)]+ assert lp.get_server("lp_test") is None+ assert not (_isolate / "lp_test.json").exists()+ assert server.proc.terminated is False # tree-kill handled it++ def test_stop_falls_back_to_terminate_when_tree_kill_fails(self, _isolate):+ server = self._seed(_isolate)+ with patch(+ "tools.process_registry.ProcessRegistry._terminate_host_pid",+ side_effect=RuntimeError("psutil missing"),+ ):+ lp.stop_lightpanda("lp_test")+ assert server.proc.terminated is True++ def test_stop_dead_server_just_drops_record(self, _isolate):+ self._seed(_isolate, alive=False)+ with patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ lp.stop_lightpanda("lp_test")+ kill.assert_not_called()+ assert not (_isolate / "lp_test.json").exists()++ def test_stop_unknown_session_is_noop(self):+ lp.stop_lightpanda("lp_nope") # must not raise++ def test_stop_all(self, _isolate):+ self._seed(_isolate, "lp_a")+ self._seed(_isolate, "lp_b")+ with patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ lp.stop_all_lightpanda()+ assert kill.call_count == 2+ assert lp.get_server("lp_a") is None and lp.get_server("lp_b") is None+++class TestReapOrphans:+ def _record(self, _isolate, name, *, pid=999, owner_pid=1, port=43111, start_time=111):+ (_isolate / f"{name}.json").write_text(+ json.dumps({"pid": pid, "port": port, "owner_pid": owner_pid,+ "start_time": start_time, "started_at": 0}),+ encoding="utf-8",+ )+ return _isolate / f"{name}.json"++ def test_live_other_owner_is_skipped(self, _isolate):+ rec = self._record(_isolate, "lp_x", owner_pid=12345)+ with patch("gateway.status._pid_exists", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ assert lp.reap_orphaned_lightpanda() == 0+ kill.assert_not_called()+ assert rec.exists()++ def test_own_tracked_session_is_skipped(self, _isolate):+ rec = self._record(_isolate, "lp_x", owner_pid=os.getpid())+ with lp._servers_lock:+ lp._servers["lp_x"] = lp.LightpandaServer("lp_x", 43111, FakeProc(), "", 111)+ with patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ assert lp.reap_orphaned_lightpanda() == 0+ kill.assert_not_called()+ assert rec.exists()++ def test_dead_owner_verified_process_is_killed(self, _isolate):+ rec = self._record(_isolate, "lp_x", owner_pid=12345, pid=999)+ with patch("gateway.status._pid_exists", return_value=False), \+ patch.object(lp, "_is_lightpanda_process", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ assert lp.reap_orphaned_lightpanda() == 1+ kill.assert_called_once_with(999, expected_start=111)+ assert not rec.exists()++ def test_own_untracked_session_is_reaped(self, _isolate):+ """Owner alive but lost its in-memory tracking: reap, don't leak."""+ self._record(_isolate, "lp_x", owner_pid=os.getpid(), pid=999)+ with patch.object(lp, "_is_lightpanda_process", return_value=True), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ assert lp.reap_orphaned_lightpanda() == 1+ kill.assert_called_once()++ def test_unverified_pid_is_never_signalled(self, _isolate):+ rec = self._record(_isolate, "lp_x", owner_pid=12345, pid=999)+ with patch("gateway.status._pid_exists", return_value=False), \+ patch.object(lp, "_is_lightpanda_process", return_value=False), \+ patch("tools.process_registry.ProcessRegistry._terminate_host_pid") as kill:+ assert lp.reap_orphaned_lightpanda() == 0+ kill.assert_not_called()+ assert not rec.exists()++ def test_corrupt_record_is_removed(self, _isolate):+ rec = _isolate / "lp_bad.json"+ rec.write_text("{not json", encoding="utf-8")+ assert lp.reap_orphaned_lightpanda() == 0+ assert not rec.exists()+++class TestProcessIdentity:+ class _P:+ def __init__(self, name, cmdline):+ self._name, self._cmdline = name, cmdline++ def name(self):+ return self._name++ def cmdline(self):+ return self._cmdline++ def test_matches_name_port_and_start_time(self):+ proc = self._P("lightpanda", ["/opt/lightpanda", "serve", "--host", "127.0.0.1", "--port", "43111"])+ with patch("psutil.Process", return_value=proc), \+ patch("gateway.status.get_process_start_time", return_value=111):+ assert lp._is_lightpanda_process(999, 43111, 111) is True+ with patch("psutil.Process", return_value=proc), \+ patch("gateway.status.get_process_start_time", return_value=222):+ assert lp._is_lightpanda_process(999, 43111, 111) is False++ def test_rejects_other_process_on_recycled_pid(self):+ proc = self._P("chrome", ["chrome", "--remote-debugging-port=43111"])+ with patch("psutil.Process", return_value=proc):+ assert lp._is_lightpanda_process(999, 43111, None) is False++ def test_rejects_lightpanda_on_other_port(self):+ proc = self._P("lightpanda", ["lightpanda", "serve", "--port", "1"])+ with patch("psutil.Process", return_value=proc):+ assert lp._is_lightpanda_process(999, 43111, None) is Falsediff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.pyindex 497619b2ba4..efcbfe5ebad 100644--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@ -1092,3 +1092,219 @@ class TestDefaultDowngradeNotice:)monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)assert bu_cli.default_downgrade_notice() is None+++class TestLightpandaBackendResolution:+ """browser.engine: lightpanda in Browser Use mode — Hermes spawns+ ``lightpanda serve`` through the same _get_session_info machinery and+ exports its endpoint, but only when nothing with higher precedence+ (BU_CDP_* env, a CDP override, a cloud provider) claimed the session."""++ def _setup(self, monkeypatch, *, engine=True, info=None, boom=None):+ import tools.browser_tool as bt++ seen = []++ def fake_session_info(key):+ seen.append(key)+ if boom:+ raise boom+ return info if info is not None else {"cdp_url": "http://127.0.0.1:43111"}++ monkeypatch.setattr(bt, "_get_cdp_override", lambda: "")+ monkeypatch.setattr(bt, "_get_cloud_provider", lambda: None)+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: engine)+ monkeypatch.setattr(bt, "_get_session_info", fake_session_info)+ return seen++ def test_exports_bu_cdp_url_and_private_sentinel(self, monkeypatch):+ seen = self._setup(monkeypatch)+ env = {}+ assert bu_cli._resolve_backend_cdp(env, "t1") is None+ assert env["BU_CDP_URL"] == "http://127.0.0.1:43111"+ assert env[bu_cli._PRIVATE_BROWSER_SENTINEL] == "1"+ assert seen == ["t1"]++ def test_named_session_keys_its_own_process(self, monkeypatch):+ seen = self._setup(monkeypatch)+ assert bu_cli._resolve_backend_cdp({}, "t1", session_name="r7k2") is None+ assert seen == ["bu-named-r7k2"]++ def test_default_key_without_task(self, monkeypatch):+ seen = self._setup(monkeypatch)+ assert bu_cli._resolve_backend_cdp({}, None) is None+ assert seen == ["browser-exec-default"]++ def test_launch_failure_returns_actionable_error(self, monkeypatch):+ self._setup(monkeypatch, boom=RuntimeError("no lightpanda binary was found"))+ err = bu_cli._resolve_backend_cdp({}, "t1")+ assert err and "no lightpanda binary was found" in err+ assert "browser.engine" in err++ def test_missing_cdp_returns_error(self, monkeypatch):+ self._setup(monkeypatch, info={"cdp_url": None})+ err = bu_cli._resolve_backend_cdp({}, "t1")+ assert err and "no CDP endpoint" in err++ def test_engine_auto_leaves_env_untouched(self, monkeypatch):+ seen = self._setup(monkeypatch, engine=False)+ env = {}+ assert bu_cli._resolve_backend_cdp(env, "t1") is None+ assert env == {}+ assert seen == []++ def test_bu_env_wins(self, monkeypatch):+ seen = self._setup(monkeypatch)+ env = {"BU_CDP_WS": "ws://operator:9222"}+ assert bu_cli._resolve_backend_cdp(env, "t1") is None+ assert env["BU_CDP_WS"] == "ws://operator:9222"+ assert seen == []++ def test_cdp_override_wins(self, monkeypatch):+ import tools.browser_tool as bt++ seen = self._setup(monkeypatch)+ monkeypatch.setattr(bt, "_get_cdp_override", lambda: "http://127.0.0.1:9222")+ env = {}+ assert bu_cli._resolve_backend_cdp(env, "t1") is None+ assert env["BU_CDP_URL"] == "http://127.0.0.1:9222"+ assert seen == []++ def test_cloud_provider_wins(self, monkeypatch):+ import tools.browser_tool as bt++ seen = self._setup(monkeypatch, info={"cdp_url": "wss://cloud.example/x"})+ monkeypatch.setattr(bt, "_get_cloud_provider", lambda: object())+ env = {}+ assert bu_cli._resolve_backend_cdp(env, "t1") is None+ assert env["BU_CDP_WS"] == "wss://cloud.example/x"+ assert seen == ["t1"] # provider path, same cache key+++class TestLightpandaPreamble:+ def test_lightpanda_session_skips_own_tab_preamble(self, tmp_path, monkeypatch):+ """A Lightpanda process is private to its session: no sibling daemon+ to collide with, and Target.createTarget would fail anyway+ (lightpanda-io/browser#1962)."""+ import tools.browser_tool as bt++ monkeypatch.setattr(bt, "_get_cdp_override", lambda: "")+ monkeypatch.setattr(bt, "_get_cloud_provider", lambda: None)+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)+ monkeypatch.setattr(+ bt, "_get_session_info", lambda key: {"cdp_url": "http://127.0.0.1:43111"}+ )+ cli = _fake_cli(tmp_path, "cat\n")+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])+ result = json.loads(bu_cli.browser_exec("print('payload')", session="r7k2"))+ assert result["success"] is True+ assert "_hermes_ensure_own_tab" not in result["output"]+ assert "print('payload')" in result["output"]+++class TestLightpandaHeader:+ def test_lightpanda_header_is_text_first_even_for_vision_models(self, monkeypatch):+ monkeypatch.setattr(+ "tools.vision_tools._should_use_native_vision_fast_path", lambda: True+ )+ monkeypatch.setattr(+ "tools.browser_tool.lightpanda_engine_status", lambda: (True, "used")+ )+ header = bu_cli._description_header()+ assert header.startswith(bu_cli._HEADER_BASE)+ assert header.endswith(bu_cli._HEADER_LIGHTPANDA)+ assert "goto_url(url)" in header+ assert "attached to your context automatically" not in header+ overrides = bu_cli._dynamic_schema_overrides()+ assert overrides["description"].startswith(bu_cli._HEADER_BASE)+ assert overrides["description"].endswith(bu_cli._HELPERS_DIGEST)++ def test_shadowed_engine_keeps_default_header(self, monkeypatch):+ monkeypatch.setattr(+ "tools.vision_tools._should_use_native_vision_fast_path", lambda: True+ )+ monkeypatch.setattr(+ "tools.browser_tool.lightpanda_engine_status", lambda: (False, "cloud")+ )+ assert bu_cli._description_header() == bu_cli._HEADER_BASE + bu_cli._HEADER_VISION+++class TestLightpandaPickerRow:+ def _rows(self):+ from hermes_cli.tools_config import TOOL_CATEGORIES++ return TOOL_CATEGORIES["browser"]["providers"]++ def _row(self, name):+ return next(r for r in self._rows() if r["name"] == name)++ def test_lightpanda_row_shape(self):+ row = self._row("Lightpanda")+ assert row["browser_provider"] == "local"+ assert row["browser_engine"] == "lightpanda"+ assert row["post_setup"] == "lightpanda"+ assert row["env_vars"] == []+ # Local Browser stays the default-highlighted first row.+ assert self._rows()[0]["name"] == "Local Browser"++ def test_selecting_lightpanda_writes_engine_and_local_keeps_backend(self):+ from hermes_cli.tools_config import _write_provider_config++ config = {"browser": {"backend": "browser-use", "cloud_provider": "browserbase"}}+ _write_provider_config(self._row("Lightpanda"), config, managed_feature=None)+ assert config["browser"]["cloud_provider"] == "local"+ assert config["browser"]["engine"] == "lightpanda"+ assert config["browser"]["backend"] == "browser-use"++ def test_selecting_local_browser_resets_engine(self):+ from hermes_cli.tools_config import _write_provider_config++ config = {"browser": {"cloud_provider": "local", "engine": "lightpanda"}}+ _write_provider_config(self._row("Local Browser"), config, managed_feature=None)+ assert config["browser"]["engine"] == "auto"++ def test_active_row_follows_engine(self):+ from hermes_cli.tools_config import _is_provider_active++ lp_row, local_row = self._row("Lightpanda"), self._row("Local Browser")+ lp_cfg = {"browser": {"cloud_provider": "local", "engine": "lightpanda"}}+ assert _is_provider_active(lp_row, lp_cfg) is True+ assert _is_provider_active(local_row, lp_cfg) is False+ default_cfg = {"browser": {"cloud_provider": "local"}}+ assert _is_provider_active(lp_row, default_cfg) is False+ assert _is_provider_active(local_row, default_cfg) is True+ cloud_cfg = {"browser": {"cloud_provider": "browserbase", "engine": "lightpanda"}}+ assert _is_provider_active(lp_row, cloud_cfg) is False+++class TestLightpandaStatusLine:+ def _status(self, monkeypatch, *, used, reason, binary="/opt/lightpanda"):+ import contextlib+ import io++ import tools.browser_tool as bt+ from hermes_cli.cli_commands_mixin import CLICommandsMixin++ monkeypatch.setattr(bu_cli, "is_browser_use_cli_mode", lambda: True)+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)+ monkeypatch.setattr(bt, "lightpanda_engine_status", lambda: (used, reason))+ monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: binary)+ buf = io.StringIO()+ with contextlib.redirect_stdout(buf):+ CLICommandsMixin._handle_browser_command(object(), "/browser status")+ return buf.getvalue()++ def test_status_reports_lightpanda_in_use(self, monkeypatch):+ out = self._status(monkeypatch, used=True, reason="Browser Use mode: Hermes spawns `lightpanda serve` per session")+ assert "Engine: Lightpanda" in out+ assert "spawns `lightpanda serve`" in out+ assert "Binary: /opt/lightpanda" in out++ def test_status_reports_missing_binary(self, monkeypatch):+ out = self._status(monkeypatch, used=True, reason="x", binary=None)+ assert "lightpanda binary not found" in out++ def test_status_reports_shadowed_engine(self, monkeypatch):+ out = self._status(monkeypatch, used=False, reason="cloud provider Browserbase is selected")+ assert "NOT in use" in out+ assert "Browserbase" in outdiff --git a/tools/browser_lightpanda.py b/tools/browser_lightpanda.pynew file mode 100644index 00000000000..c0b16de2ebf--- /dev/null+++ b/tools/browser_lightpanda.py@@ -0,0 +1,394 @@+"""Lightpanda local engine for Browser Use mode.++With ``browser.engine: lightpanda``, Browser Use mode spawns one+``lightpanda serve`` per browser session and points ``browser_exec`` at its+CDP endpoint (``BU_CDP_URL``). The built-in ``browser_*`` tools keep driving+Lightpanda through ``agent-browser --engine lightpanda``; this module is the+launcher for the path where no agent-browser daemon is involved.++Lifecycle: ``tools.browser_tool`` owns the session cache, the inactivity+reaper and the atexit sweep; it calls :func:`launch_lightpanda` /+:func:`stop_lightpanda` and :func:`reap_orphaned_lightpanda` for processes+left behind by a crashed Hermes.+"""++import json+import logging+import os+import shutil+import socket+import subprocess+import threading+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Dict, Optional, Tuple++logger = logging.getLogger(__name__)++LIGHTPANDA_INSTALL_URL = "https://lightpanda.io/docs/run-locally/installation/one-liner"+LIGHTPANDA_INSTALL_HINT = (+ f"Install Lightpanda from {LIGHTPANDA_INSTALL_URL} and make sure "+ "`lightpanda` is on PATH"+)++_READY_TIMEOUT_S = 10.0+_POLL_INTERVAL_S = 0.1+_STDERR_TAIL_LIMIT = 2000++_servers: Dict[str, "LightpandaServer"] = {}+_servers_lock = threading.Lock()+++@dataclass+class LightpandaServer:+ session_name: str+ port: int+ proc: subprocess.Popen+ log_path: str+ start_time: Optional[int] = None++ @property+ def cdp_url(self) -> str:+ # The http discovery URL: the browser-use harness resolves+ # /json/version itself on every daemon start (BU_CDP_URL).+ return f"http://127.0.0.1:{self.port}"++ def is_alive(self) -> bool:+ return self.proc.poll() is None+++def _home_candidates() -> list:+ home = Path.home()+ candidates = [+ home / ".lightpanda" / "lightpanda",+ home / ".local" / "bin" / "lightpanda",+ ]+ try:+ from hermes_constants import get_hermes_home++ candidates.append(Path(get_hermes_home()) / "bin" / "lightpanda")+ except Exception as e: # pragma: no cover - defensive+ logger.debug("hermes home unavailable for lightpanda lookup: %s", e)+ return candidates+++def find_lightpanda_binary() -> Optional[str]:+ """Return the lightpanda executable, or None.++ Order: PATH (with the same Homebrew/managed-node fallbacks agent-browser+ gets), then the locations the Lightpanda installer and agent-browser use+ (``~/.lightpanda/lightpanda``, ``~/.local/bin/lightpanda``), then+ ``$HERMES_HOME/bin/lightpanda``. Lightpanda has no Windows build.+ """+ if os.name == "nt":+ logger.debug("Lightpanda has no Windows build")+ return None+ path_env = os.environ.get("PATH", "")+ try:+ from tools.browser_tool import _merge_browser_path++ path_env = _merge_browser_path(path_env)+ except Exception as e:+ logger.debug("browser PATH merge unavailable: %s", e)+ found = shutil.which("lightpanda", path=path_env)+ if found:+ return found+ for candidate in _home_candidates():+ if candidate.is_file() and os.access(candidate, os.X_OK):+ return str(candidate)+ return None+++def _pick_free_loopback_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _state_dir() -> Path:+ from hermes_constants import get_hermes_home++ path = Path(get_hermes_home()) / "cache" / "browser-use" / "lightpanda"+ path.mkdir(parents=True, exist_ok=True)+ return path+++def _record_path(session_name: str) -> Path:+ return _state_dir() / f"{session_name}.json"+++def _browser_env() -> dict:+ try:+ from tools.browser_tool import _build_browser_env++ return _build_browser_env()+ except Exception as e:+ logger.debug("credential-scrubbed browser env unavailable: %s", e)+ return os.environ.copy()+++def _cdp_ready(url: str) -> bool:+ try:+ from hermes_cli.browser_connect import is_browser_debug_ready++ return is_browser_debug_ready(url, timeout=0.2)+ except Exception as e:+ logger.debug("CDP readiness probe failed for %s: %s", url, e)+ return False+++def _read_log_tail(path: str) -> str:+ try:+ with open(path, "rb") as fh:+ data = fh.read()+ except OSError:+ return ""+ text = data[-_STDERR_TAIL_LIMIT:].decode("utf-8", errors="replace").strip()+ lines = [line for line in text.splitlines() if line.strip()]+ return lines[-1] if lines else ""+++def _terminate(proc: subprocess.Popen) -> None:+ try:+ if proc.poll() is None:+ proc.terminate()+ try:+ proc.wait(timeout=5)+ except Exception:+ proc.kill()+ except Exception as e:+ logger.debug("lightpanda terminate failed: %s", e)+++def _safe_start_time(pid: int) -> Optional[int]:+ try:+ from tools.process_registry import ProcessRegistry++ return ProcessRegistry._safe_host_start_time(pid)+ except Exception:+ return None+++def _write_record(server: LightpandaServer) -> None:+ record = {+ "pid": server.proc.pid,+ "port": server.port,+ "owner_pid": os.getpid(),+ "start_time": server.start_time,+ "started_at": time.time(),+ }+ try:+ _record_path(server.session_name).write_text(json.dumps(record), encoding="utf-8")+ except OSError as e:+ logger.debug("could not write lightpanda record for %s: %s", server.session_name, e)+++def _unlink_record(session_name: str) -> None:+ try:+ _record_path(session_name).unlink(missing_ok=True)+ except OSError as e:+ logger.debug("could not remove lightpanda record for %s: %s", session_name, e)+++def launch_lightpanda(+ session_name: str, *, block_private_networks: bool = False+) -> Tuple[Optional[LightpandaServer], Optional[str]]:+ """Start ``lightpanda serve`` on a free loopback port for ``session_name``.++ Returns ``(server, None)`` once ``/json/version`` answers, or+ ``(None, error)`` with an actionable message. The child's stderr goes to+ ``$HERMES_HOME/cache/browser-use/lightpanda/<session>.log`` so a chatty+ process can never block on a pipe; only the tail is read on failure.+ """+ binary = find_lightpanda_binary()+ if not binary:+ if os.name == "nt":+ return None, (+ "browser.engine is 'lightpanda' but Lightpanda has no Windows "+ "build. Set browser.engine to auto (or run Hermes under WSL2)."+ )+ return None, (+ "browser.engine is 'lightpanda' but no lightpanda binary was found "+ "on PATH, ~/.lightpanda or ~/.local/bin. "+ f"{LIGHTPANDA_INSTALL_HINT}, or set browser.engine to auto."+ )++ port = _pick_free_loopback_port()+ argv = [binary, "serve", "--host", "127.0.0.1", "--port", str(port)]+ if block_private_networks:+ argv.append("--block-private-networks")+ log_path = str(_state_dir() / f"{session_name}.log")++ if os.name == "nt": # pragma: no cover - no Windows build today+ from hermes_cli._subprocess_compat import windows_hide_flags++ popen_kwargs: dict = {"creationflags": windows_hide_flags(), "close_fds": True}+ else:+ popen_kwargs = {"start_new_session": True}++ try:+ with open(log_path, "wb") as log_file:+ proc = subprocess.Popen(+ argv,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=log_file,+ env=_browser_env(),+ **popen_kwargs,+ )+ except (OSError, subprocess.SubprocessError) as e:+ return None, f"Failed to launch lightpanda serve ({binary}): {e}"++ url = f"http://127.0.0.1:{port}"+ deadline = time.monotonic() + _READY_TIMEOUT_S+ while True:+ rc = proc.poll()+ if rc is not None:+ tail = _read_log_tail(log_path)+ detail = f": {tail}" if tail else ""+ return None, (+ f"lightpanda serve exited with code {rc} before {url}/json/version "+ f"answered{detail}"+ )+ if _cdp_ready(url):+ break+ if time.monotonic() >= deadline:+ _terminate(proc)+ tail = _read_log_tail(log_path)+ detail = f" (last stderr line: {tail})" if tail else ""+ return None, (+ f"lightpanda serve did not expose {url}/json/version within "+ f"{int(_READY_TIMEOUT_S)}s{detail}"+ )+ time.sleep(_POLL_INTERVAL_S)++ server = LightpandaServer(+ session_name=session_name,+ port=port,+ proc=proc,+ log_path=log_path,+ start_time=_safe_start_time(proc.pid),+ )+ _write_record(server)+ with _servers_lock:+ _servers[session_name] = server+ logger.info(+ "Started lightpanda serve (pid %s, port %s) for session %s",+ proc.pid, port, session_name,+ )+ return server, None+++def get_server(session_name: str) -> Optional[LightpandaServer]:+ with _servers_lock:+ return _servers.get(session_name)+++def stop_lightpanda(session_name: str) -> None:+ """Stop the server for ``session_name`` (tree-kill) and drop its record."""+ with _servers_lock:+ server = _servers.pop(session_name, None)+ if server is None:+ _unlink_record(session_name)+ return+ if server.is_alive():+ try:+ from tools.process_registry import ProcessRegistry++ ProcessRegistry._terminate_host_pid(+ server.proc.pid, expected_start=server.start_time+ )+ except Exception as e:+ logger.debug("lightpanda tree-kill failed for %s: %s", session_name, e)+ _terminate(server.proc)+ try:+ server.proc.wait(timeout=5)+ except Exception:+ _terminate(server.proc)+ _unlink_record(session_name)+ logger.debug("Stopped lightpanda serve for session %s", session_name)+++def stop_all_lightpanda() -> None:+ """Stop every server this process started. Idempotent; safe from atexit."""+ with _servers_lock:+ names = list(_servers)+ for name in names:+ try:+ stop_lightpanda(name)+ except Exception as e:+ logger.debug("lightpanda stop failed for %s: %s", name, e)+++def _is_lightpanda_process(pid: int, port, start_time) -> bool:+ """True only when ``pid`` is verifiably the ``lightpanda serve`` we recorded."""+ try:+ import psutil++ proc = psutil.Process(pid)+ if "lightpanda" not in proc.name().lower():+ return False+ cmdline = proc.cmdline()+ if "serve" not in cmdline or str(port) not in cmdline:+ return False+ except Exception:+ return False+ if start_time:+ try:+ from gateway.status import get_process_start_time++ return get_process_start_time(pid) == start_time+ except Exception:+ return False+ return True+++def reap_orphaned_lightpanda() -> int:+ """Kill ``lightpanda serve`` processes whose owning Hermes is gone.++ Records are written by :func:`launch_lightpanda`; a live owner (another+ Hermes process, or this one still tracking the session) is never+ touched, and a PID is only signalled after psutil confirms it is still+ a ``lightpanda serve`` on the recorded port. Returns the reap count.+ """+ try:+ state_dir = _state_dir()+ except Exception as e:+ logger.debug("lightpanda state dir unavailable: %s", e)+ return 0+ try:+ from gateway.status import _pid_exists+ except Exception: # pragma: no cover - defensive+ return 0++ reaped = 0+ for record_path in sorted(state_dir.glob("*.json")):+ session_name = record_path.stem+ try:+ record = json.loads(record_path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ record_path.unlink(missing_ok=True)+ continue+ owner_pid = record.get("owner_pid")+ if owner_pid == os.getpid():+ with _servers_lock:+ if session_name in _servers:+ continue+ elif owner_pid and _pid_exists(int(owner_pid)):+ continue+ pid = record.get("pid")+ if not pid or not _is_lightpanda_process(int(pid), record.get("port"), record.get("start_time")):+ record_path.unlink(missing_ok=True)+ continue+ try:+ from tools.process_registry import ProcessRegistry++ ProcessRegistry._terminate_host_pid(int(pid), expected_start=record.get("start_time"))+ reaped += 1+ logger.info("Reaped orphaned lightpanda serve pid %s (session %s)", pid, session_name)+ except Exception as e:+ logger.debug("orphan lightpanda kill failed for pid %s: %s", pid, e)+ record_path.unlink(missing_ok=True)+ return reapeddiff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex b6270d35371..817881dcdca 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -1140,6 +1140,55 @@ def _using_lightpanda_engine() -> bool:return _get_browser_engine() == "lightpanda"+def lightpanda_engine_status() -> Tuple[bool, str]:+ """Whether ``browser.engine: lightpanda`` is actually in effect, and why.++ Returns ``(False, "")`` when the engine is not lightpanda. Otherwise the+ reason names the setting that shadows it (a cloud provider, Camofox, a+ CDP override, Browser Use cloud, the real-profile toggle) or, when it is+ in use, which driver runs it. Mirrors the precedence of+ ``_should_inject_engine`` (built-in tools) and+ ``browser_use_cli._resolve_backend_cdp`` (Browser Use mode) using only+ no-I/O gates, so ``/browser status`` and ``hermes doctor`` can call it.+ """+ if not _using_lightpanda_engine():+ return False, ""+ if _get_cdp_override_raw():+ return False, "a CDP override is active (/browser connect or browser.cdp_url)"+ if _is_camofox_mode():+ return False, "Camofox is the selected browser (CAMOFOX_URL)"+ try:+ provider = _get_cloud_provider()+ except Exception:+ provider = None+ if provider is not None:+ try:+ name = provider.provider_name()+ except Exception:+ name = type(provider).__name__+ return False, (+ f"cloud provider {name} is selected (browser.cloud_provider, or "+ "auto-detected from credentials)"+ )+ bu_mode = _is_browser_use_cli_mode()+ if bu_mode:+ try:+ from tools.browser_use_cli import (+ _read_browser_cfg,+ is_legacy_browser_use_cloud_config,+ )++ if is_legacy_browser_use_cloud_config(_read_browser_cfg()):+ return False, "Browser Use cloud (BROWSER_USE_API_KEY) is selected"+ except Exception as e:+ logger.debug("legacy Browser Use cloud check failed: %s", e)+ if _use_real_profile():+ return False, "browser.use_real_profile is on (Lightpanda cannot load a Chromium profile)"+ if bu_mode:+ return True, "Browser Use mode: Hermes spawns `lightpanda serve` per session"+ return True, "built-in browser tools: agent-browser --engine lightpanda"++def _lightpanda_fallback_reason(engine: str, command: str, result: Dict[str, Any]) -> Optional[str]:"""Return the user-visible reason a Lightpanda result needs Chrome fallback.@@ -2279,6 +2328,16 @@ def _emergency_cleanup_all_sessions():_session_last_activity.clear()_recording_sessions.clear()+ # Lightpanda servers (Browser Use mode) are processes we spawned; the+ # session cleanup above stops the tracked ones, this catches any that+ # fell out of ``_active_sessions``.+ try:+ from tools.browser_lightpanda import stop_all_lightpanda++ stop_all_lightpanda()+ except Exception as e:+ logger.debug("Lightpanda cleanup on exit failed: %s", e)+# Sweep orphans from other crashed hermes processes. Safe even if we# never used the browser — uses owner_pid liveness to avoid reaping# daemons owned by other live hermes processes.@@ -2492,6 +2551,16 @@ def _reap_orphaned_browser_sessions():"""import glob+ # Lightpanda servers spawned for Browser Use mode keep their own records+ # (no agent-browser socket dir); sweep them with the same owner-liveness+ # rule before the daemon scan, which may return early.+ try:+ from tools.browser_lightpanda import reap_orphaned_lightpanda++ reap_orphaned_lightpanda()+ except Exception as e:+ logger.debug("Lightpanda orphan reap failed: %s", e)+tmpdir = _socket_safe_tmpdir()pattern = os.path.join(tmpdir, "agent-browser-h_*")socket_dirs = glob.glob(pattern)@@ -2879,6 +2948,14 @@ def _create_local_session(task_id: str, allow_real_profile: bool = True) -> Dict"features": {"local": True, "real_profile": True},}+ # Browser Use mode drives whatever CDP endpoint it is handed; with+ # ``browser.engine: lightpanda`` that endpoint is a Hermes-spawned+ # ``lightpanda serve``. The built-in tools never reach this branch —+ # they are hidden in Browser Use mode — and keep driving Lightpanda via+ # ``agent-browser --engine lightpanda`` on the plain local session below.+ if _is_browser_use_cli_mode() and _using_lightpanda_engine():+ return _create_lightpanda_session(task_id)+session_name = f"h_{uuid.uuid4().hex[:10]}"logger.info("Created local browser session %s for task %s",session_name, task_id)@@ -2890,6 +2967,39 @@ def _create_local_session(task_id: str, allow_real_profile: bool = True) -> Dict}+def _create_lightpanda_session(task_id: str) -> Dict[str, Any]:+ """Spawn ``lightpanda serve`` for this session key (Browser Use mode)."""+ import uuid+ from tools.browser_lightpanda import launch_lightpanda++ session_name = f"lp_{uuid.uuid4().hex[:10]}"+ server, err = launch_lightpanda(+ session_name, block_private_networks=not _is_local_backend()+ )+ if err:+ raise RuntimeError(err)+ logger.info(+ "Created Lightpanda session %s (port %s) for task %s",+ session_name, server.port, task_id,+ )+ return {+ "session_name": session_name,+ "bb_session_id": None,+ "cdp_url": server.cdp_url,+ "features": {"local": True, "lightpanda": True},+ }+++def _local_backend_process_dead(session_info: Dict[str, Any]) -> bool:+ """True for a Lightpanda session whose ``lightpanda serve`` is gone."""+ if not (session_info.get("features") or {}).get("lightpanda"):+ return False+ from tools.browser_lightpanda import get_server++ server = get_server(session_info.get("session_name", ""))+ return server is None or not server.is_alive()++def _create_cdp_session(task_id: str, cdp_url: str) -> Dict[str, str]:"""Create a session that connects to a user-supplied CDP endpoint."""import uuid@@ -2952,11 +3062,14 @@ def _get_session_info(task_id: Optional[str] = None) -> Dict[str, Any]:existing_session = Noneif existing_session is not None:- if not _session_has_expired(existing_session):+ if (+ not _session_has_expired(existing_session)+ and not _local_backend_process_dead(existing_session)+ ):return existing_sessionlogger.info(- "Replacing expired cloud browser session for task %s",+ "Replacing expired or dead browser session for task %s",task_id,)_cleanup_single_browser_session(task_id)@@ -3042,8 +3155,11 @@ def _get_session_info(task_id: Optional[str] = None) -> Dict[str, Any]:# Lazy-start the CDP supervisor now that the session exists (if the# backend surfaces a CDP URL via override or session_info["cdp_url"]).# Idempotent; swallows errors. See _ensure_cdp_supervisor for details.- # Skip for local sidecars — they have no CDP URL.- if not force_local:+ # Skip for local sidecars — they have no CDP URL — and for Lightpanda+ # sessions: those only exist in Browser Use mode, where the browser_*+ # tools that consume supervisor state are hidden, so the supervisor+ # would just hold an idle second CDP connection to the process.+ if not force_local and not (session_info.get("features") or {}).get("lightpanda"):_ensure_cdp_supervisor(task_id)return session_info@@ -5735,10 +5851,19 @@ def _cleanup_single_browser_session(task_id: str) -> None:# Stop auto-recording before closing (saves the file)_maybe_stop_recording(task_id)+ # A Lightpanda session is a process Hermes spawned itself (Browser+ # Use mode); there is no agent-browser daemon to send ``close`` to.# An expired cloud CDP URL cannot accept an agent-browser close command.# Avoid feeding it back through _get_session_info(), which would try to# renew the session recursively while cleanup is still in progress.- if _session_has_expired(session_info):+ if (session_info.get("features") or {}).get("lightpanda"):+ try:+ from tools.browser_lightpanda import stop_lightpanda++ stop_lightpanda(session_info.get("session_name", ""))+ except Exception as e:+ logger.warning("lightpanda stop failed for task %s: %s", task_id, e)+ elif _session_has_expired(session_info):logger.debug("Skipping agent-browser close for expired session %s",task_id,diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 8e9d7191219..989f05eb913 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -500,6 +500,53 @@ def _native_screenshot_result(result: Dict[str, Any], path: str) -> Optional[Dicreturn None+def _backend_cache_key(task_id: Optional[str], session_name: str = "") -> str:+ """Session-cache key for a backend browser: named sessions get their own."""+ return f"bu-named-{session_name}" if session_name else (task_id or "browser-exec-default")+++def _resolve_lightpanda_cdp(+ env: dict, task_id: Optional[str], session_name: str = ""+) -> Optional[str]:+ """Point the harness at a Hermes-spawned ``lightpanda serve``.++ Only when ``browser.engine`` is ``lightpanda`` and nothing with higher+ precedence (BU_CDP_* env, a CDP override, a cloud provider) claimed the+ session. Each cache key gets its own Lightpanda process via the legacy+ stack's ``_get_session_info()`` (cache, inactivity reaper, atexit), so+ the browser is private to this session and the own-tab preamble is+ skipped. Returns an error string when Lightpanda cannot start.+ """+ try:+ from tools.browser_tool import _get_session_info, _using_lightpanda_engine+ except Exception as e: # pragma: no cover — stubbed browser_tool in tests+ logger.debug("browser_tool lightpanda resolution unavailable: %s", e)+ return None+ try:+ if not _using_lightpanda_engine():+ return None+ except Exception as e:+ logger.debug("browser engine lookup failed: %s", e)+ return None+ try:+ session_info = _get_session_info(_backend_cache_key(task_id, session_name))+ except Exception as e:+ return (+ f"Lightpanda could not be started: {e} Set browser.engine to auto "+ "to use local Chrome, or switch backends via `hermes tools` → "+ "Browser Automation."+ )+ cdp = str((session_info or {}).get("cdp_url") or "")+ if not cdp:+ return (+ "Lightpanda session returned no CDP endpoint. Set browser.engine "+ "to auto to use local Chrome."+ )+ env["BU_CDP_URL" if cdp.startswith(("http://", "https://")) else "BU_CDP_WS"] = cdp+ env[_PRIVATE_BROWSER_SENTINEL] = "1"+ return None++def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:@@ -516,7 +563,10 @@ def _resolve_backend_cdp(``_get_session_info()`` so browser_exec shares the SAME providersession machinery — per-task session cache, expiry replacement,inactivity reaper, and atexit cleanup — instead of duplicating it.- 4. Nothing configured: return None; the harness attaches to local+ 4. ``browser.engine: lightpanda``: a Hermes-spawned ``lightpanda serve``+ per session key, through the same ``_get_session_info()`` machinery+ (see :func:`_resolve_lightpanda_cdp`).+ 5. Nothing configured: return None; the harness attaches to localChrome (or Browser Use cloud via BU_AUTOSPAWN for legacy configs).``session_name`` (the tool's ``session`` argument / BU_NAME) keys the@@ -554,7 +604,7 @@ def _resolve_backend_cdp(logger.debug("Cloud provider lookup failed: %s", e)provider = Noneif provider is None:- return None+ return _resolve_lightpanda_cdp(env, task_id, session_name)# Browser Use direct-API configs: the CLI talks to Browser Use cloud# natively (BU_AUTOSPAWN / auth login) — routing through the legacy@@ -575,7 +625,7 @@ def _resolve_backend_cdp(# Named sessions get their OWN provider browser, keyed by name so the# same name reuses one browser across calls and tasks, and different# names never collide. Unnamed calls keep the per-task key.- cache_key = f"bu-named-{session_name}" if session_name else (task_id or "browser-exec-default")+ cache_key = _backend_cache_key(task_id, session_name)session_info = _get_session_info(cache_key)except Exception as e:return (@@ -857,6 +907,17 @@ _HEADER_TEXT_ONLY = ("clicks — skip the screenshot-driven workflow described below.")+# Appended when the local engine is Lightpanda (browser.engine). Lightpanda+# has no graphical renderer, and one CDP connection holds one page: a second+# Target.createTarget fails with TargetAlreadyLoaded+# (lightpanda-io/browser#1962) — drop the new_tab() sentence once that lands.+_HEADER_LIGHTPANDA = (+ " The local engine is Lightpanda (no graphical renderer, one page per "+ "session): capture_screenshot() is unavailable, so work text-first; "+ "navigate with new_tab(url) exactly once, then goto_url(url) for every "+ "later navigation — a second new_tab() fails with TargetAlreadyLoaded."+)+_DESCRIPTION_HEADER = _HEADER_BASE # back-compat alias for external imports# NOTE: browser_exec is additionally gated at tool-definition time — sessions@@ -868,6 +929,10 @@ _DESCRIPTION_HEADER = _HEADER_BASE # back-compat alias for external importsdef _description_header() -> str:"""Header tailored to whether the active model can see images natively"""+ if _lightpanda_engine_in_use():+ # No screenshots at all on Lightpanda: the vision workflow cannot+ # apply, whatever the model can see.+ return _HEADER_BASE + _HEADER_TEXT_ONLY + _HEADER_LIGHTPANDAtry:from tools.vision_tools import _should_use_native_vision_fast_path@@ -877,6 +942,16 @@ def _description_header() -> str:passreturn _HEADER_BASE + _HEADER_TEXT_ONLY++def _lightpanda_engine_in_use() -> bool:+ try:+ from tools.browser_tool import lightpanda_engine_status++ return lightpanda_engine_status()[0]+ except Exception as e:+ logger.debug("lightpanda engine status unavailable: %s", e)+ return False+_skill_text_cache: Optional[str] = None_skill_text_fetched = False