Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Add optional Rust runtime package integration
Gregor Žuniča91fd8702fa3
diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex 91dbad3b0..2ed3dbaa6 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -12,6 +12,7 @@ import mimetypesimport osimport reimport shutil+import sysimport tempfileimport timefrom collections.abc import Awaitable, Callable@@ -185,6 +186,9 @@ def find_browser_use_terminal_binary() -> str:env_path = os.environ.get('BROWSER_USE_TERMINAL_BINARY')if env_path:return env_path+ packaged_path = _find_packaged_browser_use_terminal_binary()+ if packaged_path:+ return packaged_pathbut_home = Path(os.environ.get('BUT_HOME', '~/.browser-use-terminal')).expanduser()but_install_dir = Path(os.environ.get('BUT_INSTALL_DIR', '~/.local/bin')).expanduser()candidates = [@@ -201,10 +205,21 @@ def find_browser_use_terminal_binary() -> str:return path_binaryraise RustAgentError(f'Could not find browser-use-terminal. Install Browser Use Terminal with `{TERMINAL_INSTALL_COMMAND}`, '- 'or set BROWSER_USE_TERMINAL_BINARY to a built terminal CLI.'+ 'install browser-use-rust, or set BROWSER_USE_TERMINAL_BINARY to a built terminal CLI.')+def _find_packaged_browser_use_terminal_binary() -> str | None:+ try:+ from browser_use_rust import binary_path+ except Exception:+ return None+ try:+ return binary_path('browser-use-terminal')+ except Exception:+ return None++class RustSdkJsonRpcError(RustAgentError):"""Raised when the Rust SDK server returns a JSON-RPC error."""@@ -6245,6 +6260,15 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._sdk_browser_id = Noneself.terminal_session_id = Noneself._sdk_client = RustSdkClient(self._sdk_server_argv(), self._run_env())+ ping = await self._sdk_client.call('runtime.ping')+ protocol_version = ping.get('sdk_protocol_version') if isinstance(ping, dict) else None+ if protocol_version != 1:+ await self._sdk_client.close()+ self._sdk_client = None+ raise RustAgentError(+ f'Unsupported browser-use-terminal SDK protocol {protocol_version!r}; expected 1. '+ 'Install a compatible browser-use-rust package or set BROWSER_USE_TERMINAL_BINARY to a compatible binary.'+ )return self._sdk_clientdef _sdk_llm_payload(self) -> dict[str, Any]:@@ -6512,6 +6536,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):env['LLM_BROWSER_OPENAI_COMPAT_INCLUDE_USAGE'] = 'true'browser_mode = self._browser_mode()env['LLM_BROWSER_BROWSER_MODE'] = browser_mode+ env.setdefault('BROWSER_USE_PYTHON', sys.executable)cdp_url = _extract_cdp_url(self.browser_session) or _extract_profile_cdp_url(self.browser_profile)if cdp_url:env['BU_CDP_URL'] = cdp_urldiff --git a/pyproject.toml b/pyproject.tomlindex 5f9d65db5..4a98c5ae0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -2,7 +2,7 @@name = "browser-use"description = "Make websites accessible for AI agents"authors = [{ name = "Gregor Zunic" }]-version = "0.12.9"+version = "0.13.0"readme = "README.md"requires-python = ">=3.11,<4.0"classifiers = [@@ -59,6 +59,7 @@ dependencies = [[project.optional-dependencies]cli = ["textual==7.4.0"]+rust = ["browser-use-rust==0.13.0"]aws = ["boto3==1.42.37"]oci = ["oci==2.166.0"]video = ["imageio[ffmpeg]==2.37.2", "numpy==2.4.1"]diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 652737d29..89ebb67bd 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -2603,6 +2603,7 @@ def test_rust_agent_translates_browser_use_args_to_terminal(monkeypatch):assert "First navigate to 'https://example.com'" in agent.taskassert env['BU_CDP_URL'] == 'wss://browser.example/devtools/browser/1'assert env['LLM_BROWSER_BROWSER_MODE'] == 'remote-cdp'+ assert env['BROWSER_USE_PYTHON'] == sys.executableassert 'BUT_FULL_LLM_INPUT_EVENTS' not in envparams = agent._sdk_run_params(max_steps=12, task=agent.task)@@ -2619,6 +2620,7 @@ def test_rust_terminal_binary_missing_error_mentions_install(monkeypatch):import browser_use.rust.service as rust_servicemonkeypatch.delenv('BROWSER_USE_TERMINAL_BINARY', raising=False)+ monkeypatch.setitem(sys.modules, 'browser_use_rust', None)monkeypatch.setattr(rust_service.Path, 'exists', lambda self: False)monkeypatch.setattr(rust_service.shutil, 'which', lambda binary: None)@@ -2627,9 +2629,27 @@ def test_rust_terminal_binary_missing_error_mentions_install(monkeypatch):message = str(exc_info.value)assert 'https://browser-use.com/terminal/install.sh' in message+ assert 'browser-use-rust' in messageassert 'BROWSER_USE_TERMINAL_BINARY' in message+def test_rust_terminal_binary_prefers_packaged_binary(monkeypatch):+ import browser_use.rust.service as rust_service++ class PackagedRust:+ @staticmethod+ def binary_path(binary_name):+ assert binary_name == 'browser-use-terminal'+ return '/tmp/packaged-browser-use-terminal'++ monkeypatch.delenv('BROWSER_USE_TERMINAL_BINARY', raising=False)+ monkeypatch.setitem(sys.modules, 'browser_use_rust', PackagedRust)+ monkeypatch.setattr(rust_service.Path, 'exists', lambda self: False)+ monkeypatch.setattr(rust_service.shutil, 'which', lambda binary_name: None)++ assert rust_service.find_browser_use_terminal_binary() == '/tmp/packaged-browser-use-terminal'++def test_rust_terminal_binary_finds_default_terminal_install(monkeypatch, tmp_path):import browser_use.rust.service as rust_service@@ -2638,6 +2658,7 @@ def test_rust_terminal_binary_finds_default_terminal_install(monkeypatch, tmp_pabinary.write_text('#!/bin/sh\n')monkeypatch.delenv('BROWSER_USE_TERMINAL_BINARY', raising=False)+ monkeypatch.setitem(sys.modules, 'browser_use_rust', None)monkeypatch.chdir(tmp_path)monkeypatch.setenv('BUT_HOME', str(tmp_path / '.browser-use-terminal'))monkeypatch.setenv('BUT_INSTALL_DIR', str(tmp_path / '.local' / 'bin'))@@ -3259,6 +3280,29 @@ print(json.dumps({"jsonrpc": "2.0", "id": 1, "result": {"ok": True}}), flush=Truassert rust_service._sdk_notification_summary(second_notification) == 'projected.item_started name=browser_script'+async def test_rust_agent_rejects_incompatible_sdk_protocol(monkeypatch):+ import browser_use.rust.service as rust_service+ from browser_use.rust import Agent++ class LLM:+ model = 'gpt-test'++ script = r"""+import json+import sys++request = json.loads(sys.stdin.readline())+print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": {"ok": True}}), flush=True)+"""+ agent = Agent(task='answer', llm=LLM())+ monkeypatch.setattr(agent, '_sdk_server_argv', lambda: [sys.executable, '-c', script])++ with pytest.raises(rust_service.RustAgentError) as exc_info:+ await agent._ensure_sdk_client()++ assert 'Unsupported browser-use-terminal SDK protocol' in str(exc_info.value)++def test_rust_agent_bridges_llm_credentials_to_terminal_env(monkeypatch):from browser_use.rust import Agent