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(cli): make tunnel command independent of browser sessions
ShawnPana94c336407d37
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex 9af7ee953..a97c3eb35 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -1280,28 +1280,62 @@ def main() -> int:print('⚠ Some checks failed. See details above.')return 0- # Handle tunnel subcommand parsing+ # Handle tunnel command - runs independently of browser sessionif args.command == 'tunnel':+ from browser_use.skill_cli import tunnel_manager+pos = getattr(args, 'port_or_subcommand', None)+if pos == 'list':- params = {'subcommand': 'list'}+ result = tunnel_manager.list_tunnels()elif pos == 'stop':port_arg = getattr(args, 'port_arg', None)if port_arg is None:- print('Usage: browser-use tunnel stop <port>', file=sys.stderr)- return 1- params = {'subcommand': 'stop', 'port': port_arg}+ # Check if it's 'stop --all'+ if '--all' in sys.argv:+ result = asyncio.get_event_loop().run_until_complete(tunnel_manager.stop_all_tunnels())+ else:+ print('Usage: browser-use tunnel stop <port>', file=sys.stderr)+ return 1+ else:+ result = asyncio.get_event_loop().run_until_complete(tunnel_manager.stop_tunnel(port_arg))elif pos is not None:try:port = int(pos)except ValueError:print(f'Unknown tunnel subcommand: {pos}', file=sys.stderr)return 1- params = {'subcommand': 'start', 'port': port}+ result = asyncio.get_event_loop().run_until_complete(tunnel_manager.start_tunnel(port))else:print('Usage: browser-use tunnel <port> | list | stop <port>', file=sys.stderr)return 0+ # Output result+ if args.json:+ print(json.dumps(result))+ else:+ if 'error' in result:+ print(f'Error: {result["error"]}', file=sys.stderr)+ return 1+ elif 'url' in result:+ existing = ' (existing)' if result.get('existing') else ''+ print(f'url: {result["url"]}{existing}')+ elif 'tunnels' in result:+ if result['tunnels']:+ for t in result['tunnels']:+ print(f' port {t["port"]}: {t["url"]}')+ else:+ print('No active tunnels')+ elif 'stopped' in result:+ if isinstance(result['stopped'], list):+ if result['stopped']:+ print(f'Stopped {len(result["stopped"])} tunnel(s): {", ".join(map(str, result["stopped"]))}')+ else:+ print('No tunnels to stop')+ else:+ print(f'Stopped tunnel on port {result["stopped"]}')+ return 0+# Set API key in environment if providedif args.api_key:os.environ['BROWSER_USE_API_KEY'] = args.api_key@@ -1321,14 +1355,13 @@ def main() -> int:# Ensure server is runningensure_server(args.session, args.browser, args.headed, args.profile, args.api_key)- # Build params from args (unless already built for tunnel)- if args.command != 'tunnel':- params = {}- skip_keys = {'command', 'session', 'browser', 'headed', 'profile', 'json', 'api_key', 'server_command'}+ # Build params from args+ params = {}+ skip_keys = {'command', 'session', 'browser', 'headed', 'profile', 'json', 'api_key', 'server_command'}- for key, value in vars(args).items():- if key not in skip_keys and value is not None:- params[key] = value+ for key, value in vars(args).items():+ if key not in skip_keys and value is not None:+ params[key] = value# Send command to serverresponse = send_command(args.session, args.command, params)diff --git a/browser_use/skill_cli/sessions.py b/browser_use/skill_cli/sessions.pyindex 57cceee70..6b94311b9 100644--- a/browser_use/skill_cli/sessions.py+++ b/browser_use/skill_cli/sessions.py@@ -93,14 +93,8 @@ class SessionRegistry:session = self._sessions.pop(name)logger.info(f'Closing session: {name}')- # Stop all tunnels first- if session.tunnels:- from browser_use.skill_cli.commands.tunnel import stop_all_tunnels-- try:- await stop_all_tunnels(session)- except Exception as e:- logger.warning(f'Error stopping tunnels for session {name}: {e}')+ # Note: Tunnels are now managed independently via tunnel_manager.py+ # They persist across session close/open cyclestry:await session.browser_session.kill()diff --git a/browser_use/skill_cli/tunnel_manager.py b/browser_use/skill_cli/tunnel_manager.pyindex 71db6fffc..98bda7870 100644--- a/browser_use/skill_cli/tunnel_manager.py+++ b/browser_use/skill_cli/tunnel_manager.py@@ -2,14 +2,36 @@This module manages the cloudflared binary for tunnel support.Cloudflared must be installed via install.sh or manually by the user.++Tunnels are managed independently of browser sessions - they are purely+a network utility for exposing local ports via Cloudflare quick tunnels."""+import asyncioimport logging+import reimport shutil+from dataclasses import dataclassfrom typing import Anylogger = logging.getLogger(__name__)+# Pattern to extract tunnel URL from cloudflared output+_URL_PATTERN = re.compile(r'(https://\S+\.trycloudflare\.com)')+++@dataclass+class TunnelInfo:+ """Information about an active cloudflare tunnel."""++ port: int+ url: str+ process: asyncio.subprocess.Process+++# Module-level storage for running tunnels (independent of browser sessions)+_active_tunnels: dict[int, TunnelInfo] = {}+class TunnelManager:"""Manages cloudflared binary location."""@@ -83,3 +105,119 @@ def get_tunnel_manager() -> TunnelManager:if _tunnel_manager is None:_tunnel_manager = TunnelManager()return _tunnel_manager+++# =============================================================================+# Standalone Tunnel Functions (no browser session required)+# =============================================================================+++async def start_tunnel(port: int) -> dict[str, Any]:+ """Start a cloudflare quick tunnel for a local port.++ Args:+ port: Local port to tunnel++ Returns:+ Dict with 'url' and 'port' on success, or 'error' on failure+ """+ # Check if tunnel already exists for this port+ if port in _active_tunnels:+ info = _active_tunnels[port]+ return {'url': info.url, 'port': port, 'existing': True}++ # Get cloudflared binary+ try:+ tunnel_manager = get_tunnel_manager()+ cloudflared_binary = tunnel_manager.get_binary_path()+ except RuntimeError as e:+ return {'error': str(e)}++ # Spawn cloudflared process+ process = await asyncio.create_subprocess_exec(+ cloudflared_binary,+ 'tunnel',+ '--url',+ f'http://localhost:{port}',+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.PIPE,+ )++ # Read stderr lines until we find the tunnel URL+ assert process.stderr is not None+ url: str | None = None+ try:+ deadline = asyncio.get_event_loop().time() + 15+ while asyncio.get_event_loop().time() < deadline:+ try:+ line_bytes = await asyncio.wait_for(process.stderr.readline(), timeout=1.0)+ except TimeoutError:+ continue+ if not line_bytes:+ break+ line = line_bytes.decode(errors='replace')+ match = _URL_PATTERN.search(line)+ if match:+ url = match.group(1)+ break+ except Exception as e:+ process.terminate()+ return {'error': f'Failed to start tunnel: {e}'}++ if url is None:+ process.terminate()+ return {'error': 'Timed out waiting for cloudflare tunnel URL (15s)'}++ # Store tunnel info+ _active_tunnels[port] = TunnelInfo(port=port, url=url, process=process)+ logger.info(f'Tunnel started: localhost:{port} -> {url}')++ return {'url': url, 'port': port}+++def list_tunnels() -> dict[str, Any]:+ """List active tunnels.++ Returns:+ Dict with 'tunnels' list and 'count'+ """+ tunnels = [{'port': info.port, 'url': info.url} for info in _active_tunnels.values()]+ return {'tunnels': tunnels, 'count': len(tunnels)}+++async def stop_tunnel(port: int) -> dict[str, Any]:+ """Stop a tunnel for a specific port.++ Args:+ port: Port number to stop tunnel for++ Returns:+ Dict with 'stopped' port and 'url' on success, or 'error'+ """+ if port not in _active_tunnels:+ return {'error': f'No tunnel running on port {port}'}++ info = _active_tunnels.pop(port)+ info.process.terminate()+ try:+ await asyncio.wait_for(info.process.wait(), timeout=5)+ except TimeoutError:+ info.process.kill()+ logger.info(f'Tunnel stopped: localhost:{port}')++ return {'stopped': port, 'url': info.url}+++async def stop_all_tunnels() -> dict[str, Any]:+ """Stop all active tunnels.++ Returns:+ Dict with 'stopped' list of ports+ """+ stopped = []+ for port in list(_active_tunnels.keys()):+ result = await stop_tunnel(port)+ if 'stopped' in result:+ stopped.append(port)++ return {'stopped': stopped, 'count': len(stopped)}diff --git a/skills/remote-browser/SKILL.md b/skills/remote-browser/SKILL.mdindex 6d1b83d5d..f59a9a618 100644--- a/skills/remote-browser/SKILL.md+++ b/skills/remote-browser/SKILL.md@@ -116,9 +116,11 @@ browser-use tunnel <port> # Start tunnel (returns URL)browser-use tunnel <port> # Idempotent - returns existing URLbrowser-use tunnel list # Show active tunnelsbrowser-use tunnel stop <port> # Stop tunnel-browser-use close # Closing session stops all tunnels+browser-use tunnel stop --all # Stop all tunnels```+**Note:** Tunnels are independent of browser sessions. They persist across `browser-use close` and can be managed separately.+Cloudflared is installed by `install.sh`. If missing, install manually (see Setup section).## Commands@@ -257,9 +259,10 @@ done2. **Don't mix modes** — if you started with local, close first before switching to remote3. **Always run `state` first** to see available elements and their indices4. **Sessions persist** across commands — the browser stays open until you close it-5. **Use `--json`** for programmatic parsing-6. **`tunnel` is idempotent** — calling it again for the same port returns the existing URL-7. **Close when done** — `browser-use close` cleans up browser and tunnels+5. **Tunnels are independent** — they don't require or create a browser session, and persist across `browser-use close`+6. **Use `--json`** for programmatic parsing+7. **`tunnel` is idempotent** — calling it again for the same port returns the existing URL+8. **Close when done** — `browser-use close` closes the browser; `browser-use tunnel stop --all` stops tunnels## Troubleshooting@@ -285,10 +288,11 @@ done## Cleanup-**Always close the browser when done:**+**Close the browser when done:**```bash-browser-use close+browser-use close # Close browser session+browser-use tunnel stop --all # Stop all tunnels (if any)```-This stops all tunnels and releases the cloud browser session.+Browser sessions and tunnels are managed separately, so close each as needed.