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
refactor: remove pycloudflared, install cloudflared directly in install.sh
ShawnPanaf40235242a33
diff --git a/browser_use/skill_cli/commands/setup.py b/browser_use/skill_cli/commands/setup.pyindex cf76f21d6..2f7d6e847 100644--- a/browser_use/skill_cli/commands/setup.py+++ b/browser_use/skill_cli/commands/setup.py@@ -188,9 +188,9 @@ def plan_actions(cloudflared_check = checks.get('cloudflared', {})if cloudflared_check.get('status') != 'ok':actions.append({- 'type': 'note_cloudflared',- 'description': 'Cloudflared will auto-install on first tunnel use',- 'required': False,+ 'type': 'install_cloudflared',+ 'description': 'Install cloudflared (for tunneling)',+ 'required': True,})return actions@@ -236,9 +236,15 @@ async def execute_actions(print(' Set via: export BROWSER_USE_API_KEY=your_key')print(' Or: browser-use setup --api-key <key>')- elif action_type == 'note_cloudflared':+ elif action_type == 'install_cloudflared':if not json_output:- print('📦 Cloudflared will auto-install on first tunnel use (~20MB)')+ print('⚠ cloudflared not installed')+ print(' Install via:')+ print(' macOS: brew install cloudflared')+ print(' Linux: curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o ~/.local/bin/cloudflared && chmod +x ~/.local/bin/cloudflared')+ print(' Windows: winget install Cloudflare.cloudflared')+ print()+ print(' Or re-run install.sh which installs cloudflared automatically.')async def validate_setup(diff --git a/browser_use/skill_cli/tunnel_manager.py b/browser_use/skill_cli/tunnel_manager.pyindex 45296a816..71db6fffc 100644--- a/browser_use/skill_cli/tunnel_manager.py+++ b/browser_use/skill_cli/tunnel_manager.py@@ -1,125 +1,75 @@-"""Cloudflared tunnel binary management via pycloudflared.+"""Cloudflared tunnel binary management.-This module manages the cloudflared binary for tunnel support, following-the same pattern as Playwright's Chromium auto-install.--Preference order:-1. System cloudflared (if user installed via brew/apt/winget)-2. pycloudflared (auto-downloaded from official Cloudflare releases)+This module manages the cloudflared binary for tunnel support.+Cloudflared must be installed via install.sh or manually by the user."""import loggingimport shutil-from typing import Any, Literal+from typing import Anylogger = logging.getLogger(__name__)class TunnelManager:- """Manages cloudflared binary installation and execution.-- Respects user's explicit choice (system install) while providing- automatic fallback for seamless first-time experience.- """+ """Manages cloudflared binary location."""def __init__(self) -> None:self._binary_path: str | None = None- self._installation_status: Literal['system', 'pycloudflared', 'none'] = 'none'def get_binary_path(self) -> str:- """Get cloudflared binary path, installing if needed.+ """Get cloudflared binary path.Returns:Absolute path to cloudflared binaryRaises:- RuntimeError: If installation fails (network, disk space, etc.)+ RuntimeError: If cloudflared is not installed"""# Cached result from previous callif self._binary_path:return self._binary_path- # Check system installation first (user preference)+ # Check system installationsystem_binary = shutil.which('cloudflared')if system_binary:- logger.info('Using system cloudflared: %s', system_binary)+ logger.info('Using cloudflared: %s', system_binary)self._binary_path = system_binary- self._installation_status = 'system'return system_binary- # Fallback to pycloudflared (auto-install)- try:- from pycloudflared import cloudflared_path # type: ignore-- # First import triggers auto-download if needed- logger.info('📦 Downloading cloudflared (~20MB, one-time setup)...')- binary = cloudflared_path()-- logger.info('✓ Cloudflared ready: %s', binary)- self._binary_path = str(binary)- self._installation_status = 'pycloudflared'- return self._binary_path-- except ImportError:- # Should never happen (pycloudflared is in dependencies)- raise RuntimeError(- 'pycloudflared not installed. This is a bug - '- 'please report to browser-use maintainers.'- )- except Exception as e:- # Network failure, disk full, platform unsupported, etc.- raise RuntimeError(- f'Failed to initialize cloudflared: {e}\n\n'- 'Possible causes:\n'- ' - Network error during download\n'- ' - Insufficient disk space (~20MB needed)\n'- ' - Platform not supported (ARM Mac needs Rosetta 2)\n\n'- 'Workaround - install manually:\n'- ' macOS: brew install cloudflared\n'- ' Linux: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/\n'- ' Windows: winget install Cloudflare.cloudflared\n\n'- 'Then retry: browser-use tunnel <port>'- ) from e+ # Not found+ raise RuntimeError(+ 'cloudflared not installed.\n\n'+ 'Install cloudflared:\n'+ ' macOS: brew install cloudflared\n'+ ' Linux: curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o ~/.local/bin/cloudflared && chmod +x ~/.local/bin/cloudflared\n'+ ' Windows: winget install Cloudflare.cloudflared\n\n'+ 'Or re-run install.sh which installs cloudflared automatically.\n\n'+ 'Then retry: browser-use tunnel <port>'+ )def is_available(self) -> bool:- """Check if cloudflared is available (without triggering download)."""+ """Check if cloudflared is available."""if self._binary_path:return Truereturn shutil.which('cloudflared') is not Nonedef get_status(self) -> dict[str, Any]:"""Get tunnel capability status for doctor command."""- if self._installation_status == 'system':- return {- 'available': True,- 'source': 'system',- 'path': self._binary_path,- 'note': 'Using system cloudflared (user installed)',- }- elif self._installation_status == 'pycloudflared':- return {- 'available': True,- 'source': 'pycloudflared',- 'path': self._binary_path,- 'note': 'Auto-downloaded from Cloudflare releases',- }-- # Not yet initialized - check what would happensystem_binary = shutil.which('cloudflared')if system_binary:return {'available': True,- 'source': 'system (not yet used)',+ 'source': 'system','path': system_binary,- 'note': 'Will use system cloudflared',+ 'note': 'cloudflared installed',}- # Would auto-download on first tunnelreturn {- 'available': True,- 'source': 'pycloudflared (will auto-download)',+ 'available': False,+ 'source': None,'path': None,- 'note': 'Will download on first tunnel (~20MB, one-time)',+ 'note': 'cloudflared not installed - run install.sh or install manually',}diff --git a/install.sh b/install.shindex f1e898849..5fa1834a7 100755--- a/install.sh+++ b/install.sh@@ -170,7 +170,11 @@ install_browser_use() {if [ -n "$BROWSER_USE_BRANCH" ]; thenBROWSER_USE_REPO="${BROWSER_USE_REPO:-ShawnPana/browser-use}"log_info "Installing from GitHub: $BROWSER_USE_REPO@$BROWSER_USE_BRANCH"- uv pip install "git+https://github.com/$BROWSER_USE_REPO@$BROWSER_USE_BRANCH"+ # Clone and install locally to ensure all dependencies are resolved+ local tmp_dir=$(mktemp -d)+ git clone --depth 1 --branch "$BROWSER_USE_BRANCH" "https://github.com/$BROWSER_USE_REPO.git" "$tmp_dir"+ uv pip install "$tmp_dir"+ rm -rf "$tmp_dir"elseuv pip install browser-usefi@@ -178,10 +182,62 @@ install_browser_use() {log_success "browser-use installed"}+# Install cloudflared for tunneling+install_cloudflared() {+ log_info "Installing cloudflared..."++ if command -v cloudflared &> /dev/null; then+ log_success "cloudflared already installed"+ return 0+ fi++ local arch=$(uname -m)++ case "$PLATFORM" in+ macos)+ if command -v brew &> /dev/null; then+ brew install cloudflared+ else+ # Direct download for macOS without Homebrew+ if [ "$arch" = "arm64" ]; then+ curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64.tgz -o /tmp/cloudflared.tgz+ else+ curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-amd64.tgz -o /tmp/cloudflared.tgz+ fi+ tar -xzf /tmp/cloudflared.tgz -C "$HOME/.local/bin/"+ rm /tmp/cloudflared.tgz+ fi+ ;;+ linux)+ mkdir -p "$HOME/.local/bin"+ if [ "$arch" = "aarch64" ] || [ "$arch" = "arm64" ]; then+ curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64 -o "$HOME/.local/bin/cloudflared"+ else+ curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o "$HOME/.local/bin/cloudflared"+ fi+ chmod +x "$HOME/.local/bin/cloudflared"+ ;;+ windows)+ log_warn "Please install cloudflared manually: winget install Cloudflare.cloudflared"+ return 0+ ;;+ esac++ # Add ~/.local/bin to PATH for current session+ export PATH="$HOME/.local/bin:$PATH"++ if command -v cloudflared &> /dev/null; then+ log_success "cloudflared installed successfully"+ else+ log_warn "cloudflared installation failed. You can install it manually later."+ fi+}+# Add to PATH permanentlyconfigure_path() {local shell_rc=""local bin_path="$HOME/.browser-use-env/bin"+ local local_bin="$HOME/.local/bin"# Detect shellif [ -n "$BASH_VERSION" ]; then@@ -198,10 +254,10 @@ configure_path() {return 0fi- # Add to shell config+ # Add to shell config (includes ~/.local/bin for cloudflared)echo "" >> "$shell_rc"echo "# Browser-Use" >> "$shell_rc"- echo "export PATH=\"$bin_path:\$PATH\"" >> "$shell_rc"+ echo "export PATH=\"$bin_path:$local_bin:\$PATH\"" >> "$shell_rc"log_success "Added to PATH in $shell_rc"log_warn "Restart your shell or run: source $shell_rc"@@ -305,16 +361,19 @@ main() {# Step 4: Install browser-useinstall_browser_use- # Step 5: Configure PATH+ # Step 5: Install cloudflared (for tunneling)+ install_cloudflared++ # Step 6: Configure PATHconfigure_path- # Step 6: Run setup wizard+ # Step 7: Run setup wizardrun_setup "$@"- # Step 7: Validate+ # Step 8: Validatevalidate- # Step 8: Show next steps+ # Step 9: Show next stepsprint_next_steps}diff --git a/pyproject.toml b/pyproject.tomlindex 964dfa0de..396faf92c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -48,7 +48,6 @@ dependencies = ["markdownify>=1.2.0","python-docx>=1.2.0","browser-use-sdk>=2.0.12",- "pycloudflared>=0.3.0",]# google-api-core: only used for Google LLM APIs# pyperclip: only used for examples that use copy/pastediff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.mdindex 8850e0ef8..ada3f58ba 100644--- a/skills/remote-browser/SKILL.md+++ b/skills/remote-browser/SKILL.md@@ -15,7 +15,7 @@ This skill is for agents running on **sandboxed remote machines** (cloud VMs, CIcurl -fsSL https://raw.githubusercontent.com/ShawnPana/browser-use/frictionless-install/install.sh | BROWSER_USE_BRANCH=frictionless-install bash```-This installs Python, uv, browser-use CLI, and validates the setup automatically.+This installs Python, uv, browser-use CLI, cloudflared (for tunneling), and validates the setup automatically.**Option 2: Manual install**```bash@@ -24,6 +24,16 @@ pip install "git+https://github.com/ShawnPana/browser-use@frictionless-install"# For production (once released):# pip install "browser-use[cli]"++# Install cloudflared for tunneling (required for browser-use tunnel command):+# macOS:+brew install cloudflared++# Linux:+curl -L https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 -o ~/.local/bin/cloudflared && chmod +x ~/.local/bin/cloudflared++# Windows:+winget install Cloudflare.cloudflared```**Then configure your API key:**@@ -76,7 +86,7 @@ browser-use tunnel stop <port> # Stop tunnelbrowser-use close # Closing session stops all tunnels```-Cloudflared auto-installs on first tunnel use (~20MB one-time download).+Cloudflared is installed by `install.sh`. If missing, install manually (see Setup section).## Commands@@ -224,7 +234,8 @@ done- Check your API key at https://browser-use.com**Tunnel not working?**-- Cloudflared auto-installs on first use; check network connectivity+- Verify cloudflared is installed: `which cloudflared`+- If missing, install manually (see Setup section) or re-run `install.sh`- `browser-use tunnel list` to check active tunnels- `browser-use tunnel stop <port>` and retrydiff --git a/tests/ci/test_tunnel_manager.py b/tests/ci/test_tunnel_manager.pyindex ff92591ad..a6e8403c7 100644--- a/tests/ci/test_tunnel_manager.py+++ b/tests/ci/test_tunnel_manager.py@@ -1,8 +1,6 @@"""Tests for TunnelManager - cloudflared binary management."""-import shutil-from pathlib import Path-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport pytest@@ -16,11 +14,10 @@ def tunnel_manager():def test_tunnel_manager_system_cloudflared(tunnel_manager):- """Test that system cloudflared is preferred."""+ """Test that system cloudflared is found."""with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):binary_path = tunnel_manager.get_binary_path()assert binary_path == '/usr/local/bin/cloudflared'- assert tunnel_manager._installation_status == 'system'def test_tunnel_manager_caches_result(tunnel_manager):@@ -33,18 +30,12 @@ def test_tunnel_manager_caches_result(tunnel_manager):assert path1 == path2-def test_tunnel_manager_pycloudflared_fallback(tunnel_manager):- """Test that pycloudflared is used when system cloudflared not found."""+def test_tunnel_manager_not_installed(tunnel_manager):+ """Test that RuntimeError is raised when cloudflared not found."""with patch('shutil.which', return_value=None):- # Mock the pycloudflared module- mock_cloudflared_path = MagicMock(return_value=Path('/home/user/.cache/pycloudflared/cloudflared'))- mock_module = MagicMock()- mock_module.cloudflared_path = mock_cloudflared_path-- with patch.dict('sys.modules', {'pycloudflared': mock_module}):- binary_path = tunnel_manager.get_binary_path()- assert str(binary_path) == '/home/user/.cache/pycloudflared/cloudflared'- assert tunnel_manager._installation_status == 'pycloudflared'+ with pytest.raises(RuntimeError) as exc_info:+ tunnel_manager.get_binary_path()+ assert 'cloudflared not installed' in str(exc_info.value)def test_tunnel_manager_is_available_cached(tunnel_manager):@@ -65,23 +56,22 @@ def test_tunnel_manager_is_available_not_found(tunnel_manager):assert tunnel_manager.is_available() is False-def test_tunnel_manager_status_system(tunnel_manager):- """Test get_status returns correct info for system cloudflared."""+def test_tunnel_manager_status_installed(tunnel_manager):+ """Test get_status returns correct info when cloudflared installed."""with patch('shutil.which', return_value='/usr/local/bin/cloudflared'):- tunnel_manager.get_binary_path() # Initializestatus = tunnel_manager.get_status()assert status['available'] is Trueassert status['source'] == 'system'assert status['path'] == '/usr/local/bin/cloudflared'-def test_tunnel_manager_status_not_initialized(tunnel_manager):- """Test get_status before initialization."""+def test_tunnel_manager_status_not_installed(tunnel_manager):+ """Test get_status when cloudflared not installed."""with patch('shutil.which', return_value=None):status = tunnel_manager.get_status()- assert status['available'] is True- assert 'pycloudflared' in status['source']- assert 'download' in status['note']+ assert status['available'] is False+ assert status['source'] is None+ assert 'not installed' in status['note']def test_get_tunnel_manager_singleton():