Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

chore: Remove auxiliary planning docs

Gregor Žunič08c72f67ba66
diff --git a/CLI_SPEC.md b/CLI_SPEC.md
deleted file mode 100644
index 647cd6a54..000000000
--- a/CLI_SPEC.md
+++ /dev/null
@@ -1,718 +0,0 @@
-# Browser-Use CLI: Complete Implementation Specification
-
-> **Standalone spec for developers** - Everything needed to implement the browser-use CLI with persistent sessions, Python execution, and multi-browser support.
-
----
-
-## Table of Contents
-
-1. [Overview](#overview)
-2. [Architecture Decision: Why NOT a Separate Daemon](#architecture-decision)
-3. [The Correct Architecture: Session Server](#the-correct-architecture)
-4. [Browser Modes](#browser-modes)
-5. [Persistent Python Execution](#persistent-python-execution)
-6. [API Key & Monetization](#api-key--monetization)
-7. [Complete Command List](#complete-command-list)
-8. [Code Structure](#code-structure)
-9. [Implementation Heuristics](#implementation-heuristics)
-10. [Future Work](#future-work)
-
----
-
-## Overview
-
-Build a **fast CLI** (`browser-use`) with:
-
-- **Persistent browser sessions** - Browser stays open between commands
-- **Multiple browser modes** - Chromium, Real Browser (user profile), Remote (Cloud)
-- **Persistent Python execution** - Jupyter-like REPL for scraping/automation
-- **Agent task execution** - Run AI agents on persistent sessions (requires API key)
-- **Claude Code integration** - API for AI assistants to control browsers
-
-### Design Principles
-
-1. **Work WITH BrowserSession, not around it** - No conflicts with existing internals
-2. **CLI must be instant** (<50ms) - Stdlib only in CLI layer
-3. **Promote Browser-Use Cloud** - Remote browsers + proxies = revenue
-4. **Python persistence is a killer feature** - Enable complex automation workflows
-
----
-
-## Architecture Decision
-
-### Why NOT a Separate Daemon?
-
-After analyzing BrowserSession internals, a **separate daemon would cause major conflicts**:
-
-| Conflict Area | Problem |
-|---------------|---------|
-| **Process Ownership** | `LocalBrowserWatchdog` owns the subprocess. Two owners = race conditions on kill/cleanup |
-| **CDP Connection** | Single `_cdp_client_root` per session. Duplicate connections = event chaos |
-| **Event Bus** | 11 watchdogs register handlers. Separate daemon misses critical events |
-| **Session State** | Shared mutable state (focus, cache, downloads). Daemon would cause inconsistencies |
-| **Cleanup** | BrowserSession.kill() stops all handlers. Daemon wouldn't participate |
-
-### The go-rod Launcher Insight
-
-The go-rod launcher is excellent for **spawning browsers and getting CDP URLs**, but browser-use already has this via:
-- `LocalBrowserWatchdog` - Process management
-- `BrowserProfile` - Configuration
-- CDP URL discovery via `/json/version`
-
-**We don't need to replace this. We need to keep BrowserSession instances alive.**
-
----
-
-## The Correct Architecture
-
-### Session Server (Not Daemon)
-
-Instead of a daemon that manages browsers directly, we build a **server that manages BrowserSession instances**:
-
-```
-┌─────────────────────────────────────────────────────────────────────────────┐
-│ FAST CLI │
-│ (stdlib only: <50ms startup) │
-│ │
-│ $ browser-use open https://example.com --session work --browser real │
-│ $ browser-use python "data = browser.scrape('table')" │
-│ $ browser-use run "fill the form" --session work # Requires API key │
-└─────────────────────────────────────────────────────────────────────────────┘
- │
- Unix Socket │ /tmp/browser-use.sock
- ▼
-┌─────────────────────────────────────────────────────────────────────────────┐
-│ SESSION SERVER │
-│ (keeps BrowserSession instances alive) │
-│ │
-│ ┌────────────────────────────────────────────────────────────────────┐ │
-│ │ Session Registry │ │
-│ │ │ │
-│ │ sessions = { │ │
-│ │ "work": { │ │
-│ │ browser_session: BrowserSession, # ← Uses existing class! │ │
-│ │ python_session: PythonSession, # ← Jupyter-like REPL │ │
-│ │ mode: "real", │ │
-│ │ ... │ │
-│ │ } │ │
-│ │ } │ │
-│ └────────────────────────────────────────────────────────────────────┘ │
-│ │
-│ The server USES BrowserSession, doesn't replace it. │
-│ All watchdogs, CDP management, event bus work normally. │
-└─────────────────────────────────────────────────────────────────────────────┘
- │
- │ (BrowserSession handles everything)
- ▼
-┌─────────────────────────────────────────────────────────────────────────────┐
-│ BROWSER │
-│ │
-│ Mode: chromium │ Mode: real │ Mode: remote │
-│ ───────────────── │ ────────────────── │ ───────────────── │
-│ Playwright binary │ User's Chrome │ Browser-Use Cloud │
-│ Temp profile │ Real profile │ CDP via API │
-│ Headless/headed │ With extensions │ Proxies available │
-│ │ Logged-in sessions │ BROWSER_USE_API_KEY req. │
-└─────────────────────────────────────────────────────────────────────────────┘
-```
-
-### Key Insight: BrowserSession Already Does Everything
-
-BrowserSession handles:
-- ✅ Browser process lifecycle (LocalBrowserWatchdog)
-- ✅ CDP connection management (SessionManager)
-- ✅ Event-driven architecture (EventBus + 11 watchdogs)
-- ✅ Crash detection & recovery
-- ✅ Screenshot, DOM, downloads, popups, etc.
-
-**Our job is just to:**
-1. Keep BrowserSession instances in memory (don't let them get garbage collected)
-2. Provide a fast CLI to interact with them
-3. Add Python execution on top
-4. Route commands to the right session
-
----
-
-## Browser Modes
-
-Three browser modes, configured via `--browser` flag:
-
-### 1. Chromium (Default)
-```bash
-browser-use open https://example.com --browser chromium
-browser-use open https://example.com --browser chromium --headed
-```
-
-- Uses Playwright-managed Chromium
-- Fresh profile (isolated)
-- Fast, reliable, headless by default
-- **No API key required**
-
-### 2. Real Browser
-```bash
-browser-use open https://example.com --browser real
-browser-use open https://example.com --browser real --profile "Profile 1"
-```
-
-- Uses user's actual Chrome installation
-- Preserves login sessions, cookies, extensions
-- Great for authenticated workflows
-- See: https://docs.browser-use.com/customize/browser/real-browser
-- **No API key required**
-
-### 3. Remote (Browser-Use Cloud)
-```bash
-browser-use open https://example.com --browser remote
-browser-use open https://example.com --browser remote --proxy residential
-```
-
-- Cloud-hosted browser via Browser-Use API
-- Supports proxies (residential, datacenter)
-- See: https://docs.browser-use.com/customize/browser/remote
-- **Requires BROWSER_USE_API_KEY** ← Revenue!
-
-### Implementation
-
-Maps directly to existing BrowserSession/BrowserProfile:
-
-```python
-def create_browser_session(mode: str, headed: bool, profile: str | None) -> BrowserSession:
- if mode == "chromium":
- return BrowserSession(
- browser_profile=BrowserProfile(headless=not headed)
- )
-
- elif mode == "real":
- # Real browser with user profile
- return BrowserSession(
- browser_profile=BrowserProfile(
- use_own_browser=True,
- chrome_instance_path=find_chrome(), # Auto-detect
- user_data_dir=get_chrome_profile(profile),
- headless=False, # Real browser is always visible
- )
- )
-
- elif mode == "remote":
- require_api_key() # Raises if missing
- return BrowserSession(
- use_cloud=True,
- cloud_config=CloudConfig(
- proxy_type=proxy, # residential, datacenter, none
- )
- )
-```
-
----
-
-## Persistent Python Execution
-
-### The Killer Feature
-
-Inspired by bu-use's `PythonSession`, we add Jupyter-like persistent execution:
-
-```bash
-# Turn 1: Scrape data
-$ browser-use python "products = browser.extract('all product names and prices')"
-
-# Turn 2: Variables persist!
-$ browser-use python "print(len(products))"
-42
-
-# Turn 3: Process and save
-$ browser-use python "
-import json
-with open('products.json', 'w') as f:
- json.dump(products, f)
-"
-
-# Turn 4: Loop through pages (deterministic automation!)
-$ browser-use python "
-for page in range(1, 10):
- browser.click(f'page-{page}')
- data = browser.extract('prices')
- all_data.extend(data)
-"
-```
-
-### Why This is Powerful
-
-1. **Deterministic automation** - Write loops, conditionals in Python
-2. **Data persistence** - Variables survive across commands
-3. **Full Python ecosystem** - pandas, numpy, BeautifulSoup, etc.
-4. **Browser access** - `browser` object provides full control
-5. **Incremental development** - Test code step by step
-
-### Implementation
-
-```python
-@dataclass
-class PythonSession:
- """Jupyter-like persistent Python execution."""
- namespace: dict[str, Any] = field(default_factory=dict)
- execution_count: int = 0
- history: list[ExecutionRecord] = field(default_factory=list)
-
- def __post_init__(self):
- # Pre-populate namespace with useful imports
- self.namespace.update({
- 'json': __import__('json'),
- 're': __import__('re'),
- 'Path': Path,
- # browser object injected per-session
- })
-
- def execute(self, code: str, browser: BrowserSession) -> ExecutionResult:
- """Execute code in persistent namespace."""
- self.namespace['browser'] = BrowserWrapper(browser)
- self.execution_count += 1
-
- # Capture stdout
- stdout = io.StringIO()
- with redirect_stdout(stdout):
- try:
- # Try as expression first (for REPL-like behavior)
- result = eval(code, self.namespace)
- if result is not None:
- print(repr(result))
- except SyntaxError:
- # Execute as statements
- exec(code, self.namespace)
-
- output = stdout.getvalue()
- self.history.append(ExecutionRecord(code, output))
- return ExecutionResult(success=True, output=output)
-```
-
-### BrowserWrapper
-
-Provides convenient methods for Python code:
-
-```python
-class BrowserWrapper:
- """Convenient browser access for Python code."""
-
- def __init__(self, session: BrowserSession):
- self.session = session
-
- @property
- def url(self) -> str:
- return self.session.current_url
-
- @property
- def title(self) -> str:
- return self.session.title
-
- def goto(self, url: str):
- """Navigate to URL."""
- asyncio.run(self.session.navigate(url))
-
- def click(self, selector_or_index: str | int):
- """Click element by selector or index."""
- asyncio.run(self.session.click(selector_or_index))
-
- def type(self, text: str, selector: str | int | None = None):
- """Type text into element."""
- asyncio.run(self.session.type(text, selector))
-
- def extract(self, query: str) -> Any:
- """Extract structured data using LLM."""
- # Uses the existing extract tool
- asyncio.run(self.session.extract(query))
-
- def screenshot(self) -> bytes:
- """Take screenshot, return bytes."""
- return asyncio.run(self.session.screenshot())
-
- @property
- def html(self) -> str:
- """Get page HTML."""
- return asyncio.run(self.session.get_html())
-
- @property
- def text(self) -> str:
- """Get page text content."""
- return asyncio.run(self.session.get_text())
-```
-
----
-
-## API Key & Monetization
-
-### Strategy
-
-1. **Free tier** - Chromium and Real browser modes work without API key
-2. **Paid features** - Remote browsers, proxies, and **agent tasks** require API key
-3. **Easy injection** - Multiple ways to provide key
-
-### When API Key is Required
-
-| Feature | API Key Required? |
-|---------|-------------------|
-| `--browser chromium` | No |
-| `--browser real` | No |
-| `--browser remote` | **Yes** |
-| `browser-use run "<task>"` (agent) | **Yes** |
-| `browser-use python "..."` | No |
-| Direct browser control (click, type, etc.) | No |
-
-### API Key Injection (Easy for Users)
-
-**Option 1: Environment variable** (recommended)
-```bash
-export BROWSER_USE_API_KEY=your_key_here
-browser-use run "fill the form"
-```
-
-**Option 2: Config file** (`~/.config/browser-use/config.json`)
-```json
-{
- "api_key": "your_key_here"
-}
-```
-
-**Option 3: CLI flag** (one-time)
-```bash
-browser-use run "fill the form" --api-key your_key_here
-```
-
-**Option 4: Interactive prompt** (first-time setup)
-```bash
-$ browser-use run "fill the form"
-
-╭─────────────────────────────────────────────────────────────╮
-│ 🔑 Browser-Use API Key Required │
-│ │
-│ Agent tasks require an API key. │
-│ Get yours at: https://browser-use.com/dashboard │
-│ │
-│ Enter API key: ________________________________________ │
-│ │
-│ [ ] Save to ~/.config/browser-use/config.json │
-╰─────────────────────────────────────────────────────────────╯
-```
-
-### Implementation
-
-```python
-def require_api_key(feature: str = "this feature") -> str:
- """Get API key or raise helpful error."""
-
- # 1. Check environment
- key = os.environ.get("BROWSER_USE_API_KEY")
- if key:
- return key
-
- # 2. Check config file
- config_path = Path.home() / ".config" / "browser-use" / "config.json"
- if config_path.exists():
- config = json.loads(config_path.read_text())
- if key := config.get("api_key"):
- return key
-
- # 3. Interactive prompt (if TTY)
- if sys.stdin.isatty():
- return prompt_for_api_key(feature)
-
- # 4. Error with helpful message
- raise APIKeyRequired(f"""
-╭─────────────────────────────────────────────────────────────╮
-│ 🔑 Browser-Use API Key Required │
-│ │
-│ {feature} requires an API key. │
-│ │
-│ Get yours at: https://browser-use.com/dashboard │
-│ │
-│ Then set it via: │
-│ export BROWSER_USE_API_KEY=your_key_here │
-│ │
-│ Or add to ~/.config/browser-use/config.json: │
-│ {{"api_key": "your_key_here"}} │
-╰─────────────────────────────────────────────────────────────╯
-""")
-```
-
----
-
-## Complete Command List
-
-### Browser Control
-
-| Command | Description | API Key? |
-|---------|-------------|----------|
-| `open <url>` | Navigate to URL | No |
-| `click <index>` | Click element | No |
-| `type <text>` | Type text | No |
-| `input <index> <text>` | Type into element | No |
-| `scroll [up\|down]` | Scroll page | No |
-| `back` | Go back | No |
-| `screenshot` | Take screenshot | No |
-| `state` | Get browser state | No |
-| `switch <tab>` | Switch tab | No |
-| `close-tab <tab>` | Close tab | No |
-| `keys <keys>` | Send keys | No |
-| `select <index> <text>` | Select dropdown | No |
-| `eval <js>` | Execute JS | No |
-| `extract <query>` | Extract data (LLM) | No |
-
-### Python Execution
-
-| Command | Description | API Key? |
-|---------|-------------|----------|
-| `python "<code>"` | Execute Python | No |
-| `python --file script.py` | Run Python file | No |
-| `python --reset` | Clear namespace | No |
-| `python --vars` | Show variables | No |
-
-### Agent Tasks
-
-| Command | Description | API Key? |
-|---------|-------------|----------|
-| `run "<task>"` | Run agent task | **Yes** |
-| `run --max-steps N` | Limit steps | **Yes** |
-
-### Session Management
-
-| Command | Description | API Key? |
-|---------|-------------|----------|
-| `sessions` | List sessions | No |
-| `close [--session X]` | Close session | No |
-| `close --all` | Close all | No |
-
-### Server Control
-
-| Command | Description |
-|---------|-------------|
-| `server status` | Check server |
-| `server stop` | Stop server |
-| `server logs` | View logs |
-
-### Global Flags
-
-| Flag | Description | Default |
-|------|-------------|---------|
-| `--session NAME` | Session name | `"default"` |
-| `--browser MODE` | chromium/real/remote | `"chromium"` |
-| `--headed` | Show browser | `false` |
-| `--profile NAME` | Chrome profile (real mode) | Default profile |
-| `--proxy TYPE` | Proxy type (remote mode) | `none` |
-| `--api-key KEY` | API key override | From env/config |
-| `--json` | JSON output | `false` |
-
----
-
-## Code Structure
-
-```
-browser_use/cli/
-├── __init__.py
-├── __main__.py # Entry: python -m browser_use.cli
-│
-├── main.py # Fast CLI (STDLIB ONLY!)
-│ ├── Argument parsing
-│ ├── ensure_server()
-│ ├── send_command()
-│ └── main()
-│
-├── server.py # Session server
-│ ├── SessionServer class
-│ ├── Socket server (asyncio)
-│ ├── Command dispatch
-│ └── Graceful shutdown
-│
-├── sessions.py # Session registry
-│ ├── SessionInfo dataclass
-│ ├── SessionRegistry class
-│ ├── create_browser_session()
-│ └── Health checks
-│
-├── commands/ # Command handlers
-│ ├── __init__.py
-│ ├── browser.py # open, click, type, etc.
-│ ├── python_exec.py # python command
-│ ├── agent.py # run command (requires API key)
-│ └── session.py # sessions, close
-│
-├── python_session.py # Jupyter-like REPL
-│ ├── PythonSession class
-│ ├── BrowserWrapper class
-│ └── execute()
-│
-├── api_key.py # API key management
-│ ├── require_api_key()
-│ ├── prompt_for_api_key()
-│ └── save_api_key()
-│
-├── protocol.py # Message types
-│ ├── Request/Response
-│ └── Serialization
-│
-└── utils.py # Helpers
- ├── Platform detection
- └── Path utilities
-```
-
-### pyproject.toml Entry Point
-
-```toml
-[project.scripts]
-browser-use = "browser_use.cli.main:main"
-```
-
----
-
-## Implementation Heuristics
-
-### 1. CLI Speed is Sacred
-
-**Rule**: The CLI file (`main.py`) must ONLY use stdlib imports.
-
-```python
-# ✅ GOOD - stdlib only
-import argparse, json, os, socket, subprocess, sys, time
-
-# ❌ BAD - external imports
-import click # NO!
-import rich # NO!
-from browser_use import ... # NO!
-```
-
-All heavy imports go in the server, which loads once and stays running.
-
-### 2. BrowserSession is the Source of Truth
-
-**Rule**: Never bypass BrowserSession. Always use its methods.
-
-```python
-# ✅ GOOD - use BrowserSession
-session.browser_session.navigate(url)
-await session.browser_session.click(index)
-
-# ❌ BAD - direct CDP calls
-cdp_client.send("Page.navigate", {"url": url}) # NO!
-```
-
-This ensures all watchdogs, events, and state stay in sync.
-
-### 3. Promote Cloud Browsers Naturally
-
-**Rule**: When remote features are needed, guide users to Browser-Use Cloud.
-
-```python
-# When user needs proxy
-if needs_proxy and mode != "remote":
- print("💡 Tip: For proxy support, use --browser remote")
- print(" Get API key at: https://browser-use.com/dashboard")
-
-# When agent task fails due to blocks
-if blocked_by_captcha:
- print("💡 Tip: Browser-Use Cloud includes CAPTCHA solving")
- print(" Try: browser-use run '...' --browser remote")
-```
-
-### 4. Python Session Isolation
-
-**Rule**: Each named session has its own Python namespace.
-
-```bash
-# Session "work" has its own variables
-browser-use python "x = 1" --session work
-
-# Session "personal" is isolated
-browser-use python "print(x)" --session personal # Error: x not defined
-```
-
-### 5. Graceful Degradation
-
-**Rule**: Always clean up resources, even on crash.
-
-```python
-# Server shutdown
-async def shutdown(self):
- for session in self.registry.all():
- try:
- await session.browser_session.stop()
- except:
- pass # Browser might already be dead
-
- # Remove socket/PID files
- cleanup_files()
-```
-
-### 6. Error Messages Should Help
-
-**Rule**: Every error should tell the user what to do next.
-
-```python
-# ❌ BAD
-raise Exception("API key missing")
-
-# ✅ GOOD
-raise APIKeyRequired("""
-API key required for agent tasks.
-Get yours at: https://browser-use.com/dashboard
-Set via: export BROWSER_USE_API_KEY=your_key
-""")
-```
-
-### 7. Session Auto-Creation
-
-**Rule**: Sessions are created on-demand, not explicitly.
-
-```bash
-# This creates session "work" if it doesn't exist
-browser-use open https://example.com --session work
-
-# No need for explicit "create session" command
-```
-
-### 8. Default to Headless
-
-**Rule**: Chromium mode defaults to headless for speed/resources.
-
-```bash
-browser-use open https://example.com # Headless
-browser-use open https://example.com --headed # Visible
-browser-use open https://example.com --browser real # Always visible
-```
-
----
-
-## Future Work
-
-### From CodeAgent/BU Agent
-- **Background shell processes** - `bash` with persistent shells
-- **File operations** - `read`, `write`, `edit`, `glob`, `grep`
-- **Todo tracking** - Task progress management
-- **Context compaction** - Auto-compress long conversations
-
-### From agent-browser
-- **Live streaming** - Stream browser view to terminal
-- **Screencast recording** - Record sessions as video
-- **Multiple browser types** - Firefox, WebKit support
-
-### From browser-use
-- **Skills integration** - Load automation skills from API
-- **Storage persistence** - Save/restore cookies across server restarts
-- **Download management** - Track and organize downloads
-
-### New Features
-- **Session snapshots** - Save/restore full browser state
-- **Event replay** - Record and replay automation sequences
-- **HTTP API** - REST endpoint for programmatic access
-- **Watch mode** - Re-run Python on file changes
-- **Notebook export** - Export Python session as .ipynb
-
----
-
-## Success Criteria
-
-- [ ] `browser-use open <url>` works with <50ms CLI startup
-- [ ] All three browser modes work (chromium, real, remote)
-- [ ] Python execution persists variables across commands
-- [ ] Agent tasks require and validate API key
-- [ ] API key prompt is user-friendly
-- [ ] Sessions are isolated and named
-- [ ] Server integrates cleanly with BrowserSession (no conflicts)
-- [ ] Graceful shutdown cleans all resources
-- [ ] Works on macOS, Linux, Windows
diff --git a/browser_use/skill_cli/IMPLEMENTATION_PLAN.md b/browser_use/skill_cli/IMPLEMENTATION_PLAN.md
deleted file mode 100644
index 663dc4546..000000000
--- a/browser_use/skill_cli/IMPLEMENTATION_PLAN.md
+++ /dev/null
@@ -1,916 +0,0 @@
-# Browser-Use CLI Implementation Plan
-
-## Overview
-
-This document outlines the implementation plan for the browser-use CLI as specified in CLI_SPEC.md.
-
-## Architecture Summary
-
-```
-┌─────────────────────────────────────────────────────────────────────────────┐
-│ FAST CLI (main.py) │
-│ (stdlib only: <50ms startup) │
-│ │
-│ $ browser-use open https://example.com --session work --browser real │
-│ $ browser-use python "data = browser.scrape('table')" │
-│ $ browser-use run "fill the form" --session work # Requires API key │
-└─────────────────────────────────────────────────────────────────────────────┘
- │
- Unix Socket │ /tmp/browser-use-{session}.sock
- ▼
-┌─────────────────────────────────────────────────────────────────────────────┐
-│ SESSION SERVER (server.py) │
-│ (keeps BrowserSession instances alive) │
-└─────────────────────────────────────────────────────────────────────────────┘
-```
-
-## File Structure
-
-```
-browser_use/cli/
-├── __init__.py # Package init, expose main()
-├── __main__.py # Entry: python -m browser_use.cli
-│
-├── main.py # Fast CLI (STDLIB ONLY!)
-│ ├── Argument parsing (argparse)
-│ ├── ensure_server()
-│ ├── send_command()
-│ └── main()
-│
-├── server.py # Session server
-│ ├── SessionServer class
-│ ├── Socket server (asyncio)
-│ ├── Command dispatch
-│ └── Graceful shutdown
-│
-├── sessions.py # Session registry
-│ ├── SessionInfo dataclass
-│ ├── SessionRegistry class
-│ ├── create_browser_session()
-│ └── Health checks
-│
-├── commands/ # Command handlers
-│ ├── __init__.py
-│ ├── browser.py # open, click, type, etc.
-│ ├── python_exec.py # python command
-│ ├── agent.py # run command (requires API key)
-│ └── session.py # sessions, close
-│
-├── python_session.py # Jupyter-like REPL
-│ ├── PythonSession class
-│ ├── BrowserWrapper class
-│ └── execute()
-│
-├── api_key.py # API key management
-│ ├── require_api_key()
-│ ├── prompt_for_api_key()
-│ └── save_api_key()
-│
-├── protocol.py # Message types
-│ ├── Request/Response
-│ └── Serialization
-│
-└── utils.py # Helpers
- ├── Platform detection
- └── Path utilities
-```
-
-## Implementation Order
-
-### Phase 1: Core Infrastructure
-1. `protocol.py` - Message types for CLI↔Server communication
-2. `utils.py` - Platform detection, socket paths, PID files
-3. `main.py` - Fast CLI layer (stdlib only)
-4. `server.py` - Basic socket server
-
-### Phase 2: Session Management
-5. `sessions.py` - Session registry
-6. `api_key.py` - API key handling
-
-### Phase 3: Commands
-7. `commands/browser.py` - Basic browser control (open, click, type, etc.)
-8. `commands/session.py` - Session management
-9. `commands/python_exec.py` - Python execution
-10. `commands/agent.py` - Agent tasks
-
-### Phase 4: Python Execution
-11. `python_session.py` - Jupyter-like REPL
-
-### Phase 5: Integration
-12. Update pyproject.toml entry point
-13. Test all features
-14. Create Claude skill description
-
-## Implementation Details
-
-### 1. protocol.py
-
-```python
-"""Wire protocol for CLI↔Server communication."""
-from dataclasses import dataclass
-from typing import Any
-import json
-
-@dataclass
-class Request:
- id: str
- action: str
- session: str
- params: dict[str, Any]
-
- def to_json(self) -> str: ...
- @classmethod
- def from_json(cls, data: str) -> 'Request': ...
-
-@dataclass
-class Response:
- id: str
- success: bool
- data: Any = None
- error: str | None = None
-
- def to_json(self) -> str: ...
- @classmethod
- def from_json(cls, data: str) -> 'Response': ...
-```
-
-### 2. utils.py
-
-```python
-"""Platform utilities."""
-import os
-import sys
-import tempfile
-from pathlib import Path
-
-def get_socket_path(session: str) -> str:
- """Get Unix socket path or TCP port for session."""
- if sys.platform == 'win32':
- # Windows: use TCP on deterministic port
- import hashlib
- port = 49152 + (int(hashlib.md5(session.encode()).hexdigest()[:4], 16) % 16383)
- return f"tcp://localhost:{port}"
- return f"/tmp/browser-use-{session}.sock"
-
-def get_pid_path(session: str) -> Path:
- return Path(tempfile.gettempdir()) / f"browser-use-{session}.pid"
-
-def is_server_running(session: str) -> bool: ...
-def find_chrome_executable() -> str | None: ...
-def get_chrome_profile_path(profile: str | None) -> str | None: ...
-```
-
-### 3. main.py (Critical: STDLIB ONLY)
-
-```python
-#!/usr/bin/env python3
-"""Fast CLI for browser-use. STDLIB ONLY - must start in <50ms."""
-import argparse
-import json
-import os
-import socket
-import subprocess
-import sys
-import time
-
-def get_socket_path(session: str) -> str: ...
-def get_pid_path(session: str) -> str: ...
-
-def is_server_running(session: str) -> bool:
- pid_path = get_pid_path(session)
- if not pid_path.exists():
- return False
- try:
- pid = int(pid_path.read_text().strip())
- os.kill(pid, 0) # Check if process exists
- return True
- except (OSError, ValueError):
- return False
-
-def ensure_server(session: str, browser: str, headed: bool, profile: str | None) -> bool:
- """Start server if not running. Returns True if started."""
- if is_server_running(session):
- # Try to connect to verify it's responsive
- try:
- conn = connect_to_server(session, timeout=0.05)
- conn.close()
- return False # Already running
- except:
- pass # Server dead, restart
-
- # Start server as background process
- cmd = [
- sys.executable, '-m', 'browser_use.cli.server',
- '--session', session,
- '--browser', browser,
- ]
- if headed:
- cmd.append('--headed')
- if profile:
- cmd.extend(['--profile', profile])
-
- subprocess.Popen(
- cmd,
- start_new_session=True,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
-
- # Wait for server to be ready
- for _ in range(50): # 2.5 seconds max
- if is_server_running(session):
- try:
- conn = connect_to_server(session, timeout=0.05)
- conn.close()
- return True
- except:
- pass
- time.sleep(0.05)
-
- print("Error: Failed to start server", file=sys.stderr)
- sys.exit(1)
-
-def connect_to_server(session: str, timeout: float = 5.0) -> socket.socket:
- sock_path = get_socket_path(session)
- if sock_path.startswith('tcp://'):
- # Windows TCP
- host, port = sock_path[6:].split(':')
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.settimeout(timeout)
- sock.connect((host, int(port)))
- else:
- # Unix socket
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- sock.settimeout(timeout)
- sock.connect(sock_path)
- return sock
-
-def send_command(session: str, action: str, params: dict) -> dict:
- import time
- request = {
- 'id': f'r{int(time.time() * 1000000) % 1000000}',
- 'action': action,
- 'session': session,
- 'params': params,
- }
-
- sock = connect_to_server(session)
- try:
- sock.sendall((json.dumps(request) + '\n').encode())
-
- # Read response
- data = b''
- while not data.endswith(b'\n'):
- chunk = sock.recv(4096)
- if not chunk:
- break
- data += chunk
-
- return json.loads(data.decode())
- finally:
- sock.close()
-
-def main():
- parser = argparse.ArgumentParser(prog='browser-use', description='Browser automation CLI')
- parser.add_argument('--session', '-s', default='default', help='Session name')
- parser.add_argument('--browser', '-b', choices=['chromium', 'real', 'remote'], default='chromium')
- parser.add_argument('--headed', action='store_true', help='Show browser window')
- parser.add_argument('--profile', help='Chrome profile (real browser mode)')
- parser.add_argument('--json', action='store_true', help='JSON output')
- parser.add_argument('--api-key', help='API key override')
-
- subparsers = parser.add_subparsers(dest='command', required=True)
-
- # open <url>
- open_p = subparsers.add_parser('open', help='Navigate to URL')
- open_p.add_argument('url', help='URL to navigate to')
-
- # click <index>
- click_p = subparsers.add_parser('click', help='Click element')
- click_p.add_argument('index', type=int, help='Element index')
-
- # type <text>
- type_p = subparsers.add_parser('type', help='Type text')
- type_p.add_argument('text', help='Text to type')
-
- # ... more subparsers for all commands
-
- args = parser.parse_args()
-
- # Handle API key
- if args.api_key:
- os.environ['BROWSER_USE_API_KEY'] = args.api_key
-
- # Ensure server is running
- ensure_server(args.session, args.browser, args.headed, args.profile)
-
- # Build params from args
- params = vars(args).copy()
- del params['command']
- del params['session']
- del params['browser']
- del params['headed']
- del params['profile']
- del params['json']
- del params['api_key']
-
- # Send command
- response = send_command(args.session, args.command, params)
-
- # Output
- if args.json:
- print(json.dumps(response))
- else:
- if response.get('success'):
- if response.get('data'):
- print(response['data'])
- else:
- print(f"Error: {response.get('error')}", file=sys.stderr)
- sys.exit(1)
-
-if __name__ == '__main__':
- main()
-```
-
-### 4. server.py
-
-```python
-"""Session server - keeps BrowserSession instances alive."""
-import asyncio
-import json
-import os
-import signal
-import sys
-from pathlib import Path
-
-# Heavy imports OK here - server loads once and stays running
-from browser_use.browser.session import BrowserSession
-from browser_use.browser.profile import BrowserProfile
-from browser_use.cli.sessions import SessionRegistry
-from browser_use.cli.commands import browser, python_exec, agent, session
-
-class SessionServer:
- def __init__(self, session_name: str, browser_mode: str, headed: bool, profile: str | None):
- self.session_name = session_name
- self.browser_mode = browser_mode
- self.headed = headed
- self.profile = profile
- self.registry = SessionRegistry()
- self.running = True
-
- async def handle_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
- while True:
- try:
- line = await reader.readline()
- if not line:
- break
-
- request = json.loads(line.decode())
- response = await self.dispatch(request)
- writer.write((json.dumps(response) + '\n').encode())
- await writer.drain()
-
- except Exception as e:
- response = {'id': '', 'success': False, 'error': str(e)}
- writer.write((json.dumps(response) + '\n').encode())
- await writer.drain()
-
- writer.close()
- await writer.wait_closed()
-
- async def dispatch(self, request: dict) -> dict:
- action = request.get('action')
- params = request.get('params', {})
- req_id = request.get('id', '')
-
- try:
- # Get or create session
- session_info = await self.registry.get_or_create(
- self.session_name,
- self.browser_mode,
- self.headed,
- self.profile,
- )
-
- # Dispatch to handler
- if action in browser.COMMANDS:
- result = await browser.handle(action, session_info, params)
- elif action == 'python':
- result = await python_exec.handle(session_info, params)
- elif action == 'run':
- result = await agent.handle(session_info, params)
- elif action in session.COMMANDS:
- result = await session.handle(action, self.registry, params)
- elif action == 'close':
- await self.shutdown()
- result = {'closed': True}
- else:
- return {'id': req_id, 'success': False, 'error': f'Unknown action: {action}'}
-
- return {'id': req_id, 'success': True, 'data': result}
-
- except Exception as e:
- return {'id': req_id, 'success': False, 'error': str(e)}
-
- async def shutdown(self):
- self.running = False
- await self.registry.close_all()
- # Remove socket/PID files
- cleanup_files(self.session_name)
-
- async def run(self):
- # Write PID file
- pid_path = get_pid_path(self.session_name)
- pid_path.write_text(str(os.getpid()))
-
- # Setup signal handlers
- loop = asyncio.get_event_loop()
- for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
- loop.add_signal_handler(sig, lambda: asyncio.create_task(self.shutdown()))
-
- # Start server
- sock_path = get_socket_path(self.session_name)
- if sock_path.startswith('tcp://'):
- host, port = sock_path[6:].split(':')
- server = await asyncio.start_server(
- self.handle_connection, host, int(port)
- )
- else:
- # Remove stale socket
- if os.path.exists(sock_path):
- os.unlink(sock_path)
- server = await asyncio.start_unix_server(
- self.handle_connection, sock_path
- )
-
- async with server:
- while self.running:
- await asyncio.sleep(0.1)
-
-def main():
- import argparse
- parser = argparse.ArgumentParser()
- parser.add_argument('--session', required=True)
- parser.add_argument('--browser', default='chromium')
- parser.add_argument('--headed', action='store_true')
- parser.add_argument('--profile')
- args = parser.parse_args()
-
- server = SessionServer(args.session, args.browser, args.headed, args.profile)
- asyncio.run(server.run())
-
-if __name__ == '__main__':
- main()
-```
-
-### 5. sessions.py
-
-```python
-"""Session registry - manages BrowserSession instances."""
-from dataclasses import dataclass, field
-from typing import Any
-
-from browser_use.browser.session import BrowserSession
-from browser_use.browser.profile import BrowserProfile
-from browser_use.cli.python_session import PythonSession
-
-@dataclass
-class SessionInfo:
- name: str
- browser_mode: str
- headed: bool
- profile: str | None
- browser_session: BrowserSession
- python_session: PythonSession = field(default_factory=PythonSession)
-
-class SessionRegistry:
- def __init__(self):
- self._sessions: dict[str, SessionInfo] = {}
-
- async def get_or_create(
- self,
- name: str,
- browser_mode: str,
- headed: bool,
- profile: str | None,
- ) -> SessionInfo:
- if name in self._sessions:
- return self._sessions[name]
-
- browser_session = await create_browser_session(
- browser_mode, headed, profile
- )
- await browser_session.start()
-
- session_info = SessionInfo(
- name=name,
- browser_mode=browser_mode,
- headed=headed,
- profile=profile,
- browser_session=browser_session,
- )
- self._sessions[name] = session_info
- return session_info
-
- def list_sessions(self) -> list[dict[str, Any]]:
- return [
- {
- 'name': s.name,
- 'browser_mode': s.browser_mode,
- 'headed': s.headed,
- }
- for s in self._sessions.values()
- ]
-
- async def close_session(self, name: str) -> bool:
- if name not in self._sessions:
- return False
- session = self._sessions.pop(name)
- await session.browser_session.kill()
- return True
-
- async def close_all(self):
- for session in self._sessions.values():
- try:
- await session.browser_session.kill()
- except:
- pass
- self._sessions.clear()
-
-async def create_browser_session(
- mode: str,
- headed: bool,
- profile: str | None,
-) -> BrowserSession:
- """Create BrowserSession based on mode."""
- if mode == 'chromium':
- return BrowserSession(
- headless=not headed,
- )
-
- elif mode == 'real':
- from browser_use.cli.utils import find_chrome_executable, get_chrome_profile_path
- return BrowserSession(
- executable_path=find_chrome_executable(),
- user_data_dir=get_chrome_profile_path(profile),
- headless=False, # Real browser always visible
- )
-
- elif mode == 'remote':
- from browser_use.cli.api_key import require_api_key
- require_api_key('Remote browser')
- return BrowserSession(
- use_cloud=True,
- )
-
- else:
- raise ValueError(f'Unknown browser mode: {mode}')
-```
-
-### 6. api_key.py
-
-```python
-"""API key management."""
-import json
-import os
-import sys
-from pathlib import Path
-
-class APIKeyRequired(Exception):
- pass
-
-def require_api_key(feature: str = 'this feature') -> str:
- """Get API key or raise helpful error."""
-
- # 1. Check environment
- key = os.environ.get('BROWSER_USE_API_KEY')
- if key:
- return key
-
- # 2. Check config file
- config_path = Path.home() / '.config' / 'browser-use' / 'config.json'
- if config_path.exists():
- try:
- config = json.loads(config_path.read_text())
- if key := config.get('api_key'):
- return key
- except:
- pass
-
- # 3. Interactive prompt (if TTY)
- if sys.stdin.isatty():
- return prompt_for_api_key(feature)
-
- # 4. Error with helpful message
- raise APIKeyRequired(f'''
-╭─────────────────────────────────────────────────────────────╮
-│ 🔑 Browser-Use API Key Required │
-│ │
-│ {feature} requires an API key. │
-│ │
-│ Get yours at: https://browser-use.com/dashboard │
-│ │
-│ Then set it via: │
-│ export BROWSER_USE_API_KEY=your_key_here │
-│ │
-│ Or add to ~/.config/browser-use/config.json: │
-│ {{"api_key": "your_key_here"}} │
-╰─────────────────────────────────────────────────────────────╯
-''')
-
-def prompt_for_api_key(feature: str) -> str:
- """Interactive prompt for API key."""
- print(f'''
-╭─────────────────────────────────────────────────────────────╮
-│ 🔑 Browser-Use API Key Required │
-│ │
-│ {feature} requires an API key. │
-│ Get yours at: https://browser-use.com/dashboard │
-╰─────────────────────────────────────────────────────────────╯
-''')
- key = input('Enter API key: ').strip()
- if not key:
- raise APIKeyRequired('No API key provided')
-
- save = input('Save to config? [y/N]: ').strip().lower()
- if save == 'y':
- save_api_key(key)
-
- return key
-
-def save_api_key(key: str):
- """Save API key to config file."""
- config_path = Path.home() / '.config' / 'browser-use' / 'config.json'
- config_path.parent.mkdir(parents=True, exist_ok=True)
-
- config = {}
- if config_path.exists():
- try:
- config = json.loads(config_path.read_text())
- except:
- pass
-
- config['api_key'] = key
- config_path.write_text(json.dumps(config, indent=2))
- print(f'Saved to {config_path}')
-```
-
-### 7. python_session.py
-
-```python
-"""Jupyter-like persistent Python execution."""
-import asyncio
-import io
-from contextlib import redirect_stdout
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-from browser_use.browser.session import BrowserSession
-
-@dataclass
-class ExecutionResult:
- success: bool
- output: str = ''
- error: str | None = None
-
-@dataclass
-class PythonSession:
- """Jupyter-like persistent Python execution."""
- namespace: dict[str, Any] = field(default_factory=dict)
- execution_count: int = 0
-
- def __post_init__(self):
- # Pre-populate namespace with useful imports
- self.namespace.update({
- 'json': __import__('json'),
- 're': __import__('re'),
- 'Path': Path,
- })
-
- def execute(self, code: str, browser: BrowserSession) -> ExecutionResult:
- """Execute code in persistent namespace."""
- self.namespace['browser'] = BrowserWrapper(browser)
- self.execution_count += 1
-
- stdout = io.StringIO()
- try:
- with redirect_stdout(stdout):
- try:
- # Try as expression first (for REPL-like behavior)
- result = eval(code, self.namespace)
- if result is not None:
- print(repr(result))
- except SyntaxError:
- # Execute as statements
- exec(code, self.namespace)
-
- return ExecutionResult(success=True, output=stdout.getvalue())
-
- except Exception as e:
- return ExecutionResult(success=False, error=str(e), output=stdout.getvalue())
-
- def reset(self):
- """Clear namespace."""
- self.namespace.clear()
- self.__post_init__()
-
- def get_variables(self) -> dict[str, str]:
- """Get user-defined variables."""
- return {
- k: type(v).__name__
- for k, v in self.namespace.items()
- if not k.startswith('_') and k not in ('json', 're', 'Path', 'browser')
- }
-
-class BrowserWrapper:
- """Convenient browser access for Python code."""
-
- def __init__(self, session: BrowserSession):
- self._session = session
- self._loop = asyncio.new_event_loop()
-
- def _run(self, coro):
- return self._loop.run_until_complete(coro)
-
- @property
- def url(self) -> str:
- # Get current URL from session
- return self._run(self._get_url())
-
- async def _get_url(self) -> str:
- state = await self._session.get_state()
- return state.url if state else ''
-
- def goto(self, url: str):
- """Navigate to URL."""
- self._run(self._session.navigate(url))
-
- def click(self, index: int):
- """Click element by index."""
- from browser_use.browser.events import ClickElementEvent
- self._run(self._session.event_bus.adispatch(
- ClickElementEvent(index=index)
- ))
-
- def type(self, text: str):
- """Type text."""
- from browser_use.browser.events import TypeTextEvent
- self._run(self._session.event_bus.adispatch(
- TypeTextEvent(text=text)
- ))
-
- def screenshot(self) -> bytes:
- """Take screenshot, return bytes."""
- return self._run(self._session.take_screenshot())
-
- @property
- def html(self) -> str:
- """Get page HTML."""
- return self._run(self._session.get_html())
-
- def scroll(self, direction: str = 'down', amount: int = 500):
- """Scroll page."""
- from browser_use.browser.events import ScrollEvent
- self._run(self._session.event_bus.adispatch(
- ScrollEvent(direction=direction, amount=amount)
- ))
-```
-
-### 8. commands/browser.py
-
-```python
-"""Browser control commands."""
-from typing import Any
-from browser_use.cli.sessions import SessionInfo
-from browser_use.browser.events import (
- NavigateToUrlEvent,
- ClickElementEvent,
- TypeTextEvent,
- ScrollEvent,
- SendKeysEvent,
- SwitchTabEvent,
- CloseTabEvent,
-)
-
-COMMANDS = {
- 'open', 'click', 'type', 'input', 'scroll', 'back',
- 'screenshot', 'state', 'switch', 'close-tab', 'keys',
- 'select', 'eval', 'extract',
-}
-
-async def handle(action: str, session: SessionInfo, params: dict) -> Any:
- bs = session.browser_session
-
- if action == 'open':
- await bs.event_bus.adispatch(NavigateToUrlEvent(url=params['url']))
- return {'url': params['url']}
-
- elif action == 'click':
- await bs.event_bus.adispatch(ClickElementEvent(index=params['index']))
- return {'clicked': params['index']}
-
- elif action == 'type':
- await bs.event_bus.adispatch(TypeTextEvent(text=params['text']))
- return {'typed': params['text']}
-
- elif action == 'input':
- await bs.event_bus.adispatch(ClickElementEvent(index=params['index']))
- await bs.event_bus.adispatch(TypeTextEvent(text=params['text']))
- return {'input': params['text'], 'to': params['index']}
-
- elif action == 'scroll':
- direction = params.get('direction', 'down')
- await bs.event_bus.adispatch(ScrollEvent(direction=direction))
- return {'scrolled': direction}
-
- elif action == 'back':
- # TODO: Implement back navigation
- return {'back': True}
-
- elif action == 'screenshot':
- data = await bs.take_screenshot()
- if params.get('path'):
- from pathlib import Path
- Path(params['path']).write_bytes(data)
- return {'saved': params['path']}
- import base64
- return {'screenshot': base64.b64encode(data).decode()}
-
- elif action == 'state':
- state = await bs.get_state()
- return {
- 'url': state.url if state else '',
- 'title': state.title if state else '',
- }
-
- elif action == 'switch':
- await bs.event_bus.adispatch(SwitchTabEvent(tab_index=params['tab']))
- return {'switched': params['tab']}
-
- elif action == 'close-tab':
- await bs.event_bus.adispatch(CloseTabEvent(tab_index=params.get('tab')))
- return {'closed': params.get('tab')}
-
- elif action == 'keys':
- await bs.event_bus.adispatch(SendKeysEvent(keys=params['keys']))
- return {'sent': params['keys']}
-
- elif action == 'eval':
- # TODO: Implement JS eval
- return {'eval': params['js']}
-
- elif action == 'extract':
- # TODO: Implement LLM extraction
- return {'query': params['query']}
-
- raise ValueError(f'Unknown browser action: {action}')
-```
-
-### 9. Claude Skill Description
-
-Located at: `skills/browser-use/SKILL.md`
-
-## Testing Plan
-
-1. **Unit Tests**
- - Protocol serialization
- - Session registry operations
- - API key handling
-
-2. **Integration Tests**
- - Server startup/shutdown
- - CLI↔Server communication
- - Browser session creation
-
-3. **E2E Tests**
- - Full workflow: open → click → type → screenshot
- - Python execution with variable persistence
- - Multi-session isolation
-
-## Open Questions
-
-1. **Real Browser Detection**: How to reliably find Chrome on different platforms?
- - macOS: `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`
- - Linux: `which google-chrome` or `which chromium`
- - Windows: Check registry or common paths
-
-2. **Cloud Proxy Configuration**: The spec mentions `--proxy residential` for remote mode. Need to verify CloudBrowserParams supports this.
-
-3. **Agent Task Implementation**: The `run` command requires the full Agent class. Need to determine:
- - Which LLM to use (from config?)
- - How to stream output back to CLI
-
-4. **Event Loop Management**: The Python session needs to run async browser methods from sync code. Current approach uses a separate event loop but this may conflict with the server's loop.
-
-5. **Backward Compatibility**: The existing `browser_use/cli.py` is a TUI app. We need to:
- - Keep the TUI as a separate command (`browser-use tui`)?
- - Or replace it entirely?
-
-## Notes
-
-- The CLI layer (main.py) MUST only use stdlib imports for <50ms startup
-- All heavy imports go in the server layer
-- Use Unix sockets on macOS/Linux, TCP on Windows
-- Session names allow parallel browser instances
-- API key is only required for remote browsers and agent tasks
diff --git a/browser_use/skill_cli/OPEN_QUESTIONS.md b/browser_use/skill_cli/OPEN_QUESTIONS.md
deleted file mode 100644
index 270c6df81..000000000
--- a/browser_use/skill_cli/OPEN_QUESTIONS.md
+++ /dev/null
@@ -1,171 +0,0 @@
-# Browser-Use CLI: Open Questions & Implementation Notes
-
-## Implementation Status
-
-### Completed Features
-- [x] Fast CLI layer (stdlib only, <50ms startup)
-- [x] Session server with Unix socket IPC (TCP on Windows)
-- [x] Session registry with named sessions
-- [x] Browser modes: chromium, real, remote
-- [x] Browser commands: open, click, type, input, scroll, back, screenshot, state, switch, close-tab, keys, select, eval
-- [x] Python execution with persistent namespace (Jupyter-like REPL)
-- [x] API key management with environment, config file, and interactive prompt support
-- [x] Agent task execution (basic implementation)
-- [x] JSON output mode
-- [x] Claude skill description (SKILL.md)
-
-### Features Not Fully Implemented
-- [ ] `extract` command - Returns placeholder, needs LLM integration
-- [ ] Agent task `run` command - Basic implementation, may need tuning
-- [ ] Cloud browser proxy configuration (`--proxy residential`)
-
-## Open Questions
-
-### 1. TUI vs CLI Coexistence
-
-**Current State**:
-- The existing `browser_use/cli.py` is a Textual TUI application
-- The new CLI is in `browser_use/skill_cli/` with entry point `bu`
-- Both coexist: `browser-use` launches TUI, `bu` launches fast CLI
-
-**Question**: Should we:
-1. Keep both (`browser-use` = TUI, `bu` = fast CLI)
-2. Replace TUI with fast CLI (`browser-use` = fast CLI, deprecate TUI)
-3. Make TUI a subcommand (`browser-use tui`, `browser-use` = fast CLI)
-
-**Recommendation**: Option 3 - Make TUI accessible via `browser-use tui` and have `browser-use` launch the fast CLI. This provides a migration path.
-
-### 2. Agent Task LLM Configuration
-
-**Current State**:
-The `run` command tries to auto-detect LLM from environment variables (OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY).
-
-**Question**: Should we:
-1. Require explicit LLM configuration in `~/.config/browser-use/config.json`
-2. Keep auto-detection from environment
-3. Add `--llm` flag to specify model
-
-**Recommendation**: Keep auto-detection, add optional `--llm` flag for overrides.
-
-### 3. Remote Browser Proxy Configuration
-
-**Spec mentions**: `--proxy residential` for remote browser mode
-
-**Current State**: Not implemented. The `CloudBrowserParams` supports `proxy_country_code` but not proxy type.
-
-**Question**: What proxy types does Browser-Use Cloud support?
-- residential
-- datacenter
-- none
-
-**Action Needed**: Verify with Browser-Use Cloud API documentation.
-
-### 4. Real Browser Mode Profile Handling
-
-**Current State**:
-- `--profile NAME` passes the profile name to `user_data_dir`
-- This may not work correctly as Chrome expects specific paths
-
-**Question**: How should profile selection work?
-1. Pass profile name as subdirectory
-2. Use Chrome's `--profile-directory` flag
-3. Let user specify full path
-
-**Recommendation**: Support both `--profile "Profile 1"` (Chrome's named profile) and `--user-data-dir /path` for full control.
-
-### 5. Session Cleanup on Server Restart
-
-**Current State**:
-- Server writes PID and socket files to temp directory
-- On shutdown, files are cleaned up
-- If server crashes, files may remain
-
-**Question**: Should we:
-1. Clean up stale files on CLI startup
-2. Add a `bu server clean` command
-3. Both
-
-**Recommendation**: Clean up stale files on startup (check if PID exists, if not, remove socket).
-
-### 6. Event Loop Handling in Python Session
-
-**Current State**:
-The `BrowserWrapper` in `python_session.py` uses `concurrent.futures.ThreadPoolExecutor` to run async operations from sync context.
-
-**Potential Issues**:
-- May conflict with the server's event loop
-- Thread pool overhead
-
-**Question**: Is there a better approach? Consider:
-1. Using `asyncio.run_coroutine_threadsafe()`
-2. Making Python execution async and handling differently
-
-### 7. Browser State Element Indices
-
-**Current State**:
-The `state` command returns elements from `dom_state.selector_map` with their original indices.
-
-**Observation**: Indices are not sequential (e.g., 18, 19, 20...). This is because they're mapped to actual DOM elements.
-
-**Question**: Should we:
-1. Keep original indices (consistent with how the agent works)
-2. Re-number 0, 1, 2... (easier for humans but may cause confusion)
-
-**Recommendation**: Keep original indices for consistency with agent.
-
-## Architecture Notes
-
-### Socket Communication
-- Unix sockets on macOS/Linux: `/var/.../browser-use-{session}.sock`
-- TCP on Windows: `tcp://localhost:{port}` where port is hash-derived
-- Line-delimited JSON protocol
-
-### Session Lifecycle
-```
-CLI Command → ensure_server() → connect_to_server() → send_command()
- ↓
- (if not running)
- ↓
- spawn server process
- ↓
- wait for socket ready
-```
-
-### Server Architecture
-```
-SessionServer
- ├── SessionRegistry (manages BrowserSession instances)
- ├── Socket Server (asyncio.start_unix_server)
- └── Command Dispatch
- ├── browser.py (open, click, type, etc.)
- ├── python_exec.py (Python REPL)
- ├── agent.py (run command)
- └── session.py (sessions, close)
-```
-
-## Testing Notes
-
-All basic features have been tested:
-- `bu open <url>` - Works (headed and headless)
-- `bu state` - Works (returns elements with indices)
-- `bu click <index>` - Works
-- `bu type "text"` - Works
-- `bu screenshot` - Works (base64 and file output)
-- `bu eval "js"` - Works (returns JS result)
-- `bu python "code"` - Works (persistent namespace)
-- `bu python --vars` - Works
-- `bu close` - Works
-- `bu server status/stop` - Works
-- `--json` mode - Works
-- `--headed` mode - Works
-
-## Future Improvements
-
-1. **Streaming Output**: For long-running agent tasks, stream progress updates
-2. **Tab Completion**: Add shell completion for commands
-3. **History**: Remember command history across sessions
-4. **Config File**: Support more configuration options
-5. **Plugins**: Allow extending with custom commands
-6. **HTTP API**: Add REST endpoint for programmatic access
-7. **Watch Mode**: Re-run Python on file changes
-8. **Notebook Export**: Export Python session as .ipynb