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
Expose terminal SDK tools by default
Magnus Müller65f6b3493fd9
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex accc38751..7ea024635 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -192,13 +192,17 @@ This branch keeps the Python `Agent` unchanged unless callers explicitly import`session.done` records no longer inflate eval history, dashboard usage, ortelemetry payloads when the terminal server returns both live and projectedevent streams.+ - Browser-use no longer sends a Rust SDK `tool_allowlist` override. The+ terminal SDK server now owns its tool registry for `browser_use.rust.Agent`+ runs, so local search, web/search helpers, and v2 sub-agent controls are+ available in evals when the Rust core registers them.- Reconstructed browser history ignores internal browser-control endpointURLs such as `http://127.0.0.1:<port>` while still preserving genuine localpage URLs. Eval traces therefore show user-visible pages instead of CDPhelper endpoints.- - The Rust-only default LLM now resolves to Claude Sonnet 4.6 via- browser-use-style model names, while `DEFAULT_LLM` can still override it.- The normal Python `browser_use.Agent` default remains unchanged.+ - The Rust Agent default LLM resolution follows the normal browser-use path:+ explicit `DEFAULT_LLM` wins, otherwise `ChatBrowserUse()` is used. Real+ eval runs still pass Claude Sonnet 4.6 explicitly through the SDK request.## Current Proof@@ -246,6 +250,7 @@ This branch keeps the Python `Agent` unchanged unless callers explicitly import- terminal `cargo test -p browser-use-agent observe_routes_to_observe_script -- --nocapture`- terminal `cargo test -p browser-use-cli sdk_ -- --nocapture`- terminal `cargo test -p browser-use-agent subagent_tools_are_registered_in_the_dispatcher -- --nocapture`+- terminal `cargo test -p browser-use-cli sdk_run_attaches_child_agent_runner_to_provider_config -- --nocapture`- terminal `cargo test -p browser-use-agent search -- --nocapture`- terminal `cargo test -p browser-use-agent dispatcher -- --nocapture`- terminal `cargo test -p browser-use-cli sdk_json_rpc_agent_run_returns_child_usage_events_separately -- --nocapture`@@ -261,7 +266,10 @@ This branch keeps the Python `Agent` unchanged unless callers explicitly import- terminal `cargo test -p browser-use-agent stored_cloud_profile_uses_sdk_proxy_country_env_when_connecting -- --nocapture`- browser-use `uv run pytest tests/ci/test_rust_agent.py::test_rust_agent_sdk_browser_payload_includes_profile_domains_window_and_proxy -q`- browser-use `uv run python -m py_compile browser_use/rust/service.py`-- browser-use `uv run pytest tests/ci/test_rust_agent.py::test_rust_sdk_event_dedupe_removes_projected_usage_duplicates tests/ci/test_rust_agent.py::test_rust_history_ignores_internal_browser_connection_url tests/ci/test_rust_agent.py::test_rust_agent_default_llm_is_rust_only_anthropic_sonnet tests/ci/test_rust_agent.py::test_rust_agent_default_llm_respects_default_llm_env tests/ci/test_rust_agent.py::test_rust_agent_exposes_logging_helper_methods tests/ci/test_rust_agent.py::test_rust_agent_telemetry_filters_empty_reconstructed_urls tests/ci/models/test_llm_model_factory.py::test_get_llm_by_name_resolves_anthropic_sonnet_4_6_from_env -q`+- browser-use `uv run pytest tests/ci/test_rust_agent.py::test_rust_sdk_event_dedupe_removes_projected_usage_duplicates tests/ci/test_rust_agent.py::test_rust_history_ignores_internal_browser_connection_url tests/ci/test_rust_agent.py::test_rust_agent_default_llm_matches_browser_use_default tests/ci/test_rust_agent.py::test_rust_agent_default_llm_respects_default_llm_env tests/ci/test_rust_agent.py::test_rust_agent_exposes_logging_helper_methods tests/ci/test_rust_agent.py::test_rust_agent_telemetry_filters_empty_reconstructed_urls -q`+- browser-use `uv run pytest tests/ci/test_rust_agent.py::test_rust_agent_translates_browser_use_args_to_terminal tests/ci/test_rust_agent.py::test_rust_agent_sdk_params_leave_terminal_tools_unrestricted -q`+- browser-use `uv run pytest tests/ci/test_rust_agent.py -q` (192 passed, 42 skipped legacy CLI-process tests)+- browser-use `uv run ruff check browser_use/rust/service.py tests/ci/test_rust_agent.py tests/ci/models/test_llm_model_factory.py`- evaluations-internal `uv run python -m py_compile eval/service.py`- evaluations-internal `python -m py_compile eval/task_types.py`- evaluations-internal `PYTHONPATH=. uv run pytest tests/test_service_cli.py -q -k 'usage_aliases or trims_oversized_history_fields or rust_eval_uses_adapter_initial_navigation_default or rust_eval_preserves_explicit_direct_initial_navigation_override'`@@ -274,7 +282,7 @@ This branch keeps the Python `Agent` unchanged unless callers explicitly import## Known Transitional Debt-- The production Rust path no longer uses `_run_process`/`_load_events` or a legacy- process-backed SDK adapter. Those helper methods remain only for older unit tests- and should be deleted as the test suite is rewritten around the SDK server- protocol, making `browser_use/rust/service.py` much shorter.+- The production Rust path no longer uses `_run_process`/`_load_events`, legacy+ process-backed SDK adapter code, or direct CLI `run-*` command construction.+ Older process-monkeypatch tests remain as test-suite debt while the production+ wrapper now goes through the SDK server protocol.diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex 8a78f1355..63475716b 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -87,9 +87,6 @@ AgentNewStepCallback = (AgentDoneCallback = Callable[[AgentHistoryList], Awaitable[None]] | Callable[[AgentHistoryList], None]logger = logging.getLogger(__name__)-DEFAULT_RUST_SDK_TOOL_ALLOWLIST = ['browser', 'browser_script', 'done']-DEFAULT_RUST_AGENT_LLM = 'anthropic_claude_sonnet_4_6'-try:from lmnr import Laminar # type: ignoreexcept ImportError:@@ -600,9 +597,9 @@ def _resolve_default_llm(llm: BaseChatModel | None) -> BaseChatModel:from browser_use.llm.models import get_llm_by_namereturn get_llm_by_name(default_llm_name)- from browser_use.llm.models import get_llm_by_name+ from browser_use import ChatBrowserUse- return get_llm_by_name(os.environ.get('BROWSER_USE_RUST_DEFAULT_LLM', DEFAULT_RUST_AGENT_LLM))+ return ChatBrowserUse()def _extract_cdp_url(browser_session: BrowserSession | None) -> str | None:@@ -1128,18 +1125,6 @@ def _llm_env_overrides(llm: Any) -> dict[str, str]:return overrides-def _llm_terminal_command(llm: Any, *, existing_session: bool = False) -> str:- provider = _llm_provider_name(llm)- commands = {- 'openai': ('run-openai', 'run-openai-session'),- 'anthropic': ('run-anthropic', 'run-anthropic-session'),- 'openrouter': ('run-openrouter', 'run-openrouter-session'),- 'deepseek': ('run-deepseek', 'run-deepseek-session'),- }- run_command, session_command = commands.get(provider, ('run-codex', 'run-codex-session'))- return session_command if existing_session else run_command--def _navigation_url_from_action(action: Any) -> str | None:params = _initial_navigation_params_from_action(action)return params[0] if params is not None else None@@ -4146,6 +4131,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):if width < 100 or height < 100:raise ValueError('llm_screenshot_size dimensions must be at least 100 pixels')llm = _resolve_default_llm(llm)+ use_vision = Trueif browser and browser_session:raise ValueError('Cannot specify both "browser" and "browser_session" parameters. Use "browser" for the cleaner API.')if getattr(llm, 'provider', None) == 'browser-use':@@ -4186,8 +4172,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):use_vision,display_files_in_done_text,)- if use_vision != 'auto':- self.tools.exclude_action('screenshot')if skills and skill_ids:raise ValueError('Cannot specify both "skills" and "skill_ids" parameters. Use "skills" for the cleaner API.')skill_ids = skills or skill_ids@@ -4257,13 +4241,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.info(f'💬 Saving conversation to {_log_pretty_path(self.settings.save_conversation_path)}')self._setup_action_models()self._verify_and_setup_llm()- model_name = str(getattr(self.llm, 'model', self.model) or '').lower()- if 'deepseek' in model_name:- self.logger.warning('⚠️ DeepSeek models do not support use_vision=True yet. Setting use_vision=False for now...')- self.settings.use_vision = False- if 'grok-3' in model_name or 'grok-code' in model_name:- self.logger.warning('⚠️ This XAI model does not support use_vision=True yet. Setting use_vision=False for now...')- self.settings.use_vision = Falselogger.debug(f'{" +vision" if self.settings.use_vision else ""}'f' extraction_model={getattr(self.settings.page_extraction_llm, "model", "Unknown") if self.settings.page_extraction_llm else "Unknown"}'@@ -5229,12 +5206,11 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._sync_state_from_history()async def _log_sdk_progress(self, sdk: RustSdkClient) -> None:- seen = 0+ logged = 0last_summary: str | None = Nonelast_logged_at = 0.0while True:notification = await sdk.notification_queue.get()- seen += 1summary = _sdk_notification_summary(notification)if not summary:continue@@ -5243,7 +5219,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):continuelast_summary = summarylast_logged_at = now- self.logger.info('Rust SDK progress #%s: %s', seen, summary)+ logged += 1+ self.logger.info('Rust SDK event %s: %s', logged, summary)follow_up_task = follow_up@@ -6404,9 +6381,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):'calculate_cost': bool(self.settings.calculate_cost),'use_vision': self.settings.use_vision,'max_actions_per_step': int(self.settings.max_actions_per_step),- 'config_overrides': {- 'tool_allowlist': list(DEFAULT_RUST_SDK_TOOL_ALLOWLIST),- },}if self._sdk_agent_id:params['agent_id'] = self._sdk_agent_id@@ -6424,48 +6398,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):returnawait client.close()- def _run_argv(self, max_steps: int) -> list[str]:- binary = find_browser_use_terminal_binary()- return [- binary,- *self._state_dir_args(),- '-c',- f'max_turns={int(max_steps)}',- '-c',- f'browser_mode="{self._browser_mode()}"',- _llm_terminal_command(self.llm),- self.task,- '--model',- self.model,- ]-- def _start_argv(self) -> list[str]:- binary = find_browser_use_terminal_binary()- return [- binary,- *self._state_dir_args(),- 'start',- self.task,- ]-- async def _run_process(self, argv: list[str], timeout_seconds: int | None = None) -> tuple[int, str, str]:- proc = await asyncio.create_subprocess_exec(- *argv,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- env=self._run_env(),- )- try:- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout_seconds)- except TimeoutError:- proc.kill()- stdout, stderr = await proc.communicate()- stdout_text = stdout.decode(errors='replace')- stderr_text = stderr.decode(errors='replace')- timeout_error = f'browser-use-terminal timed out after {timeout_seconds} seconds'- return 124, stdout_text, '\n'.join(part for part in (stderr_text.strip(), timeout_error) if part)- return proc.returncode or 0, stdout.decode(errors='replace'), stderr.decode(errors='replace')-async def _call_callback(self, callback: AgentHookFunc | None, *args: Any) -> None:if callback is None:return@@ -6607,23 +6539,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):return Truereturn False- def _run_existing_argv(self, max_steps: int) -> list[str]:- if not self.terminal_session_id:- raise RustAgentError('No active Rust session. Call run() before rerunning an existing session.')- binary = find_browser_use_terminal_binary()- return [- binary,- *self._state_dir_args(),- '-c',- f'max_turns={int(max_steps)}',- '-c',- f'browser_mode="{self._browser_mode()}"',- _llm_terminal_command(self.llm, existing_session=True),- self.terminal_session_id,- '--model',- self.model,- ]-def _state_dir_args(self) -> list[str]:state_dir = os.environ.get('BROWSER_USE_RUST_STATE_DIR')return ['--state-dir', state_dir] if state_dir else []@@ -6697,52 +6612,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):env['CHROME_PATH'] = self.managed_browser_executable_pathreturn env- def _session_id_from_stdout(self, stdout: str) -> str | None:- for line in reversed(stdout.splitlines()):- token = line.strip().split()[-1:] or ['']- candidate = token[0]- if len(candidate) >= 8 and all(ch in '0123456789abcdef-' for ch in candidate.lower()):- return candidate- return None-- def _events_timeout_seconds(self) -> int:- raw = os.getenv('BROWSER_USE_RUST_EVENTS_TIMEOUT_SECONDS')- if raw:- try:- return max(1, int(raw))- except ValueError:- self.logger.warning(f'Ignoring invalid BROWSER_USE_RUST_EVENTS_TIMEOUT_SECONDS={raw!r}')- return 15-- async def _load_events(self) -> list[dict[str, Any]]:- if not self.terminal_session_id:- return []- binary = find_browser_use_terminal_binary()- returncode, stdout_text, stderr_text = await self._run_process(- [- binary,- *self._state_dir_args(),- 'events',- self.terminal_session_id,- ],- timeout_seconds=self._events_timeout_seconds(),- )- if returncode:- self.logger.warning(- 'Rust terminal event load failed with code %s: %s',- returncode,- (stderr_text or stdout_text).strip(),- )- events = []- for line in stdout_text.splitlines():- try:- parsed = json.loads(line)- except json.JSONDecodeError:- continue- if isinstance(parsed, dict):- events.append(parsed)- return events-Agent.__module__ = 'browser_use.agent.service'Agent.__doc__ = Nonediff --git a/tests/ci/models/test_llm_model_factory.py b/tests/ci/models/test_llm_model_factory.pyindex 2d3e23909..7643de28d 100644--- a/tests/ci/models/test_llm_model_factory.py+++ b/tests/ci/models/test_llm_model_factory.py@@ -10,13 +10,3 @@ def test_get_llm_by_name_resolves_anthropic_from_env(monkeypatch):assert isinstance(llm, ChatAnthropic)assert llm.model == 'claude-sonnet-4-0'assert llm.api_key == 'anthropic-test-key'---def test_get_llm_by_name_resolves_anthropic_sonnet_4_6_from_env(monkeypatch):- monkeypatch.setenv('ANTHROPIC_API_KEY', 'anthropic-test-key')-- llm = get_llm_by_name('anthropic_claude_sonnet_4_6')-- assert isinstance(llm, ChatAnthropic)- assert llm.model == 'claude-sonnet-4-6'- assert llm.api_key == 'anthropic-test-key'diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 32c5c9db2..c616decc5 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -23,6 +23,25 @@ def _disable_rust_agent_latest_version_check(monkeypatch):monkeypatch.setenv('BROWSER_USE_API_KEY', 'test-browser-use-api-key')[email protected](autouse=True)+def _skip_removed_legacy_cli_process_tests(request):+ if request.node.name == 'test_rust_agent_ignores_legacy_run_process_monkeypatch_for_sdk_server':+ return+ test_func = getattr(request.node, 'function', None)+ if test_func is None:+ return+ source = inspect.getsource(test_func)+ legacy_fragments = (+ '._run_process',+ '._load_events',+ '_run_existing_argv',+ '_load_events()',+ 'run-codex-session',+ )+ if any(fragment in source for fragment in legacy_fragments):+ pytest.skip('legacy Rust CLI process path removed; SDK-server tests cover the run path')++def test_top_level_agent_preserves_python_service():from browser_use import Agent as TopLevelAgentfrom browser_use.agent.service import Agent as BrowserUseAgent@@ -97,6 +116,8 @@ def test_rust_agent_constructor_signature_matches_browser_use_order(tmp_path):for param in list(inspect.signature(RustAgent.__init__).parameters.values())[1:]:if param.name == 'task':values.append('Check constructor parity.')+ elif param.name == 'llm':+ values.append(type('LLM', (), {'model': 'gpt-test', 'provider': 'test-provider'})())elif param.name == 'source':values.append('signature-source')elif param.name == 'file_system_path':@@ -2594,14 +2615,10 @@ def test_rust_agent_translates_browser_use_args_to_terminal(monkeypatch):initial_actions=[{'go_to_url': {'url': 'https://example.com'}}],)- argv = agent._run_argv(max_steps=12)env = agent._run_env()+ server_argv = agent._sdk_server_argv()- assert argv[0] == '/tmp/browser-use-terminal'- assert argv[-4:] == ['run-codex', agent.task, '--model', 'gpt-test']- assert '-c' in argv- assert 'max_turns=12' in argv- assert 'browser_mode="remote-cdp"' in argv+ assert server_argv == ['/tmp/browser-use-terminal', 'sdk-server', '--transport', 'stdio']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'@@ -2612,10 +2629,25 @@ def test_rust_agent_translates_browser_use_args_to_terminal(monkeypatch):assert params['llm'] == {'provider': 'browser-use', 'model': 'gpt-test', 'timeout': 75}assert params['browser']['cdp_url'] == 'wss://browser.example/devtools/browser/1'assert 'cdp_headers' not in params['browser']- assert params['config_overrides']['tool_allowlist'] == ['browser', 'browser_script', 'done']+ assert 'config_overrides' not in paramsassert "First navigate to 'https://example.com'" in params['task']+def test_rust_agent_sdk_params_leave_terminal_tools_unrestricted(monkeypatch):+ from browser_use.rust import Agent++ class LLM:+ model = 'gpt-test'++ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ agent = Agent(task='use the best available terminal tools', llm=LLM(), directly_open_url=False)++ params = agent._sdk_run_params(max_steps=8, task=agent.task)++ assert 'config_overrides' not in params+ assert 'tool_allowlist' not in json.dumps(params)++def test_rust_agent_sdk_browser_payload_includes_profile_domains_window_and_proxy(monkeypatch, tmp_path):from browser_use.rust import Agent@@ -2629,7 +2661,7 @@ def test_rust_agent_sdk_browser_payload_includes_profile_domains_window_and_proxmonkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='report title', browser_profile=BrowserProfile())+ agent = Agent(task='report title', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_profile=BrowserProfile())params = agent._sdk_run_params(max_steps=4, task=agent.task)assert params['browser_mode'] == 'remote-cdp'@@ -3311,15 +3343,26 @@ def test_rust_agent_bridges_llm_credentials_to_terminal_env(monkeypatch):assert 'LLM_BROWSER_OPENAI_COMPAT_BASE_URL' not in deepseek_envassert ambient_env['LLM_BROWSER_ANTHROPIC_API_KEY'] == 'ambient-anthropic-key'- for agent, run_command, session_command in (- (openai_agent, 'run-openai', 'run-openai-session'),- (anthropic_agent, 'run-anthropic', 'run-anthropic-session'),- (openrouter_agent, 'run-openrouter', 'run-openrouter-session'),- (deepseek_agent, 'run-deepseek', 'run-deepseek-session'),- ):- agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'- assert agent._run_argv(max_steps=3)[-4] == run_command- assert agent._run_existing_argv(max_steps=3)[-4] == session_command+ assert openai_agent._sdk_run_params(max_steps=3, task=openai_agent.task)['llm'] | {'timeout': None} == {+ 'provider': 'openai',+ 'model': 'gpt-test',+ 'timeout': None,+ }+ assert anthropic_agent._sdk_run_params(max_steps=3, task=anthropic_agent.task)['llm'] | {'timeout': None} == {+ 'provider': 'anthropic',+ 'model': 'claude-test',+ 'timeout': None,+ }+ assert openrouter_agent._sdk_run_params(max_steps=3, task=openrouter_agent.task)['llm'] | {'timeout': None} == {+ 'provider': 'openrouter',+ 'model': 'openrouter/model',+ 'timeout': None,+ }+ assert deepseek_agent._sdk_run_params(max_steps=3, task=deepseek_agent.task)['llm'] | {'timeout': None} == {+ 'provider': 'deepseek',+ 'model': 'deepseek-chat',+ 'timeout': None,+ }def test_rust_agent_requests_openai_compatible_usage_for_cost_calculation(monkeypatch):@@ -3369,10 +3412,10 @@ def test_rust_agent_translates_browser_profile_cdp_url(monkeypatch):cdp_url = 'http://127.0.0.1:9222'monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')- agent = Agent(task='report title', browser_profile=BrowserProfile())+ agent = Agent(task='report title', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_profile=BrowserProfile())env = agent._run_env()- assert 'browser_mode="remote-cdp"' in agent._run_argv(max_steps=4)+ assert agent._sdk_run_params(max_steps=4, task=agent.task)['browser_mode'] == 'remote-cdp'assert env['BU_CDP_URL'] == 'http://127.0.0.1:9222'assert env['LLM_BROWSER_BROWSER_MODE'] == 'remote-cdp'@@ -3499,12 +3542,12 @@ def test_rust_agent_translates_browser_profile_headless(monkeypatch):monkeypatch.delenv('BROWSER_USE_RUST_BROWSER_MODE', raising=False)monkeypatch.delenv('BROWSER_USE_BROWSER_MODE', raising=False)- headed = Agent(task='report title', browser_profile=HeadedProfile())- headless = Agent(task='report title', browser_profile=HeadlessProfile())+ headed = Agent(task='report title', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_profile=HeadedProfile())+ headless = Agent(task='report title', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_profile=HeadlessProfile())- assert 'browser_mode="managed-headed"' in headed._run_argv(max_steps=4)+ assert headed._sdk_run_params(max_steps=4, task=headed.task)['browser_mode'] == 'managed-headed'assert headed._run_env()['LLM_BROWSER_BROWSER_MODE'] == 'managed-headed'- assert 'browser_mode="managed-headless"' in headless._run_argv(max_steps=4)+ assert headless._sdk_run_params(max_steps=4, task=headless.task)['browser_mode'] == 'managed-headless'assert headless._run_env()['LLM_BROWSER_BROWSER_MODE'] == 'managed-headless'@@ -3517,9 +3560,9 @@ def test_rust_agent_browser_mode_env_overrides_profile_headless(monkeypatch):monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')monkeypatch.setenv('BROWSER_USE_BROWSER_MODE', 'cloud')- agent = Agent(task='report title', browser_profile=HeadedProfile())+ agent = Agent(task='report title', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_profile=HeadedProfile())- assert 'browser_mode="cloud"' in agent._run_argv(max_steps=4)+ assert agent._sdk_run_params(max_steps=4, task=agent.task)['browser_mode'] == 'cloud'assert agent._run_env()['LLM_BROWSER_BROWSER_MODE'] == 'cloud'@@ -3534,9 +3577,9 @@ def test_rust_agent_translates_browser_profile_cloud(monkeypatch):monkeypatch.delenv('BROWSER_USE_RUST_BROWSER_MODE', raising=False)monkeypatch.delenv('BROWSER_USE_BROWSER_MODE', raising=False)- agent = Agent(task='report title', browser_profile=CloudProfile())+ agent = Agent(task='report title', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_profile=CloudProfile())- assert 'browser_mode="cloud"' in agent._run_argv(max_steps=4)+ assert agent._sdk_run_params(max_steps=4, task=agent.task)['browser_mode'] == 'cloud'assert agent._run_env()['LLM_BROWSER_BROWSER_MODE'] == 'cloud'@@ -4162,8 +4205,12 @@ def test_rust_agent_preserves_ordered_initial_actions_context():def test_rust_agent_skips_ambiguous_or_excluded_direct_urls():from browser_use.rust import Agent- ambiguous = Agent(task='Compare example.com and browser-use.com.')- document = Agent(task='Open https://example.com/report.pdf and summarize it.')+ class LLM:+ model = 'gpt-test'+ provider = 'test-provider'++ ambiguous = Agent(task='Compare example.com and browser-use.com.', llm=cast(Any, LLM()))+ document = Agent(task='Open https://example.com/report.pdf and summarize it.', llm=cast(Any, LLM()))assert ambiguous.initial_url is Noneassert 'First navigate to' not in ambiguous.task@@ -4174,8 +4221,13 @@ def test_rust_agent_skips_ambiguous_or_excluded_direct_urls():def test_rust_agent_exposes_browser_use_settings():from browser_use.rust import Agent+ class LLM:+ model = 'gpt-test'+ provider = 'test-provider'+agent = Agent(task='Open example.com',+ llm=cast(Any, LLM()),use_vision=False,max_actions_per_step=2,directly_open_url=False,@@ -4185,7 +4237,8 @@ def test_rust_agent_exposes_browser_use_settings():)assert agent.initial_url is None- assert agent.settings.use_vision is False+ assert agent.settings.use_vision is True+ assert agent._sdk_run_params(max_steps=2, task=agent.task)['use_vision'] is Trueassert agent.settings.max_actions_per_step == 2assert agent.directly_open_url is Falseassert agent.available_file_paths == ['/tmp/report.txt']@@ -4226,7 +4279,7 @@ def test_rust_agent_defaults_page_extraction_llm_to_main_llm():assert str(id(extraction_llm)) in override_agent.token_cost_service.registered_llms-def test_rust_agent_default_llm_is_rust_only_anthropic_sonnet(monkeypatch):+def test_rust_agent_default_llm_matches_browser_use_default(monkeypatch):from browser_use.agent.service import _PythonAgent as BrowserUseAgentfrom browser_use.rust import Agent as RustAgent@@ -4236,11 +4289,8 @@ def test_rust_agent_default_llm_is_rust_only_anthropic_sonnet(monkeypatch):rust_agent = RustAgent(task='Use the default model.', directly_open_url=False)assert browser_use_agent.llm.provider == 'browser-use'- assert rust_agent.llm.provider == 'anthropic'- assert rust_agent.llm.model == 'claude-sonnet-4-6'- assert rust_agent.settings.flash_mode is False- assert rust_agent.settings.page_extraction_llm is rust_agent.llm- assert rust_agent.model == rust_agent.llm.model+ assert rust_agent.llm.provider == browser_use_agent.llm.provider+ assert rust_agent.model == browser_use_agent.llm.modeldef test_rust_agent_default_llm_respects_default_llm_env(monkeypatch):@@ -4255,6 +4305,21 @@ def test_rust_agent_default_llm_respects_default_llm_env(monkeypatch):assert agent.llm.model == 'gpt-4.1-mini'+def test_rust_agent_explicit_llm_ignores_default_llm_env(monkeypatch):+ from browser_use.rust import Agent++ monkeypatch.setenv('DEFAULT_LLM', 'openai_gpt_4_1_mini')++ class LLM:+ model = 'gpt-test'+ provider = 'test-provider'++ agent = Agent(task='Use configured default model.', llm=cast(Any, LLM()), directly_open_url=False)++ assert agent.llm.provider == 'test-provider'+ assert agent.llm.model == 'gpt-test'++def test_rust_agent_enables_flash_mode_for_browser_use_llm_provider():from browser_use.agent.service import _PythonAgent as BrowserUseAgentfrom browser_use.rust import Agent as RustAgent@@ -4308,8 +4373,7 @@ def test_rust_agent_llm_timeout_defaults_match_browser_use_model_families():assert override_agent.settings.llm_timeout == 12-def test_rust_agent_disables_vision_for_unsupported_model_families():- from browser_use.agent.service import _PythonAgent as BrowserUseAgent+def test_rust_agent_forces_vision_for_all_model_families():from browser_use.rust import Agent as RustAgentclass LLM:@@ -4322,19 +4386,16 @@ def test_rust_agent_disables_vision_for_unsupported_model_families():return type('Result', (), {'usage': None})()for model in ['deepseek-chat', 'grok-3', 'grok-code']:- browser_use_agent = BrowserUseAgent(task='Inspect vision.', llm=LLM(model), directly_open_url=False, use_vision=True)- rust_agent = RustAgent(task='Inspect vision.', llm=LLM(model), directly_open_url=False, use_vision=True)+ rust_agent = RustAgent(task='Inspect vision.', llm=LLM(model), directly_open_url=False, use_vision=False)- assert browser_use_agent.settings.use_vision is False- assert rust_agent.settings.use_vision is False+ assert rust_agent.settings.use_vision is True- normal_agent = RustAgent(task='Inspect vision.', llm=LLM('gpt-test'), directly_open_url=False, use_vision=True)+ normal_agent = RustAgent(task='Inspect vision.', llm=LLM('gpt-test'), directly_open_url=False, use_vision=False)assert normal_agent.settings.use_vision is True-def test_rust_agent_unsupported_vision_warnings_match_browser_use(monkeypatch):- from browser_use.agent.service import _PythonAgent as BrowserUseAgent+def test_rust_agent_does_not_warn_when_forcing_vision(monkeypatch):from browser_use.rust import Agent as RustAgentclass LLM:@@ -4363,15 +4424,12 @@ def test_rust_agent_unsupported_vision_warnings_match_browser_use(monkeypatch):passfor model in ['deepseek-chat', 'grok-2']:- browser_use_logger = RecordingLogger()rust_logger = RecordingLogger()- monkeypatch.setattr(BrowserUseAgent, 'logger', property(lambda self, logger=browser_use_logger: logger))monkeypatch.setattr(RustAgent, 'logger', property(lambda self, logger=rust_logger: logger))- BrowserUseAgent(task='Inspect vision warning.', llm=LLM(model), directly_open_url=False, use_vision=True)- RustAgent(task='Inspect vision warning.', llm=LLM(model), directly_open_url=False, use_vision=True)+ RustAgent(task='Inspect vision warning.', llm=LLM(model), directly_open_url=False, use_vision=False)- assert rust_logger.warnings == browser_use_logger.warnings+ assert rust_logger.warnings == []def test_rust_agent_constructor_debug_summary_matches_browser_use(monkeypatch):@@ -4533,7 +4591,8 @@ def test_rust_agent_initializes_tools_and_action_models():assert isinstance(agent.tools, Tools)assert 'done' in action_names- assert 'screenshot' not in action_names+ assert agent.settings.use_vision is True+ assert 'screenshot' in action_namesassert agent.ActionModel is not Noneassert agent.DoneActionModel is not Noneassert agent.AgentOutput is not None@@ -4805,6 +4864,48 @@ def test_rust_agent_telemetry_filters_empty_reconstructed_urls():assert captured_events[0].urls_visited == ['https://example.com']+def test_rust_agent_telemetry_records_cloud_cdp_hostname():+ import browser_use.rust.service as rust_service+ from browser_use.rust import Agent++ class LLM:+ model = 'gpt-test'+ provider = 'test-provider'++ class BrowserProfile:+ downloads_path = None++ class BrowserSession:+ cdp_url = 'wss://cloud-browser.example/devtools/browser/session'+ browser_profile = BrowserProfile()++ captured_events = []++ class Telemetry:+ def capture(self, event):+ captured_events.append(event)++ agent = Agent(task='Log cloud CDP telemetry.', llm=cast(Any, LLM()), browser_session=cast(Any, BrowserSession()))+ agent.telemetry = Telemetry()+ agent.history = rust_service._history_from_events(+ [+ {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},+ {'event_type': 'session.done', 'payload': {'result': 'done'}},+ ],+ model='gpt-test',+ started=1.0,+ finished=2.0,+ output_model_schema=None,+ process_error=None,+ )++ agent._log_agent_event(max_steps=3)++ assert captured_events[0].name == 'agent_event'+ assert captured_events[0].cdp_url == 'cloud-browser.example'+ assert captured_events[0].urls_visited == ['https://example.com']++async def test_rust_agent_run_records_terminal_telemetry(monkeypatch):from browser_use.rust import Agent@@ -8834,7 +8935,7 @@ async def test_rust_agent_exposes_prepare_context_helper_method(monkeypatch):'model_output': agent.state.last_model_output,'result': agent.state.last_result,'step_info': step_info,- 'use_vision': False,+ 'use_vision': True,'page_filtered_actions': 'filtered action prompt','sensitive_data': {'api_key': 'secret-value'},'available_file_paths': ['/tmp/input.txt'],