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
better remote session management
Gregor Žunič5fc3a428c7b0
diff --git a/browser_use/skill_cli/README.md b/browser_use/skill_cli/README.mdindex 359521548..4b54c6449 100644--- a/browser_use/skill_cli/README.md+++ b/browser_use/skill_cli/README.md@@ -123,6 +123,8 @@ browser-use python --file script.py # Run Python file| `--json` | Output as JSON || `--api-key KEY` | Override API key |+**Session behavior**: All commands without `--session` use the same "default" session. The browser stays open and is reused across commands. Use `--session NAME` to run multiple browsers in parallel.+## Examples### Fill a Formdiff --git a/browser_use/skill_cli/__init__.py b/browser_use/skill_cli/__init__.pyindex 7c45f5652..49b3c444a 100644--- a/browser_use/skill_cli/__init__.py+++ b/browser_use/skill_cli/__init__.py@@ -12,6 +12,13 @@ Usage:browser-use close"""-from browser_use.skill_cli.main import main-__all__ = ['main']+++def __getattr__(name: str):+ """Lazy import to avoid runpy warnings when running as module."""+ if name == 'main':+ from browser_use.skill_cli.main import main++ return main+ raise AttributeError(f'module {__name__!r} has no attribute {name!r}')diff --git a/browser_use/skill_cli/commands/session.py b/browser_use/skill_cli/commands/session.pyindex ded333428..eb05d4ecc 100644--- a/browser_use/skill_cli/commands/session.py+++ b/browser_use/skill_cli/commands/session.py@@ -11,7 +11,7 @@ logger = logging.getLogger(__name__)COMMANDS = {'sessions', 'close'}-async def handle(action: str, registry: 'SessionRegistry', params: dict[str, Any]) -> Any:+async def handle(action: str, session_name: str, registry: 'SessionRegistry', params: dict[str, Any]) -> Any:"""Handle session management command."""if action == 'sessions':sessions = registry.list_sessions()@@ -31,9 +31,8 @@ async def handle(action: str, registry: 'SessionRegistry', params: dict[str, Any'_shutdown': True, # Signal to stop server}else:- # Close current session and signal shutdown- name = params.get('session', 'default')- await registry.close_session(name)- return {'closed': name, '_shutdown': True}+ # Close this server's session and shutdown+ await registry.close_session(session_name)+ return {'closed': session_name, '_shutdown': True}raise ValueError(f'Unknown session action: {action}')diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.pyindex db8b289e8..b3dc5758f 100755--- a/browser_use/skill_cli/main.py+++ b/browser_use/skill_cli/main.py@@ -204,6 +204,7 @@ Examples:# open <url>p = subparsers.add_parser('open', help='Navigate to URL')p.add_argument('url', help='URL to navigate to')+ p.add_argument('--headed', action='store_true', help='Show browser window')# click <index>p = subparsers.add_parser('click', help='Click element by index')@@ -347,12 +348,12 @@ def main() -> int:if args.command == 'server':return handle_server_command(args)- # Handle sessions list (may need to check multiple sessions)+ # Handle sessions list - find all running sessionsif args.command == 'sessions':- # For now, just check the current session- sessions = []- if is_server_running(args.session):- sessions.append({'name': args.session, 'status': 'running'})+ from browser_use.skill_cli.utils import find_all_sessions++ session_names = find_all_sessions()+ sessions = [{'name': name, 'status': 'running'} for name in session_names]if args.json:print(json.dumps(sessions))@@ -364,6 +365,29 @@ def main() -> int:print('No active sessions')return 0+ # Handle close --all by closing all running sessions+ if args.command == 'close' and getattr(args, 'all', False):+ from browser_use.skill_cli.utils import find_all_sessions++ session_names = find_all_sessions()+ closed = []+ for name in session_names:+ try:+ response = send_command(name, 'close', {})+ if response.get('success'):+ closed.append(name)+ except Exception:+ pass # Server may already be stopping++ if args.json:+ print(json.dumps({'closed': closed, 'count': len(closed)}))+ else:+ if closed:+ print(f'Closed {len(closed)} session(s): {", ".join(closed)}')+ else:+ print('No active sessions')+ return 0+# Set API key in environment if providedif args.api_key:os.environ['BROWSER_USE_API_KEY'] = args.api_keydiff --git a/browser_use/skill_cli/server.py b/browser_use/skill_cli/server.pyindex b85d0a94a..442ae87ed 100644--- a/browser_use/skill_cli/server.py+++ b/browser_use/skill_cli/server.py@@ -110,7 +110,7 @@ class SessionServer:# Session commands don't need a browser sessionif action in session.COMMANDS:- result = await session.handle(action, self.registry, params)+ result = await session.handle(action, self.session_name, self.registry, params)# Check if command wants to shutdown serverif result.get('_shutdown'):asyncio.create_task(self.shutdown())diff --git a/browser_use/skill_cli/utils.py b/browser_use/skill_cli/utils.pyindex 34371f495..bfc45ba64 100644--- a/browser_use/skill_cli/utils.py+++ b/browser_use/skill_cli/utils.py@@ -47,6 +47,18 @@ def is_server_running(session: str) -> bool:return False+def find_all_sessions() -> list[str]:+ """Find all running browser-use sessions by scanning PID files."""+ sessions = []+ tmpdir = Path(tempfile.gettempdir())+ for pid_file in tmpdir.glob('browser-use-*.pid'):+ # Extract session name from filename: browser-use-{session}.pid+ name = pid_file.stem.replace('browser-use-', '', 1)+ if is_server_running(name):+ sessions.append(name)+ return sessions++def cleanup_session_files(session: str) -> None:"""Remove session socket and PID files."""sock_path = get_socket_path(session)diff --git a/pyproject.toml b/pyproject.tomlindex 560c66b9c..e33af63ca 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -93,6 +93,7 @@ Repository = "https://github.com/browser-use/browser-use"[project.scripts]browser-use = "browser_use.skill_cli.main:main" # Fast CLI for browser automation+browseruse = "browser_use.skill_cli.main:main" # Alias for browser-usebu = "browser_use.skill_cli.main:main" # Alias for browser-usebrowser = "browser_use.skill_cli.main:main" # Alias for browser-usebrowser-use-tui = "browser_use.cli:main" # Legacy TUI interfacediff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.mdindex 24784f783..40cd3cc19 100644--- a/skills/browser-use/SKILL.md+++ b/skills/browser-use/SKILL.md@@ -134,6 +134,8 @@ browser-use server logs # View server logs| `--json` | Output as JSON || `--api-key KEY` | Override API key |+**Session behavior**: All commands without `--session` use the same "default" session. The browser stays open and is reused across commands. Use `--session NAME` to run multiple browsers in parallel.+## Examples### Form Submission