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
Include Rust SDK child usage in totals
Magnus Müller78df92cceea7
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex 22e5c2efe..19f092723 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -153,6 +153,11 @@ This branch keeps the Python `Agent` unchanged unless callers explicitly importthe terminal web-search merge. URL-finding and general web-search tasks candiscover candidate pages without spending browser-navigation turns on searchengine result pages.+ - Terminal SDK histories now return child-agent events separately from parent+ events and expose a combined `usage_events` stream. Browser-use prices and+ traces against that combined stream, so sub-agent model calls contribute to+ run token/cost totals without letting child `session.done` events override+ the parent final answer.## Current Proof@@ -202,6 +207,8 @@ This branch keeps the Python `Agent` unchanged unless callers explicitly import- terminal `cargo test -p browser-use-agent subagent_tools_are_registered_in_the_dispatcher -- --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`+- browser-use `uv run pytest tests/ci/test_rust_agent.py::test_rust_agent_prices_sdk_child_usage_events_without_overriding_parent_result -q`- browser-use `uv run pytest tests/ci/test_rust_agent.py::test_rust_agent_runs_through_sdk_and_reuses_session_for_followup tests/ci/test_rust_agent.py::test_rust_agent_recovers_final_result_from_sdk_notifications_after_transport_error tests/ci/test_rust_agent.py::test_rust_agent_preserves_sdk_notification_history_on_cancel -q`- evaluations-internal `uv run python -m py_compile eval/service.py`- evaluations-internal `python -m py_compile eval/task_types.py`diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex b929f6eba..4eea12d38 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -4357,6 +4357,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.history: AgentHistoryList[AgentStructuredOutput] = AgentHistoryList(history=[], usage=None)self.result: AgentHistoryList[AgentStructuredOutput] | None = Noneself.last_events: list[dict[str, Any]] = []+ self.last_child_events: list[dict[str, Any]] = []+ self.last_usage_events: list[dict[str, Any]] = []+ self.last_observability_events: list[dict[str, Any]] = []self.last_stdout = ''self.last_stderr = ''self._last_synced_history_id: int | None = None@@ -4654,7 +4657,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):'final_result_preview': _laminar_preview(final_result, limit=2000),'terminal_session_id': self.terminal_session_id,'browser_use_session_id': self.session_id,- 'terminal_events_count': len(self.last_events or []),+ 'terminal_events_count': len(self.last_observability_events or self.last_events or []),'duration_seconds': duration_seconds,'process_error': process_error,}@@ -4673,13 +4676,14 @@ class Agent(Generic[Context, AgentStructuredOutput]):'usage_total_cost': usage.total_cost,})+ observability_events = self.last_observability_events or self.last_events or []_record_laminar_terminal_llm_spans(- self.last_events or [],+ observability_events,default_model=str(model),default_provider=str(provider),)_record_laminar_terminal_tool_spans(- self.last_events or [],+ observability_events,max_spans=_int_value(os.getenv('BROWSER_USE_RUST_LAMINAR_MAX_TOOL_SPANS') or 160),)_laminar_set_span_attributes(@@ -5074,6 +5078,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.last_stdout = str(getattr(sdk, 'stdout_text', '') or '')self.last_stderr = str(getattr(sdk, 'stderr_text', '') or '\n'.join(line for line in sdk.stderr_lines if line))notification_events = _sdk_notification_events(sdk)+ child_events: list[dict[str, Any]] = []+ usage_events: list[dict[str, Any]] = []if isinstance(result, dict):agent_id = result.get('agent_id')session_id = result.get('session_id')@@ -5092,17 +5098,30 @@ class Agent(Generic[Context, AgentStructuredOutput]):errors = history_payload.get('errors')if process_error is None and history_payload.get('success') is False and isinstance(errors, list) and errors:process_error = '\n'.join(str(error) for error in errors if error)+ raw_child_events = history_payload.get('child_events')+ if isinstance(raw_child_events, list):+ child_events = [event for event in raw_child_events if isinstance(event, dict)]+ raw_usage_events = history_payload.get('usage_events')+ if isinstance(raw_usage_events, list):+ usage_events = [event for event in raw_usage_events if isinstance(event, dict)]elif process_error is None:process_error = 'Rust SDK server returned an invalid response.'if notification_events and (not events or _sdk_events_truncated_for_transport(events) or len(notification_events) > len(events)):events = notification_events+ child_events = []+ usage_events = notification_events+ if not usage_events:+ usage_events = [*events, *child_events]if _result_from_events(events) is not None and (process_error == 'CancelledError' or _sdk_transport_error_after_final_result(process_error)):process_error = Noneself.last_events = events+ self.last_child_events = child_events+ self.last_usage_events = usage_events+ self.last_observability_events = usage_eventsself.result = _history_from_events(self.last_events,model=self.model,@@ -5115,7 +5134,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.result.history = [*self._pending_history_prefix, *self.result.history]self._pending_history_prefix = []self.history = self.result- await self._apply_terminal_usage_costs(self.last_events)+ await self._apply_terminal_usage_costs(self.last_usage_events)self._sync_state_from_history()await self._log_run_usage_summary()self._record_laminar_run_observability(@@ -5154,6 +5173,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):):effective_error = Noneself.last_events = events+ self.last_child_events = []+ self.last_usage_events = events+ self.last_observability_events = eventsself.result = _history_from_events(self.last_events,model=self.model,@@ -5166,7 +5188,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.result.history = [*self._pending_history_prefix, *self.result.history]self._pending_history_prefix = []self.history = self.result- await self._apply_terminal_usage_costs(self.last_events)+ await self._apply_terminal_usage_costs(self.last_usage_events)self._sync_state_from_history()async def _log_sdk_progress(self, sdk: RustSdkClient) -> None:@@ -6493,6 +6515,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):'urls': self.history.urls(),'usage': self.history.usage.model_dump() if self.history.usage else None,'events': self.last_events,+ 'child_events': self.last_child_events,+ 'usage_events': self.last_usage_events,'stdout': self.last_stdout,'stderr': self.last_stderr,}diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 81eb827b6..e25825920 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -2608,6 +2608,65 @@ async def test_rust_agent_runs_through_sdk_and_reuses_session_for_followup(monkeassert fake_sdk.calls[1][1]['max_steps'] == 5+async def test_rust_agent_prices_sdk_child_usage_events_without_overriding_parent_result(monkeypatch):+ from browser_use.rust import Agent++ class LLM:+ model = 'fake'++ class FakeSdk:+ stderr_lines = []+ notifications = []++ async def call(self, method, params):+ assert method == 'agent.run_task'+ parent_events = [+ {'event_type': 'model.usage', 'payload': {'input_tokens': 7000, 'output_tokens': 20}},+ {'event_type': 'session.done', 'payload': {'result': 'parent answer', 'success': True}},+ ]+ child_events = [+ {+ 'event_type': 'model.usage',+ 'session_id': 'child-1',+ 'payload': {'input_tokens': 3000, 'cached_input_tokens': 1000, 'output_tokens': 10},+ },+ {'event_type': 'session.done', 'session_id': 'child-1', 'payload': {'result': 'child answer'}},+ ]+ return {+ 'agent_id': 'agent-1',+ 'session_id': 'parent-1',+ 'browser_id': 'browser-1',+ 'history': {+ 'output': 'parent answer',+ 'success': True,+ 'done': True,+ 'errors': [],+ 'events': parent_events,+ 'child_events': child_events,+ 'usage_events': [*parent_events, *child_events],+ },+ }++ fake_sdk = FakeSdk()++ async def fake_ensure_sdk_client(self):+ return fake_sdk++ monkeypatch.setattr(Agent, '_ensure_sdk_client', fake_ensure_sdk_client)++ agent = Agent(task='parent task', llm=LLM(), directly_open_url=False)+ history = await agent.run(max_steps=3)++ assert history.final_result() == 'parent answer'+ assert agent.last_events[-1]['payload']['result'] == 'parent answer'+ assert agent.last_child_events[-1]['payload']['result'] == 'child answer'+ assert history.usage is not None+ assert history.usage.total_prompt_tokens == 10_000+ assert history.usage.total_prompt_cached_tokens == 1000+ assert history.usage.total_completion_tokens == 30+ assert history.usage.entry_count == 2++async def test_rust_agent_recovers_final_result_from_sdk_notifications_after_transport_error(monkeypatch):from browser_use.rust import Agent