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
fix: bound Bash pipe cleanup and preserve Cloud scope behavior
Gregor Žunič3e3884e27997
diff --git a/README.md b/README.mdindex f6a071cc5..a13a286f7 100644--- a/README.md+++ b/README.md@@ -163,6 +163,8 @@ Bash is included in the Browser Use integration for processing data and writing<img src="examples/integrations/anthropic/architecture.svg" alt="Claude uses Browser Use browser actions and Bash through the Anthropic SDK. The browser can be local or remote; Bash runs on the SDK host." width="100%">Requires an Anthropic SDK version that includes `anthropic.tools.browser`.+Bash requires a Linux or macOS host with `/bin/bash`; use WSL on Windows.+The snippet below runs inside an async function; see the quickstart for a complete script.```pythonimport osdiff --git a/browser_use/browser/cloud/cloud.py b/browser_use/browser/cloud/cloud.pyindex 9b2c240a1..13ae07833 100644--- a/browser_use/browser/cloud/cloud.py+++ b/browser_use/browser/cloud/cloud.py@@ -52,7 +52,8 @@ class CloudBrowserClient:for existing keys and only fall through on the backend's explicitmissing-version-scope response."""- versions = (self.current_api_version,) if self.current_api_version else _BROWSER_API_VERSIONS+ # A new session may use a different scoped key. Only cleanup is pinned.+ versions = (self.current_api_version,) if method != 'POST' and self.current_api_version else _BROWSER_API_VERSIONSlast_response = Nonelast_version = versions[-1]for version in versions:diff --git a/browser_use/integrations/anthropic/__init__.py b/browser_use/integrations/anthropic/__init__.pyindex 914264660..0649a94d1 100644--- a/browser_use/integrations/anthropic/__init__.py+++ b/browser_use/integrations/anthropic/__init__.py@@ -22,7 +22,7 @@ def __getattr__(name: str):try:from .browser_use import BrowserUseexcept ModuleNotFoundError as exc:- if exc.name in {'anthropic.tools', 'anthropic.tools.browser'}:+ if exc.name in {'anthropic', 'anthropic.tools', 'anthropic.tools.browser'}:raise ImportError('Browser Use requires an Anthropic Python SDK release that includes ''anthropic.tools.browser and client.beta.messages.tool_runner.'diff --git a/browser_use/integrations/anthropic/bash.py b/browser_use/integrations/anthropic/bash.pyindex fc5cfc9b2..e27b7cd12 100644--- a/browser_use/integrations/anthropic/bash.py+++ b/browser_use/integrations/anthropic/bash.py@@ -13,19 +13,29 @@ from pathlib import Pathfrom typing import Any-async def _drain_bounded(stream: asyncio.StreamReader, limit: int) -> tuple[bytes, bool]:- chunks: list[bytes] = []- retained = 0- truncated = False- while chunk := await stream.read(64 * 1024):- remaining = limit - retained- if remaining > 0:- kept = chunk[:remaining]- chunks.append(kept)- retained += len(kept)- if len(chunk) > max(remaining, 0):- truncated = True- return b''.join(chunks), truncated+class _BashOutput(asyncio.SubprocessProtocol):+ """Collect bounded output until both the process and its pipes have closed."""++ def __init__(self, limit: int) -> None:+ self.limit = limit+ self.output = bytearray()+ self.truncated = False+ loop = asyncio.get_running_loop()+ self.closed = loop.create_future()+ self.exited = loop.create_future()++ def pipe_data_received(self, fd: int, data: bytes) -> None:+ remaining = self.limit - len(self.output)+ self.output.extend(data[:remaining])+ self.truncated |= len(data) > remaining++ def process_exited(self) -> None:+ if not self.exited.done():+ self.exited.set_result(None)++ def connection_lost(self, exc: Exception | None) -> None:+ if not self.closed.done():+ self.closed.set_result(None)def _prepare_output_dir(output_dir: str | Path) -> tuple[Path, Path]:@@ -52,7 +62,9 @@ async def run_bash(raise ValueError('max_output_bytes must be positive')root, tmp = await asyncio.to_thread(_prepare_output_dir, output_dir)- process = await asyncio.create_subprocess_exec(+ protocol = _BashOutput(max_output_bytes)+ transport, _ = await asyncio.get_running_loop().subprocess_exec(+ lambda: protocol,'/bin/bash','--noprofile','--norc',@@ -67,33 +79,35 @@ async def run_bash('PYTHONNOUSERSITE': '1','TMPDIR': str(tmp),},+ stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,start_new_session=True,)- assert process.stdout is not None- drain = asyncio.create_task(_drain_bounded(process.stdout, max_output_bytes))timed_out = Falsetry:- await asyncio.wait_for(process.wait(), timeout=timeout_seconds)+ # connection_lost covers the shell AND inherited output pipes.+ await asyncio.wait_for(asyncio.shield(protocol.closed), timeout=timeout_seconds)except TimeoutError:timed_out = True- with contextlib.suppress(ProcessLookupError):- os.killpg(process.pid, signal.SIGKILL)- await process.wait()except asyncio.CancelledError:with contextlib.suppress(ProcessLookupError):- os.killpg(process.pid, signal.SIGKILL)- await process.wait()- await drain+ os.killpg(transport.get_pid(), signal.SIGKILL)raise- output, truncated = await drain+ finally:+ if timed_out:+ with contextlib.suppress(ProcessLookupError):+ os.killpg(transport.get_pid(), signal.SIGKILL)+ # Close pipes even if a detached descendant still holds their write end.+ transport.close()+ with contextlib.suppress(TimeoutError):+ await asyncio.wait_for(asyncio.shield(protocol.exited), timeout=1)return json.dumps({- 'exit_code': process.returncode,+ 'exit_code': transport.get_returncode(),'timed_out': timed_out,- 'truncated': truncated,- 'output': output.decode('utf-8', errors='replace'),+ 'truncated': protocol.truncated,+ 'output': protocol.output.decode('utf-8', errors='replace'),},ensure_ascii=False,)diff --git a/browser_use/skills/browser-use/SKILL.md b/browser_use/skills/browser-use/SKILL.mdindex ca98fee56..12b493474 100644--- a/browser_use/skills/browser-use/SKILL.md+++ b/browser_use/skills/browser-use/SKILL.md@@ -281,7 +281,7 @@ If you get stuck on a browser mechanic, check https://github.com/browser-use/bro## Gotchas- `chrome://inspect/#remote-debugging` must be enabled for local Chrome control.-- On macOS, if local Chrome shows an "Allow remote debugging?" popup, call `mac-approve` once with the same `BU_NAME` while the original browser command waits. Do not poll or rerun the browser command; remote and cloud browsers do not use this helper.+- On macOS, if local Chrome shows an "Allow remote debugging?" popup, call `mac-approve` once with the same `BU_NAME` while the original browser command waits. Wait for the original process result; do not invoke the browser command again; remote and cloud browsers do not use this helper.- Omnibox popups are not real work tabs.- CDP target order is not Chrome's visible tab-strip order.- `BU_CDP_URL` is an HTTP DevTools endpoint; the daemon resolves it to WebSocket.diff --git a/examples/integrations/anthropic/README.md b/examples/integrations/anthropic/README.mdindex 8e274a1c1..ced571fe8 100644--- a/examples/integrations/anthropic/README.md+++ b/examples/integrations/anthropic/README.md@@ -21,7 +21,8 @@ The same program works with three browser runtimes:## Quickstart-Browser Use requires Python 3.11 or newer. Anthropic's browser toolset requires+This example requires Python 3.11 or newer and Linux or macOS with `/bin/bash`.+On Windows, run it inside WSL. Anthropic's browser toolset requiresthe Anthropic SDK release that includes `anthropic.tools.browser` and`client.beta.messages.tool_runner`.@@ -169,7 +170,8 @@ stops it when the context exits.## Existing or remote browserPass an already started `BrowserSession` to the driver. Your application keeps-responsibility for that session's lifecycle:+responsibility for that session's lifecycle. Run this excerpt inside an async+function (or a notebook that supports top-level await):```pythonimport osdiff --git a/examples/integrations/anthropic/quickstart.py b/examples/integrations/anthropic/quickstart.pyindex 0ea03d698..6bb81a39e 100644--- a/examples/integrations/anthropic/quickstart.py+++ b/examples/integrations/anthropic/quickstart.py@@ -1,4 +1,7 @@-"""Build a Hacker News reading list with Anthropic and Browser Use."""+"""Build a Hacker News reading list with Anthropic and Browser Use.++Requires Linux/macOS with /bin/bash, or WSL on Windows.+"""import asyncioimport osdiff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex ca98fee56..12b493474 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -281,7 +281,7 @@ If you get stuck on a browser mechanic, check https://github.com/browser-use/bro## Gotchas- `chrome://inspect/#remote-debugging` must be enabled for local Chrome control.-- On macOS, if local Chrome shows an "Allow remote debugging?" popup, call `mac-approve` once with the same `BU_NAME` while the original browser command waits. Do not poll or rerun the browser command; remote and cloud browsers do not use this helper.+- On macOS, if local Chrome shows an "Allow remote debugging?" popup, call `mac-approve` once with the same `BU_NAME` while the original browser command waits. Wait for the original process result; do not invoke the browser command again; remote and cloud browsers do not use this helper.- Omnibox popups are not real work tabs.- CDP target order is not Chrome's visible tab-strip order.- `BU_CDP_URL` is an HTTP DevTools endpoint; the daemon resolves it to WebSocket.diff --git a/tests/ci/browser/test_cloud_browser.py b/tests/ci/browser/test_cloud_browser.pyindex 0edcb65f1..6d8310a16 100644--- a/tests/ci/browser/test_cloud_browser.py+++ b/tests/ci/browser/test_cloud_browser.py@@ -121,6 +121,46 @@ class TestCloudBrowserClient:]assert client.current_api_version == 'v3'+ stopped = AsyncMock()+ stopped.status_code = 200+ stopped.is_success = True+ stopped.json = lambda: {**created.json(), 'status': 'stopped', 'liveUrl': None, 'cdpUrl': None}+ mock_client.request.side_effect = [stopped]+ await client.stop_browser()+ assert mock_client.request.call_args.args[:2] == (+ 'PATCH',+ 'https://api.browser-use.com/api/v3/browsers/test-browser-id',+ )+ assert client.current_session_id is None+ assert client.current_api_version is None++ async def test_create_browser_renegotiates_for_a_new_scoped_key(self, mock_auth_config, monkeypatch):+ monkeypatch.setenv('BROWSER_USE_API_KEY', 'new-v2-key')+ with patch('httpx.AsyncClient') as mock_client_class:+ response = AsyncMock()+ response.status_code = 201+ response.is_success = True+ response.json = lambda: {+ 'id': 'new-browser',+ 'status': 'active',+ 'liveUrl': None,+ 'cdpUrl': 'wss://example.invalid',+ 'timeoutAt': '2025-09-17T04:35:36',+ 'startedAt': '2025-09-17T03:35:36',+ 'finishedAt': None,+ }+ mock_client_class.return_value = AsyncMock()+ mock_client_class.return_value.request.return_value = response+ client = CloudBrowserClient()+ client.current_api_version = 'v3'+ await client.create_browser(CreateBrowserRequest())+ assert mock_client_class.return_value.request.call_args.args[:2] == (+ 'POST',+ 'https://api.browser-use.com/api/v2/browsers',+ )+ assert mock_client_class.return_value.request.call_args.kwargs['headers']['X-Browser-Use-API-Key'] == 'new-v2-key'+ assert client.current_api_version == 'v2'+async def test_create_browser_auth_error(self, temp_config_dir, monkeypatch):"""Test cloud browser creation with auth error."""diff --git a/tests/ci/integrations/test_anthropic_browser_use.py b/tests/ci/integrations/test_anthropic_browser_use.pyindex b67fe5ac1..e1e8d7275 100644--- a/tests/ci/integrations/test_anthropic_browser_use.py+++ b/tests/ci/integrations/test_anthropic_browser_use.py@@ -197,6 +197,59 @@ async def test_bash_bounds_output_and_kills_on_timeout(tmp_path: Path) -> None:assert timed_out['exit_code'] < 0+async def test_bash_deadline_closes_inherited_output_pipes(tmp_path: Path) -> None:+ # setsid escapes the shell's process group while retaining stdout.+ import shlex+ import signal++ pid_path = tmp_path / 'descendant.pid'+ child = "import os,time; os.setsid(); open('descendant.pid','w').write(str(os.getpid())); print('started',flush=True); time.sleep(10)"+ command = f'{shlex.quote(sys.executable)} -c {shlex.quote(child)} & wait'+ try:+ result = json.loads(await asyncio.wait_for(run_bash(command, output_dir=tmp_path, timeout_seconds=0.3), timeout=2))+ assert result['timed_out'] is True+ assert 'started' in result['output']+ finally:+ if pid_path.exists():+ try:+ os.kill(int(pid_path.read_text()), signal.SIGKILL)+ except ProcessLookupError:+ pass+++async def test_bash_cancellation_closes_inherited_output_pipes(tmp_path: Path, monkeypatch) -> None:+ import shlex+ import signal++ import browser_use.integrations.anthropic.bash as bash_module++ started = asyncio.Event()+ original = bash_module._BashOutput.pipe_data_received++ def observe_output(protocol, fd, data):+ original(protocol, fd, data)+ if b'started' in protocol.output:+ started.set()++ monkeypatch.setattr(bash_module._BashOutput, 'pipe_data_received', observe_output)+ pid_path = tmp_path / 'descendant.pid'+ child = "import os,time; os.setsid(); open('descendant.pid','w').write(str(os.getpid())); print('started',flush=True); time.sleep(10)"+ task = asyncio.create_task(run_bash(f'{shlex.quote(sys.executable)} -c {shlex.quote(child)} & wait', output_dir=tmp_path))+ try:+ await asyncio.wait_for(started.wait(), timeout=2)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=2)+ finally:+ if pid_path.exists():+ try:+ os.kill(int(pid_path.read_text()), signal.SIGKILL)+ except ProcessLookupError:+ pass+ if not task.done():+ task.cancel()++def test_quickstart_uses_peer_browser_use_and_bash_tools() -> None:source = QUICKSTART_PATH.read_text()tree = ast.parse(source)