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 message manager parity
Magnus Müller568da7b373b2
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex 31a3ba8e3..6ea027d50 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -421,10 +421,15 @@ Terminal core branch: `magnus/browser-use-rust-integration` at terminal main `ee- 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`.+83. Rust Agent message manager parity+ - The Rust-backed `Agent` now initializes a Browser Use `MessageManager` and exposes it through `agent.message_manager`.+ - `add_new_task(...)` now updates the message manager follow-up history, resets pause/stop state, and recreates a valid event bus name without depending on the Python Agent run loop.+ - Proof: `test_rust_agent_initializes_message_manager_and_followup_state`.+## 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` (56 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (57 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 31a318d5c..350d1689f 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -19,6 +19,8 @@ from pydantic import BaseModel, ValidationErrorfrom typing_extensions import TypeVarfrom uuid_extensions import uuid7str+from browser_use.agent.message_manager.service import MessageManager+from browser_use.agent.prompts import SystemPromptfrom browser_use.agent.views import (ActionResult,AgentHistory,@@ -960,6 +962,18 @@ def _register_llm_for_usage(token_cost_service: TokenCost, llm: Any | None) -> Nreturn+def _eventbus_name(agent_id: str, prefix: str = 'RustAgent') -> str:+ suffix = re.sub(r'\W', '_', str(agent_id)[-8:])+ if suffix and suffix[0].isdigit():+ suffix = 'a' + suffix+ return f'{prefix}_{suffix or "agent"}'+++def _unique_eventbus_name(agent_id: str, prefix: str = 'RustAgent') -> str:+ unique_suffix = re.sub(r'\W', '_', uuid7str()[-8:])+ return f'{_eventbus_name(agent_id, prefix)}_{unique_suffix}'++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):@@ -1134,8 +1148,7 @@ class Agent(Generic[AgentStructuredOutput]):_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.eventbus = EventBus(name=_eventbus_name(self.id))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')@@ -1187,6 +1200,26 @@ class Agent(Generic[AgentStructuredOutput]):),output_model_schema,)+ self._message_manager = MessageManager(+ task=self.task,+ system_message=SystemPrompt(+ max_actions_per_step=self.settings.max_actions_per_step,+ override_system_message=self.settings.override_system_message,+ extend_system_message=self.settings.extend_system_message,+ use_thinking=self.settings.use_thinking,+ flash_mode=self.settings.flash_mode,+ ).get_system_message(),+ file_system=self.file_system,+ state=self.state.message_manager_state,+ use_thinking=self.settings.use_thinking,+ include_attributes=self.settings.include_attributes,+ sensitive_data=sensitive_data,+ max_history_items=self.settings.max_history_items,+ vision_detail_level=self.settings.vision_detail_level,+ include_tool_call_examples=self.settings.include_tool_call_examples,+ include_recent_events=self.include_recent_events,+ sample_images=self.sample_images,+ )self.session_id: str | None = Noneself.history: AgentHistoryList[AgentStructuredOutput] = AgentHistoryList(history=[], usage=None)self.result: AgentHistoryList[AgentStructuredOutput] | None = None@@ -1317,6 +1350,10 @@ class Agent(Generic[AgentStructuredOutput]):f'browser_use.rust.Agent {self.task_id[-4:]} -> BrowserSession {str(browser_session_id)[-4:]} Target {target_id}')+ @property+ def message_manager(self) -> MessageManager:+ return self._message_manager+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)@@ -1440,9 +1477,11 @@ class Agent(Generic[AgentStructuredOutput]):def add_new_task(self, new_task: str) -> None:"""Add a follow-up task while keeping the same Browser Use-style agent object."""self.task = _task_with_schema(new_task, self.output_model_schema)+ self._message_manager.add_new_task(new_task)self.state.follow_up_task = Trueself.state.stopped = Falseself.state.paused = False+ self.eventbus = EventBus(name=_unique_eventbus_name(self.id))self._external_pause_event.set()def save_history(self, file_path: str | Path | None = None) -> None:diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 916ede48c..87e4b991f 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -838,6 +838,31 @@ def test_rust_agent_initializes_runtime_metadata_and_observability():assert agent.DoneAgentOutput is not None+def test_rust_agent_initializes_message_manager_and_followup_state():+ from browser_use.agent.message_manager.service import MessageManager+ from browser_use.rust import Agent++ agent = Agent(+ task='Initial task.',+ task_id='task-with-hyphen',+ include_recent_events=True,+ )+ initial_eventbus_name = agent.eventbus.name++ agent.add_new_task('Follow up task.')++ assert isinstance(agent.message_manager, MessageManager)+ assert agent.message_manager is agent._message_manager+ assert agent.message_manager.include_recent_events is True+ assert '<initial_user_request>' in agent.message_manager.task+ assert '<follow_up_user_request> Follow up task. </follow_up_user_request>' in agent.message_manager.task+ assert agent.state.follow_up_task is True+ assert agent.state.stopped is False+ assert agent.state.paused is False+ assert agent.eventbus.name.startswith(initial_eventbus_name)+ assert agent.eventbus.name.isidentifier()++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