Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking...
---
name: agent-browser
description: Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction.
allowed-tools: Bash(npx agent-browser:*), Bash(agent-browser:*)
---
# Browser Automation with agent-browser
## Core Workflow
Every browser automation follows this pattern:
1. **Navigate**: `agent-browser open <url>`
2. **Snapshot**: `agent-browser snapshot -i` (get element refs like `@e1`, `@e2`)
3. **Interact**: Use refs to click, fill, select
4. **Re-snapshot**: After navigation or DOM changes, get fresh refs
```bash
agent-browser open https://example.com/form
agent-browser snapshot -i
# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"
agent-browser fill @e1 "user@example.com"
agent-browser fill @e2 "password123"
agent-browser click @e3
agent-browser wait --load networkidle
agent-browser snapshot -i # Check result
```
## Command Chaining
Commands can be chained with `&&` in a single shell invocation. The browser persists between commands via a background daemon, so chaining is safe and more efficient than separate calls.
```bash
# Chain open + wait + snapshot in one call
agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i
# Chain multiple interactions
agent-browser fill @e1 "user@example.com" && agent-browser fill @e2 "password123" && agent-browser click @e3
# Navigate and capture
agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser screenshot page.png
```
**When to chain:** Use `&&` when you don't need to read the output of an intermediate command before proceeding (e.g., open + wait + screenshot). Run commands separately when you need to parse the output first (e.g., snapshot to discover refs, then interact using those refs).
## Essential Commands
```bash
# Navigation
agent-browser open <url> # Navigate (aliases: goto, navigate)
agent-browser close # Close browser
# Snapshot
agent-browser snapshot -i # Interactive elements with refs (recommended)
agent-browser snapshot -i -C # Include cursor-interactive elements (divs with onclick, cursor:pointer)
agent-browser snapshot -s "#selector" # Scope to CSS selector
# Interaction (use @refs from snapshot)
agent-browser click @e1 # Click element
agent-browser click @e1 --new-tab # Click and open in new tab
agent-browser fill @e2 "text" # Clear and type text
agent-browser type @e2 "text" # Type without clearing
agent-browser select @e1 "option" # Select dropdown option
agent-browser check @e1 # Check checkbox
agent-browser press Enter # Press key
agent-browser scroll down 500 # Scroll page
# Get information
agent-browser get text @e1 # Get element text
agent-browser get url # Get current URL
agent-browser get title # Get page title
# Wait
agent-browser wait @e1 # Wait for element
agent-browser wait --load networkidle # Wait for network idle
agent-browser wait --url "**/page" # Wait for URL pattern
agent-browser wait 2000 # Wait milliseconds
# Capture
agent-browser screenshot # Screenshot to temp dir
agent-browser screenshot --full # Full page screenshot
agent-browser screenshot --annotate # Annotated screenshot with numbered element labels
agent-browser pdf output.pdf # Save as PDF
```
## Common Patterns
### Form Submission
```bash
agent-browser open https://example.com/signup
agent-browser snapshot -i
agent-browser fill @e1 "Jane Doe"
agent-browser fill @e2 "jane@example.com"
agent-browser select @e3 "California"
agent-browser check @e4
agent-browser click @e5
agent-browser wait --load networkidle
```
### Authentication with State Persistence
```bash
# Login once and save state
agent-browser open https://app.example.com/login
agent-browser snapshot -i
agent-browser fill @e1 "$USERNAME"
agent-browser fill @e2 "$PASSWORD"
agent-browser click @e3
agent-browser wait --url "**/dashboard"
agent-browser state save auth.json
# Reuse in future sessions
agent-browser state load auth.json
agent-browser open https://app.example.com/dashboard
```
### Session Persistence
```bash
# Auto-save/restore cookies and localStorage across browser restarts
agent-browser --session-name myapp open https://app.example.com/login
# ... login flow ...
agent-browser close # State auto-saved to ~/.agent-browser/sessions/
# Next time, state is auto-loaded
agent-browser --session-name myapp open https://app.example.com/dashboard
# Encrypt state at rest
export AGENT_BROWSER_ENCRYPTION_KEY=$(openssl rand -hex 32)
agent-browser --session-name secure open https://app.example.com
# Manage saved states
agent-browser state list
agent-browser state show myapp-default.json
agent-browser state clear myapp
agent-browser state clean --older-than 7
```
### Data Extraction
```bash
agent-browser open https://example.com/products
agent-browser snapshot -i
agent-browser get text @e5 # Get specific element text
agent-browser get text body > page.txt # Get all page text
# JSON output for parsing
agent-browser snapshot -i --json
agent-browser get text @e1 --json
```
### Parallel Sessions
```bash
agent-browser --session site1 open https://site-a.com
agent-browser --session site2 open https://site-b.com
agent-browser --session site1 snapshot -i
agent-browser --session site2 snapshot -i
agent-browser session list
```
### Connect to Existing Chrome
```bash
# Auto-discover running Chrome with remote debugging enabled
agent-browser --auto-connect open https://example.com
agent-browser --auto-connect snapshot
# Or with explicit CDP port
agent-browser --cdp 9222 snapshot
```
### Visual Browser (Debugging)
```bash
agent-browser --headed open https://example.com
agent-browser highlight @e1 # Highlight element
agent-browser record start demo.webm # Record session
agent-browser profiler start # Start Chrome DevTools profiling
agent-browser profiler stop trace.json # Stop and save profile (path optional)
```
### Local Files (PDFs, HTML)
```bash
# Open local files with file:// URLs
agent-browser --allow-file-access open file:///path/to/document.pdf
agent-browser --allow-file-access open file:///path/to/page.html
agent-browser screenshot output.png
```
### iOS Simulator (Mobile Safari)
```bash
# List available iOS simulators
agent-browser device list
# Launch Safari on a specific device
agent-browser -p ios --device "iPhone 16 Pro" open https://example.com
# Same workflow as desktop - snapshot, interact, re-snapshot
agent-browser -p ios snapshot -i
agent-browser -p ios tap @e1 # Tap (alias for click)
agent-browser -p ios fill @e2 "text"
agent-browser -p ios swipe up # Mobile-specific gesture
# Take screenshot
agent-browser -p ios screenshot mobile.png
# Close session (shuts down simulator)
agent-browser -p ios close
```
**Requirements:** macOS with Xcode, Appium (`npm install -g appium && appium driver install xcuitest`)
**Real devices:** Works with physical iOS devices if pre-configured. Use `--device "<UDID>"` where UDID is from `xcrun xctrace list devices`.
## Timeouts and Slow Pages
The default Playwright timeout is 60 seconds for local browsers. For slow websites or large pages, use explicit waits instead of relying on the default timeout:
```bash
# Wait for network activity to settle (best for slow pages)
agent-browser wait --load networkidle
# Wait for a specific element to appear
agent-browser wait "#content"
agent-browser wait @e1
# Wait for a specific URL pattern (useful after redirects)
agent-browser wait --url "**/dashboard"
# Wait for a JavaScript condition
agent-browser wait --fn "document.readyState === 'complete'"
# Wait a fixed duration (milliseconds) as a last resort
agent-browser wait 5000
```
When dealing with consistently slow websites, use `wait --load networkidle` after `open` to ensure the page is fully loaded before taking a snapshot. If a specific element is slow to render, wait for it directly with `wait <selector>` or `wait @ref`.
## Session Management and Cleanup
When running multiple agents or automations concurrently, always use named sessions to avoid conflicts:
```bash
# Each agent gets its own isolated session
agent-browser --session agent1 open site-a.com
agent-browser --session agent2 open site-b.com
# Check active sessions
agent-browser session list
```
Always close your browser session when done to avoid leaked processes:
```bash
agent-browser close # Close default session
agent-browser --session agent1 close # Close specific session
```
If a previous session was not closed properly, the daemon may still be running. Use `agent-browser close` to clean it up before starting new work.
## Ref Lifecycle (Important)
Refs (`@e1`, `@e2`, etc.) are invalidated when the page changes. Always re-snapshot after:
- Clicking links or buttons that navigate
- Form submissions
- Dynamic content loading (dropdowns, modals)
```bash
agent-browser click @e5 # Navigates to new page
agent-browser snapshot -i # MUST re-snapshot
agent-browser click @e1 # Use new refs
```
## Annotated Screenshots (Vision Mode)
Use `--annotate` to take a screenshot with numbered labels overlaid on interactive elements. Each label `[N]` maps to ref `@eN`. This also caches refs, so you can interact with elements immediately without a separate snapshot.
```bash
agent-browser screenshot --annotate
# Output includes the image path and a legend:
# [1] @e1 button "Submit"
# [2] @e2 link "Home"
# [3] @e3 textbox "Email"
agent-browser click @e2 # Click using ref from annotated screenshot
```
Use annotated screenshots when:
- The page has unlabeled icon buttons or visual-only elements
- You need to verify visual layout or styling
- Canvas or chart elements are present (invisible to text snapshots)
- You need spatial reasoning about element positions
## Semantic Locators (Alternative to Refs)
When refs are unavailable or unreliable, use semantic locators:
```bash
agent-browser find text "Sign In" click
agent-browser find label "Email" fill "user@test.com"
agent-browser find role button click --name "Submit"
agent-browser find placeholder "Search" type "query"
agent-browser find testid "submit-btn" click
```
## JavaScript Evaluation (eval)
Use `eval` to run JavaScript in the browser context. **Shell quoting can corrupt complex expressions** -- use `--stdin` or `-b` to avoid issues.
```bash
# Simple expressions work with regular quoting
agent-browser eval 'document.title'
agent-browser eval 'document.querySelectorAll("img").length'
# Complex JS: use --stdin with heredoc (RECOMMENDED)
agent-browser eval --stdin <<'EVALEOF'
JSON.stringify(
Array.from(document.querySelectorAll("img"))
.filter(i => !i.alt)
.map(i => ({ src: i.src.split("/").pop(), width: i.width }))
)
EVALEOF
# Alternative: base64 encoding (avoids all shell escaping issues)
agent-browser eval -b "$(echo -n 'Array.from(document.querySelectorAll("a")).map(a => a.href)' | base64)"
```
**Why this matters:** When the shell processes your command, inner double quotes, `!` characters (history expansion), backticks, and `$()` can all corrupt the JavaScript before it reaches agent-browser. The `--stdin` and `-b` flags bypass shell interpretation entirely.
**Rules of thumb:**
- Single-line, no nested quotes -> regular `eval 'expression'` with single quotes is fine
- Nested quotes, arrow functions, template literals, or multiline -> use `eval --stdin <<'EVALEOF'`
- Programmatic/generated scripts -> use `eval -b` with base64
## Configuration File
Create `agent-browser.json` in the project root for persistent settings:
```json
{
"headed": true,
"proxy": "http://localhost:8080",
"profile": "./browser-data"
}
```
Priority (lowest to highest): `~/.agent-browser/config.json` < `./agent-browser.json` < env vars < CLI flags. Use `--config <path>` or `AGENT_BROWSER_CONFIG` env var for a custom config file (exits with error if missing/invalid). All CLI options map to camelCase keys (e.g., `--executable-path` -> `"executablePath"`). Boolean flags accept `true`/`false` values (e.g., `--headed false` overrides config). Extensions from user and project configs are merged, not replaced.
## Deep-Dive Documentation
| Reference | When to Use |
|-----------|-------------|
| [references/commands.md](references/commands.md) | Full command reference with all options |
| [references/snapshot-refs.md](references/snapshot-refs.md) | Ref lifecycle, invalidation rules, troubleshooting |
| [references/session-management.md](references/session-management.md) | Parallel sessions, state persistence, concurrent scraping |
| [references/authentication.md](references/authentication.md) | Login flows, OAuth, 2FA handling, state reuse |
| [references/video-recording.md](references/video-recording.md) | Recording workflows for debugging and documentation |
| [references/profiling.md](references/profiling.md) | Chrome DevTools profiling for performance analysis |
| [references/proxy-support.md](references/proxy-support.md) | Proxy configuration, geo-testing, rotating proxies |
## Ready-to-Use Templates
| Template | Description |
|----------|-------------|
| [templates/form-automation.sh](templates/form-automation.sh) | Form filling with validation |
| [templates/authenticated-session.sh](templates/authenticated-session.sh) | Login once, reuse state |
| [templates/capture-workflow.sh](templates/capture-workflow.sh) | Content extraction with screenshots |
```bash
./templates/form-automation.sh https://example.com/form
./templates/authenticated-session.sh https://app.example.com/login
./templates/capture-workflow.sh https://example.com ./output
```
don't have the plugin yet? install it then click "run inline in claude" again.
agent-browser is a headless browser automation CLI for AI agents and developers. use it when you need to programmatically interact with websites: navigate pages, fill forms, click buttons, extract data, take screenshots, test web apps, handle authentication, or automate any browser-based workflow. triggers include explicit requests like "open a website", "fill out a form", "login to a site", "scrape data", or any task requiring programmatic web interaction. it persists a background browser daemon across command invocations, so chaining operations is efficient and state carries forward within a session.
http://, https://, and file:// (local files) protocols. file:// access requires --allow-file-access flag.npm install -g agent-browser or npx agent-browser:*. verify with agent-browser --version.--auto-connect to discover a running Chrome with remote debugging enabled (--remote-debugging-port=9222), or specify explicit CDP port via --cdp <port>. useful for reusing existing browser context.--proxy <url> flag or AGENT_BROWSER_PROXY env var. required for geo-testing, rotating proxies, or routing through corporate proxies. proxy auth supported in URL format http://user:pass@host:port.npm install -g appium && appium driver install xcuitest). real devices need pre-configuration; use UDID from xcrun xctrace list devices.AGENT_BROWSER_SESSION: default session name (overridden by --session flag).AGENT_BROWSER_CONFIG: path to custom config file (defaults to ~/.agent-browser/config.json then ./agent-browser.json).AGENT_BROWSER_ENCRYPTION_KEY: hex-encoded 32-byte key for encrypting saved session state at rest. generate via openssl rand -hex 32.AGENT_BROWSER_PROXY: proxy URL if not passed via flag.create agent-browser.json in project root for persistent settings (lowest priority) or ~/.agent-browser/config.json (system-wide). CLI flags override env vars which override config files. example:
{
"headed": true,
"proxy": "http://localhost:8080",
"profile": "./browser-data",
"timeout": 60000
}
input: url (http/https/file), optional session name, optional flags (headed, proxy, allow-file-access, auto-connect, cdp port)
step: run agent-browser open <url> with desired flags. if using an existing session, prefix with --session <name>. background daemon spawns and loads page.
output: browser loads page; stdout confirms navigation (e.g., "Navigated to https://example.com"). process waits for initial navigation, not full page load.
edge case: slow pages may timeout at 60s (Playwright default). if timeout occurs, re-run and chain with explicit wait (see step 2).
input: optional wait mode (networkidle, domcontentloaded), optional selector, optional url pattern, optional millisecond duration, optional js condition.
step: after open, run agent-browser wait --load networkidle (recommended for slow pages) or agent-browser wait <selector> to block until element exists, or agent-browser wait --url "**/pattern" for redirects, or agent-browser wait <ms> for fixed delay, or agent-browser wait --fn "condition" for custom js. chain with && to open if output not needed.
output: command exits when condition met (0 exit code) or timeout (1 exit code after 60s default).
edge case: networkidle mode waits for no pending network requests; can be slow on pages with background polling. domcontentloaded is faster but doesn't guarantee all resources loaded. use specific selectors when possible.
input: optional scope selector, optional flags (interactive-only -i recommended, include-cursor -C, json output -j).
step: run agent-browser snapshot -i to list all clickable/fillable elements with auto-generated refs (@e1, @e2, etc.). output maps each ref to element type and text/label. if page has cursor-interactive divs (onclick handlers), add -C flag. to scope to subset, use -s "#selector".
output: stdout lists elements in order: @e1 [input type="email"] placeholder="Email", @e2 [button] "Submit", etc. or json format with --json flag for parsing.
edge case: dynamic content (lazy-loaded, ajax-driven) won't appear until loaded. re-snapshot after clicks/navigation. refs invalidate on page change; must re-snapshot to use fresh refs.
input: element ref from snapshot (@e1, etc.), optional interaction args (text for fill/type, option text for select, key for press, distance for scroll).
step: run agent-browser click @e1 (click), agent-browser fill @e2 "text" (clear then type), agent-browser type @e2 "text" (type without clearing), agent-browser select @e3 "option text" (select dropdown), agent-browser check @e4 (check checkbox), agent-browser press <key> (press key like Enter, Tab, Escape), or agent-browser scroll <direction> <pixels> (scroll page).
output: interaction executes; command exits 0 on success. element must be visible and clickable.
edge case: if element is outside viewport, auto-scrolls into view. if element references stale (from old snapshot), interaction fails with error message "element not found". always re-snapshot after navigation or form submission.
input: optional filename, optional flags (full-page --full, annotated --annotate, with element labels).
step: run agent-browser screenshot <filename> to save png (or agent-browser screenshot --full for full-page capture). use --annotate to overlay numbered labels on interactive elements (each label maps to ref @eN). or agent-browser pdf <filename> for pdf output. or agent-browser get text @e1 to extract element text, agent-browser get text body > file.txt for all page text, agent-browser get url for current url, agent-browser get title for page title.
output: file written to disk with relative or absolute path, or stdout for get commands. annotated screenshots cache refs for immediate use without re-snapshot.
edge case: full-page screenshots may be very large on long pages. annotated mode useful for vision-based reasoning (models can see element positions and labels). refs from --annotate remain valid for subsequent interactions in same session.
input: same as step 3 (optional scope, flags).
step: after any click that navigates, form submission, or dynamic load, run agent-browser snapshot -i again to refresh element refs. do not reuse old refs on new page.
output: fresh element refs for new page state.
edge case: refs are page-specific and browser session-specific. if browser restarted or session closed, all refs invalidate.
input: optional session name, optional state filename, optional encryption key (env var or generated).
step: after completing auth flow or setup, run agent-browser state save <filename> to persist cookies and localStorage. on next invocation, run agent-browser state load <filename> to restore. or use --session-name <name> flag on all commands; state auto-saves to ~/.agent-browser/sessions/<name>.json and auto-loads on next use. for encryption, set AGENT_BROWSER_ENCRYPTION_KEY env var before open/save.
output: state file written (plain json or encrypted), loaded silently on next session. list saved states with agent-browser state list, show one with agent-browser state show <file>, clear with agent-browser state clear <name>, clean old states with agent-browser state clean --older-than <days>.
edge case: state only persists cookies and localStorage, not javascript variables. encrypted state requires matching key on load; wrong key causes load failure. state files are session-specific; cannot reuse auth state across different user accounts or sites unless manually exported/imported.
input: multiple commands, optional session names for isolation.
step: chain operations with && when output of earlier command not needed (e.g., agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i). for concurrent work on multiple sites, use distinct session names: agent-browser --session site1 open https://a.com and agent-browser --session site2 open https://b.com in parallel. manage with agent-browser session list and agent-browser --session <name> close.
output: chained commands execute sequentially in same shell invocation; background daemon persists browser. parallel sessions are isolated; daemon spawns separate browser instance per session.
edge case: chaining is safe and more efficient than spawning separate shell invocations. if command output needed to decide next step (e.g., parse snapshot to find ref), run separately to capture stdout. avoid chaining if early command might fail (exit code will stop chain). cleanup: always close session to avoid leaked processes.
input: javascript expression (single-line simple or multiline via --stdin or base64 via -b), or semantic locator pattern (text, role, label, placeholder, testid).
step: run agent-browser eval 'expression' for simple js, or agent-browser eval --stdin <<'EVALEOF' ... EVALEOF for complex (multiline, nested quotes), or agent-browser eval -b "$(echo -n 'expression' | base64)" for generated scripts. or use agent-browser find text "Label" click to click element containing text, agent-browser find role button click --name "Submit" to click button by name, agent-browser find label "Email" fill "text" to fill by label, etc.
output: js eval returns result as json-serialized output. find commands resolve to element and execute action. both bypass snapshot refs (useful when refs stale or snapshot missed element).
edge case: shell quoting can corrupt js expressions (especially !, $(), backticks, nested quotes). use --stdin with heredoc or -b base64 to avoid shell interpretation. find commands are slower than ref-based interaction (they re-query on each call).
input: optional session name.
step: run agent-browser close (closes default session) or agent-browser --session <name> close (closes specific session). cleans up browser process and saves session state if using --session-name.
output: browser closed, daemon process exits or remains for other sessions.
edge case: if session not closed (e.g., script interrupted), daemon may still hold resources. manually kill with agent-browser close next time, or check agent-browser session list to see orphaned sessions.
agent-browser wait --load networkidle after open to block until network settles. or use agent-browser wait --fn "document.readyState === 'complete'" for javascript readiness.agent-browser wait @e1 or agent-browser wait "#selector" before interacting.agent-browser snapshot -i and use fresh refs.agent-browser find semantic locators instead of refs, or take annotated screenshot to verify element exists and is labeled.agent-browser state save auth.json after login, then agent-browser state load auth.json before subsequent operations.--session-name <name> flag on all commands; state auto-persists and auto-loads.--session agent1, --session agent2, etc. on all commands. each agent gets isolated browser and state.--session flag). reuse same browser across tasks.--allow-file-access flag and agent-browser open file:///path/to/file.pdf.agent-browser -p ios open <url>. snapshot, interact, and screenshot work same as desktop. use agent-browser -p ios tap @e1 for tap (click alias) and agent-browser -p ios swipe <direction> for gestures.agent-browser click @e1 (fastest, cached).agent-browser eval --stdin to run javascript and parse results, or agent-browser find semantic locators to locate by text/role/placeholder.Navigated to <url>. exit code 0.@e1 [input type="email"], @e2 [button] "Submit". or json with --json flag: [{"ref":"@e1","tag":"input","type":"email",...}]. exit code 0.--json flag.~/.agent-browser/sessions/<name>.json. stdout confirms path. exit code 0. file is json (plain or encrypted if key set).site1, site2 (one per line). exit code 0.page loaded: url matches expectation and content visible (if headed flag set, can see in window). stdout says "Navigated to
elements found and labeled: snapshot output lists elements with refs. if using --annotate screenshot, image shows numbered labels on interactive elements matching output refs.
interaction succeeded: element state changed (input filled, button clicked, checkbox checked, page navigated). next snapshot shows updated page state or new page loaded.
form submitted: after click on submit button, page navigates or shows confirmation. re-snapshot confirms you're on success page (check url or new elements).
login successful: after filling credentials and clicking login, page navigates to authenticated area (dashboard, account page, etc.). state file saved for reuse.
data extracted: get text returns content. screenshot or pdf files written to disk. eval returns parsed json result.
session persisted: state save writes file. state load restores without requiring re-login. next session with same --session-name auto-loads state.