# Human-Browser A browser automation service that acts as a competent assistant for an external AI agent -- navigating the web autonomously, pausing only when it needs information or hits a blocker it cannot handle alone. ![Python](https://img.shields.io/badge/python-3.11+-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Browser](https://img.shields.io/badge/chrome-CDP-orange) ![Status](https://img.shields.io/badge/status-research%20prototype-lightgrey) > **Research & educational project — not commercial.** This is a non-commercial research and > educational project exploring what is achievable in autonomous, vision-driven browser > automation. It is not a product, is not sold or operated as a service, and is provided as-is > with no warranty. ```mermaid flowchart LR Brain["Brain
(Claude / GPT-4 / Gemini)
decides WHAT"] Brain -- "goal (HTTP)" --> Loop subgraph Container["Human-Browser container"] Loop["Browse loop
(browse.py)"] Loop --> DOM["DOM classify
~80% of pages, ~10ms"] Loop --> VL["VL model
Qwen3-VL 32B · decides HOW"] Loop --> Exec["Action executor
human-simulated mouse/keys"] Exec --> Chrome["Chrome via CDP
Xvfb + VNC"] end Loop -- "pause: login / form / CAPTCHA" --> Brain ``` ## What Is This? Human-Browser is a semantic browser co-processor. An external AI agent (the "brain" -- Claude, GPT-4, or any LLM) tells it *what* to accomplish on the web, and Human-Browser figures out *how* to do it. It clicks, scrolls, reads pages, fills search forms, and dismisses cookie banners without asking. When it encounters a personal data form, a login wall without credentials, or a CAPTCHA, it pauses and asks the brain for help. The service runs inside Docker with a full Chrome instance, a virtual display, VNC access for debugging, and a local VL model (Qwen) for visual understanding of pages. All browser interactions use human simulation -- realistic mouse movements, typing cadence with occasional typos, and natural reading pauses -- to avoid bot detection. The brain communicates via a simple HTTP API. A typical task involves one `POST /browse` call, zero or more `GET /session/{id}/result` + `POST /session/{id}/input` exchanges, and then the final result. For edge cases where the brain needs direct control, a full set of low-level browser tools is also available. ## Engineering highlights The interesting problems, and where to read the code: - **A two-tier "eyes and hands" loop that keeps the frontier model off the hot path.** Calling a frontier LLM for *every* click is slow and expensive. Cheap DOM heuristics classify ~80% of pages in ~10ms; a local **Qwen3-VL 32B** decides only the ambiguous rest; the external "brain" is consulted only for goals and genuine escalations. (`human_browser/browse.py`, `page_model.py`) - **A hand-rolled async Chrome DevTools Protocol client — no Selenium/Playwright.** Direct CDP-over-WebSocket, chosen for fine-grained control and stealth (those frameworks leak automation tells). (`human_browser/browser/cdp_client.py`) - **"Be a real human, on a real Chrome."** The cursor moves along **Bézier curves with Fitts's-Law timing**, typing has variable cadence and occasional typos, and an idle animator adds micro-tremor while the model "thinks" so the cursor is never unnaturally still. (`human_browser/human/`) - **Anti-detection as a first-class concern.** No `Runtime.enable` (a high-value automation tell), plus JS patches for `navigator.webdriver`, canvas/WebGL fingerprints, and plugin lists. (`human_browser/anti_detect.py`) - **DOM-assisted visual grounding.** Rather than ask the model for raw pixel coordinates (unreliable), the VL picks an element from a labeled list and the system resolves it to exact coordinates via an element registry; coordinate clicking is only a fallback. (`human_browser/targeting.py`) - **Knows when it's stuck.** Perceptual-hash (pHash) progress tracking plus an "action-identity" detector catch the model looping; a recovery ladder (escape → scroll → tab+enter → reload) and hard step/time circuit breakers prevent runaway sessions. (`human_browser/browse.py`) - **A measurable North Star.** Every task emits a `task_outcome` rollup stamped with `git_sha` + model, scored on four axes — correctness, autonomy, account-safety, efficiency — so *Autonomous Success Rate* can be tracked per commit against a 75-case real-world benchmark. (`human_browser/events.py`, `tests/realworld/`) - **A test pyramid that caught what unit mocks couldn't.** ~630 unit tests (warnings-as-errors, a signature-faithful fake CDP client), tiered Docker e2e (contract → protocol → LLM-agent → real-VL fullstack), and 75 live-internet cases with an LLM-judge rubric. (`tests/`) For a candid, consultant-facing deep dive — including current limitations and open questions — see [`PROJECT_OVERVIEW.md`](PROJECT_OVERVIEW.md). ## Architecture ``` +---------------------------+ +----------------------------------------------+ | Brain | | Human-Browser Container | | (Claude / GPT-4) | | | | | HTTP | +------------------+ +----------------+ | | Decides WHAT to do -----+--------->| | FastAPI API |-->| Browse Loop | | | Provides info when <----+---------+| | (api.py) | | (browse.py) | | | asked | | +------------------+ +-------+--------+ | | | | | | +---------------------------+ | +----------------------+--+ | | | | | | +-------v--------+ +---------v--------+ | | | VL Model | | Action Executor | | | | (Qwen via | | + Human | | | | Ollama) | | Simulation | | | +----------------+ +--------+---------+ | | | | | +----------v----------+ | | | Chrome (CDP) | | | | Xvfb + VNC | | | +---------------------+ | +----------------------------------------------+ ``` **Key insight:** The brain decides *what* to accomplish. The browser decides *how* to navigate there. ## Quick Start ```bash # Build and start docker compose up -d --build # Health check curl http://localhost:8080/health # Browse a page curl -X POST http://localhost:8080/browse \ -H "Content-Type: application/json" \ -d '{"url": "https://bbc.com", "goal": "find the top 3 news headlines"}' # -> {"session_id": "abc123"} # Wait for result (blocks until done) curl http://localhost:8080/session/abc123/result # -> {"status": "done", "result": "Top 3 headlines:\n1. ...", "steps_taken": 8} ``` **Prerequisites:** Docker with compose v2, and an Ollama instance with `qwen3-vl:32b` loaded. Set `OLLAMA_BASE_URL` if Ollama is not on the default Docker network. ## API Reference ### POST /browse Start an autonomous browse session. Returns immediately with a session ID. ```json // Request {"url": "https://example.com", "goal": "find pricing information", "context": {"credentials": {"email": "u@t.com", "password": "secret"}}} // Response {"session_id": "a1b2c3d4"} ``` - `url` (optional) -- starting URL. - `goal` (required) -- what to accomplish, in natural language. - `context` (optional) -- background info. Supports structured `credentials` key for auto-login. ### GET /session/{id}/result Block until the session produces a result. Retryable if the connection drops. Returns one of five status variants: **done** -- goal accomplished: ```json {"status": "done", "result": "Top 3 stories:\n1. ...", "page_summary": "BBC News", "steps_taken": 12, "auto_handled": [{"type": "cookie_banner", "action": "dismissed"}]} ``` **needs_input** -- form or decision required: ```json {"status": "needs_input", "input_type": "form", "message": "I found an application form:", "fields": [{"id": "e1", "label": "First Name", "type": "text", "required": true}], "steps_taken": 5} ``` **needs_input** -- confirmation before submit: ```json {"status": "needs_input", "input_type": "form_confirmation", "message": "Please review:", "filled_fields": [{"label": "First Name", "type": "text", "value": "John"}], "steps_taken": 5} ``` **blocked** -- login, CAPTCHA, paywall: ```json {"status": "blocked", "blocker": "login_required", "message": "This page requires login credentials.", "steps_taken": 3} ``` **stuck** -- no progress after recovery attempts: ```json {"status": "stuck", "message": "Stuck for 5 steps.", "tried": ["escape", "scroll", "tab+enter", "back"], "steps_taken": 20} ``` **failed** -- error or circuit breaker: ```json {"status": "failed", "error": "Circuit breaker: max steps exceeded", "steps_taken": 500} ``` ### POST /session/{id}/input Provide information to a paused session. Returns immediately. ```bash # Form values curl -X POST http://localhost:8080/session/s1/input \ -H "Content-Type: application/json" \ -d '{"session_id": "s1", "fields": {"First Name": "John", "Email": "john@test.com"}}' # Confirm submission curl -X POST http://localhost:8080/session/s1/input \ -H "Content-Type: application/json" \ -d '{"session_id": "s1", "action": "submit"}' # Login credentials curl -X POST http://localhost:8080/session/s1/input \ -H "Content-Type: application/json" \ -d '{"session_id": "s1", "fields": {"email": "user@test.com", "password": "secret"}}' ``` Response: `{"session_id": "s1", "accepted": true}` ### GET /session/{id} Non-blocking monitoring. Returns current state without waiting. ```json {"session_id": "a1b2c3d4", "state": "running", "goal": "find pricing", "steps_taken": 7, "current_result": null} ``` State values: `running`, `paused`, `done`, `stuck`, `blocked`, `failed`, `cancelled`. ### DELETE /session/{id} Cancel a running session. Response: `{"status": "cancelled", "session_id": "a1b2c3d4"}` ### Direct Control Endpoints (Fallback) For when the brain needs manual control. All return a **fat response** with the action result, page model, auto-handled events, and tab info: ```json {"result": {"status": "ok"}, "page": {"url": "...", "page_type": "article", "focus": {"forms": [], "actions": [{"id": "e1", "text": "Next", "type": "link"}]}, "text_content": "...", "blockers": [], "state": "ready", "generation": 5}, "auto_handled": [], "tabs": []} ``` | Endpoint | Method | Body | Description | |----------|--------|------|-------------| | `/observe` | GET | `?screenshot=true` | Page model, optionally with base64 screenshot | | `/click` | POST | `{"element_id": "e3"}` or `{"description": "Submit"}` or `{"x": 100, "y": 200}` | Click with human simulation | | `/type` | POST | `{"element_id": "e1", "text": "hello", "clear_first": true}` | Type with human simulation | | `/scroll` | POST | `{"direction": "down", "amount": 300}` | Smooth scroll | | `/key` | POST | `{"key": "Enter", "modifiers": ["Control"]}` | Key press | | `/goto` | POST | `{"url": "https://example.com"}` | Navigate to URL | | `/back` | POST | (empty) | Browser back | | `/wait` | POST | `{"seconds": 3.0}` | Wait (default 2s) | | `/switch-tab` | POST | `{"tab_id": "tab-123"}` | Switch browser tab | | `/upload` | POST | multipart `file=@resume.pdf` | Upload file to container | | `/read` | POST | `{"query": "what are the pricing tiers?"}` | VL model extracts info from current page | ### GET /health Check Chrome CDP and Ollama reachability. ```json {"status": "ok", "checks": {"chrome": "ok", "ollama": "ok"}} ``` ## Usage Examples ### Example 1: Read a News Article ```bash curl -X POST http://localhost:8080/browse \ -H "Content-Type: application/json" \ -d '{"url": "https://bbc.com", "goal": "find the top 3 Middle East news stories"}' # -> {"session_id": "s1"} curl http://localhost:8080/session/s1/result # -> {"status": "done", "result": "Top 3 stories:\n1. ...", "steps_taken": 12} ``` ### Example 2: Fill a Job Application (Multi-Step) ```bash # 1. Start curl -X POST http://localhost:8080/browse -H "Content-Type: application/json" \ -d '{"url": "https://company.com/careers/123", "goal": "apply for this position"}' # 2. Browser finds form, pauses -> GET /session/s2/result # -> {"status": "needs_input", "input_type": "form", "fields": [...]} # 3. Provide values -> POST /session/s2/input # -> {"session_id": "s2", "fields": {"First Name": "John", "Email": "john@test.com"}} # 4. Browser fills, asks confirmation -> GET /session/s2/result # -> {"status": "needs_input", "input_type": "form_confirmation", "filled_fields": [...]} # 5. Confirm -> POST /session/s2/input # -> {"session_id": "s2", "action": "submit"} # 6. Done -> GET /session/s2/result # -> {"status": "done", "result": "Application submitted successfully."} ``` ### Example 3: Handle a Login Wall ```bash # 1. Start browsing a site that requires login curl -X POST http://localhost:8080/browse -H "Content-Type: application/json" \ -d '{"url": "https://linkedin.com/jobs/123", "goal": "get the job description"}' # 2. Browser hits login wall -> GET /session/s3/result # -> {"status": "blocked", "blocker": "login_required"} # 3. Provide credentials -> POST /session/s3/input # -> {"session_id": "s3", "fields": {"email": "user@test.com", "password": "mypassword"}} # 4. Browser logs in and continues -> GET /session/s3/result # -> {"status": "done", "result": "Job description: Senior Engineer at ..."} ``` ### Example 4: Direct Control ```bash curl -X POST http://localhost:8080/goto -H "Content-Type: application/json" \ -d '{"url": "https://example.com"}' curl http://localhost:8080/observe curl -X POST http://localhost:8080/click -H "Content-Type: application/json" \ -d '{"element_id": "e2"}' curl -X POST http://localhost:8080/type -H "Content-Type: application/json" \ -d '{"element_id": "e1", "text": "search query"}' ``` ## Python Client Example ```python import httpx import asyncio async def browse_news(): async with httpx.AsyncClient(base_url="http://localhost:8080", timeout=120) as client: # Start a browse session resp = await client.post("/browse", json={ "url": "https://bbc.com", "goal": "find the top 3 news stories about the Middle East", }) session_id = resp.json()["session_id"] # Wait for result (blocks until done or paused) resp = await client.get(f"/session/{session_id}/result") result = resp.json() if result["status"] == "done": print(result["result"]) elif result["status"] == "needs_input": await client.post(f"/session/{session_id}/input", json={ "session_id": session_id, "fields": {"Email": "user@test.com"}, }) resp = await client.get(f"/session/{session_id}/result") print(resp.json()) elif result["status"] == "blocked": print(f"Blocked: {result['blocker']} - {result['message']}") asyncio.run(browse_news()) ``` ## How It Works Internally The browse loop (`browse.py`) runs as a background asyncio task per session: 1. **Auto-handler** -- dismiss cookie banners, popups, notification prompts via common CSS selectors. 2. **Screenshot** -- capture current page state via CDP. 3. **Build page model** -- DOM extraction of forms, actionable elements, text content, blockers. 4. **DOM classification** (~10ms) -- detect login forms (password field), search forms, personal data forms (3+ fields), CAPTCHAs, content creation forms. 5. **VL classify** (fallback, only if DOM ambiguous) -- Qwen answers A/B/C: (A) continue, (B) need brain help, (C) goal done. 6. **VL navigate** -- Qwen picks next action via tool-calling with the screenshot. 7. **Execute** -- human-simulated action (Bezier mouse curves, typing cadence, natural pauses). 8. **Progress tracking** -- perceptual hash comparison (pHash, Hamming distance >= 5). 9. **Stall recovery** -- after 5 stalls: try Escape, scroll, Tab+Enter, back. If all fail, report stuck. **Circuit breakers:** 25-step and 5-minute ceilings (both tunable) prevent runaway processes. ## Configuration All settings via environment variables: | Variable | Default | Description | |----------|---------|-------------| | `OLLAMA_BASE_URL` | `http://localhost:11434` | Ollama API endpoint | | `VL_MODEL` | `qwen3-vl:32b` | Vision-language model name | | `CDP_PORT` | `9222` | Chrome DevTools Protocol port | | `AGENT_PORT` | `8080` | Human-Browser API port | | `SCREEN_WIDTH` | `1440` | Virtual display width | | `SCREEN_HEIGHT` | `900` | Virtual display height | | `TYPING_WPM` | `65` | Simulated typing speed (words per minute) | | `TYPO_RATE` | `0.03` | Typo probability per character | | `ACTION_DELAY_MEAN` | `1.5` | Mean delay between actions (seconds) | | `ACTION_DELAY_STD` | `0.4` | Std dev of action delay | | `READING_WPM` | `250` | Simulated reading speed | | `MAX_BROWSE_TIME_S` | `300` | Hard time ceiling per session (seconds) | | `MAX_BROWSE_STEPS` | `25` | Hard step ceiling per session | | `STALL_THRESHOLD` | `5` | Stall steps before recovery kicks in | | `MAX_LOGIN_RETRIES` | `3` | Max auto-login attempts per domain | | `VNC_PASSWORD` | (none) | VNC access password | | `ALLOW_NO_VNC_PASSWORD` | `0` | Set `1` for passwordless VNC | | `START_URL` | `about:blank` | Initial Chrome URL | | `CHROME_EXTRA_ARGS` | (none) | Additional Chrome flags | ## Project Structure ``` human_browser/ api.py FastAPI endpoints (session + direct control) models.py Pydantic request/response models, BrowseResult union browse.py Core browse loop with pause points and stall recovery session.py BrowseSession state, SessionManager, concurrency page_model.py DOM extraction, form classification, element registry auto_handler.py Cookie banner / popup / overlay auto-dismissal targeting.py Element ID resolution + VL grounding fallback config.py All settings from environment variables anti_detect.py Browser fingerprint evasion browser/ cdp_client.py Chrome DevTools Protocol client (websocket) actions.py Action executor with human simulation dispatch screenshot.py Screenshot capture utilities human/ mouse.py Realistic mouse movement (Bezier curves) keyboard.py Human-like typing with typo simulation scroll.py Smooth scroll with natural easing timing.py Gaussian delays, reading time estimation vision/ qwen_client.py Ollama Qwen VL model client prompts.py Classify, navigate, grounding, describe prompts parser.py Qwen3 tool-call response parser Dockerfile Debian + Chrome + Xvfb + VNC + Python + API docker-compose.yml Container config with volumes and networking docker-entrypoint.sh Startup: Xvfb, fluxbox, x11vnc, Chrome, nginx, API ``` ## Error Handling All errors return structured JSON: ```json {"error": "error_code", "message": "Human-readable description", "retryable": false} ``` | Code | HTTP | Description | |------|------|-------------| | `stale_element` | 409 | Page changed since element ID was assigned. Call `/observe` to refresh. | | `session_not_found` | 404 | No session with that ID. | | `session_busy` | 409 | Session is running, not paused. | | `session_not_paused` | 409 | Cannot provide input to a non-paused session. | | `invalid_input` | 400 | Malformed request. | | `internal_error` | 500 | Unexpected server error. | | `chrome_unavailable` | 503 | Chrome CDP connection failed. | | `vl_model_unavailable` | 503 | Ollama/VL model not reachable. | ## Responsible use This project automates a real browser and deliberately presents as an ordinary human user. That capability carries responsibility: - **Research and authorized use only.** Use it on sites you own or are permitted to automate. - **Respect site terms, `robots.txt`, and rate limits.** Many sites' Terms of Service prohibit automated access; the stealth/anti-detection work is research into *detectability*, not a license to evade access controls. - **Don't use it to bypass authentication, paywalls, or CAPTCHAs** you aren't authorized to pass, or to harvest personal data. - Provided as-is for educational purposes; the author is not responsible for misuse. ## Security Notes - **VNC** is password-protected by default. Container refuses to start without `VNC_PASSWORD` unless `ALLOW_NO_VNC_PASSWORD=1`. - **Chrome runs `--no-sandbox`** inside the container. The container itself is the isolation boundary. - **No API auth** built in. Run behind a reverse proxy or on a trusted network. - **Upload sanitization** validates filenames and blocks path traversal. - **Credentials are per-session** and never persisted to disk. Chrome cookies may persist in the profile volume. - **Anti-detection** applied at startup (WebDriver masking, automation feature flags disabled). ## Development ### Running Tests ```bash pip install -r requirements-agent.txt && pip install pytest pytest-asyncio pytest tests/ ``` ### Adding a New Auto-Handler Pattern Edit `human_browser/auto_handler.py`. Add a CSS selector to `detect_and_handle` and return an `AutoHandledEvent`. ### Adding a New Form Type 1. `human_browser/page_model.py` -- add heuristics to `classify_form()`. 2. `human_browser/browse.py` -- add a handler in `_classify_page()` and the browse loop. 3. `human_browser/models.py` -- add new `input_type` values if needed. ### Spec Reference Full design specification: `docs/superpowers/specs/2026-03-23-human-browser-design.md`