97cbcf3eb3
CI / Version Sync Check (push) Has been cancelled
CI / Rust (push) Has been cancelled
CI / Dashboard (push) Has been cancelled
CI / Sandbox Package (push) Has been cancelled
CI / Rust (macos-latest - aarch64-apple-darwin) (push) Has been cancelled
CI / Rust (macos-latest - x86_64-apple-darwin) (push) Has been cancelled
CI / Rust (windows-latest - x86_64-pc-windows-msvc) (push) Has been cancelled
Release / Check for new version (push) Has been cancelled
CI / Native E2E Tests (push) Has been cancelled
CI / Windows Integration Test (push) Has been cancelled
CI / Global Install (macos-latest) (push) Has been cancelled
CI / Global Install (ubuntu-latest) (push) Has been cancelled
CI / Global Install (windows-latest) (push) Has been cancelled
Release / Build macOS ARM64 (push) Has been cancelled
Release / Build Windows x64 (push) Has been cancelled
Release / Publish to npm (push) Has been cancelled
Release / Publish sandbox package to npm (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
Release / Build macOS x64 (push) Has been cancelled
Release / Build Linux ARM64 (push) Has been cancelled
Release / Build Linux musl ARM64 (push) Has been cancelled
Release / Build Linux musl x64 (push) Has been cancelled
Release / Build Linux x64 (push) Has been cancelled
1727 lines
73 KiB
Markdown
1727 lines
73 KiB
Markdown
<!-- WEHUB_ZH_README -->
|
||
> [!NOTE]
|
||
> 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
|
||
> [English](./README.en.md) · [原始项目](https://github.com/vercel-labs/agent-browser) · [上游 README](https://github.com/vercel-labs/agent-browser/blob/HEAD/README.md)
|
||
> 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
|
||
|
||
# agent-browser
|
||
|
||
面向 AI 智能体的浏览器自动化 CLI。原生 Rust CLI,运行快速。
|
||
|
||
[](https://skills.sh/vercel-labs/agent-browser)
|
||
|
||
## 安装
|
||
|
||
### 全局安装(推荐)
|
||
|
||
安装原生 Rust 二进制文件:
|
||
|
||
```bash
|
||
npm install -g agent-browser
|
||
agent-browser install # Download Chrome from Chrome for Testing (first time only)
|
||
```
|
||
|
||
### 项目安装(本地依赖)
|
||
|
||
适用于希望在 `package.json` 中固定版本的项目:
|
||
|
||
```bash
|
||
npm install agent-browser
|
||
agent-browser install
|
||
```
|
||
|
||
随后可通过 `package.json` 脚本使用,或直接调用 `agent-browser`。
|
||
|
||
### Homebrew(macOS)
|
||
|
||
```bash
|
||
brew install agent-browser
|
||
agent-browser install # Download Chrome from Chrome for Testing (first time only)
|
||
```
|
||
|
||
### Cargo(Rust)
|
||
|
||
```bash
|
||
cargo install agent-browser
|
||
agent-browser install # Download Chrome from Chrome for Testing (first time only)
|
||
```
|
||
|
||
### 从源码构建
|
||
|
||
需要 Node.js 24+、pnpm 11+ 和 Rust。
|
||
|
||
```bash
|
||
git clone https://github.com/vercel-labs/agent-browser
|
||
cd agent-browser
|
||
pnpm install
|
||
pnpm build
|
||
pnpm build:native # Requires Rust (https://rustup.rs)
|
||
pnpm link --global # Makes agent-browser available globally
|
||
agent-browser install
|
||
```
|
||
|
||
### Linux 依赖
|
||
|
||
在 Linux 上,请安装系统依赖:
|
||
|
||
```bash
|
||
agent-browser install --with-deps
|
||
```
|
||
|
||
如果包管理器无法安装所有必需的浏览器库,进程将以非零状态退出。
|
||
|
||
### 更新
|
||
|
||
升级到最新版本:
|
||
|
||
```bash
|
||
agent-browser upgrade
|
||
```
|
||
|
||
自动检测你的安装方式(npm、Homebrew 或 Cargo),并运行相应的更新命令。
|
||
|
||
### 系统要求
|
||
|
||
- **Chrome** — 运行 `agent-browser install` 从 [Chrome for Testing](https://developer.chrome.com/blog/chrome-for-testing/)(Google 官方自动化渠道)下载 Chrome。现有的 Chrome、Brave、Playwright 和 Puppeteer 安装会被自动检测。守护进程(daemon)无需 Playwright 或 Node.js。
|
||
- **Node.js 24+ 和 pnpm 11+** — 仅在从源码构建时需要。
|
||
- **Rust** — 仅在从源码构建时需要(参见上文「从源码构建」)。
|
||
|
||
## 快速入门
|
||
|
||
```bash
|
||
agent-browser open example.com
|
||
agent-browser snapshot # Get accessibility tree with refs
|
||
agent-browser click @e2 # Click by ref from snapshot
|
||
agent-browser fill @e3 "test@example.com" # Fill by ref
|
||
agent-browser get text @e1 # Get text by ref
|
||
agent-browser screenshot page.png
|
||
agent-browser close
|
||
```
|
||
|
||
当其他元素遮挡目标的点击位置时(例如同意横幅或模态框),点击会提前失败。请先关闭或与报告中的遮挡元素交互,然后重新获取快照,再重试原始 ref。
|
||
|
||
无头(Headless)Chromium 截图会隐藏原生滚动条,以保证图像输出一致。启动时传入 `--hide-scrollbars false` 可保留原生滚动条可见。
|
||
|
||
### 传统选择器(同样支持)
|
||
|
||
```bash
|
||
agent-browser click "#submit"
|
||
agent-browser fill "#email" "test@example.com"
|
||
agent-browser find role button click --name "Submit"
|
||
```
|
||
|
||
## 命令
|
||
|
||
### 核心命令
|
||
|
||
```bash
|
||
agent-browser open # Launch browser (no navigation); stays on about:blank
|
||
agent-browser open <url> # Launch + navigate to URL (aliases: goto, navigate)
|
||
agent-browser read [url] # Fetch agent-readable text, or read rendered active-tab DOM
|
||
agent-browser click <sel> # Click element (--new-tab to open in new tab)
|
||
agent-browser dblclick <sel> # Double-click element
|
||
agent-browser focus <sel> # Focus element
|
||
agent-browser type <sel> <text> # Type into element
|
||
agent-browser fill <sel> <text> # Clear and fill
|
||
agent-browser press <key> # Press key (Enter, Tab, Control+a) (alias: key)
|
||
agent-browser keyboard type <text> # Type with real keystrokes (no selector, current focus)
|
||
agent-browser keyboard inserttext <text> # Insert text without key events (no selector)
|
||
agent-browser keydown <key> # Hold key down
|
||
agent-browser keyup <key> # Release key
|
||
agent-browser hover <sel> # Hover element
|
||
agent-browser select <sel> <val> # Select dropdown option
|
||
agent-browser check <sel> # Check checkbox
|
||
agent-browser uncheck <sel> # Uncheck checkbox
|
||
agent-browser scroll <dir> [px] # Scroll (up/down/left/right, --selector <sel>)
|
||
agent-browser scrollintoview <sel> # Scroll element into view (alias: scrollinto)
|
||
agent-browser drag <src> <tgt> # Drag and drop
|
||
agent-browser upload <sel> <files> # Upload files
|
||
agent-browser screenshot [path] # Take screenshot (--full for full page, saves to a temporary directory if no path)
|
||
agent-browser screenshot --annotate # Annotated screenshot with numbered element labels
|
||
agent-browser screenshot --screenshot-dir ./shots # Save to custom directory
|
||
agent-browser screenshot --screenshot-format jpeg --screenshot-quality 80
|
||
agent-browser pdf <path> # Save as PDF
|
||
agent-browser snapshot # Accessibility tree with refs (best for AI)
|
||
agent-browser eval <js> # Run JavaScript (-b for base64, --stdin for piped input)
|
||
agent-browser connect <port> # Connect to browser via CDP
|
||
agent-browser stream enable [--port <port>] # Start runtime WebSocket streaming
|
||
agent-browser stream status # Show runtime streaming state and bound port
|
||
agent-browser stream disable # Stop runtime WebSocket streaming
|
||
agent-browser close # Close browser (aliases: quit, exit)
|
||
agent-browser close --all # Close all active sessions
|
||
agent-browser chat "<instruction>" # AI chat: natural language browser control (single-shot)
|
||
agent-browser chat # AI chat: interactive REPL mode
|
||
```
|
||
|
||
### 获取信息
|
||
|
||
```bash
|
||
agent-browser get text <sel> # Get text content
|
||
agent-browser get html <sel> # Get innerHTML
|
||
agent-browser get value <sel> # Get input value
|
||
agent-browser get attr <sel> <attr> # Get attribute
|
||
agent-browser get title # Get page title
|
||
agent-browser get url # Get current URL
|
||
agent-browser get cdp-url # Get CDP WebSocket URL (for DevTools, debugging)
|
||
agent-browser get count <sel> # Count matching elements
|
||
agent-browser get box <sel> # Get bounding box
|
||
agent-browser get styles <sel> # Get computed styles
|
||
```
|
||
|
||
### 读取对智能体友好的文本
|
||
|
||
```bash
|
||
agent-browser read
|
||
agent-browser read https://example.com/article
|
||
agent-browser read https://example.com/article --filter overview
|
||
agent-browser read https://example.com/article --outline
|
||
agent-browser read https://docs.example.com --llms index --filter auth
|
||
agent-browser read https://docs.example.com --llms full --filter auth
|
||
agent-browser read example.com/article --require-md
|
||
agent-browser read https://example.com/article --json
|
||
```
|
||
|
||
`read` 可在不启动 Chrome 的情况下获取 URL。省略 URL 时,会读取当前浏览器会话中活动标签页的渲染后 DOM,包括浏览器认证状态和客户端更新。显式指定 URL 读取时,默认发送 `Accept: text/markdown`;若首次响应不是 markdown,可尝试在同一 URL 后追加 `.md`;沿祖先路径向 `/` 遍历,以查找最近的匹配文档链接 `llms.txt`;在可用时输出 markdown 或纯文本,否则回退到从 HTML 提取的可读文本。未指定 URL 时,`--llms` 和 `--require-md` 使用活动标签页 URL,因为它们依赖 HTTP 资源。除非你明确要求,否则 `read` 不会读取 `llms-full.txt`。
|
||
|
||
选项:`--raw` 直接打印响应体,不进行 HTML 提取;`--require-md` 除非服务器返回 `Content-Type: text/markdown` 否则失败;`--outline` 打印单页的紧凑标题大纲;`--llms index` 打印紧凑的最近祖先 `llms.txt` 链接列表;`--llms full` 读取最近祖先 `llms-full.txt`;`--filter <text>` 可缩小页面区块、llms 链接/区块或大纲标题范围;`--timeout <ms>` 可更改请求超时。`--allowed-domains`、`--content-boundaries` 和 `--max-output` 等全局保护措施同样适用于读取请求与输出。
|
||
|
||
### 检查状态(Check State)
|
||
|
||
```bash
|
||
agent-browser is visible <sel> # Check if visible
|
||
agent-browser is enabled <sel> # Check if enabled
|
||
agent-browser is checked <sel> # Check if checked
|
||
```
|
||
|
||
### 查找元素(语义定位器 Semantic Locators)
|
||
|
||
```bash
|
||
agent-browser find role <role> <action> [value] # By ARIA role
|
||
agent-browser find text <text> <action> # By text content
|
||
agent-browser find label <label> <action> [value] # By label
|
||
agent-browser find placeholder <ph> <action> [value] # By placeholder
|
||
agent-browser find alt <text> <action> # By alt text
|
||
agent-browser find title <text> <action> # By title attr
|
||
agent-browser find testid <id> <action> [value] # By data-testid
|
||
agent-browser find first <sel> <action> [value] # First match
|
||
agent-browser find last <sel> <action> [value] # Last match
|
||
agent-browser find nth <n> <sel> <action> [value] # Nth match
|
||
```
|
||
|
||
**操作:** `click`、`fill`、`type`、`hover`、`focus`、`check`、`uncheck`、`text`
|
||
|
||
**选项:** `--name <name>`(按可访问名称 accessible name 筛选角色 role)、`--exact`(要求精确文本匹配)
|
||
|
||
**示例:**
|
||
|
||
```bash
|
||
agent-browser find role button click --name "Submit"
|
||
agent-browser find text "Sign In" click
|
||
agent-browser find label "Email" fill "test@test.com"
|
||
agent-browser find first ".item" click
|
||
agent-browser find nth 2 "a" text
|
||
```
|
||
|
||
### 等待(Wait)
|
||
|
||
```bash
|
||
agent-browser wait <selector> # Wait for element to be visible
|
||
agent-browser wait <ms> # Wait for time (milliseconds)
|
||
agent-browser wait --text "Welcome" # Wait for text to appear (substring match)
|
||
agent-browser wait --url "**/dash" # Wait for URL pattern
|
||
agent-browser wait --load networkidle # Wait for load state
|
||
agent-browser wait --fn "window.ready === true" # Wait for JS condition
|
||
|
||
# Wait for text/element to disappear
|
||
agent-browser wait --fn "!document.body.innerText.includes('Loading...')"
|
||
agent-browser wait "#spinner" --state hidden
|
||
```
|
||
|
||
**加载状态:** `load`、`domcontentloaded`、`networkidle`
|
||
|
||
### 批量执行(Batch Execution)
|
||
|
||
在单次调用中执行多条命令。命令可作为带引号的参数传入,或通过 stdin 以 JSON 管道方式传入。这可以避免在多步骤工作流中逐条执行命令时的进程启动开销。
|
||
|
||
```bash
|
||
# Argument mode: each quoted argument is a full command
|
||
agent-browser batch "open https://example.com" "snapshot -i" "screenshot"
|
||
|
||
# With --bail to stop on first error
|
||
agent-browser batch --bail "open https://example.com" "click @e1" "screenshot"
|
||
|
||
# Stdin mode: pipe commands as JSON
|
||
echo '[
|
||
["open", "https://example.com"],
|
||
["snapshot", "-i"],
|
||
["click", "@e1"],
|
||
["screenshot", "result.png"]
|
||
]' | agent-browser batch --json
|
||
```
|
||
|
||
### 剪贴板(Clipboard)
|
||
|
||
```bash
|
||
agent-browser clipboard read # Read text from clipboard
|
||
agent-browser clipboard write "Hello, World!" # Write text to clipboard
|
||
agent-browser clipboard copy # Copy current selection (Ctrl+C)
|
||
agent-browser clipboard paste # Paste from clipboard (Ctrl+V)
|
||
```
|
||
|
||
### 鼠标控制(Mouse Control)
|
||
|
||
```bash
|
||
agent-browser mouse move <x> <y> # Move mouse
|
||
agent-browser mouse down [button] # Press button (left/right/middle)
|
||
agent-browser mouse up [button] # Release button
|
||
agent-browser mouse wheel <dy> [dx] # Scroll wheel
|
||
```
|
||
|
||
### 浏览器设置(Browser Settings)
|
||
|
||
```bash
|
||
agent-browser set viewport <w> <h> [scale] # Set viewport size (scale for retina, e.g. 2)
|
||
agent-browser set device <name> # Emulate device ("iPhone 14")
|
||
agent-browser set geo <lat> <lng> # Set geolocation
|
||
agent-browser set offline [on|off] # Toggle offline mode
|
||
agent-browser set headers <json> # Extra HTTP headers
|
||
agent-browser set credentials <u> <p> # HTTP basic auth
|
||
agent-browser set media [dark|light] # Emulate color scheme
|
||
```
|
||
|
||
### Cookie 与存储(Cookies & Storage)
|
||
|
||
```bash
|
||
agent-browser cookies # Get all cookies
|
||
agent-browser cookies set <name> <val> # Set cookie
|
||
agent-browser cookies set --curl <file> # Import cookies from a Copy-as-cURL dump,
|
||
# JSON array, or bare Cookie header (auto-detected)
|
||
agent-browser cookies clear # Clear cookies
|
||
|
||
agent-browser storage local # Get all localStorage
|
||
agent-browser storage local <key> # Get specific key
|
||
agent-browser storage local set <k> <v> # Set value
|
||
agent-browser storage local clear # Clear all
|
||
|
||
agent-browser storage session # Same for sessionStorage
|
||
```
|
||
|
||
### 网络(Network)
|
||
|
||
```bash
|
||
agent-browser network route <url> # Intercept requests
|
||
agent-browser network route <url> --abort # Block requests
|
||
agent-browser network route <url> --body <json> # Mock response
|
||
agent-browser network route '*' --abort --resource-type script # Block scripts only
|
||
agent-browser network unroute [url] # Remove routes
|
||
agent-browser network requests # View tracked requests
|
||
agent-browser network requests --filter api # Filter requests
|
||
agent-browser network requests --type xhr,fetch # Filter by resource type
|
||
agent-browser network requests --method POST # Filter by HTTP method
|
||
agent-browser network requests --status 2xx # Filter by status (200, 2xx, 400-499)
|
||
agent-browser network request <requestId> # View full request/response detail
|
||
agent-browser network har start # Start HAR recording
|
||
agent-browser network har stop [output.har] # Stop and save HAR (temp path if omitted)
|
||
```
|
||
|
||
### 标签页与窗口(Tabs & Windows)
|
||
|
||
```bash
|
||
agent-browser tab # List tabs (shows `tabId` and optional label)
|
||
agent-browser tab new [url] # New tab (optionally with URL)
|
||
agent-browser tab new --label docs [url] # New tab with a user-assigned label
|
||
agent-browser tab <t<N>|label> # Switch to a tab by id or label
|
||
agent-browser tab close [t<N>|label] # Close a tab (defaults to active)
|
||
agent-browser window new # New window
|
||
```
|
||
|
||
标签页 id 是形如 `t1`、`t2`、`t3` 的稳定字符串。在同一会话内它们不会被复用,因此即使其他标签页被打开或关闭,脚本和 agent 仍可继续引用同一标签页。像 `tab 2` 这样的位置整数**不**被接受;`t` 前缀用于将句柄与索引区分开,并与元素引用所使用的 `@e1` 约定保持一致。
|
||
|
||
你也可以指定一个易记的标签(`docs`、`app`、`admin`),并与 id 互换使用。标签不会自动生成,也不会在导航时被重写——由你命名并保留:
|
||
|
||
```bash
|
||
agent-browser tab new --label docs https://docs.example.com
|
||
agent-browser tab docs # switch to the docs tab
|
||
agent-browser snapshot # populate refs for docs
|
||
agent-browser click @e3 # click uses docs's refs
|
||
agent-browser tab close docs # close by label
|
||
```
|
||
|
||
### 框架(Frames)
|
||
|
||
```bash
|
||
agent-browser frame <sel> # Switch to iframe
|
||
agent-browser frame main # Back to main frame
|
||
```
|
||
|
||
### 对话框(Dialogs)
|
||
|
||
```bash
|
||
agent-browser dialog accept [text] # Accept (with optional prompt text)
|
||
agent-browser dialog dismiss # Dismiss
|
||
agent-browser dialog status # Check if a dialog is currently open
|
||
```
|
||
|
||
默认情况下,`alert` 和 `beforeunload` 对话框会自动接受,因此不会阻塞 agent。`confirm` 和 `prompt` 对话框仍需显式处理。使用 `--no-auto-dialog`(或 `AGENT_BROWSER_NO_AUTO_DIALOG=1`)可禁用自动处理。
|
||
|
||
当 JavaScript 对话框处于待处理状态时,所有命令响应都会包含一个 `warning` 字段,其中带有对话框类型和消息。
|
||
|
||
### 差异对比(Diff)
|
||
|
||
```bash
|
||
agent-browser diff snapshot # Compare current vs last snapshot
|
||
agent-browser diff snapshot --baseline before.txt # Compare current vs saved snapshot file
|
||
agent-browser diff snapshot --selector "#main" --compact # Scoped snapshot diff
|
||
agent-browser diff screenshot --baseline before.png # Visual pixel diff against baseline
|
||
agent-browser diff screenshot --baseline b.png -o d.png # Save diff image to custom path
|
||
agent-browser diff screenshot --baseline b.png -t 0.2 # Adjust color threshold (0-1)
|
||
agent-browser diff url https://v1.com https://v2.com # Compare two URLs (snapshot diff)
|
||
agent-browser diff url https://v1.com https://v2.com --screenshot # Also visual diff
|
||
agent-browser diff url https://v1.com https://v2.com --wait-until networkidle # Custom wait strategy
|
||
agent-browser diff url https://v1.com https://v2.com --selector "#main" # Scope to element
|
||
```
|
||
|
||
### Debug
|
||
|
||
```bash
|
||
agent-browser trace start # Start recording trace
|
||
agent-browser trace stop [path] # Stop and save trace
|
||
agent-browser profiler start # Start Chrome DevTools profiling
|
||
agent-browser profiler stop [path] # Stop and save profile (.json)
|
||
agent-browser console # View console messages (log, error, warn, info)
|
||
agent-browser console --json # JSON output with raw CDP args for programmatic access
|
||
agent-browser console --clear # Clear console
|
||
agent-browser errors # View page errors (uncaught JavaScript exceptions)
|
||
agent-browser errors --clear # Clear errors
|
||
agent-browser highlight <sel> # Highlight element
|
||
agent-browser inspect # Open Chrome DevTools for the active page
|
||
agent-browser state save <path> # Save auth state
|
||
agent-browser state load <path> # Load auth state
|
||
agent-browser state list # List saved state files
|
||
agent-browser state show <file> # Show state summary
|
||
agent-browser state rename <old> <new> # Rename state file
|
||
agent-browser state clear [name] # Clear states for session
|
||
agent-browser state clear --all # Clear all saved states
|
||
agent-browser state clean --older-than <days> # Delete old states
|
||
```
|
||
|
||
### Navigation
|
||
|
||
```bash
|
||
agent-browser back # Go back
|
||
agent-browser forward # Go forward
|
||
agent-browser reload # Reload page
|
||
agent-browser pushstate <url> # SPA client-side nav; auto-detects window.next.router.push,
|
||
# falls back to history.pushState + popstate
|
||
```
|
||
|
||
### 导航前准备
|
||
|
||
部分流程(SSR 调试、受保护来源的 auth cookies、init scripts)需要在首次导航*之前*完成状态设置。使用不带 URL 的 `open` 启动浏览器,然后配置 cookies / routes / init scripts,再进行导航。`batch` 可在一次 CLI 调用中完成上述全部操作:
|
||
|
||
```bash
|
||
agent-browser batch \
|
||
'["open"]' \
|
||
'["network","route","*","--abort","--resource-type","script"]' \
|
||
'["cookies","set","--curl","cookies.curl","--domain","localhost"]' \
|
||
'["navigate","http://localhost:3000/target"]'
|
||
```
|
||
|
||
若不使用 `batch`,相同流程需要三条命令,但都会复用同一 daemon(速度快,但不是一轮完成)。
|
||
|
||
### React / Web Vitals
|
||
|
||
agent-browser 内置一流的 React 内省(introspection)和通用的 Web Vitals 指标。React 命令需要在启动时安装 React DevTools hook;Web Vitals 和 pushstate 与框架无关。
|
||
|
||
```bash
|
||
agent-browser open --enable react-devtools <url> # Launch with React hook installed
|
||
agent-browser react tree # Full component tree
|
||
agent-browser react inspect <fiberId> # props, hooks, state, source
|
||
agent-browser react renders start # Begin fiber render recording
|
||
agent-browser react renders stop [--json] # Stop and print profile (--json for raw data)
|
||
agent-browser react suspense [--only-dynamic] [--json] # Suspense boundaries + classifier
|
||
# --only-dynamic hides the "static" list
|
||
agent-browser vitals [url] [--json] # LCP/CLS/TTFB/FCP/INP + hydration summary
|
||
```
|
||
|
||
每个 `react ...` 子命令都要求启动时传入 `--enable react-devtools`(React DevTools `installHook.js` 已嵌入二进制文件)。未传入时,命令会报错:`React DevTools hook not installed
|
||
- relaunch with --enable react-devtools`。
|
||
|
||
适用于任意 React 应用 — Next.js、Remix、Vite+React、CRA、TanStack Start、React Native Web 等。`vitals` 和 `pushstate` 与框架无关。`vitals` 默认打印摘要;传入 `--json` 可获取完整的结构化 payload。
|
||
|
||
### Init scripts
|
||
|
||
```bash
|
||
agent-browser open --init-script <path> # Register page init script before first navigation
|
||
# (repeatable; also AGENT_BROWSER_INIT_SCRIPTS env)
|
||
agent-browser addinitscript <js> # Register at runtime (returns identifier)
|
||
agent-browser removeinitscript <identifier> # Remove a previously registered init script
|
||
```
|
||
|
||
### Setup
|
||
|
||
```bash
|
||
agent-browser install # Download Chrome from Chrome for Testing (Google's official automation channel)
|
||
agent-browser install --with-deps # Also install system deps (Linux)
|
||
agent-browser upgrade # Upgrade agent-browser to the latest version
|
||
agent-browser doctor # Diagnose the install and auto-clean stale daemon files
|
||
agent-browser doctor --fix # Also run destructive repairs (reinstall Chrome, purge old state, ...)
|
||
agent-browser doctor --offline --quick # Skip network probes and the live launch test
|
||
agent-browser mcp # Start an MCP stdio server
|
||
```
|
||
|
||
`doctor` 会检查你的环境、Chrome 安装、daemon 状态、配置文件、加密密钥、providers、网络可达性,并运行一次实时的无头浏览器启动测试。过期的 socket/pid sidecar 文件会自动清理。输出也可通过 `--json` 供 agents 使用。
|
||
|
||
### Skills
|
||
|
||
```bash
|
||
agent-browser skills # List available skills
|
||
agent-browser skills list # Same as above
|
||
agent-browser skills get <name> # Output a skill's full content
|
||
agent-browser skills get <name> --full # Include references and templates
|
||
agent-browser skills get --all # Output every skill
|
||
agent-browser skills path [name] # Print skill directory path
|
||
```
|
||
|
||
提供与已安装 CLI 版本始终一致的捆绑 skill 内容。AI agents 通过此方式获取最新指令,而不是依赖缓存副本。设置 `AGENT_BROWSER_SKILLS_DIR` 可覆盖 skills 目录路径。
|
||
|
||
### MCP Server
|
||
|
||
```bash
|
||
agent-browser mcp
|
||
agent-browser mcp --tools all
|
||
agent-browser mcp --tools core,network,react
|
||
```
|
||
|
||
通过 stdio 启动 Model Context Protocol(MCP)服务器。MCP 客户端将此命令作为子进程启动,并在 stdin 与 stdout 上交换换行分隔的 JSON-RPC。服务器默认使用 MCP 协议 2025-11-25,并在初始化期间接受更早的受支持客户端协议版本。
|
||
|
||
默认 tools profile 为 `core`,可保持 MCP 上下文精简,适用于日常浏览器自动化。使用 `--tools all` 可获取完整的 typed CLI 对等能力,或用逗号组合多个 profile,例如 `--tools core,network,react`。
|
||
|
||
Profiles:
|
||
|
||
- `core` — 默认。导航、快照、交互、等待、读取、截图、JavaScript eval、close、标签页基础操作,以及 profile 发现
|
||
- `network` — 网络 routes、请求检查、HAR、headers、credentials、offline
|
||
- `state` — Cookies、storage、auth、saved state、sessions、profiles、skills
|
||
- `debug` — Console/errors、tracing、profiling、recording、clipboard、plugins、doctor、dashboard、install、upgrade、chat、diff、batch、confirm/deny
|
||
- `tabs` — 后退/前进/刷新、tabs、windows、frames、dialogs
|
||
- `react` — React tree/inspect/renders/suspense、vitals、pushstate
|
||
- `mobile` — Viewport/device/geolocation/media、touch、swipe、mouse、keyboard
|
||
- `all` — 全部 MCP tool,包括完整的 typed CLI 对等能力
|
||
|
||
常用 tools 包括:
|
||
|
||
- `agent_browser_tools_profiles`
|
||
- `agent_browser_open`
|
||
- `agent_browser_snapshot`
|
||
- `agent_browser_click`
|
||
- `agent_browser_fill`
|
||
- `agent_browser_type`
|
||
- `agent_browser_press`
|
||
- `agent_browser_wait_for_selector`
|
||
- `agent_browser_screenshot`
|
||
- `agent_browser_get_url`
|
||
- `agent_browser_eval`
|
||
- `agent_browser_close`
|
||
|
||
每个 tool 都有类型化字段,例如 `url`、`selector`、`text`、`key` 和 `session`,因此 MCP 客户端会显示有意义的审批提示,而不是原始命令数组。每个 tool 也接受 `extraArgs`,用于高级 CLI flags 和精确的 CLI 对等。Tool 发现支持分页,并包含只读/open-world 注解,以便现代 MCP 客户端可增量加载庞大的 typed 能力面。
|
||
|
||
MCP 客户端配置示例:
|
||
|
||
```json
|
||
{
|
||
"mcpServers": {
|
||
"agent-browser": {
|
||
"command": "agent-browser",
|
||
"args": ["mcp"]
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
完整对等 MCP 客户端配置:
|
||
|
||
```json
|
||
{
|
||
"mcpServers": {
|
||
"agent-browser": {
|
||
"command": "agent-browser",
|
||
"args": ["mcp", "--tools", "all"]
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
工具调用与 CLI 使用相同的配置文件和环境变量。在工具参数中使用 `session`,或设置 `AGENT_BROWSER_SESSION`,以隔离浏览器状态。
|
||
|
||
## 身份验证
|
||
|
||
agent-browser 提供多种方式来持久化登录会话,这样你就不必在每次运行时都重新进行身份验证。
|
||
|
||
### 快速概览
|
||
|
||
| 方式 | 适用场景 | 标志 / 环境变量 |
|
||
|----------|----------|------------|
|
||
| **Chrome profile reuse** | 零配置即可复用你现有的 Chrome 登录状态(cookie、会话) | `--profile <name>` / `AGENT_BROWSER_PROFILE` |
|
||
| **Persistent profile** | 在重启后保留完整浏览器状态(cookie、IndexedDB、service worker、缓存) | `--profile <path>` / `AGENT_BROWSER_PROFILE` |
|
||
| **Session persistence** | 通过稳定的会话键自动保存/恢复 cookie 与 localStorage | `--session <id> --restore` / `AGENT_BROWSER_RESTORE` |
|
||
| **Import from your browser** | 从你已登录的 Chrome 会话中获取身份验证信息 | `--auto-connect` + `state save` |
|
||
| **State file** | 启动时加载先前保存的状态 JSON | `--state <path>` / `AGENT_BROWSER_STATE` |
|
||
| **Auth vault** | 在本地存储凭据(加密),按名称登录 | `auth save` / `auth login` |
|
||
|
||
### 从浏览器导入身份验证信息
|
||
|
||
如果你已在 Chrome 中登录某个网站,可以获取该身份验证状态并重复使用:
|
||
|
||
```bash
|
||
# 1. Launch Chrome with remote debugging enabled
|
||
# macOS:
|
||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --remote-debugging-port=9222
|
||
# Or use --auto-connect to discover an already-running Chrome
|
||
|
||
# 2. Connect and save the authenticated state
|
||
agent-browser --auto-connect state save ./my-auth.json
|
||
|
||
# 3. Use the saved auth in future sessions
|
||
agent-browser --state ./my-auth.json open https://app.example.com/dashboard
|
||
|
||
# 4. Or use --restore for automatic persistence
|
||
SESSION="$(agent-browser session id --scope worktree --prefix myapp)"
|
||
agent-browser --session "$SESSION" --restore --state ./my-auth.json open https://app.example.com/dashboard
|
||
# From now on, --session "$SESSION" --restore auto-saves/restores this state
|
||
```
|
||
|
||
> **安全说明:**
|
||
> - `--remote-debugging-port` 会在 localhost 上暴露完整的浏览器控制能力。任何本地进程都可以连接。仅在受信任的机器上使用,用完后关闭 Chrome。
|
||
> - 状态文件以明文形式包含会话令牌。请将它们加入 `.gitignore`,并在不再需要时删除。若要对静态存储进行加密,请设置 `AGENT_BROWSER_ENCRYPTION_KEY`(参见[状态加密](#state-encryption))。
|
||
|
||
有关登录流程、OAuth、2FA、基于 cookie 的身份验证以及 auth vault 的完整说明,请参阅 [Authentication](docs/src/app/sessions/page.mdx) 文档。
|
||
|
||
## 会话
|
||
|
||
运行多个相互隔离的浏览器实例:
|
||
|
||
```bash
|
||
# Different sessions
|
||
agent-browser --session agent1 open site-a.com
|
||
agent-browser --session agent2 open site-b.com
|
||
|
||
# Or via environment variable
|
||
AGENT_BROWSER_SESSION=agent1 agent-browser click "#btn"
|
||
|
||
# List active sessions
|
||
agent-browser session list
|
||
# Output:
|
||
# Active sessions:
|
||
# -> default
|
||
# agent1
|
||
|
||
# Show current session
|
||
agent-browser session
|
||
|
||
# Generate a stable worktree-scoped session id
|
||
agent-browser session id --scope worktree --prefix next-dev-loop
|
||
|
||
# Inspect daemon, launch, and restore status
|
||
agent-browser session info --json
|
||
```
|
||
|
||
每个会话都拥有独立的:
|
||
|
||
- 浏览器实例
|
||
- Cookie 与存储
|
||
- 导航历史
|
||
- 身份验证状态
|
||
|
||
## 复用 Chrome 配置文件
|
||
|
||
使用现有登录状态的最快方式:向 `--profile` 传入 Chrome 配置文件名称:
|
||
|
||
```bash
|
||
# List available Chrome profiles
|
||
agent-browser profiles
|
||
|
||
# Reuse your default Chrome profile's login state
|
||
agent-browser --profile Default open https://gmail.com
|
||
|
||
# Use a named profile (by display name or directory name)
|
||
agent-browser --profile "Work" open https://app.example.com
|
||
|
||
# Or via environment variable
|
||
AGENT_BROWSER_PROFILE=Default agent-browser open https://gmail.com
|
||
```
|
||
|
||
这会将你的 Chrome 配置文件复制到临时目录(只读快照,不会修改原始配置文件),因此浏览器启动时会带上你现有的 cookie 和会话。
|
||
|
||
> **注意:** 在 Windows 上,如果 Chrome 正在运行,使用 `--profile <name>` 前请先关闭 Chrome,因为部分配置文件可能被锁定。
|
||
|
||
## 持久化配置文件
|
||
|
||
若要在浏览器重启后仍保留状态,请向 `--profile` 传入持久化自定义配置文件目录的路径:
|
||
|
||
```bash
|
||
# Use a persistent profile directory
|
||
agent-browser --profile ~/.myapp-profile open myapp.com
|
||
|
||
# Login once, then reuse the authenticated session
|
||
agent-browser --profile ~/.myapp-profile open myapp.com/dashboard
|
||
|
||
# Or via environment variable
|
||
AGENT_BROWSER_PROFILE=~/.myapp-profile agent-browser open myapp.com
|
||
```
|
||
|
||
配置文件目录会存储:
|
||
|
||
- Cookie 与 localStorage
|
||
- IndexedDB 数据
|
||
- Service Worker
|
||
- 浏览器缓存
|
||
- 登录会话
|
||
|
||
**提示**:为不同项目使用不同的配置文件路径,以保持各自的浏览器状态相互隔离。
|
||
|
||
## 会话持久化
|
||
|
||
将 `--restore` 与稳定的 `--session` 配合使用,可在浏览器重启后自动保存并恢复 cookie 与 localStorage:
|
||
|
||
```bash
|
||
# Generate a stable id for this worktree and auto-save/load state
|
||
SESSION="$(agent-browser session id --scope worktree --prefix twitter)"
|
||
agent-browser --session "$SESSION" --restore open twitter.com
|
||
|
||
# Login once, then state persists automatically
|
||
# State files stored in ~/.agent-browser/sessions/
|
||
|
||
# Optional: validate restored state before auto-saving again
|
||
agent-browser --session "$SESSION" --restore --restore-check-text Dashboard open twitter.com
|
||
```
|
||
|
||
浏览器关闭时会保存状态(显式 `close`、空闲超时或守护进程关闭),在浏览器运行期间也会定期保存,因此你手动关闭的浏览器窗口仍会留下最近的保存记录。定期自动保存会等待命令执行完毕,然后最多每 `AGENT_BROWSER_AUTOSAVE_INTERVAL_MS` 保存一次(默认 30000;设为 `0` 则仅在关闭时保存)。空闲会话仍按相同间隔保存,因此页面自行产生的变更(令牌刷新、后台请求)也会被捕获。它会遵循 `--restore-save` 策略。
|
||
|
||
### 状态加密
|
||
|
||
使用 AES-256-GCM 对静态存储的会话数据进行加密:
|
||
|
||
```bash
|
||
# Generate key: openssl rand -hex 32
|
||
export AGENT_BROWSER_ENCRYPTION_KEY=<64-char-hex-key>
|
||
|
||
# State files are now encrypted automatically
|
||
agent-browser --session secure --restore open example.com
|
||
```
|
||
|
||
| 变量 | 说明 |
|
||
| --------------------------------- | -------------------------------------------------- |
|
||
| `AGENT_BROWSER_RESTORE` | 自动保存/加载状态持久化名称 |
|
||
| `AGENT_BROWSER_RESTORE_SAVE` | 恢复保存策略:`auto`、`always` 或 `never` |
|
||
| `AGENT_BROWSER_AUTOSAVE_INTERVAL_MS` | 定期自动保存之间的最小毫秒数(默认:30000,0 表示禁用) |
|
||
| `AGENT_BROWSER_NAMESPACE` | 守护进程套接字与恢复状态的命名空间 |
|
||
| `AGENT_BROWSER_SESSION_NAME` | 旧版自动保存/加载状态持久化名称 |
|
||
| `AGENT_BROWSER_ENCRYPTION_KEY` | 用于 AES-256-GCM 加密的 64 字符十六进制密钥 |
|
||
| `AGENT_BROWSER_STATE_EXPIRE_DAYS` | 自动删除超过 N 天的状态(默认:30) |
|
||
|
||
## 安全
|
||
|
||
agent-browser 包含用于安全部署 AI agent 的安全功能。所有功能均为可选启用,在你显式启用某项功能之前,现有工作流不受影响:
|
||
|
||
- **Authentication Vault(身份验证保险库)**:在本地存储凭据(始终加密),按名称引用。LLM 永远不会看到密码。`auth login` 使用 `load` 导航,然后等待登录表单选择器出现(适配 SPA,超时遵循默认操作超时)。若未设置 `AGENT_BROWSER_ENCRYPTION_KEY`,会在 `~/.agent-browser/.encryption-key` 自动生成密钥:`echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin`,然后 `agent-browser auth login github`
|
||
- **Plugin System(插件系统)**:通过外部可执行插件扩展 agent-browser。插件通过 `agent-browser.plugin.v1` stdio JSON 协议在进程外运行,并声明 `credential.read`、`browser.provider`、`launch.mutate` 或 `command.run` 等能力。
|
||
- **Content Boundary Markers(内容边界标记)**:用分隔符包裹页面输出,使 LLM 能区分工具输出与不受信任的内容:`--content-boundaries`
|
||
- **Domain Allowlist(域名允许列表)**:将导航限制在受信任域名(通配符如 `*.example.com` 也会匹配裸域名):`--allowed-domains "example.com,*.example.com"`。对非允许域名的子资源请求(脚本、图片、fetch)以及 WebSocket/EventSource 连接也会被阻止。请包含目标页面所依赖的任何 CDN 域名(例如 `*.cdn.example.com`)。
|
||
- **Action Policy(操作策略)**:通过静态策略文件管控破坏性操作:`--action-policy ./policy.json`
|
||
- **Action Confirmation(操作确认)**:对敏感操作类别要求显式批准:`--confirm-actions eval,download`
|
||
- **Output Length Limits(输出长度限制)**:防止上下文泛滥:`--max-output 50000`
|
||
|
||
| 变量 | 说明 |
|
||
| ----------------------------------- | ---------------------------------------- |
|
||
| `AGENT_BROWSER_CONTENT_BOUNDARIES` | 在页面输出外包装边界标记 |
|
||
| `AGENT_BROWSER_MAX_OUTPUT` | 页面输出的最大字符数 |
|
||
| `AGENT_BROWSER_ALLOWED_DOMAINS` | 逗号分隔的允许域名模式 |
|
||
| `AGENT_BROWSER_ACTION_POLICY` | 操作策略 JSON 文件路径 |
|
||
| `AGENT_BROWSER_CONFIRM_ACTIONS` | 需要确认的操作类别 |
|
||
| `AGENT_BROWSER_CONFIRM_INTERACTIVE` | 启用交互式确认提示 |
|
||
| `AGENT_BROWSER_PLUGINS` | JSON 插件注册表覆盖 |
|
||
|
||
详见[安全文档](https://agent-browser.dev/security) 了解详情。
|
||
|
||
### 插件系统
|
||
|
||
插件允许第三方工具集成,而无需成为 agent-browser 的内置依赖。从 npm 或 GitHub 添加插件:
|
||
|
||
```bash
|
||
agent-browser plugin add agent-browser-plugin-captcha
|
||
agent-browser plugin add @company/agent-browser-plugin-vault --name vault
|
||
agent-browser plugin add org/agent-browser-plugin-cloud-browser
|
||
```
|
||
|
||
引用按形态解析:`name` 使用 npm,`@scope/name` 使用 npm,`owner/repo` 使用 GitHub。`plugin add` 默认写入 `./agent-browser.json`;对 `~/.agent-browser/config.json` 使用 `--global`。
|
||
|
||
插件包应支持 `plugin.manifest`,以便 `plugin add` 能自动发现其名称和功能。若插件不支持清单(manifest),在添加时传入 `--capability <name>`。
|
||
|
||
也可以在 `agent-browser.json` 中手动配置插件:
|
||
|
||
```json
|
||
{
|
||
"plugins": [
|
||
{
|
||
"name": "vault",
|
||
"command": "agent-browser-plugin-vault",
|
||
"capabilities": ["credential.read"]
|
||
},
|
||
{
|
||
"name": "cloud-browser",
|
||
"command": "agent-browser-plugin-cloud-browser",
|
||
"capabilities": ["browser.provider"]
|
||
},
|
||
{
|
||
"name": "stealth",
|
||
"command": "agent-browser-plugin-stealth",
|
||
"capabilities": ["launch.mutate"]
|
||
},
|
||
{
|
||
"name": "captcha",
|
||
"command": "agent-browser-plugin-captcha",
|
||
"capabilities": ["command.run", "captcha.solve"]
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
检查已配置的插件:
|
||
|
||
```bash
|
||
agent-browser plugin list
|
||
agent-browser plugin show vault
|
||
```
|
||
|
||
使用凭据提供方(credential provider)插件进行单次登录:
|
||
|
||
```bash
|
||
agent-browser auth login my-app --credential-provider vault --item "My App"
|
||
agent-browser auth login my-app --credential-provider vault --item "My App" --url https://app.example.com/login --username-selector "#email" --password-selector "#password" --submit-selector "button[type=submit]"
|
||
```
|
||
|
||
使用浏览器提供方(browser provider)插件:
|
||
|
||
```bash
|
||
agent-browser --provider cloud-browser open https://example.com
|
||
```
|
||
|
||
使用启动变更(launch mutator)插件实现隐身或本地启动自定义。浏览器启动前,插件可追加 Chrome 参数、扩展和初始化脚本:
|
||
|
||
```bash
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
对 CAPTCHA 求解器等特定领域工具,使用通用插件命令:
|
||
|
||
```bash
|
||
agent-browser plugin run captcha captcha.solve --payload '{"siteKey":"...","url":"https://example.com"}'
|
||
```
|
||
|
||
协议请求始终包含 `protocol`、`type`、`capability` 和 `request`。凭据插件接收 `credential.resolve`,浏览器提供方接收 `browser.launch`,启动变更器接收 `launch.mutate`,通用命令接收所提供的请求类型。`plugin run` 用于 `command.run` 及自定义能力;核心能力和协议请求类型使用其专用命令路径。agent-browser 将浏览器自动化、脱敏敏感输出和策略强制执行保留在核心中。
|
||
|
||
按能力操作限制插件访问:
|
||
|
||
```bash
|
||
agent-browser --confirm-actions plugin:vault:credential.read auth login my-app --credential-provider vault --item "My App"
|
||
agent-browser --confirm-actions plugin:cloud-browser:browser.provider --provider cloud-browser open https://example.com
|
||
agent-browser --confirm-actions plugin:stealth:launch.mutate open https://example.com
|
||
```
|
||
|
||
不要在插件命令参数中放置保管库(vault)令牌或密码。请使用保管库供应商自身的登录/会话机制,或在 agent-browser 配置之外的环境变量中配置。
|
||
|
||
## 快照选项
|
||
|
||
`snapshot` 命令支持过滤以减小输出体积:
|
||
|
||
```bash
|
||
agent-browser snapshot # Full accessibility tree
|
||
agent-browser snapshot -i # Interactive elements only (buttons, inputs, links)
|
||
agent-browser snapshot -i --urls # Interactive elements with link URLs
|
||
agent-browser snapshot -c # Compact (remove empty structural elements)
|
||
agent-browser snapshot -d 3 # Limit depth to 3 levels
|
||
agent-browser snapshot -s "#main" # Scope to CSS selector
|
||
agent-browser snapshot -i -c -d 5 # Combine options
|
||
```
|
||
|
||
| 选项 | 说明 |
|
||
| ---------------------- | ----------------------------------------------------------------------- |
|
||
| `-i, --interactive` | 仅显示交互元素(按钮、链接、输入框) |
|
||
| `-u, --urls` | 为链接元素包含 href URL |
|
||
| `-c, --compact` | 移除空的结构元素 |
|
||
| `-d, --depth <n>` | 限制树深度 |
|
||
| `-s, --selector <sel>` | 限定为 CSS 选择器范围 |
|
||
|
||
## 标注截图
|
||
|
||
`--annotate` 标志会在截图中的交互元素上叠加编号标签。每个标签 `[N]` 对应 ref `@eN`,因此同一套 ref 可同时用于视觉工作流和基于文本的工作流。
|
||
|
||
基于 CDP(Chrome DevTools Protocol)的浏览器路径(Chrome/Lightpanda)支持标注截图。Safari/WebDriver 后端尚不支持 `--annotate`。
|
||
|
||
```bash
|
||
agent-browser screenshot --annotate
|
||
# -> Screenshot saved to /tmp/screenshot-2026-02-17T12-00-00-abc123.png
|
||
# [1] @e1 button "Submit"
|
||
# [2] @e2 link "Home"
|
||
# [3] @e3 textbox "Email"
|
||
```
|
||
|
||
标注截图后,ref 会被缓存,便于立即与元素交互:
|
||
|
||
```bash
|
||
agent-browser screenshot --annotate ./page.png
|
||
agent-browser click @e2 # Click the "Home" link labeled [2]
|
||
```
|
||
|
||
这对能够推理视觉布局、无文字图标按钮、canvas 元素或文本无障碍树无法捕获的视觉状态的多模态 AI 模型很有用。
|
||
|
||
## 选项
|
||
|
||
| 选项 | 说明 |
|
||
|--------|-------------|
|
||
| `--session <name>` | 使用隔离会话(或 `AGENT_BROWSER_SESSION` 环境变量) |
|
||
| `--restore [name]` | 自动保存/恢复会话状态。单独的 `--restore` 以 `--session` 作为键 |
|
||
| `--restore-save <policy>` | 恢复保存策略:`auto`、`always` 或 `never` |
|
||
| `--restore-check-url <glob>` | 根据 URL 模式验证恢复的状态 |
|
||
| `--restore-check-text <text>` | 根据页面文本验证恢复的状态 |
|
||
| `--restore-check-fn <js>` | 根据为真的 JavaScript 表达式验证恢复的状态 |
|
||
| `--namespace <name>` | 隔离守护进程套接字和恢复状态目录 |
|
||
| `--session-name <name>` | 恢复持久化键的旧版别名 |
|
||
| `--profile <name\|path>` | Chrome 配置文件名称或持久目录路径(或 `AGENT_BROWSER_PROFILE` 环境变量) |
|
||
| `--state <path>` | 从 JSON 文件加载存储状态(或 `AGENT_BROWSER_STATE` 环境变量) |
|
||
| `--headers <json>` | 设置限定于 URL 源(origin)的 HTTP 标头 |
|
||
| `--executable-path <path>` | 自定义浏览器可执行文件(或 `AGENT_BROWSER_EXECUTABLE_PATH` 环境变量) |
|
||
| `--extension <path>` | 加载浏览器扩展(可重复;或 `AGENT_BROWSER_EXTENSIONS` 环境变量) |
|
||
| `--init-script <path>` | 在首次导航前注册页面初始化脚本(可重复;或 `AGENT_BROWSER_INIT_SCRIPTS` 环境变量) |
|
||
| `--enable <feature>` | 内置初始化脚本:`react-devtools`(可重复或逗号分隔列表;或 `AGENT_BROWSER_ENABLE` 环境变量) |
|
||
| `--args <args>` | 浏览器启动参数,逗号或换行分隔(或 `AGENT_BROWSER_ARGS` 环境变量) |
|
||
| `--user-agent <ua>` | 自定义 User-Agent 字符串(或 `AGENT_BROWSER_USER_AGENT` 环境变量) |
|
||
| `--proxy <url>` | 代理服务器 URL,可选身份验证(或 `AGENT_BROWSER_PROXY` 环境变量) |
|
||
| `--proxy-bypass <hosts>` | 绕过代理的主机(或 `AGENT_BROWSER_PROXY_BYPASS` 环境变量) |
|
||
| `--ignore-https-errors` | 忽略 HTTPS 证书错误(适用于自签名证书) |
|
||
| `--allow-file-access` | 允许 file:// URL 访问本地文件(仅 Chromium) |
|
||
| `--hide-scrollbars <bool>` | 在无头 Chromium 截图中隐藏原生滚动条,默认启用(或 `AGENT_BROWSER_HIDE_SCROLLBARS` 环境变量) |
|
||
| `-p, --provider <name>` | 浏览器提供方,包括已配置的 `browser.provider` 插件(或 `AGENT_BROWSER_PROVIDER` 环境变量) |
|
||
| `--device <name>` | iOS 设备名称,例如 "iPhone 15 Pro"(或 `AGENT_BROWSER_IOS_DEVICE` 环境变量) |
|
||
| `--json` | JSON 输出(供 agent 使用) |
|
||
| `--annotate` | 带编号元素标签的标注截图(或 `AGENT_BROWSER_ANNOTATE` 环境变量) |
|
||
| `--screenshot-dir <path>` | 默认截图输出目录(或 `AGENT_BROWSER_SCREENSHOT_DIR` 环境变量) |
|
||
| `--screenshot-quality <n>` | JPEG 质量 0-100(或 `AGENT_BROWSER_SCREENSHOT_QUALITY` 环境变量) |
|
||
| `--screenshot-format <fmt>` | 截图格式:`png`、`jpeg`(或 `AGENT_BROWSER_SCREENSHOT_FORMAT` 环境变量) |
|
||
| `--headed` | 显示浏览器窗口(非无头模式)(或 `AGENT_BROWSER_HEADED` 环境变量) |
|
||
| `--cdp <port\|url>` | 通过 Chrome DevTools Protocol(CDP)连接(端口或 WebSocket URL) |
|
||
| `--auto-connect` | 自动发现并连接正在运行的 Chrome(或 `AGENT_BROWSER_AUTO_CONNECT` 环境变量) |
|
||
| `--color-scheme <scheme>` | 配色方案:`dark`、`light`、`no-preference`(或 `AGENT_BROWSER_COLOR_SCHEME` 环境变量) |
|
||
| `--download-path <path>` | 默认下载目录(或 `AGENT_BROWSER_DOWNLOAD_PATH` 环境变量) |
|
||
| `--content-boundaries` | 为 LLM 安全在页面输出外包装边界标记(或 `AGENT_BROWSER_CONTENT_BOUNDARIES` 环境变量) |
|
||
| `--max-output <chars>` | 将页面输出截断至 N 个字符(或 `AGENT_BROWSER_MAX_OUTPUT` 环境变量) |
|
||
| `--allowed-domains <list>` | 逗号分隔的允许域名模式(或 `AGENT_BROWSER_ALLOWED_DOMAINS` 环境变量) |
|
||
| `--action-policy <path>` | 操作策略 JSON 文件路径(或 `AGENT_BROWSER_ACTION_POLICY` 环境变量) |
|
||
| `--confirm-actions <list>` | 需要确认的操作类别(或 `AGENT_BROWSER_CONFIRM_ACTIONS` 环境变量) |
|
||
| `--confirm-interactive` | 交互式确认提示;若 stdin 不是 TTY 则自动拒绝(或 `AGENT_BROWSER_CONFIRM_INTERACTIVE` 环境变量) |
|
||
| `--engine <name>` | 浏览器引擎:`chrome`(默认)、`lightpanda`(或 `AGENT_BROWSER_ENGINE` 环境变量) |
|
||
| `--no-auto-dialog` | 禁用 `alert`/`beforeunload` 对话框的自动关闭(或 `AGENT_BROWSER_NO_AUTO_DIALOG` 环境变量) |
|
||
| `--model <name>` | 聊天命令使用的 AI 模型(或 `AI_GATEWAY_MODEL` 环境变量) |
|
||
| `-v`, `--verbose` | 显示工具命令及其原始输出(聊天) |
|
||
| `-q`, `--quiet` | 仅显示 AI 文本回复,隐藏工具调用(聊天) |
|
||
| `--config <path>` | 使用自定义配置文件(或 `AGENT_BROWSER_CONFIG` 环境变量) |
|
||
| `--debug` | 调试输出 |
|
||
|
||
## 可观测性仪表板(Observability Dashboard)
|
||
|
||
通过本地 Web 仪表板实时监控 agent-browser 会话,展示实时视口和命令活动流。
|
||
|
||
```bash
|
||
# Start the dashboard server (runs in background on port 4848)
|
||
agent-browser dashboard start
|
||
agent-browser dashboard start --port 8080 # Custom port
|
||
|
||
# All sessions are automatically visible in the dashboard
|
||
agent-browser open example.com
|
||
|
||
# Stop the dashboard
|
||
agent-browser dashboard stop
|
||
```
|
||
|
||
仪表板在 4848 端口作为独立后台进程运行,与浏览器会话无关。即使没有会话在运行,它仍保持可用,并且可从 `http://localhost:4848` 或能访问仪表板服务器的代理/转发 URL(例如 `https://dashboard.agent-browser.localhost` 或 Coder 工作区 URL)使用。浏览器始终停留在仪表板源站;会话专属的标签页、状态和流式流量在内部被代理,因此无需暴露会话端口。
|
||
|
||
仪表板展示:
|
||
- **实时视口**:来自浏览器的实时 JPEG 帧
|
||
- **活动流**:按时间顺序排列的命令/结果流,含耗时和可展开的详情
|
||
- **控制台输出**:浏览器控制台消息(log、warn、error)
|
||
- **会话创建**:通过 UI 使用本地引擎(Chrome、Lightpanda)或云提供商(AgentCore、Browserbase、Browserless、Browser Use、Kernel)创建新会话
|
||
- **AI 聊天**:在仪表板中直接与 AI 助手对话(需配置 Vercel AI Gateway)
|
||
|
||
### AI 聊天
|
||
|
||
仪表板包含由 Vercel AI Gateway 驱动的可选 AI 聊天面板。相同功能也可通过 CLI 的 `chat` 命令直接使用。设置以下环境变量以启用 AI 聊天:
|
||
|
||
```bash
|
||
export AI_GATEWAY_API_KEY=gw_your_key_here
|
||
export AI_GATEWAY_MODEL=anthropic/claude-sonnet-4.6 # optional, this is the default
|
||
export AI_GATEWAY_URL=https://ai-gateway.vercel.sh # optional, this is the default
|
||
```
|
||
|
||
**CLI 用法:**
|
||
|
||
```bash
|
||
agent-browser chat "open google.com and search for cats" # Single-shot
|
||
agent-browser chat # Interactive REPL
|
||
agent-browser -q chat "summarize this page" # Quiet mode (text only)
|
||
agent-browser -v chat "fill in the login form" # Verbose (show command output)
|
||
agent-browser --model openai/gpt-4o chat "take a screenshot" # Override model
|
||
```
|
||
|
||
`chat` 命令将自然语言指令转换为 agent-browser 命令、执行它们并流式传输 AI 响应。在交互模式下,输入 `quit` 退出。使用 `--json` 获取适合代理消费的结构化输出。
|
||
|
||
**仪表板用法:**
|
||
|
||
聊天选项卡在仪表板中始终可见。当设置 `AI_GATEWAY_API_KEY` 时,Rust 服务器将请求代理到网关,并使用 Vercel AI SDK 的 UI Message Stream 协议流式返回响应。未设置密钥时,发送消息会在界面内显示错误。
|
||
|
||
## 配置
|
||
|
||
创建 `agent-browser.json` 文件以设置持久默认值,避免在每条命令上重复指定标志。
|
||
|
||
**位置(优先级从低到高):**
|
||
|
||
1. `~/.agent-browser/config.json`:用户级默认值
|
||
2. `./agent-browser.json`:项目级覆盖(在工作目录中)
|
||
3. `AGENT_BROWSER_*` 环境变量覆盖配置文件值
|
||
4. CLI 标志覆盖一切
|
||
|
||
**`agent-browser.json` 示例:**
|
||
|
||
```json
|
||
{
|
||
"headed": true,
|
||
"proxy": "http://localhost:8080",
|
||
"profile": "./browser-data",
|
||
"userAgent": "my-agent/1.0",
|
||
"hideScrollbars": false,
|
||
"ignoreHttpsErrors": true,
|
||
"plugins": [
|
||
{
|
||
"name": "vault",
|
||
"command": "agent-browser-plugin-vault",
|
||
"capabilities": ["credential.read"]
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
使用 `--config <path>` 或 `AGENT_BROWSER_CONFIG` 加载特定配置文件,而非默认配置:
|
||
|
||
```bash
|
||
agent-browser --config ./ci-config.json open example.com
|
||
AGENT_BROWSER_CONFIG=./ci-config.json agent-browser open example.com
|
||
```
|
||
|
||
上表中的所有选项均可在配置文件中使用 camelCase 键设置(例如,`--executable-path` 变为 `"executablePath"`,`--proxy-bypass` 变为 `"proxyBypass"`)。插件通过上文所示的 `"plugins"` 数组配置。为向前兼容,未知键会被忽略。
|
||
|
||
提供 [JSON Schema](agent-browser.schema.json) 供 IDE 自动补全和校验。在配置文件中添加 `$schema` 键以启用:
|
||
|
||
```json
|
||
{
|
||
"$schema": "https://agent-browser.dev/schema.json",
|
||
"headed": true
|
||
}
|
||
```
|
||
|
||
布尔标志可接受可选的 `true`/`false` 值以覆盖配置设置。例如,`--headed false` 会禁用配置文件中的 `"headed": true`。单独的 `--headed` 等同于 `--headed true`。
|
||
|
||
自动发现的缺失配置文件会被静默忽略。若 `--config <path>` 指向缺失或无效文件,agent-browser 会以错误退出。用户级与项目级配置中的扩展会合并(拼接),而非替换。
|
||
|
||
> **提示:** 若项目级 `agent-browser.json` 包含环境相关值(路径、代理等),建议将其加入 `.gitignore`。
|
||
|
||
## 默认超时
|
||
|
||
标准操作(点击、等待、填充等)的默认超时为 25 秒。此值有意低于 CLI 的 30 秒 IPC 读取超时,以便守护进程返回正确错误,而非 CLI 因 EAGAIN 超时。
|
||
|
||
通过环境变量覆盖默认超时:
|
||
|
||
```bash
|
||
# Set a longer timeout for slow pages (in milliseconds)
|
||
export AGENT_BROWSER_DEFAULT_TIMEOUT=45000
|
||
```
|
||
|
||
> **注意:** 将此值设为超过 30000(30 秒)可能导致慢操作出现 EAGAIN 错误,因为 CLI 的读取超时会在守护进程响应前过期。CLI 会自动重试瞬时错误,但响应时间会增加。
|
||
|
||
| 变量 | 说明 |
|
||
| ------------------------------- | ---------------------------------------- |
|
||
| `AGENT_BROWSER_DEFAULT_TIMEOUT` | 默认操作超时(毫秒,默认:25000) |
|
||
|
||
## 选择器
|
||
|
||
### Refs(推荐用于 AI)
|
||
|
||
Refs 从快照提供确定性的元素选择:
|
||
|
||
```bash
|
||
# 1. Get snapshot with refs
|
||
agent-browser snapshot
|
||
# Output:
|
||
# - heading "Example Domain" [ref=e1] [level=1]
|
||
# - button "Submit" [ref=e2]
|
||
# - textbox "Email" [ref=e3]
|
||
# - link "Learn more" [ref=e4]
|
||
|
||
# 2. Use refs to interact
|
||
agent-browser click @e2 # Click the button
|
||
agent-browser fill @e3 "test@example.com" # Fill the textbox
|
||
agent-browser get text @e1 # Get heading text
|
||
agent-browser hover @e4 # Hover the link
|
||
```
|
||
|
||
当 ref 点击被遮罩层阻挡时,错误信息会包含遮盖元素,例如 `covered by <div#consent-banner>`。请先点击横幅或对话框控件,再重新运行 `snapshot`,然后方可复用 refs。
|
||
|
||
**为何使用 refs?**
|
||
|
||
- **确定性**:Ref 指向快照中的精确元素
|
||
- **快速**:无需重新查询 DOM
|
||
- **AI 友好**:快照 + ref 工作流最适合 LLM
|
||
|
||
### CSS 选择器
|
||
|
||
```bash
|
||
agent-browser click "#id"
|
||
agent-browser click ".class"
|
||
agent-browser click "div > button"
|
||
```
|
||
|
||
### 文本与 XPath
|
||
|
||
```bash
|
||
agent-browser click "text=Submit"
|
||
agent-browser click "xpath=//button"
|
||
```
|
||
|
||
### 语义定位器
|
||
|
||
```bash
|
||
agent-browser find role button click --name "Submit"
|
||
agent-browser find label "Email" fill "test@test.com"
|
||
```
|
||
|
||
## 代理模式
|
||
|
||
使用 `--json` 获取机器可读输出:
|
||
|
||
```bash
|
||
agent-browser snapshot --json
|
||
# Returns: {"success":true,"data":{"snapshot":"...","refs":{"e1":{"role":"heading","name":"Title"},...}}}
|
||
|
||
agent-browser get text @e1 --json
|
||
agent-browser is visible @e2 --json
|
||
```
|
||
|
||
### 最佳 AI 工作流
|
||
|
||
```bash
|
||
# 1. Navigate and get snapshot
|
||
agent-browser open example.com
|
||
agent-browser snapshot -i --json # AI parses tree and refs
|
||
|
||
# 2. AI identifies target refs from snapshot
|
||
# 3. Execute actions using refs
|
||
agent-browser click @e2
|
||
agent-browser fill @e3 "input text"
|
||
|
||
# 4. Get new snapshot if page changed
|
||
agent-browser snapshot -i --json
|
||
```
|
||
|
||
### 命令链
|
||
|
||
可在单次 shell 调用中使用 `&&` 将多条命令串联起来。浏览器通过后台守护进程保持运行,因此串联执行既安全又更高效:
|
||
|
||
```bash
|
||
# Open, wait for load, and snapshot in one call
|
||
agent-browser open 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 "pass" && agent-browser click @e3
|
||
|
||
# Navigate and screenshot
|
||
agent-browser open example.com && agent-browser wait --load networkidle && agent-browser screenshot page.png
|
||
```
|
||
|
||
当你不需要中间输出时,请使用 `&&`。若需要先解析输出(例如,先快照以发现引用再交互),请分别运行各条命令。
|
||
|
||
## 有界面模式(Headed Mode)
|
||
|
||
显示浏览器窗口以便调试:
|
||
|
||
```bash
|
||
agent-browser open example.com --headed
|
||
```
|
||
|
||
这将打开可见的浏览器窗口,而非以无头(headless)方式运行。
|
||
|
||
> **注意:** 浏览器扩展在有界面和无头模式下均可使用(Chrome 的 `--headless=new`)。
|
||
|
||
## 已认证会话
|
||
|
||
使用 `--headers` 为特定源(origin)设置 HTTP 头,无需登录流程即可实现认证:
|
||
|
||
```bash
|
||
# Headers are scoped to api.example.com only
|
||
agent-browser open api.example.com --headers '{"Authorization": "Bearer <token>"}'
|
||
|
||
# Requests to api.example.com include the auth header
|
||
agent-browser snapshot -i --json
|
||
agent-browser click @e2
|
||
|
||
# Navigate to another domain - headers are NOT sent (safe!)
|
||
agent-browser open other-site.com
|
||
```
|
||
|
||
适用于:
|
||
|
||
- **跳过登录流程** - 通过请求头认证,而非 UI 登录
|
||
- **切换用户** - 使用不同认证令牌启动新会话
|
||
- **API 测试** - 直接访问受保护的端点
|
||
- **安全性** - 请求头限定于该源,不会泄露到其他域名
|
||
|
||
要为多个源设置请求头,请在每条 `open` 命令中使用 `--headers`:
|
||
|
||
```bash
|
||
agent-browser open api.example.com --headers '{"Authorization": "Bearer token1"}'
|
||
agent-browser open api.acme.com --headers '{"Authorization": "Bearer token2"}'
|
||
```
|
||
|
||
对于全局请求头(所有域名),请使用 `set headers`:
|
||
|
||
```bash
|
||
agent-browser set headers '{"X-Custom-Header": "value"}'
|
||
```
|
||
|
||
## 自定义浏览器可执行文件
|
||
|
||
使用自定义浏览器可执行文件,而非捆绑的 Chromium。适用于:
|
||
|
||
- **Serverless 部署**:使用轻量级 Chromium 构建,如 `@sparticuz/chromium`(约 50MB,对比约 684MB)
|
||
- **系统浏览器**:使用已有的 Chrome/Chromium 安装
|
||
- **自定义构建**:使用修改过的浏览器构建
|
||
|
||
### CLI 用法
|
||
|
||
```bash
|
||
# Via flag
|
||
agent-browser --executable-path /path/to/chromium open example.com
|
||
|
||
# Via environment variable
|
||
AGENT_BROWSER_EXECUTABLE_PATH=/path/to/chromium agent-browser open example.com
|
||
```
|
||
|
||
### Serverless(Vercel)
|
||
|
||
在临时的 Vercel Sandbox microVM 中运行 agent-browser 与 Chrome。无需外部服务器:
|
||
|
||
```typescript
|
||
import { runAgentBrowserCommand, withAgentBrowserSandbox } from "@agent-browser/sandbox/vercel";
|
||
|
||
const result = await withAgentBrowserSandbox(async (sandbox) => {
|
||
await runAgentBrowserCommand(sandbox, ["open", "https://example.com"]);
|
||
return runAgentBrowserCommand(sandbox, ["screenshot"]);
|
||
});
|
||
```
|
||
|
||
在消费端应用中安装 `@agent-browser/sandbox` 和 `@vercel/sandbox`。请参阅 [sandbox helper 示例](examples/sandbox/) 了解 Eve 与 Vercel Sandbox 的最小用法,或参阅 [environments 示例](examples/environments/) 查看带「部署到 Vercel」按钮的完整 UI 演示。
|
||
|
||
全新的 Vercel 和 Eve 沙箱默认会安装 Chromium 系统依赖。仅当你的沙箱镜像已包含这些库时,才传入 `installSystemDependencies: false`。
|
||
|
||
### Serverless(AWS Lambda)
|
||
|
||
```typescript
|
||
import chromium from '@sparticuz/chromium';
|
||
import { execSync } from 'child_process';
|
||
|
||
export async function handler() {
|
||
const executablePath = await chromium.executablePath();
|
||
const result = execSync(
|
||
`AGENT_BROWSER_EXECUTABLE_PATH=${executablePath} agent-browser open https://example.com && agent-browser snapshot -i --json`,
|
||
{ encoding: 'utf-8' }
|
||
);
|
||
return JSON.parse(result);
|
||
}
|
||
```
|
||
|
||
## 本地文件
|
||
|
||
使用 `file://` URL 打开并操作本地文件(PDF、HTML 等):
|
||
|
||
```bash
|
||
# Enable file access (required for JavaScript to access local files)
|
||
agent-browser --allow-file-access open file:///path/to/document.pdf
|
||
agent-browser --allow-file-access open file:///path/to/page.html
|
||
|
||
# Take screenshot of a local PDF
|
||
agent-browser --allow-file-access open file:///Users/me/report.pdf
|
||
agent-browser screenshot report.png
|
||
```
|
||
|
||
`--allow-file-access` 标志会添加 Chromium 标志(`--allow-file-access-from-files`、`--allow-file-access`),使 `file://` URL 能够:
|
||
|
||
- 加载并渲染本地文件
|
||
- 通过 JavaScript(XHR、fetch)访问其他本地文件
|
||
- 加载本地资源(图片、脚本、样式表)
|
||
|
||
**注意:** 此标志仅适用于 Chromium。出于安全考虑,默认禁用。
|
||
|
||
## CDP 模式
|
||
|
||
通过 Chrome DevTools Protocol(CDP)连接到现有浏览器:
|
||
|
||
```bash
|
||
# Start Chrome with: google-chrome --remote-debugging-port=9222
|
||
|
||
# Connect once, then run commands without --cdp
|
||
agent-browser connect 9222
|
||
agent-browser snapshot
|
||
agent-browser tab
|
||
agent-browser close
|
||
|
||
# Or pass --cdp on each command
|
||
agent-browser --cdp 9222 snapshot
|
||
|
||
# Connect to remote browser via WebSocket URL
|
||
agent-browser --cdp "wss://your-browser-service.com/cdp?token=..." snapshot
|
||
```
|
||
|
||
`--cdp` 标志可接受:
|
||
|
||
- 端口号(例如 `9222`),用于通过 `http://localhost:{port}` 进行本地连接
|
||
- 完整的 WebSocket URL(例如 `wss://...` 或 `ws://...`),用于远程浏览器服务
|
||
|
||
由此可控制:
|
||
|
||
- Electron 应用
|
||
- 启用远程调试的 Chrome/Chromium 实例
|
||
- WebView2 应用
|
||
- 任何暴露 CDP 端点的浏览器
|
||
|
||
### 自动连接
|
||
|
||
使用 `--auto-connect` 自动发现并连接到正在运行的 Chrome 实例,无需指定端口:
|
||
|
||
```bash
|
||
# Auto-discover running Chrome with remote debugging
|
||
agent-browser --auto-connect open example.com
|
||
agent-browser --auto-connect snapshot
|
||
|
||
# Or via environment variable
|
||
AGENT_BROWSER_AUTO_CONNECT=1 agent-browser snapshot
|
||
```
|
||
|
||
自动连接通过以下方式发现 Chrome:
|
||
|
||
1. 从默认用户数据目录读取 Chrome 的 `DevToolsActivePort` 文件
|
||
2. 回退到探测常见调试端口(9222、9229)
|
||
3. 若基于 HTTP 的发现(`/json/version`、`/json/list`)失败,则回退到直接 WebSocket 连接
|
||
|
||
适用于:
|
||
|
||
- Chrome 144+ 已通过 `chrome://inspect/#remote-debugging` 启用远程调试(使用动态端口)
|
||
- 你希望零配置连接到现有浏览器
|
||
- 你不想跟踪 Chrome 正在使用的端口
|
||
|
||
## 流式传输(浏览器预览)
|
||
|
||
通过 WebSocket 流式传输浏览器视口,用于实时预览或「结对浏览」(pair browsing),让人类可与 AI 智能体一同观看并交互。
|
||
|
||
### 流式传输
|
||
|
||
每个会话会自动在操作系统分配的端口上启动 WebSocket 流服务器。使用 `stream status` 查看绑定端口与连接状态:
|
||
|
||
```bash
|
||
agent-browser stream status
|
||
```
|
||
|
||
要绑定到特定端口,请设置 `AGENT_BROWSER_STREAM_PORT`:
|
||
|
||
```bash
|
||
AGENT_BROWSER_STREAM_PORT=9223 agent-browser open example.com
|
||
```
|
||
|
||
你也可以在运行时使用 `stream enable`、`stream disable` 和 `stream status` 管理流式传输:
|
||
|
||
```bash
|
||
agent-browser stream enable --port 9223 # Re-enable on a specific port
|
||
agent-browser stream disable # Stop streaming for the session
|
||
```
|
||
|
||
WebSocket 服务器会流式传输浏览器视口并接收输入事件。
|
||
|
||
### WebSocket 协议
|
||
|
||
连接到 `ws://localhost:9223` 以接收帧并发送输入:
|
||
|
||
**接收帧:**
|
||
|
||
```json
|
||
{
|
||
"type": "frame",
|
||
"data": "<base64-encoded-jpeg>",
|
||
"metadata": {
|
||
"deviceWidth": 1280,
|
||
"deviceHeight": 720,
|
||
"pageScaleFactor": 1,
|
||
"offsetTop": 0,
|
||
"scrollOffsetX": 0,
|
||
"scrollOffsetY": 0
|
||
}
|
||
}
|
||
```
|
||
|
||
**发送鼠标事件:**
|
||
|
||
```json
|
||
{
|
||
"type": "input_mouse",
|
||
"eventType": "mousePressed",
|
||
"x": 100,
|
||
"y": 200,
|
||
"button": "left",
|
||
"clickCount": 1
|
||
}
|
||
```
|
||
|
||
**发送键盘事件:**
|
||
|
||
```json
|
||
{
|
||
"type": "input_keyboard",
|
||
"eventType": "keyDown",
|
||
"key": "Enter",
|
||
"code": "Enter"
|
||
}
|
||
```
|
||
|
||
**发送触摸事件:**
|
||
|
||
```json
|
||
{
|
||
"type": "input_touch",
|
||
"eventType": "touchStart",
|
||
"touchPoints": [{ "x": 100, "y": 200 }]
|
||
}
|
||
```
|
||
|
||
## 架构
|
||
|
||
agent-browser 采用客户端-守护进程(client-daemon)架构:
|
||
|
||
1. **Rust CLI** - 解析命令,并与守护进程通信
|
||
2. **Rust Daemon** - 纯 Rust 守护进程,直接使用 CDP,无需 Node.js
|
||
|
||
守护进程会在首次执行命令时自动启动,并在命令之间保持运行,以便后续操作更快。若要在一段时间无活动后自动关闭守护进程,请设置 `AGENT_BROWSER_IDLE_TIMEOUT_MS`(值为毫秒)。设置后,若在所指定时长内未收到任何命令,守护进程将关闭浏览器并退出。
|
||
|
||
**浏览器引擎:** 默认使用 Chrome(来自 Chrome for Testing)。`--engine` 标志可在 `chrome` 与 `lightpanda` 之间选择。支持的浏览器:Chromium/Chrome(通过 CDP)和 Safari(通过 WebDriver for iOS)。
|
||
|
||
## 平台
|
||
|
||
| 平台 | 二进制 |
|
||
| ----------- | ----------- |
|
||
| macOS ARM64 | Native Rust |
|
||
| macOS x64 | Native Rust |
|
||
| Linux ARM64 | Native Rust |
|
||
| Linux x64 | Native Rust |
|
||
| Windows x64 | Native Rust |
|
||
|
||
## 与 AI Agent 配合使用
|
||
|
||
### 直接让 Agent 使用
|
||
|
||
最简单的方式是告诉你的 Agent 使用它:
|
||
|
||
```
|
||
Use agent-browser to test the login flow. Run agent-browser --help to see available commands.
|
||
```
|
||
|
||
`--help` 的输出内容很全面,大多数 Agent 都能据此自行掌握用法。
|
||
|
||
### AI 编程助手(推荐)
|
||
|
||
将 skill 添加到你的 AI 编程助手中,以获得更丰富的上下文:
|
||
|
||
```bash
|
||
npx skills add vercel-labs/agent-browser
|
||
```
|
||
|
||
适用于 Claude Code、Codex、Cursor、Gemini CLI、GitHub Copilot、Goose、OpenCode 和 Windsurf。该 skill 从仓库获取,因此会自动保持最新。请勿从 `node_modules` 复制 `SKILL.md`,否则内容会过时。
|
||
|
||
### Claude Code
|
||
|
||
安装为 Claude Code skill:
|
||
|
||
```bash
|
||
npx skills add vercel-labs/agent-browser
|
||
```
|
||
|
||
这会在 `.claude/skills/agent-browser/SKILL.md` 添加一个轻量的发现桩(discovery stub)。该桩有意保持精简——它会在运行时引导 Claude Code 加载 `agent-browser skills get core` 中的实际工作流内容。这样,指令始终与已安装的 CLI 版本一致,而不会在版本发布之间过时。
|
||
|
||
### AGENTS.md / CLAUDE.md
|
||
|
||
为获得更稳定的结果,请添加到你的项目或全局指令文件中:
|
||
|
||
```markdown
|
||
## Browser Automation
|
||
|
||
Use `agent-browser` for web automation. Run `agent-browser --help` for all commands.
|
||
|
||
Core workflow:
|
||
|
||
1. `agent-browser open <url>` - Navigate to page
|
||
2. `agent-browser snapshot -i` - Get interactive elements with refs (@e1, @e2)
|
||
3. `agent-browser click @e1` / `fill @e2 "text"` - Interact using refs
|
||
4. Re-snapshot after page changes
|
||
```
|
||
|
||
## 集成
|
||
|
||
### iOS 模拟器
|
||
|
||
在 iOS 模拟器中控制真实的 Mobile Safari,以进行真实的移动端 Web 测试。需要安装了 Xcode 的 macOS。
|
||
|
||
**设置:**
|
||
|
||
```bash
|
||
# Install Appium and XCUITest driver
|
||
npm install -g appium
|
||
appium driver install xcuitest
|
||
```
|
||
|
||
**用法:**
|
||
|
||
```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 commands as desktop
|
||
agent-browser -p ios snapshot -i
|
||
agent-browser -p ios tap @e1
|
||
agent-browser -p ios fill @e2 "text"
|
||
agent-browser -p ios screenshot mobile.png
|
||
|
||
# Mobile-specific commands
|
||
agent-browser -p ios swipe up
|
||
agent-browser -p ios swipe down 500
|
||
|
||
# Close session
|
||
agent-browser -p ios close
|
||
```
|
||
|
||
或使用环境变量:
|
||
|
||
```bash
|
||
export AGENT_BROWSER_PROVIDER=ios
|
||
export AGENT_BROWSER_IOS_DEVICE="iPhone 16 Pro"
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
| 变量 | 说明 |
|
||
| -------------------------- | ----------------------------------------------- |
|
||
| `AGENT_BROWSER_PROVIDER` | 设置为 `ios` 以启用 iOS 模式 |
|
||
| `AGENT_BROWSER_IOS_DEVICE` | 设备名称(例如 "iPhone 16 Pro"、"iPad Pro") |
|
||
| `AGENT_BROWSER_IOS_UDID` | 设备 UDID(可替代设备名称) |
|
||
|
||
**支持的设备:** Xcode 中所有可用的 iOS 模拟器(iPhone、iPad),以及真实 iOS 设备。
|
||
|
||
**注意:** iOS 提供程序会启动模拟器、启动 Appium 并控制 Safari。首次启动大约需要 30-60 秒;后续命令会很快。
|
||
|
||
#### 真机支持
|
||
|
||
Appium 也支持通过 USB 连接的真实 iOS 设备。这需要额外的一次性设置:
|
||
|
||
**1. 获取设备 UDID:**
|
||
|
||
```bash
|
||
xcrun xctrace list devices
|
||
# or
|
||
system_profiler SPUSBDataType | grep -A 5 "iPhone\|iPad"
|
||
```
|
||
|
||
**2. 签名 WebDriverAgent(一次性):**
|
||
|
||
```bash
|
||
# Open the WebDriverAgent Xcode project
|
||
cd ~/.appium/node_modules/appium-xcuitest-driver/node_modules/appium-webdriveragent
|
||
open WebDriverAgent.xcodeproj
|
||
```
|
||
|
||
在 Xcode 中:
|
||
|
||
- 选择 `WebDriverAgentRunner` 目标
|
||
- 前往 Signing & Capabilities
|
||
- 选择你的 Team(需要 Apple Developer 账户,免费套餐即可)
|
||
- 让 Xcode 自动管理签名
|
||
|
||
**3. 与 agent-browser 配合使用:**
|
||
|
||
```bash
|
||
# Connect device via USB, then:
|
||
agent-browser -p ios --device "<DEVICE_UDID>" open https://example.com
|
||
|
||
# Or use the device name if unique
|
||
agent-browser -p ios --device "John's iPhone" open https://example.com
|
||
```
|
||
|
||
**真机注意事项:**
|
||
|
||
- 首次运行会将 WebDriverAgent 安装到设备上(可能需要信任提示)
|
||
- 设备必须已解锁并通过 USB 连接
|
||
- 初始连接比模拟器稍慢
|
||
- 可测试真实 Safari 的性能与行为
|
||
|
||
### Browserless
|
||
|
||
[Browserless](https://browserless.io) provides cloud browser infrastructure with a Sessions API. Use it when running agent-browser in environments where a local browser isn't available.
|
||
|
||
要启用 Browserless,请使用 `-p` 标志:
|
||
|
||
```bash
|
||
export BROWSERLESS_API_KEY="your-api-token"
|
||
agent-browser -p browserless open https://example.com
|
||
```
|
||
|
||
或在 CI/脚本中使用环境变量:
|
||
|
||
```bash
|
||
export AGENT_BROWSER_PROVIDER=browserless
|
||
export BROWSERLESS_API_KEY="your-api-token"
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
可通过环境变量进行可选配置:
|
||
|
||
| 变量 | 说明 | 默认值 |
|
||
| -------------------------- | ------------------------------------------------ | --------------------------------------- |
|
||
| `BROWSERLESS_API_URL` | Base API URL(用于自定义区域或自托管) | `https://production-sfo.browserless.io` |
|
||
| `BROWSERLESS_BROWSER_TYPE` | 要使用的浏览器类型(chromium 或 chrome) | chromium |
|
||
| `BROWSERLESS_TTL` | 会话 TTL(毫秒) | `300000` |
|
||
| `BROWSERLESS_STEALTH` | 启用隐身模式(`true`/`false`) | `true` |
|
||
|
||
启用后,agent-browser 会连接到 Browserless 云会话,而不是启动本地浏览器。所有命令的行为完全相同。
|
||
|
||
从 [Browserless Dashboard](https://browserless.io). 获取你的 API 令牌
|
||
|
||
### Browserbase
|
||
|
||
[Browserbase](https://browserbase.com) provides remote browser infrastructure to make deployment of agentic browsing agents easy. Use it when running the agent-browser CLI in an environment where a local browser isn't feasible.
|
||
|
||
要启用 Browserbase,请使用 `-p` 标志:
|
||
|
||
```bash
|
||
export BROWSERBASE_API_KEY="your-api-key"
|
||
agent-browser -p browserbase open https://example.com
|
||
```
|
||
|
||
或在 CI/脚本中使用环境变量:
|
||
|
||
```bash
|
||
export AGENT_BROWSER_PROVIDER=browserbase
|
||
export BROWSERBASE_API_KEY="your-api-key"
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
启用后,agent-browser 会连接到 Browserbase 会话,而不是启动本地浏览器。所有命令的行为完全相同。
|
||
|
||
从 [Browserbase Dashboard](https://browserbase.com/overview). 获取你的 API 密钥
|
||
|
||
### Browser Use
|
||
|
||
[Browser Use](https://browser-use.com) provides cloud browser infrastructure for AI agents. Use it when running agent-browser in environments where a local browser isn't available (serverless, CI/CD, etc.).
|
||
|
||
要启用 Browser Use,请使用 `-p` 标志:
|
||
|
||
```bash
|
||
export BROWSER_USE_API_KEY="your-api-key"
|
||
agent-browser -p browseruse open https://example.com
|
||
```
|
||
|
||
或在 CI/脚本中使用环境变量:
|
||
|
||
```bash
|
||
export AGENT_BROWSER_PROVIDER=browseruse
|
||
export BROWSER_USE_API_KEY="your-api-key"
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
启用后,agent-browser 会连接到 Browser Use 云端会话,而不是启动本地浏览器。所有命令的行为保持一致。
|
||
|
||
从 [Browser Use Cloud Dashboard](https://cloud.browser-use.com/settings?tab=api-keys). 获取 API 密钥。提供免费额度可供上手,之后按量计费。
|
||
|
||
### Kernel
|
||
|
||
[Kernel](https://www.kernel.sh) 为 AI 智能体提供云端浏览器基础设施,具备隐身模式(stealth mode)和持久化配置(persistent profiles)等功能。
|
||
|
||
要启用 Kernel,请使用 `-p` 标志:
|
||
|
||
```bash
|
||
export KERNEL_API_KEY="your-api-key"
|
||
agent-browser -p kernel open https://example.com
|
||
```
|
||
|
||
或在 CI/脚本中使用环境变量:
|
||
|
||
```bash
|
||
export AGENT_BROWSER_PROVIDER=kernel
|
||
export KERNEL_API_KEY="your-api-key"
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
可通过环境变量进行可选配置:
|
||
|
||
| 变量 | 说明 | 默认值 |
|
||
| ------------------------ | -------------------------------------------------------------------------------- | ------- |
|
||
| `KERNEL_HEADLESS` | 以无头模式(headless)运行浏览器(`true`/`false`) | `true` |
|
||
| `KERNEL_STEALTH` | 启用隐身模式以避免机器人检测(`true`/`false`) | `false` |
|
||
| `KERNEL_TIMEOUT_SECONDS` | 会话超时时间(秒) | `300` |
|
||
| `KERNEL_PROFILE_NAME` | 用于持久化 Cookie/登录信息的浏览器配置名称(不存在时将自动创建) | (无) |
|
||
|
||
启用后,agent-browser 会连接到 Kernel 云端会话,而不是启动本地浏览器。所有命令的行为保持一致。
|
||
|
||
**配置持久化(Profile Persistence):** 设置 `KERNEL_PROFILE_NAME` 后,若该配置尚不存在,将自动创建。浏览器会话结束时,Cookie、登录信息和会话数据会自动保存回该配置,供后续会话使用。
|
||
|
||
从 [Kernel Dashboard](https://dashboard.onkernel.com). 获取 API 密钥。
|
||
|
||
### AgentCore
|
||
|
||
[AWS Bedrock AgentCore](https://aws.amazon.com/bedrock/agentcore/) 提供带 SigV4 认证的云端浏览器会话。
|
||
|
||
要启用 AgentCore,请使用 `-p` 标志:
|
||
|
||
```bash
|
||
agent-browser -p agentcore open https://example.com
|
||
```
|
||
|
||
或在 CI/脚本中使用环境变量:
|
||
|
||
```bash
|
||
export AGENT_BROWSER_PROVIDER=agentcore
|
||
agent-browser open https://example.com
|
||
```
|
||
|
||
凭证会自动从环境变量(`AWS_ACCESS_KEY_ID`、`AWS_SECRET_ACCESS_KEY`)或 AWS CLI(`aws configure export-credentials`)解析,支持 SSO、配置文件和 IAM 角色。
|
||
|
||
可通过环境变量进行可选配置:
|
||
|
||
| 变量 | 说明 | 默认值 |
|
||
| -------------------------- | -------------------------------------------------------------------- | ---------------- |
|
||
| `AGENTCORE_REGION` | AgentCore 端点的 AWS 区域 | `us-east-1` |
|
||
| `AGENTCORE_BROWSER_ID` | 浏览器标识符 | `aws.browser.v1` |
|
||
| `AGENTCORE_PROFILE_ID` | 用于持久化状态(cookies、localStorage)的浏览器配置 | (无) |
|
||
| `AGENTCORE_SESSION_TIMEOUT`| 会话超时时间(秒) | `3600` |
|
||
| `AWS_PROFILE` | 用于解析凭证的 AWS CLI 配置文件 | `default` |
|
||
|
||
**浏览器配置(Browser profiles):** 设置 `AGENTCORE_PROFILE_ID` 后,浏览器状态(cookies、localStorage)会在各会话间自动持久化。
|
||
|
||
启用后,agent-browser 会连接到 AgentCore 云端浏览器会话,而不是启动本地浏览器。所有命令的行为保持一致。
|
||
|
||
## 许可证
|
||
|
||
Apache-2.0
|