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 Rust agent runtime metadata
Magnus Müllerbe4ea77bdf1f
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex 208197e19..31a3ba8e3 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -416,10 +416,15 @@ Terminal core branch: `magnus/browser-use-rust-integration` at terminal main `ee- Common Browser Use legacy aliases such as `go_to_url`, `open_tab`, `click_element_by_index`, and `input_text` normalize to the current `navigate`, `click`, and `input` actions when the local registry can validate them.- Proof: `test_rust_agent_preserves_ordered_initial_actions_context` and `test_rust_agent_mirrors_direct_url_startup`.+82. Rust Agent runtime metadata and observability parity+ - The Rust-backed `Agent` now exposes Browser Use-style `version`, `source`, `logger`, `eventbus`, `telemetry`, and `token_cost_service` attributes.+ - The wrapper registers supplied LLMs with token-cost tracking when they expose `ainvoke`, creates a valid Bubus event bus name for arbitrary task IDs, and exposes `DoneAgentOutput` alongside `DoneActionModel`.+ - Proof: `test_rust_agent_initializes_runtime_metadata_and_observability`.+## Current Verification- `python3 -m py_compile browser_use/rust/service.py browser_use/rust/__init__.py browser_use/__init__.py tests/ci/test_rust_agent.py examples/rust_agent/basic.py examples/rust_agent/real_v8_smoke.py`-- `uv run pytest -q tests/ci/test_rust_agent.py` (55 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (56 tests)- `cargo build -q -p browser-use-cli`- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent selected_remote_cdp_mode_allows_remote_cdp_connect -- --nocapture`- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent bare_browser_connect_resolves_to_selected_managed_mode_with_launch_args -- --nocapture`diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex 8cf3e45f1..31a318d5c 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport inspectimport json+import loggingimport osimport reimport shutil@@ -13,6 +14,7 @@ from datetime import datetimefrom pathlib import Pathfrom typing import Any, Generic, Literal+from bubus import EventBusfrom pydantic import BaseModel, ValidationErrorfrom typing_extensions import TypeVarfrom uuid_extensions import uuid7str@@ -31,8 +33,11 @@ from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.browser.profile import CHROME_DETERMINISTIC_RENDERING_ARGS, CHROME_DISABLE_SECURITY_ARGS, CHROME_DOCKER_ARGSfrom browser_use.browser.views import BrowserStateHistory, TabInfofrom browser_use.filesystem.file_system import FileSystem+from browser_use.telemetry.service import ProductTelemetry+from browser_use.tokens.service import TokenCostfrom browser_use.tokens.views import ModelUsageStats, UsageSummaryfrom browser_use.tools.service import Tools+from browser_use.utils import get_browser_use_versionAgentStructuredOutput = TypeVar('AgentStructuredOutput', bound=BaseModel)@@ -933,6 +938,28 @@ def _resolve_tools(return resolved_tools+def _browser_use_version_and_source(source_override: str | None = None) -> tuple[str | None, str]:+ version = get_browser_use_version()+ try:+ package_root = Path(__file__).parent.parent.parent+ repo_files = ['.git', 'README.md', 'docs', 'examples']+ source = 'git' if all((package_root / file).exists() for file in repo_files) else 'pip'+ except Exception:+ source = 'unknown'+ if source_override is not None:+ source = source_override+ return version, source+++def _register_llm_for_usage(token_cost_service: TokenCost, llm: Any | None) -> None:+ if llm is None or not hasattr(llm, 'ainvoke'):+ return+ try:+ token_cost_service.register_llm(llm)+ except Exception:+ return++def _action_payload(action: Any) -> dict[str, Any]:"""Serialize a Browser Use action model into JSON-like data for Rust task context."""if isinstance(action, dict):@@ -1074,7 +1101,7 @@ class Agent(Generic[AgentStructuredOutput]):self.register_external_agent_status_raise_error_callback = register_external_agent_status_raise_error_callbackself.register_should_stop_callback = register_should_stop_callbackself.output_model_schema = output_model_schema- self.source = source+ self.version, self.source = _browser_use_version_and_source(source)self.kwargs = kwargsself.model = _model_name(llm)self.state = injected_agent_state or AgentState(agent_id=self.id)@@ -1103,6 +1130,12 @@ class Agent(Generic[AgentStructuredOutput]):final_response_after_failure=final_response_after_failure,)self._setup_action_models()+ self.token_cost_service = TokenCost(include_cost=calculate_cost)+ _register_llm_for_usage(self.token_cost_service, llm)+ _register_llm_for_usage(self.token_cost_service, page_extraction_llm)+ self.telemetry = ProductTelemetry()+ eventbus_suffix = re.sub(r'\W', '_', str(self.id)[-8:])+ self.eventbus = EventBus(name=f'RustAgent_{eventbus_suffix}')self.available_file_paths = available_file_paths or []self.allowed_domains = _extract_profile_domains(self.browser_session, self.browser_profile, 'allowed_domains')self.prohibited_domains = _extract_profile_domains(self.browser_session, self.browser_profile, 'prohibited_domains')@@ -1272,6 +1305,18 @@ class Agent(Generic[AgentStructuredOutput]):def usage(self) -> UsageSummary | None:return self.history.usage+ @property+ def logger(self) -> logging.Logger:+ browser_session_id = getattr(self.browser_session, 'id', '----') or '----'+ target_id = '--'+ agent_focus = getattr(self.browser_session, 'agent_focus', None)+ focus_target_id = getattr(agent_focus, 'target_id', None)+ if isinstance(focus_target_id, str) and focus_target_id:+ target_id = focus_target_id[-2:]+ return logging.getLogger(+ f'browser_use.rust.Agent {self.task_id[-4:]} -> BrowserSession {str(browser_session_id)[-4:]} Target {target_id}'+ )+def _setup_action_models(self, page_url: str | None = None) -> None:"""Expose Browser Use-style action model classes from the configured tools."""registry = getattr(self.tools, 'registry', None)@@ -1289,6 +1334,12 @@ class Agent(Generic[AgentStructuredOutput]):else:self.AgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.ActionModel)self.DoneActionModel = create_action_model(include_actions=['done'], page_url=page_url)+ if self.settings.flash_mode:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions_flash_mode(self.DoneActionModel)+ elif self.settings.use_thinking:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)+ else:+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.DoneActionModel)def _convert_initial_actions(self, actions: list[dict[str, dict[str, Any]]]) -> list[Any]:"""Convert dictionary initial actions to Browser Use action model instances when possible."""diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex c69a0f44e..916ede48c 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -805,6 +805,39 @@ def test_rust_agent_initializes_tools_and_action_models():assert 'done' in str(done_schema)+def test_rust_agent_initializes_runtime_metadata_and_observability():+ from browser_use.rust import Agent+ from browser_use.tokens.service import TokenCost++ class LLM:+ model = 'gpt-test'+ provider = 'test'++ async def ainvoke(self, messages, output_format=None, **kwargs):+ return type('Result', (), {'usage': None})()++ llm = LLM()+ agent = Agent(+ task='Inspect metadata.',+ llm=llm,+ task_id='task-1234',+ source='ci',+ calculate_cost=True,+ use_thinking=False,+ )++ assert agent.version+ assert agent.source == 'ci'+ assert agent.logger.name.endswith('1234 Target --')+ assert agent.eventbus is not None+ assert callable(agent.telemetry.capture)+ assert callable(agent.telemetry.flush)+ assert isinstance(agent.token_cost_service, TokenCost)+ assert agent.token_cost_service.include_cost is True+ assert str(id(llm)) in agent.token_cost_service.registered_llms+ assert agent.DoneAgentOutput is not None++def test_rust_agent_initializes_browser_use_session_and_file_system(tmp_path):from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.rust import Agent