Compare commits
16
Commits
v1.4.1
...
v0.14.0-fork.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
058a286326 | ||
|
|
b1f27236d8 | ||
|
|
a5a9327b7d | ||
|
|
699ccbd3cb | ||
|
|
893ddfd259 | ||
|
|
ea2e93dbba | ||
|
|
4c6afe3e69 | ||
|
|
9f9a90cf63 | ||
|
|
0443e4ed7a | ||
|
|
c5b2292caa | ||
|
|
2ed0c6f8ec | ||
|
|
3a91aef4c9 | ||
|
|
02ebc9f328 | ||
|
|
955543b757 | ||
|
|
ecad112707 | ||
|
|
8932f28926 |
@@ -11,6 +11,7 @@ concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
# Build native binaries for all platforms first
|
||||
@@ -219,7 +220,6 @@ jobs:
|
||||
commit: 'chore: version packages'
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_VERCEL_TOKEN_ELEVATED }}
|
||||
|
||||
# Create GitHub release with binaries after npm publish
|
||||
github-release:
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# agent-browser
|
||||
|
||||
## 0.14.0-fork.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix CLI typing delay parsing so `--delay` is treated as an option instead of typed text.
|
||||
- Add `--delay <ms>` parsing for `type` and `keyboard type`
|
||||
- Support `--` to type literal `--delay` text
|
||||
- Add regression tests for parsing and delay behavior
|
||||
- Update CLI help, README, skills, and docs command references
|
||||
|
||||
## 0.14.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
# agent-browser
|
||||
|
||||
Headless browser automation CLI for AI agents. Fast Rust CLI with Node.js fallback.
|
||||
Stealth-first browser automation CLI engineered for anti-bot evasion. Fast Rust CLI with Node.js fallback.
|
||||
|
||||
Designed for production automation on detection-heavy sites:
|
||||
- Always-on stealth (no opt-in flag)
|
||||
- Browser and protocol-level anti-fingerprint patches
|
||||
- Humanized interaction behavior by default
|
||||
- Verified against CreepJS using the built-in check script
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -9,7 +15,7 @@ Headless browser automation CLI for AI agents. Fast Rust CLI with Node.js fallba
|
||||
Installs the native Rust binary for maximum performance:
|
||||
|
||||
```bash
|
||||
npm install -g agent-browser
|
||||
npm install -g agent-browser-stealth
|
||||
agent-browser install # Download Chromium
|
||||
```
|
||||
|
||||
@@ -20,8 +26,8 @@ This is the fastest option -- commands run through the native Rust CLI directly
|
||||
Run directly with `npx` if you want to try it without installing globally:
|
||||
|
||||
```bash
|
||||
npx agent-browser install # Download Chromium (first time only)
|
||||
npx agent-browser open example.com
|
||||
npx agent-browser-stealth install # Download Chromium (first time only)
|
||||
npx agent-browser-stealth open example.com
|
||||
```
|
||||
|
||||
> **Note:** `npx` routes through Node.js before reaching the Rust CLI, so it is noticeably slower than a global install. For regular use, install globally.
|
||||
@@ -31,14 +37,14 @@ npx agent-browser open example.com
|
||||
For projects that want to pin the version in `package.json`:
|
||||
|
||||
```bash
|
||||
npm install agent-browser
|
||||
npx agent-browser install
|
||||
npm install agent-browser-stealth
|
||||
npx agent-browser-stealth install
|
||||
```
|
||||
|
||||
Then use via `npx` or `package.json` scripts:
|
||||
|
||||
```bash
|
||||
npx agent-browser open example.com
|
||||
npx agent-browser-stealth open example.com
|
||||
```
|
||||
|
||||
### Homebrew (macOS)
|
||||
@@ -51,7 +57,7 @@ agent-browser install # Download Chromium
|
||||
### From Source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/vercel-labs/agent-browser
|
||||
git clone https://github.com/leeguooooo/agent-browser
|
||||
cd agent-browser
|
||||
pnpm install
|
||||
pnpm build
|
||||
@@ -60,6 +66,44 @@ pnpm link --global # Makes agent-browser available globally
|
||||
agent-browser install
|
||||
```
|
||||
|
||||
### Fork Maintenance (Independent Release + Upstream Sync)
|
||||
|
||||
If you maintain a fork and publish your own CLI, use this workflow:
|
||||
|
||||
1. Keep an upstream-tracking branch (`upstream-main`) for clean sync history.
|
||||
2. Keep your release branch (`main`) for production-ready code only.
|
||||
3. Merge upstream into short-lived sync branches, then open PRs into `main`.
|
||||
|
||||
One-time setup:
|
||||
|
||||
```bash
|
||||
git remote add upstream https://github.com/vercel-labs/agent-browser.git
|
||||
git fetch upstream
|
||||
```
|
||||
|
||||
Regular sync:
|
||||
|
||||
```bash
|
||||
pnpm run sync:upstream:push
|
||||
```
|
||||
|
||||
This command:
|
||||
- Fetches `upstream/main`
|
||||
- Fast-forwards local `upstream-main`
|
||||
- Creates `sync/YYYY-MM-DD` from local `main`
|
||||
- Merges `upstream-main` into the sync branch
|
||||
- Pushes the sync branch to `origin` (with `sync:upstream:push`)
|
||||
|
||||
If merge conflicts occur, resolve them on the sync branch and open a PR as usual.
|
||||
|
||||
Independent release checklist for forks:
|
||||
- Use your own npm package name and CLI binary name (avoid conflicts with upstream package ownership).
|
||||
- Update `repository`, `bugs`, and `homepage` in `package.json` to your fork.
|
||||
- Configure npm Trusted Publishing (OIDC) for your package and repository workflow.
|
||||
- Keep release tags and changelog in your own namespace/versioning policy.
|
||||
- Use dual-version format: `<upstream>-fork.<fork>` (example: `0.14.0-fork.1`).
|
||||
- `agent-browser --version` should show all three: full version, upstream version, and fork version.
|
||||
|
||||
### Linux Dependencies
|
||||
|
||||
On Linux, install system dependencies:
|
||||
@@ -78,6 +122,7 @@ 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 --version # Includes upstream/fork metadata on fork builds
|
||||
agent-browser close
|
||||
```
|
||||
|
||||
@@ -98,10 +143,10 @@ agent-browser open <url> # Navigate to URL (aliases: goto, navigate
|
||||
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 type <sel> <text> [--delay <ms>] # 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 type <text> [--delay <ms>] # 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
|
||||
@@ -177,6 +222,7 @@ agent-browser find nth 2 "a" text
|
||||
```bash
|
||||
agent-browser wait <selector> # Wait for element to be visible
|
||||
agent-browser wait <ms> # Wait for time (milliseconds)
|
||||
agent-browser wait 2000-5000 # Random wait between 2-5 seconds
|
||||
agent-browser wait --text "Welcome" # Wait for text to appear
|
||||
agent-browser wait --url "**/dash" # Wait for URL pattern
|
||||
agent-browser wait --load networkidle # Wait for load state
|
||||
@@ -337,33 +383,9 @@ Each session has its own:
|
||||
- Navigation history
|
||||
- Authentication state
|
||||
|
||||
## Persistent Profiles
|
||||
|
||||
By default, browser state (cookies, localStorage, login sessions) is ephemeral and lost when the browser closes. Use `--profile` to persist state across browser restarts:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
The profile directory stores:
|
||||
- Cookies and localStorage
|
||||
- IndexedDB data
|
||||
- Service workers
|
||||
- Browser cache
|
||||
- Login sessions
|
||||
|
||||
**Tip**: Use different profile paths for different projects to keep their browser state isolated.
|
||||
|
||||
## Session Persistence
|
||||
|
||||
Alternatively, use `--session-name` to automatically save and restore cookies and localStorage across browser restarts:
|
||||
Use `--session-name` to automatically save and restore cookies and localStorage across browser restarts:
|
||||
|
||||
```bash
|
||||
# Auto-save/load state for "twitter" session
|
||||
@@ -446,7 +468,6 @@ This is useful for multimodal AI models that can reason about visual layout, unl
|
||||
|--------|-------------|
|
||||
| `--session <name>` | Use isolated session (or `AGENT_BROWSER_SESSION` env) |
|
||||
| `--session-name <name>` | Auto-save/restore session state (or `AGENT_BROWSER_SESSION_NAME` env) |
|
||||
| `--profile <path>` | Persistent browser profile directory (or `AGENT_BROWSER_PROFILE` env) |
|
||||
| `--state <path>` | Load storage state from JSON file (or `AGENT_BROWSER_STATE` env) |
|
||||
| `--headers <json>` | Set HTTP headers scoped to the URL's origin |
|
||||
| `--executable-path <path>` | Custom browser executable (or `AGENT_BROWSER_EXECUTABLE_PATH` env) |
|
||||
@@ -469,6 +490,11 @@ This is useful for multimodal AI models that can reason about visual layout, unl
|
||||
| `--config <path>` | Use a custom config file (or `AGENT_BROWSER_CONFIG` env) |
|
||||
| `--debug` | Debug output |
|
||||
|
||||
Project policy:
|
||||
- `--profile` / `AGENT_BROWSER_PROFILE` are forbidden
|
||||
- `--channel` / `AGENT_BROWSER_CHANNEL` are forbidden
|
||||
- Default mode must connect to an existing browser at `localhost:9333` (no automatic local-launch fallback)
|
||||
|
||||
## Configuration
|
||||
|
||||
Create an `agent-browser.json` file to set persistent defaults instead of repeating flags on every command.
|
||||
@@ -486,7 +512,6 @@ Create an `agent-browser.json` file to set persistent defaults instead of repeat
|
||||
{
|
||||
"headed": true,
|
||||
"proxy": "http://localhost:8080",
|
||||
"profile": "./browser-data",
|
||||
"userAgent": "my-agent/1.0",
|
||||
"ignoreHttpsErrors": true
|
||||
}
|
||||
@@ -684,7 +709,7 @@ AGENT_BROWSER_EXECUTABLE_PATH=/path/to/chromium agent-browser open example.com
|
||||
|
||||
```typescript
|
||||
import chromium from '@sparticuz/chromium';
|
||||
import { BrowserManager } from 'agent-browser';
|
||||
import { BrowserManager } from 'agent-browser-stealth';
|
||||
|
||||
export async function handler() {
|
||||
const browser = new BrowserManager();
|
||||
@@ -717,10 +742,72 @@ The `--allow-file-access` flag adds Chromium flags (`--allow-file-access-from-fi
|
||||
|
||||
**Note:** This flag only works with Chromium. For security, it's disabled by default.
|
||||
|
||||
## Stealth Mode
|
||||
|
||||
`agent-browser-stealth` is built around stealth as a primary design goal, not an add-on.
|
||||
Stealth is **always on** with no flag needed. Every browser session automatically applies anti-detection countermeasures:
|
||||
|
||||
- **Uses Chrome channel for Chromium launches** -- local Chromium sessions are launched through Playwright's `chrome` channel for a genuine Chrome fingerprint
|
||||
|
||||
- Removes `navigator.webdriver` automation indicator
|
||||
- Disables Chromium's `AutomationControlled` blink feature
|
||||
- Replaces "HeadlessChrome" in User-Agent and userAgentData (including CDP-level override)
|
||||
- Uses ANGLE rendering instead of SwiftShader to avoid GPU fingerprinting
|
||||
- Adds realistic `navigator.plugins` and `navigator.mimeTypes` (passes `instanceof` checks)
|
||||
- Patches `window.chrome.runtime` to match real Chrome
|
||||
- Masks WebGL vendor/renderer
|
||||
- Fixes `navigator.permissions.query` for notifications
|
||||
- Reports realistic `navigator.hardwareConcurrency` and `performance.memory`
|
||||
- Provides default media devices for `enumerateDevices()`
|
||||
- Patches screen/window dimensions to avoid viewport-equals-screen fingerprint
|
||||
- Sets opaque background color (headless default is transparent)
|
||||
- Cleans up CDP-injected properties on the document
|
||||
|
||||
### Stealth Verification
|
||||
|
||||
On February 24, 2026, local validation against CreepJS using `scripts/check-creepjs-headless.js` reported:
|
||||
|
||||
| Metric | Result |
|
||||
| --- | --- |
|
||||
| like headless | 0% |
|
||||
| headless | 0% |
|
||||
| stealth | 0% |
|
||||
|
||||
Reproduce:
|
||||
|
||||
```bash
|
||||
node scripts/check-creepjs-headless.js --binary ./cli/target/release/agent-browser
|
||||
```
|
||||
|
||||
### Humanized Interactions
|
||||
|
||||
All interactions are automatically humanized to avoid behavioral detection:
|
||||
|
||||
- **Randomized typing** -- When using `type --delay`, each keystroke delay varies by +-40% so timing appears natural rather than mechanical
|
||||
- **Random wait ranges** -- `wait 2000-5000` pauses for a random duration between 2 and 5 seconds
|
||||
- **Bezier curve mouse movement** -- Before every `click`, the mouse moves to the target element along a randomized cubic Bezier curve with natural-looking control points
|
||||
- **Navigation pacing** -- Each page navigation includes a short random delay (300-1000ms) to avoid burst patterns
|
||||
|
||||
These behaviors are always active and require no additional flags.
|
||||
|
||||
### Auto Region Detection
|
||||
|
||||
When navigating to a site, the URL's TLD is used to automatically match locale, timezone, and Accept-Language headers to the target region. For example, opening `shopee.tw` automatically sets locale to `zh-TW` and timezone to `Asia/Taipei`, eliminating region-signal mismatches that server-side risk systems commonly flag.
|
||||
|
||||
Supported TLDs include: `.tw`, `.cn`, `.hk`, `.jp`, `.kr`, `.th`, `.vn`, `.sg`, `.my`, `.id`, `.ph`, `.br`, `.mx`, `.de`, `.fr`, `.uk`, `.ru`, `.in`, `.au`, and more.
|
||||
|
||||
Override with environment variables: `AGENT_BROWSER_LOCALE`, `AGENT_BROWSER_TIMEZONE`.
|
||||
|
||||
### Captcha / Verification Detection
|
||||
|
||||
If a navigation lands on a known captcha or verification page (detected by URL patterns like `/verify/captcha` or titles like "Checking your browser"), the browser automatically retries up to 2 times with randomized backoff (3-7 seconds). If all retries are exhausted, a warning suggests `--headed` mode or `--session-name` persistence.
|
||||
|
||||
## CDP Mode
|
||||
|
||||
Connect to an existing browser via Chrome DevTools Protocol:
|
||||
|
||||
By default in this fork, when you run commands without `--cdp`, agent-browser requires an existing browser at `localhost:9333` (resident browser via CDP). If CDP is unavailable, the command fails fast instead of launching a new managed browser.
|
||||
|
||||
```bash
|
||||
# Start Chrome with: google-chrome --remote-debugging-port=9222
|
||||
|
||||
@@ -762,7 +849,7 @@ AGENT_BROWSER_AUTO_CONNECT=1 agent-browser snapshot
|
||||
|
||||
Auto-connect discovers Chrome by:
|
||||
1. Reading Chrome's `DevToolsActivePort` file from the default user data directory
|
||||
2. Falling back to probing common debugging ports (9222, 9229)
|
||||
2. Falling back to probing common debugging ports (9222, 9229, 9333)
|
||||
|
||||
This is useful when:
|
||||
- Chrome 144+ has remote debugging enabled via `chrome://inspect/#remote-debugging` (which uses a dynamic port)
|
||||
@@ -839,7 +926,7 @@ Connect to `ws://localhost:9223` to receive frames and send input:
|
||||
For advanced use, control streaming directly via the protocol:
|
||||
|
||||
```typescript
|
||||
import { BrowserManager } from 'agent-browser';
|
||||
import { BrowserManager } from 'agent-browser-stealth';
|
||||
|
||||
const browser = new BrowserManager();
|
||||
await browser.launch({ headless: true });
|
||||
@@ -915,7 +1002,7 @@ The `--help` output is comprehensive and most agents can figure it out from ther
|
||||
Add the skill to your AI coding assistant for richer context:
|
||||
|
||||
```bash
|
||||
npx skills add vercel-labs/agent-browser
|
||||
npx skills add leeguooooo/agent-browser
|
||||
```
|
||||
|
||||
This works with Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, Goose, OpenCode, and Windsurf. The skill is fetched from the repository, so it stays up to date automatically -- do not copy `SKILL.md` from `node_modules` as it will become stale.
|
||||
@@ -925,7 +1012,7 @@ This works with Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, Goose, O
|
||||
Install as a Claude Code skill:
|
||||
|
||||
```bash
|
||||
npx skills add vercel-labs/agent-browser
|
||||
npx skills add leeguooooo/agent-browser
|
||||
```
|
||||
|
||||
This adds the skill to `.claude/skills/agent-browser/SKILL.md` in your project. The skill teaches Claude Code the full agent-browser workflow, including the snapshot-ref interaction pattern, session management, and timeout handling.
|
||||
|
||||
Generated
+2
-2
@@ -3,8 +3,8 @@
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "agent-browser"
|
||||
version = "0.14.0"
|
||||
name = "agent-browser-stealth"
|
||||
version = "0.14.0-fork.3"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"dirs",
|
||||
|
||||
+11
-3
@@ -1,10 +1,18 @@
|
||||
[package]
|
||||
name = "agent-browser"
|
||||
version = "0.14.0"
|
||||
name = "agent-browser-stealth"
|
||||
version = "0.14.0-fork.3"
|
||||
edition = "2021"
|
||||
description = "Fast browser automation CLI for AI agents"
|
||||
description = "Stealth browser automation CLI for AI agents with anti-bot evasions"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[[bin]]
|
||||
name = "agent-browser"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "agent-browser-stealth"
|
||||
path = "src/main_stealth.rs"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
+168
-37
@@ -71,6 +71,62 @@ pub fn gen_id() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse free-form text arguments with optional `--delay <ms>`.
|
||||
///
|
||||
/// `--` can be used to stop flag parsing if text must include `--delay` literally.
|
||||
fn parse_text_with_optional_delay(
|
||||
args: &[&str],
|
||||
context: &str,
|
||||
usage: &'static str,
|
||||
) -> Result<(String, Option<u64>), ParseError> {
|
||||
let mut text_parts: Vec<&str> = Vec::new();
|
||||
let mut delay_ms: Option<u64> = None;
|
||||
let mut parse_flags = true;
|
||||
let mut i = 0;
|
||||
|
||||
while i < args.len() {
|
||||
let arg = args[i];
|
||||
|
||||
if parse_flags && arg == "--" {
|
||||
parse_flags = false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if parse_flags && arg == "--delay" {
|
||||
let raw = args
|
||||
.get(i + 1)
|
||||
.ok_or_else(|| ParseError::MissingArguments {
|
||||
context: format!("{} --delay", context),
|
||||
usage,
|
||||
})?;
|
||||
let parsed = raw.parse::<u64>().map_err(|_| ParseError::InvalidValue {
|
||||
message: format!(
|
||||
"Invalid --delay value: {} (must be a non-negative integer in milliseconds)",
|
||||
raw
|
||||
),
|
||||
usage,
|
||||
})?;
|
||||
delay_ms = Some(parsed);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
text_parts.push(arg);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
let text = text_parts.join(" ");
|
||||
if text.is_empty() {
|
||||
return Err(ParseError::MissingArguments {
|
||||
context: context.to_string(),
|
||||
usage,
|
||||
});
|
||||
}
|
||||
|
||||
Ok((text, delay_ms))
|
||||
}
|
||||
|
||||
pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError> {
|
||||
if args.is_empty() {
|
||||
return Err(ParseError::MissingArguments {
|
||||
@@ -111,10 +167,12 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
let mut nav_cmd = json!({ "id": id, "action": "navigate", "url": url });
|
||||
// If --headers flag is set, include headers (scoped to this origin)
|
||||
if let Some(ref headers_json) = flags.headers {
|
||||
let headers = serde_json::from_str::<serde_json::Value>(headers_json)
|
||||
.map_err(|_| ParseError::InvalidValue {
|
||||
message: format!("Invalid JSON for --headers: {}", headers_json),
|
||||
usage: "open <url> --headers '{\"Key\": \"Value\"}'",
|
||||
let headers =
|
||||
serde_json::from_str::<serde_json::Value>(headers_json).map_err(|_| {
|
||||
ParseError::InvalidValue {
|
||||
message: format!("Invalid JSON for --headers: {}", headers_json),
|
||||
usage: "open <url> --headers '{\"Key\": \"Value\"}'",
|
||||
}
|
||||
})?;
|
||||
nav_cmd["headers"] = headers;
|
||||
}
|
||||
@@ -163,9 +221,18 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
"type" => {
|
||||
let sel = rest.first().ok_or_else(|| ParseError::MissingArguments {
|
||||
context: "type".to_string(),
|
||||
usage: "type <selector> <text>",
|
||||
usage: "type <selector> <text> [--delay <ms>]",
|
||||
})?;
|
||||
Ok(json!({ "id": id, "action": "type", "selector": sel, "text": rest[1..].join(" ") }))
|
||||
let (text, delay) = parse_text_with_optional_delay(
|
||||
&rest[1..],
|
||||
"type",
|
||||
"type <selector> <text> [--delay <ms>]",
|
||||
)?;
|
||||
let mut cmd = json!({ "id": id, "action": "type", "selector": sel, "text": text });
|
||||
if let Some(ms) = delay {
|
||||
cmd["delay"] = json!(ms);
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
"hover" => {
|
||||
let sel = rest.first().ok_or_else(|| ParseError::MissingArguments {
|
||||
@@ -270,14 +337,16 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
})?;
|
||||
match *sub {
|
||||
"type" => {
|
||||
let text: String = rest[1..].join(" ");
|
||||
if text.is_empty() {
|
||||
return Err(ParseError::MissingArguments {
|
||||
context: "keyboard type".to_string(),
|
||||
usage: "keyboard type <text>",
|
||||
});
|
||||
let (text, delay) = parse_text_with_optional_delay(
|
||||
&rest[1..],
|
||||
"keyboard type",
|
||||
"keyboard type <text> [--delay <ms>]",
|
||||
)?;
|
||||
let mut cmd = json!({ "id": id, "action": "keyboard", "subaction": "type", "text": text });
|
||||
if let Some(ms) = delay {
|
||||
cmd["delay"] = json!(ms);
|
||||
}
|
||||
Ok(json!({ "id": id, "action": "keyboard", "subaction": "type", "text": text }))
|
||||
Ok(cmd)
|
||||
}
|
||||
"inserttext" | "insertText" => {
|
||||
let text: String = rest[1..].join(" ");
|
||||
@@ -287,7 +356,9 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
usage: "keyboard inserttext <text>",
|
||||
});
|
||||
}
|
||||
Ok(json!({ "id": id, "action": "keyboard", "subaction": "insertText", "text": text }))
|
||||
Ok(
|
||||
json!({ "id": id, "action": "keyboard", "subaction": "insertText", "text": text }),
|
||||
)
|
||||
}
|
||||
_ => Err(ParseError::UnknownSubcommand {
|
||||
subcommand: sub.to_string(),
|
||||
@@ -386,8 +457,16 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
return Ok(cmd);
|
||||
}
|
||||
|
||||
// Default: selector or timeout
|
||||
// Default: selector, timeout, or range (e.g. 2000-5000)
|
||||
if let Some(arg) = rest.first() {
|
||||
// Check for range syntax: "2000-5000"
|
||||
if let Some((min_str, max_str)) = arg.split_once('-') {
|
||||
if let (Ok(min), Ok(max)) = (min_str.parse::<u64>(), max_str.parse::<u64>()) {
|
||||
return Ok(
|
||||
json!({ "id": id, "action": "wait", "timeout": min, "timeoutMax": max }),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Ok(timeout) = arg.parse::<u64>() {
|
||||
Ok(json!({ "id": id, "action": "wait", "timeout": timeout }))
|
||||
} else {
|
||||
@@ -396,7 +475,7 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
} else {
|
||||
Err(ParseError::MissingArguments {
|
||||
context: "wait".to_string(),
|
||||
usage: "wait <selector|ms|--url|--load|--fn|--text>",
|
||||
usage: "wait <selector|ms|min-max|--url|--load|--fn|--text>",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -929,9 +1008,7 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
})?;
|
||||
Ok(json!({ "id": id, "action": "state_load", "path": path }))
|
||||
}
|
||||
Some("list") => {
|
||||
Ok(json!({ "id": id, "action": "state_list" }))
|
||||
}
|
||||
Some("list") => Ok(json!({ "id": id, "action": "state_list" })),
|
||||
Some("clear") => {
|
||||
let mut session_name: Option<&str> = None;
|
||||
let mut all = false;
|
||||
@@ -952,7 +1029,9 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
|
||||
if let Some(name) = session_name {
|
||||
if !is_valid_session_name(name) {
|
||||
return Err(ParseError::InvalidSessionName { name: name.to_string() });
|
||||
return Err(ParseError::InvalidSessionName {
|
||||
name: name.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1006,13 +1085,19 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
|
||||
let new_name = new_name.trim_end_matches(".json");
|
||||
|
||||
if !is_valid_session_name(old_name) {
|
||||
return Err(ParseError::InvalidSessionName { name: old_name.to_string() });
|
||||
return Err(ParseError::InvalidSessionName {
|
||||
name: old_name.to_string(),
|
||||
});
|
||||
}
|
||||
if !is_valid_session_name(new_name) {
|
||||
return Err(ParseError::InvalidSessionName { name: new_name.to_string() });
|
||||
return Err(ParseError::InvalidSessionName {
|
||||
name: new_name.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(json!({ "id": id, "action": "state_rename", "oldName": old_name, "newName": new_name }))
|
||||
Ok(
|
||||
json!({ "id": id, "action": "state_rename", "oldName": old_name, "newName": new_name }),
|
||||
)
|
||||
}
|
||||
Some(sub) => Err(ParseError::UnknownSubcommand {
|
||||
subcommand: sub.to_string(),
|
||||
@@ -1121,7 +1206,10 @@ fn parse_diff(rest: &[&str], id: &str, flags: &Flags) -> Result<Value, ParseErro
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(ParseError::InvalidValue {
|
||||
message: format!("Depth must be a non-negative integer, got: {}", d),
|
||||
message: format!(
|
||||
"Depth must be a non-negative integer, got: {}",
|
||||
d
|
||||
),
|
||||
usage: "diff snapshot --depth <n>",
|
||||
});
|
||||
}
|
||||
@@ -1187,7 +1275,10 @@ fn parse_diff(rest: &[&str], id: &str, flags: &Flags) -> Result<Value, ParseErro
|
||||
}
|
||||
Ok(n) => {
|
||||
return Err(ParseError::InvalidValue {
|
||||
message: format!("Threshold must be between 0 and 1, got {}", n),
|
||||
message: format!(
|
||||
"Threshold must be between 0 and 1, got {}",
|
||||
n
|
||||
),
|
||||
usage: "diff screenshot --threshold <0-1>",
|
||||
});
|
||||
}
|
||||
@@ -1304,7 +1395,10 @@ fn parse_diff(rest: &[&str], id: &str, flags: &Flags) -> Result<Value, ParseErro
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(ParseError::InvalidValue {
|
||||
message: format!("Depth must be a non-negative integer, got: {}", d),
|
||||
message: format!(
|
||||
"Depth must be a non-negative integer, got: {}",
|
||||
d
|
||||
),
|
||||
usage: "diff url <url1> <url2> --depth <n>",
|
||||
});
|
||||
}
|
||||
@@ -1874,7 +1968,6 @@ mod tests {
|
||||
executable_path: None,
|
||||
extensions: Vec::new(),
|
||||
cdp: None,
|
||||
profile: None,
|
||||
state: None,
|
||||
proxy: None,
|
||||
proxy_bypass: None,
|
||||
@@ -1888,7 +1981,6 @@ mod tests {
|
||||
session_name: None,
|
||||
cli_executable_path: false,
|
||||
cli_extensions: false,
|
||||
cli_profile: false,
|
||||
cli_state: false,
|
||||
cli_args: false,
|
||||
cli_user_agent: false,
|
||||
@@ -2275,6 +2367,29 @@ mod tests {
|
||||
assert_eq!(cmd["text"], "some text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_type_command_with_delay() {
|
||||
let cmd =
|
||||
parse_command(&args("type #input some text --delay 120"), &default_flags()).unwrap();
|
||||
assert_eq!(cmd["action"], "type");
|
||||
assert_eq!(cmd["selector"], "#input");
|
||||
assert_eq!(cmd["text"], "some text");
|
||||
assert_eq!(cmd["delay"], 120);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_type_command_with_literal_delay_text() {
|
||||
let cmd = parse_command(
|
||||
&args("type #input -- --delay 120 should be typed"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "type");
|
||||
assert_eq!(cmd["selector"], "#input");
|
||||
assert_eq!(cmd["text"], "--delay 120 should be typed");
|
||||
assert!(cmd.get("delay").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_select() {
|
||||
let cmd = parse_command(&args("select #menu option1"), &default_flags()).unwrap();
|
||||
@@ -2454,6 +2569,19 @@ mod tests {
|
||||
assert_eq!(cmd["selector"], "#element");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_keyboard_type_with_delay() {
|
||||
let cmd = parse_command(
|
||||
&args("keyboard type natural typing --delay 90"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "keyboard");
|
||||
assert_eq!(cmd["subaction"], "type");
|
||||
assert_eq!(cmd["text"], "natural typing");
|
||||
assert_eq!(cmd["delay"], 90);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wait_timeout() {
|
||||
let cmd = parse_command(&args("wait 5000"), &default_flags()).unwrap();
|
||||
@@ -3029,8 +3157,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_diff_snapshot_baseline() {
|
||||
let cmd =
|
||||
parse_command(&args("diff snapshot --baseline before.txt"), &default_flags()).unwrap();
|
||||
let cmd = parse_command(
|
||||
&args("diff snapshot --baseline before.txt"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "diff_snapshot");
|
||||
assert_eq!(cmd["baseline"], "before.txt");
|
||||
}
|
||||
@@ -3050,9 +3181,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_diff_snapshot_short_flags() {
|
||||
let cmd =
|
||||
parse_command(&args("diff snapshot -b snap.txt -s .content -c -d 2"), &default_flags())
|
||||
.unwrap();
|
||||
let cmd = parse_command(
|
||||
&args("diff snapshot -b snap.txt -s .content -c -d 2"),
|
||||
&default_flags(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmd["action"], "diff_snapshot");
|
||||
assert_eq!(cmd["baseline"], "snap.txt");
|
||||
assert_eq!(cmd["selector"], ".content");
|
||||
@@ -3100,8 +3233,7 @@ mod tests {
|
||||
fn test_diff_screenshot_global_full_flag() {
|
||||
let mut flags = default_flags();
|
||||
flags.full = true;
|
||||
let cmd =
|
||||
parse_command(&args("diff screenshot --baseline b.png"), &flags).unwrap();
|
||||
let cmd = parse_command(&args("diff screenshot --baseline b.png"), &flags).unwrap();
|
||||
assert_eq!(cmd["action"], "diff_screenshot");
|
||||
assert_eq!(cmd["fullPage"], true);
|
||||
}
|
||||
@@ -3145,8 +3277,7 @@ mod tests {
|
||||
fn test_diff_url_global_full_flag() {
|
||||
let mut flags = default_flags();
|
||||
flags.full = true;
|
||||
let cmd =
|
||||
parse_command(&args("diff url https://a.com https://b.com"), &flags).unwrap();
|
||||
let cmd = parse_command(&args("diff url https://a.com https://b.com"), &flags).unwrap();
|
||||
assert_eq!(cmd["fullPage"], true);
|
||||
}
|
||||
|
||||
|
||||
+15
-13
@@ -215,11 +215,11 @@ pub fn ensure_daemon(
|
||||
proxy_bypass: Option<&str>,
|
||||
ignore_https_errors: bool,
|
||||
allow_file_access: bool,
|
||||
profile: Option<&str>,
|
||||
state: Option<&str>,
|
||||
provider: Option<&str>,
|
||||
device: Option<&str>,
|
||||
session_name: Option<&str>,
|
||||
debug: bool,
|
||||
) -> Result<DaemonResult, String> {
|
||||
// Check if daemon is running AND responsive
|
||||
if is_daemon_running(session) && daemon_ready(session) {
|
||||
@@ -344,10 +344,6 @@ pub fn ensure_daemon(
|
||||
cmd.env("AGENT_BROWSER_ALLOW_FILE_ACCESS", "1");
|
||||
}
|
||||
|
||||
if let Some(prof) = profile {
|
||||
cmd.env("AGENT_BROWSER_PROFILE", prof);
|
||||
}
|
||||
|
||||
if let Some(st) = state {
|
||||
cmd.env("AGENT_BROWSER_STATE", st);
|
||||
}
|
||||
@@ -364,6 +360,11 @@ pub fn ensure_daemon(
|
||||
cmd.env("AGENT_BROWSER_SESSION_NAME", sn);
|
||||
}
|
||||
|
||||
cmd.env("AGENT_BROWSER_STEALTH", "1");
|
||||
if debug {
|
||||
cmd.env("AGENT_BROWSER_DEBUG", "1");
|
||||
}
|
||||
|
||||
// Create new process group and session to fully detach
|
||||
unsafe {
|
||||
cmd.pre_exec(|| {
|
||||
@@ -375,8 +376,8 @@ pub fn ensure_daemon(
|
||||
|
||||
cmd.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.stderr(Stdio::null());
|
||||
cmd.spawn()
|
||||
.map_err(|e| format!("Failed to start daemon: {}", e))?;
|
||||
}
|
||||
|
||||
@@ -427,10 +428,6 @@ pub fn ensure_daemon(
|
||||
cmd.env("AGENT_BROWSER_ALLOW_FILE_ACCESS", "1");
|
||||
}
|
||||
|
||||
if let Some(prof) = profile {
|
||||
cmd.env("AGENT_BROWSER_PROFILE", prof);
|
||||
}
|
||||
|
||||
if let Some(st) = state {
|
||||
cmd.env("AGENT_BROWSER_STATE", st);
|
||||
}
|
||||
@@ -447,6 +444,11 @@ pub fn ensure_daemon(
|
||||
cmd.env("AGENT_BROWSER_SESSION_NAME", sn);
|
||||
}
|
||||
|
||||
cmd.env("AGENT_BROWSER_STEALTH", "1");
|
||||
if debug {
|
||||
cmd.env("AGENT_BROWSER_DEBUG", "1");
|
||||
}
|
||||
|
||||
// CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
|
||||
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
|
||||
const DETACHED_PROCESS: u32 = 0x00000008;
|
||||
@@ -454,8 +456,8 @@ pub fn ensure_daemon(
|
||||
cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.stderr(Stdio::null());
|
||||
cmd.spawn()
|
||||
.map_err(|e| format!("Failed to start daemon: {}", e))?;
|
||||
}
|
||||
|
||||
|
||||
+61
-65
@@ -19,7 +19,6 @@ pub struct Config {
|
||||
pub session_name: Option<String>,
|
||||
pub executable_path: Option<String>,
|
||||
pub extensions: Option<Vec<String>>,
|
||||
pub profile: Option<String>,
|
||||
pub state: Option<String>,
|
||||
pub proxy: Option<String>,
|
||||
pub proxy_bypass: Option<String>,
|
||||
@@ -53,7 +52,6 @@ impl Config {
|
||||
}
|
||||
(a, b) => b.or(a),
|
||||
},
|
||||
profile: other.profile.or(self.profile),
|
||||
state: other.state.or(self.state),
|
||||
proxy: other.proxy.or(self.proxy),
|
||||
proxy_bypass: other.proxy_bypass.or(self.proxy_bypass),
|
||||
@@ -132,6 +130,7 @@ fn extract_config_path(args: &[String]) -> Option<Option<String>> {
|
||||
"--device",
|
||||
"--session-name",
|
||||
"--color-scheme",
|
||||
"--channel",
|
||||
];
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
@@ -156,8 +155,7 @@ pub fn load_config(args: &[String]) -> Result<Config, String> {
|
||||
});
|
||||
|
||||
if let Some((source, maybe_path)) = explicit {
|
||||
let path_str =
|
||||
maybe_path.ok_or_else(|| format!("{} requires a file path", source))?;
|
||||
let path_str = maybe_path.ok_or_else(|| format!("{} requires a file path", source))?;
|
||||
let path = PathBuf::from(&path_str);
|
||||
if !path.exists() {
|
||||
return Err(format!("config file not found: {}", path_str));
|
||||
@@ -189,7 +187,6 @@ pub struct Flags {
|
||||
pub executable_path: Option<String>,
|
||||
pub cdp: Option<String>,
|
||||
pub extensions: Vec<String>,
|
||||
pub profile: Option<String>,
|
||||
pub state: Option<String>,
|
||||
pub proxy: Option<String>,
|
||||
pub proxy_bypass: Option<String>,
|
||||
@@ -208,7 +205,6 @@ pub struct Flags {
|
||||
// (as opposed to being set only via environment variables)
|
||||
pub cli_executable_path: bool,
|
||||
pub cli_extensions: bool,
|
||||
pub cli_profile: bool,
|
||||
pub cli_state: bool,
|
||||
pub cli_args: bool,
|
||||
pub cli_user_agent: bool,
|
||||
@@ -241,53 +237,49 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
};
|
||||
|
||||
let mut flags = Flags {
|
||||
json: env_var_is_truthy("AGENT_BROWSER_JSON")
|
||||
|| config.json.unwrap_or(false),
|
||||
full: env_var_is_truthy("AGENT_BROWSER_FULL")
|
||||
|| config.full.unwrap_or(false),
|
||||
headed: env_var_is_truthy("AGENT_BROWSER_HEADED")
|
||||
|| config.headed.unwrap_or(false),
|
||||
debug: env_var_is_truthy("AGENT_BROWSER_DEBUG")
|
||||
|| config.debug.unwrap_or(false),
|
||||
session: env::var("AGENT_BROWSER_SESSION").ok()
|
||||
json: env_var_is_truthy("AGENT_BROWSER_JSON") || config.json.unwrap_or(false),
|
||||
full: env_var_is_truthy("AGENT_BROWSER_FULL") || config.full.unwrap_or(false),
|
||||
headed: match env::var("AGENT_BROWSER_HEADED") {
|
||||
Ok(val) => !matches!(val.to_lowercase().as_str(), "0" | "false" | "no" | ""),
|
||||
Err(_) => config.headed.unwrap_or(true),
|
||||
},
|
||||
debug: env_var_is_truthy("AGENT_BROWSER_DEBUG") || config.debug.unwrap_or(false),
|
||||
session: env::var("AGENT_BROWSER_SESSION")
|
||||
.ok()
|
||||
.or(config.session)
|
||||
.unwrap_or_else(|| "default".to_string()),
|
||||
headers: config.headers,
|
||||
executable_path: env::var("AGENT_BROWSER_EXECUTABLE_PATH").ok()
|
||||
executable_path: env::var("AGENT_BROWSER_EXECUTABLE_PATH")
|
||||
.ok()
|
||||
.or(config.executable_path),
|
||||
cdp: config.cdp,
|
||||
extensions,
|
||||
profile: env::var("AGENT_BROWSER_PROFILE").ok()
|
||||
.or(config.profile),
|
||||
state: env::var("AGENT_BROWSER_STATE").ok()
|
||||
.or(config.state),
|
||||
proxy: env::var("AGENT_BROWSER_PROXY").ok()
|
||||
.or(config.proxy),
|
||||
proxy_bypass: env::var("AGENT_BROWSER_PROXY_BYPASS").ok()
|
||||
state: env::var("AGENT_BROWSER_STATE").ok().or(config.state),
|
||||
proxy: env::var("AGENT_BROWSER_PROXY").ok().or(config.proxy),
|
||||
proxy_bypass: env::var("AGENT_BROWSER_PROXY_BYPASS")
|
||||
.ok()
|
||||
.or(config.proxy_bypass),
|
||||
args: env::var("AGENT_BROWSER_ARGS").ok()
|
||||
.or(config.args),
|
||||
user_agent: env::var("AGENT_BROWSER_USER_AGENT").ok()
|
||||
args: env::var("AGENT_BROWSER_ARGS").ok().or(config.args),
|
||||
user_agent: env::var("AGENT_BROWSER_USER_AGENT")
|
||||
.ok()
|
||||
.or(config.user_agent),
|
||||
provider: env::var("AGENT_BROWSER_PROVIDER").ok()
|
||||
.or(config.provider),
|
||||
provider: env::var("AGENT_BROWSER_PROVIDER").ok().or(config.provider),
|
||||
ignore_https_errors: env_var_is_truthy("AGENT_BROWSER_IGNORE_HTTPS_ERRORS")
|
||||
|| config.ignore_https_errors.unwrap_or(false),
|
||||
allow_file_access: env_var_is_truthy("AGENT_BROWSER_ALLOW_FILE_ACCESS")
|
||||
|| config.allow_file_access.unwrap_or(false),
|
||||
device: env::var("AGENT_BROWSER_IOS_DEVICE").ok()
|
||||
.or(config.device),
|
||||
device: env::var("AGENT_BROWSER_IOS_DEVICE").ok().or(config.device),
|
||||
auto_connect: env_var_is_truthy("AGENT_BROWSER_AUTO_CONNECT")
|
||||
|| config.auto_connect.unwrap_or(false),
|
||||
session_name: env::var("AGENT_BROWSER_SESSION_NAME").ok()
|
||||
session_name: env::var("AGENT_BROWSER_SESSION_NAME")
|
||||
.ok()
|
||||
.or(config.session_name),
|
||||
annotate: env_var_is_truthy("AGENT_BROWSER_ANNOTATE")
|
||||
|| config.annotate.unwrap_or(false),
|
||||
color_scheme: env::var("AGENT_BROWSER_COLOR_SCHEME").ok()
|
||||
annotate: env_var_is_truthy("AGENT_BROWSER_ANNOTATE") || config.annotate.unwrap_or(false),
|
||||
color_scheme: env::var("AGENT_BROWSER_COLOR_SCHEME")
|
||||
.ok()
|
||||
.or(config.color_scheme),
|
||||
cli_executable_path: false,
|
||||
cli_extensions: false,
|
||||
cli_profile: false,
|
||||
cli_state: false,
|
||||
cli_args: false,
|
||||
cli_user_agent: false,
|
||||
@@ -303,22 +295,30 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
"--json" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.json = val;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--full" | "-f" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.full = val;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--headed" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.headed = val;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--debug" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.debug = val;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--session" => {
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
@@ -352,13 +352,6 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--profile" => {
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
flags.profile = Some(s.clone());
|
||||
flags.cli_profile = true;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--state" => {
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
flags.state = Some(s.clone());
|
||||
@@ -403,13 +396,17 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
"--ignore-https-errors" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.ignore_https_errors = val;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--allow-file-access" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.allow_file_access = val;
|
||||
flags.cli_allow_file_access = true;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--device" => {
|
||||
if let Some(d) = args.get(i + 1) {
|
||||
@@ -420,7 +417,9 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
"--auto-connect" => {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.auto_connect = val;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--session-name" => {
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
@@ -432,7 +431,9 @@ pub fn parse_flags(args: &[String]) -> Flags {
|
||||
let (val, consumed) = parse_bool_arg(args, i);
|
||||
flags.annotate = val;
|
||||
flags.cli_annotate = true;
|
||||
if consumed { i += 1; }
|
||||
if consumed {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
"--color-scheme" => {
|
||||
if let Some(s) = args.get(i + 1) {
|
||||
@@ -473,7 +474,6 @@ pub fn clean_args(args: &[String]) -> Vec<String> {
|
||||
"--executable-path",
|
||||
"--cdp",
|
||||
"--extension",
|
||||
"--profile",
|
||||
"--state",
|
||||
"--proxy",
|
||||
"--proxy-bypass",
|
||||
@@ -655,12 +655,6 @@ mod tests {
|
||||
assert!(flags.cli_extensions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cli_profile_tracking() {
|
||||
let flags = parse_flags(&args("--profile /path/to/profile snapshot"));
|
||||
assert!(flags.cli_profile);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cli_annotate_tracking() {
|
||||
let flags = parse_flags(&args("--annotate screenshot"));
|
||||
@@ -677,10 +671,9 @@ mod tests {
|
||||
#[test]
|
||||
fn test_cli_multiple_flags_tracking() {
|
||||
let flags = parse_flags(&args(
|
||||
"--executable-path /chrome --profile /profile --proxy http://proxy snapshot",
|
||||
"--executable-path /chrome --proxy http://proxy snapshot",
|
||||
));
|
||||
assert!(flags.cli_executable_path);
|
||||
assert!(flags.cli_profile);
|
||||
assert!(flags.cli_proxy);
|
||||
assert!(!flags.cli_extensions);
|
||||
assert!(!flags.cli_state);
|
||||
@@ -699,7 +692,6 @@ mod tests {
|
||||
"sessionName": "my-app",
|
||||
"executablePath": "/usr/bin/chromium",
|
||||
"extensions": ["/ext1", "/ext2"],
|
||||
"profile": "/tmp/profile",
|
||||
"state": "/tmp/state.json",
|
||||
"proxy": "http://proxy:8080",
|
||||
"proxyBypass": "localhost",
|
||||
@@ -721,8 +713,10 @@ mod tests {
|
||||
assert_eq!(config.session.as_deref(), Some("test-session"));
|
||||
assert_eq!(config.session_name.as_deref(), Some("my-app"));
|
||||
assert_eq!(config.executable_path.as_deref(), Some("/usr/bin/chromium"));
|
||||
assert_eq!(config.extensions, Some(vec!["/ext1".to_string(), "/ext2".to_string()]));
|
||||
assert_eq!(config.profile.as_deref(), Some("/tmp/profile"));
|
||||
assert_eq!(
|
||||
config.extensions,
|
||||
Some(vec!["/ext1".to_string(), "/ext2".to_string()])
|
||||
);
|
||||
assert_eq!(config.state.as_deref(), Some("/tmp/state.json"));
|
||||
assert_eq!(config.proxy.as_deref(), Some("http://proxy:8080"));
|
||||
assert_eq!(config.proxy_bypass.as_deref(), Some("localhost"));
|
||||
@@ -768,7 +762,6 @@ mod tests {
|
||||
let user = Config {
|
||||
headed: Some(true),
|
||||
proxy: Some("http://user-proxy:8080".to_string()),
|
||||
profile: Some("/user/profile".to_string()),
|
||||
..Config::default()
|
||||
};
|
||||
let project = Config {
|
||||
@@ -779,7 +772,6 @@ mod tests {
|
||||
let merged = user.merge(project);
|
||||
assert_eq!(merged.headed, Some(true)); // kept from user
|
||||
assert_eq!(merged.proxy.as_deref(), Some("http://project-proxy:9090")); // overridden by project
|
||||
assert_eq!(merged.profile.as_deref(), Some("/user/profile")); // kept from user
|
||||
assert_eq!(merged.debug, Some(true)); // added by project
|
||||
}
|
||||
|
||||
@@ -1030,7 +1022,11 @@ mod tests {
|
||||
let merged = user.merge(project);
|
||||
assert_eq!(
|
||||
merged.extensions,
|
||||
Some(vec!["/ext1".to_string(), "/ext2".to_string(), "/ext3".to_string()])
|
||||
Some(vec![
|
||||
"/ext1".to_string(),
|
||||
"/ext2".to_string(),
|
||||
"/ext3".to_string()
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+143
-55
@@ -153,6 +153,47 @@ fn main() {
|
||||
return;
|
||||
}
|
||||
|
||||
if args.iter().any(|a| a == "--profile") {
|
||||
let msg =
|
||||
"Project policy: --profile is forbidden. Use your existing browser and --session-name for state persistence.";
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
if env::var("AGENT_BROWSER_PROFILE").is_ok() {
|
||||
let msg =
|
||||
"Project policy: AGENT_BROWSER_PROFILE is forbidden. Remove it and use --session-name.";
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if args.iter().any(|a| a == "--channel") {
|
||||
let msg = "Project policy: --channel is forbidden. Browser selection follows your existing browser session.";
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
if env::var("AGENT_BROWSER_CHANNEL").is_ok() {
|
||||
let msg =
|
||||
"Project policy: AGENT_BROWSER_CHANNEL is forbidden. Remove it and use your existing browser session.";
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if clean.is_empty() {
|
||||
print_help();
|
||||
return;
|
||||
@@ -221,11 +262,11 @@ fn main() {
|
||||
flags.proxy_bypass.as_deref(),
|
||||
flags.ignore_https_errors,
|
||||
flags.allow_file_access,
|
||||
flags.profile.as_deref(),
|
||||
flags.state.as_deref(),
|
||||
flags.provider.as_deref(),
|
||||
flags.device.as_deref(),
|
||||
flags.session_name.as_deref(),
|
||||
flags.debug,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(e) => {
|
||||
@@ -253,11 +294,6 @@ fn main() {
|
||||
} else {
|
||||
None
|
||||
},
|
||||
if flags.cli_profile {
|
||||
Some("--profile")
|
||||
} else {
|
||||
None
|
||||
},
|
||||
if flags.cli_state {
|
||||
Some("--state")
|
||||
} else {
|
||||
@@ -448,22 +484,29 @@ fn main() {
|
||||
launch_cmd["colorScheme"] = json!(cs);
|
||||
}
|
||||
|
||||
let err = match send_command(launch_cmd, &flags.session) {
|
||||
Ok(resp) if resp.success => None,
|
||||
Ok(resp) => Some(
|
||||
resp.error
|
||||
.unwrap_or_else(|| "CDP connection failed".to_string()),
|
||||
),
|
||||
Err(e) => Some(e.to_string()),
|
||||
};
|
||||
|
||||
if let Some(msg) = err {
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
match send_command(launch_cmd, &flags.session) {
|
||||
Ok(resp) => {
|
||||
if !resp.success {
|
||||
let msg = resp
|
||||
.error
|
||||
.unwrap_or_else(|| "CDP connection failed".to_string());
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
Err(e) => {
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, e);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), e);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,37 +522,87 @@ fn main() {
|
||||
launch_cmd["colorScheme"] = json!(cs);
|
||||
}
|
||||
|
||||
let err = match send_command(launch_cmd, &flags.session) {
|
||||
Ok(resp) if resp.success => None,
|
||||
Ok(resp) => Some(
|
||||
resp.error
|
||||
.unwrap_or_else(|| "Provider connection failed".to_string()),
|
||||
),
|
||||
Err(e) => Some(e.to_string()),
|
||||
};
|
||||
|
||||
if let Some(msg) = err {
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
match send_command(launch_cmd, &flags.session) {
|
||||
Ok(resp) => {
|
||||
if !resp.success {
|
||||
let msg = resp
|
||||
.error
|
||||
.unwrap_or_else(|| "Provider connection failed".to_string());
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
Err(e) => {
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, e);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), e);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Project policy: when no explicit connection mode is provided,
|
||||
// commands must attach to an existing browser on CDP :9333.
|
||||
// If unavailable, fail fast instead of launching a managed browser.
|
||||
let can_try_default_cdp = flags.cdp.is_none()
|
||||
&& !flags.auto_connect
|
||||
&& flags.provider.is_none()
|
||||
&& flags.executable_path.is_none()
|
||||
&& flags.state.is_none()
|
||||
&& flags.proxy.is_none()
|
||||
&& flags.args.is_none()
|
||||
&& flags.user_agent.is_none()
|
||||
&& !flags.ignore_https_errors
|
||||
&& !flags.allow_file_access
|
||||
&& flags.extensions.is_empty();
|
||||
|
||||
let mut launched_via_default_cdp = false;
|
||||
if can_try_default_cdp {
|
||||
let mut launch_cmd = json!({
|
||||
"id": gen_id(),
|
||||
"action": "launch",
|
||||
"cdpPort": 9333
|
||||
});
|
||||
|
||||
if let Some(ref cs) = flags.color_scheme {
|
||||
launch_cmd["colorScheme"] = json!(cs);
|
||||
}
|
||||
|
||||
if let Ok(resp) = send_command(launch_cmd, &flags.session) {
|
||||
launched_via_default_cdp = resp.success;
|
||||
}
|
||||
}
|
||||
if can_try_default_cdp && !launched_via_default_cdp {
|
||||
let msg = "Project policy requires using your existing browser. Could not connect to CDP at localhost:9333. Start your browser with remote debugging on port 9333, or pass --cdp <port|url>.";
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Launch headed browser or configure browser options (without CDP or provider)
|
||||
if (flags.headed
|
||||
|| flags.executable_path.is_some()
|
||||
|| flags.profile.is_some()
|
||||
|| flags.state.is_some()
|
||||
|| flags.proxy.is_some()
|
||||
|| flags.args.is_some()
|
||||
|| flags.user_agent.is_some()
|
||||
|| flags.ignore_https_errors
|
||||
|| flags.allow_file_access
|
||||
|| flags.debug
|
||||
|| flags.color_scheme.is_some())
|
||||
&& flags.cdp.is_none()
|
||||
&& flags.provider.is_none()
|
||||
&& !launched_via_default_cdp
|
||||
{
|
||||
let mut launch_cmd = json!({
|
||||
"id": gen_id(),
|
||||
@@ -526,11 +619,6 @@ fn main() {
|
||||
cmd_obj.insert("executablePath".to_string(), json!(exec_path));
|
||||
}
|
||||
|
||||
// Add profile path if specified
|
||||
if let Some(ref profile_path) = flags.profile {
|
||||
cmd_obj.insert("profile".to_string(), json!(profile_path));
|
||||
}
|
||||
|
||||
// Add state path if specified
|
||||
if let Some(ref state_path) = flags.state {
|
||||
cmd_obj.insert("storageState".to_string(), json!(state_path));
|
||||
@@ -574,17 +662,20 @@ fn main() {
|
||||
}
|
||||
|
||||
match send_command(launch_cmd, &flags.session) {
|
||||
Ok(resp) if !resp.success => {
|
||||
// Launch command failed (e.g., invalid state file, profile error)
|
||||
let error_msg = resp
|
||||
.error
|
||||
.unwrap_or_else(|| "Browser launch failed".to_string());
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, error_msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), error_msg);
|
||||
Ok(resp) => {
|
||||
if !resp.success {
|
||||
// Launch command failed (e.g., invalid state file)
|
||||
let error_msg = resp
|
||||
.error
|
||||
.unwrap_or_else(|| "Browser launch failed".to_string());
|
||||
if flags.json {
|
||||
println!(r#"{{"success":false,"error":"{}"}}"#, error_msg);
|
||||
} else {
|
||||
eprintln!("{} {}", color::error_indicator(), error_msg);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
exit(1);
|
||||
|
||||
}
|
||||
Err(e) => {
|
||||
if flags.json {
|
||||
@@ -598,9 +689,6 @@ fn main() {
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
Ok(_) => {
|
||||
// Launch succeeded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
include!("main.rs");
|
||||
+100
-37
@@ -22,6 +22,9 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
if let Some(title) = data.get("title").and_then(|v| v.as_str()) {
|
||||
println!("{} {}", color::success_indicator(), color::bold(title));
|
||||
println!(" {}", color::dim(url));
|
||||
if let Some(warning) = data.get("warning").and_then(|v| v.as_str()) {
|
||||
println!("{} {}", color::warning_indicator(), warning);
|
||||
}
|
||||
return;
|
||||
}
|
||||
println!("{}", url);
|
||||
@@ -39,15 +42,11 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
return;
|
||||
}
|
||||
Some("diff_url") => {
|
||||
if let Some(snap_data) =
|
||||
obj.get("snapshot").and_then(|v| v.as_object())
|
||||
{
|
||||
if let Some(snap_data) = obj.get("snapshot").and_then(|v| v.as_object()) {
|
||||
println!("{}", color::bold("Snapshot diff:"));
|
||||
print_snapshot_diff(snap_data);
|
||||
}
|
||||
if let Some(ss_data) =
|
||||
obj.get("screenshot").and_then(|v| v.as_object())
|
||||
{
|
||||
if let Some(ss_data) = obj.get("screenshot").and_then(|v| v.as_object()) {
|
||||
println!("\n{}", color::bold("Screenshot diff:"));
|
||||
print_screenshot_diff(ss_data);
|
||||
}
|
||||
@@ -310,11 +309,7 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
}
|
||||
_ => {
|
||||
if let Some(path) = data.get("path").and_then(|v| v.as_str()) {
|
||||
println!(
|
||||
"{} Recording started: {}",
|
||||
color::success_indicator(),
|
||||
path
|
||||
);
|
||||
println!("{} Recording started: {}", color::success_indicator(), path);
|
||||
} else {
|
||||
println!("{} Recording started", color::success_indicator());
|
||||
}
|
||||
@@ -497,7 +492,10 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
let filename = file.get("filename").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let size = file.get("size").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let modified = file.get("modified").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let encrypted = file.get("encrypted").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let encrypted = file
|
||||
.get("encrypted")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let size_str = if size > 1024 {
|
||||
format!("{:.1}KB", size as f64 / 1024.0)
|
||||
} else {
|
||||
@@ -505,7 +503,11 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
};
|
||||
let date_str = modified.split('T').next().unwrap_or(modified);
|
||||
let enc_str = if encrypted { " [encrypted]" } else { "" };
|
||||
println!(" {} {}", filename, color::dim(&format!("({}, {}){}", size_str, date_str, enc_str)));
|
||||
println!(
|
||||
" {} {}",
|
||||
filename,
|
||||
color::dim(&format!("({}, {}){}", size_str, date_str, enc_str))
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -515,13 +517,22 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
if let Some(true) = data.get("renamed").and_then(|v| v.as_bool()) {
|
||||
let old_name = data.get("oldName").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let new_name = data.get("newName").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!("{} Renamed {} -> {}", color::success_indicator(), old_name, new_name);
|
||||
println!(
|
||||
"{} Renamed {} -> {}",
|
||||
color::success_indicator(),
|
||||
old_name,
|
||||
new_name
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// State clear
|
||||
if let Some(cleared) = data.get("cleared").and_then(|v| v.as_i64()) {
|
||||
println!("{} Cleared {} state file(s)", color::success_indicator(), cleared);
|
||||
println!(
|
||||
"{} Cleared {} state file(s)",
|
||||
color::success_indicator(),
|
||||
cleared
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -529,7 +540,10 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
if let Some(summary) = data.get("summary") {
|
||||
let cookies = summary.get("cookies").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let origins = summary.get("origins").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let encrypted = data.get("encrypted").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let encrypted = data
|
||||
.get("encrypted")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let enc_str = if encrypted { " (encrypted)" } else { "" };
|
||||
println!("State file summary{}:", enc_str);
|
||||
println!(" Cookies: {}", cookies);
|
||||
@@ -539,7 +553,11 @@ pub fn print_response(resp: &Response, json_mode: bool, action: Option<&str>) {
|
||||
|
||||
// State clean
|
||||
if let Some(cleaned) = data.get("cleaned").and_then(|v| v.as_i64()) {
|
||||
println!("{} Cleaned {} old state file(s)", color::success_indicator(), cleaned);
|
||||
println!(
|
||||
"{} Cleaned {} old state file(s)",
|
||||
color::success_indicator(),
|
||||
cleaned
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -701,10 +719,11 @@ Examples:
|
||||
r##"
|
||||
agent-browser type - Type text into an element
|
||||
|
||||
Usage: agent-browser type <selector> <text>
|
||||
Usage: agent-browser type <selector> <text> [--delay <ms>]
|
||||
|
||||
Types text into the specified element character by character.
|
||||
Unlike fill, this does not clear existing content first.
|
||||
Use --delay to add per-character delay (milliseconds).
|
||||
|
||||
Global Options:
|
||||
--json Output as JSON
|
||||
@@ -712,7 +731,9 @@ Global Options:
|
||||
|
||||
Examples:
|
||||
agent-browser type "#search" "hello"
|
||||
agent-browser type "#search" "iphone" --delay 120
|
||||
agent-browser type @e2 "additional text"
|
||||
agent-browser type @e2 -- "--delay 120 (literal text)"
|
||||
|
||||
See Also:
|
||||
For typing into contenteditable editors (Lexical, ProseMirror, etc.)
|
||||
@@ -943,7 +964,7 @@ the current focus — essential for contenteditable editors like
|
||||
Lexical, ProseMirror, CodeMirror, and Monaco.
|
||||
|
||||
Subcommands:
|
||||
type <text> Type text character-by-character with real
|
||||
type <text> [--delay <ms>] Type text character-by-character with real
|
||||
key events (keydown, keypress, keyup per char)
|
||||
inserttext <text> Insert text without key events (like paste)
|
||||
|
||||
@@ -956,6 +977,7 @@ Global Options:
|
||||
|
||||
Examples:
|
||||
agent-browser keyboard type "Hello, World!"
|
||||
agent-browser keyboard type "human pacing" --delay 90
|
||||
agent-browser keyboard type "# My Heading"
|
||||
agent-browser keyboard inserttext "pasted content"
|
||||
|
||||
@@ -1017,13 +1039,14 @@ Examples:
|
||||
r##"
|
||||
agent-browser wait - Wait for condition
|
||||
|
||||
Usage: agent-browser wait <selector|ms|option>
|
||||
Usage: agent-browser wait <selector|ms|min-max|option>
|
||||
|
||||
Waits for an element to appear, a timeout, or other conditions.
|
||||
|
||||
Modes:
|
||||
<selector> Wait for element to appear
|
||||
<ms> Wait for specified milliseconds
|
||||
<min>-<max> Wait for random time between min and max ms
|
||||
--url <pattern> Wait for URL to match pattern
|
||||
--load <state> Wait for load state (load, domcontentloaded, networkidle)
|
||||
--fn <expression> Wait for JavaScript expression to be truthy
|
||||
@@ -1040,6 +1063,7 @@ Global Options:
|
||||
Examples:
|
||||
agent-browser wait "#loading-spinner"
|
||||
agent-browser wait 2000
|
||||
agent-browser wait 2000-5000 # Random wait between 2-5 seconds
|
||||
agent-browser wait --url "**/dashboard"
|
||||
agent-browser wait --load networkidle
|
||||
agent-browser wait --fn "window.appReady === true"
|
||||
@@ -1996,10 +2020,10 @@ Core Commands:
|
||||
open <url> Navigate to URL
|
||||
click <sel> Click element (or @ref)
|
||||
dblclick <sel> Double-click element
|
||||
type <sel> <text> Type into element
|
||||
type <sel> <text> [--delay <ms>] Type into element
|
||||
fill <sel> <text> Clear and fill
|
||||
press <key> Press key (Enter, Tab, Control+a)
|
||||
keyboard type <text> Type text with real keystrokes (no selector)
|
||||
keyboard type <text> [--delay <ms>] Type text with real keystrokes (no selector)
|
||||
keyboard inserttext <text> Insert text without key events
|
||||
hover <sel> Hover element
|
||||
focus <sel> Focus element
|
||||
@@ -2011,7 +2035,7 @@ Core Commands:
|
||||
download <sel> <path> Download file by clicking element
|
||||
scroll <dir> [px] Scroll (up/down/left/right)
|
||||
scrollintoview <sel> Scroll element into view
|
||||
wait <sel|ms> Wait for element or time
|
||||
wait <sel|ms|min-max> Wait for element, time, or random range
|
||||
screenshot [path] Take screenshot
|
||||
pdf <path> Save as PDF
|
||||
snapshot Accessibility tree with refs (for AI)
|
||||
@@ -2083,7 +2107,6 @@ Snapshot Options:
|
||||
|
||||
Options:
|
||||
--session <name> Isolated session (or AGENT_BROWSER_SESSION env)
|
||||
--profile <path> Persistent browser profile (or AGENT_BROWSER_PROFILE env)
|
||||
--state <path> Load storage state from JSON file (or AGENT_BROWSER_STATE env)
|
||||
--headers <json> HTTP headers scoped to URL's origin (for auth)
|
||||
--executable-path <path> Custom browser executable (or AGENT_BROWSER_EXECUTABLE_PATH)
|
||||
@@ -2105,11 +2128,17 @@ Options:
|
||||
--headed Show browser window (not headless)
|
||||
--cdp <port> Connect via CDP (Chrome DevTools Protocol)
|
||||
--auto-connect Auto-discover and connect to running Chrome
|
||||
Project default: require existing browser at localhost:9333 (no auto local fallback)
|
||||
--color-scheme <scheme> Color scheme: dark, light, no-preference (or AGENT_BROWSER_COLOR_SCHEME)
|
||||
--session-name <name> Auto-save/restore session state (cookies, localStorage)
|
||||
--config <path> Use a custom config file (or AGENT_BROWSER_CONFIG env)
|
||||
--debug Debug output
|
||||
--version, -V Show version
|
||||
--version, -V Show version (fork builds include upstream/fork info)
|
||||
|
||||
Policy:
|
||||
--profile / AGENT_BROWSER_PROFILE are forbidden
|
||||
--channel / AGENT_BROWSER_CHANNEL are forbidden
|
||||
Use existing browser session (CDP localhost:9333) or pass --cdp explicitly
|
||||
|
||||
Configuration:
|
||||
agent-browser looks for agent-browser.json in these locations (lowest to highest priority):
|
||||
@@ -2128,7 +2157,7 @@ Configuration:
|
||||
Extensions from user and project configs are merged (not replaced).
|
||||
|
||||
Example agent-browser.json:
|
||||
{{"headed": true, "proxy": "http://localhost:8080", "profile": "./browser-data"}}
|
||||
{{"headed": true, "proxy": "http://localhost:8080", "userAgent": "my-agent/1.0"}}
|
||||
|
||||
Environment:
|
||||
AGENT_BROWSER_CONFIG Path to config file (or use --config)
|
||||
@@ -2147,6 +2176,9 @@ Environment:
|
||||
AGENT_BROWSER_PROVIDER Browser provider (ios, browserbase, kernel, browseruse)
|
||||
AGENT_BROWSER_AUTO_CONNECT Auto-discover and connect to running Chrome
|
||||
AGENT_BROWSER_ALLOW_FILE_ACCESS Allow file:// URLs to access local files
|
||||
|
||||
AGENT_BROWSER_LOCALE Override auto-detected locale (e.g., zh-TW, ja-JP)
|
||||
AGENT_BROWSER_TIMEZONE Override auto-detected timezone (e.g., Asia/Taipei)
|
||||
AGENT_BROWSER_COLOR_SCHEME Color scheme preference (dark, light, no-preference)
|
||||
AGENT_BROWSER_DEFAULT_TIMEOUT Default Playwright timeout in ms (default: 25000)
|
||||
AGENT_BROWSER_SESSION_NAME Auto-save/load state persistence name
|
||||
@@ -2157,11 +2189,11 @@ Environment:
|
||||
AGENT_BROWSER_IOS_UDID Default iOS device UDID
|
||||
|
||||
Install (recommended, fastest - native Rust CLI):
|
||||
npm install -g agent-browser
|
||||
npm install -g agent-browser-stealth
|
||||
agent-browser install # Download Chromium (first time)
|
||||
|
||||
Try without installing (slower, routes through Node.js):
|
||||
npx agent-browser open example.com
|
||||
npx agent-browser-stealth open example.com
|
||||
|
||||
Examples:
|
||||
agent-browser open example.com
|
||||
@@ -2176,7 +2208,6 @@ Examples:
|
||||
agent-browser --cdp 9222 snapshot # Connect via CDP port
|
||||
agent-browser --auto-connect snapshot # Auto-discover running Chrome
|
||||
agent-browser --color-scheme dark open example.com # Dark mode
|
||||
agent-browser --profile ~/.myapp open example.com # Persistent profile
|
||||
agent-browser --session-name myapp open example.com # Auto-save/restore state
|
||||
|
||||
Command Chaining:
|
||||
@@ -2232,10 +2263,7 @@ fn print_screenshot_diff(data: &serde_json::Map<String, serde_json::Value>) {
|
||||
.get("mismatchPercentage")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let is_match = data
|
||||
.get("match")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let is_match = data.get("match").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let dim_mismatch = data
|
||||
.get("dimensionMismatch")
|
||||
.and_then(|v| v.as_bool())
|
||||
@@ -2246,7 +2274,10 @@ fn print_screenshot_diff(data: &serde_json::Map<String, serde_json::Value>) {
|
||||
color::error_indicator()
|
||||
);
|
||||
} else if is_match {
|
||||
println!("{} Images match (0% difference)", color::success_indicator());
|
||||
println!(
|
||||
"{} Images match (0% difference)",
|
||||
color::success_indicator()
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"{} {:.2}% pixels differ",
|
||||
@@ -2257,7 +2288,10 @@ fn print_screenshot_diff(data: &serde_json::Map<String, serde_json::Value>) {
|
||||
if let Some(diff_path) = data.get("diffPath").and_then(|v| v.as_str()) {
|
||||
println!(" Diff image: {}", color::green(diff_path));
|
||||
}
|
||||
let total = data.get("totalPixels").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let total = data
|
||||
.get("totalPixels")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
let different = data
|
||||
.get("differentPixels")
|
||||
.and_then(|v| v.as_i64())
|
||||
@@ -2269,6 +2303,35 @@ fn print_screenshot_diff(data: &serde_json::Map<String, serde_json::Value>) {
|
||||
);
|
||||
}
|
||||
|
||||
pub fn print_version() {
|
||||
println!("agent-browser {}", env!("CARGO_PKG_VERSION"));
|
||||
/// Parse fork version metadata from semver-like strings:
|
||||
/// <upstream>-fork.<fork>
|
||||
/// Example:
|
||||
/// 0.14.0-fork.1 -> (0.14.0, 1)
|
||||
fn parse_fork_version(version: &str) -> Option<(&str, &str)> {
|
||||
let (upstream, fork) = version.split_once("-fork.")?;
|
||||
if upstream.is_empty() || fork.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !upstream
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_digit() || c == '.' || c == '-')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if !fork.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') {
|
||||
return None;
|
||||
}
|
||||
Some((upstream, fork))
|
||||
}
|
||||
|
||||
pub fn print_version() {
|
||||
let version = env!("CARGO_PKG_VERSION");
|
||||
if let Some((upstream, fork)) = parse_fork_version(version) {
|
||||
println!(
|
||||
"agent-browser {} (upstream {}, fork {})",
|
||||
version, upstream, fork
|
||||
);
|
||||
} else {
|
||||
println!("agent-browser {}", version);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
/// Check if a session name is valid (alphanumeric, hyphens, and underscores only)
|
||||
pub fn is_valid_session_name(name: &str) -> bool {
|
||||
!name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_')
|
||||
!name.is_empty()
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_alphanumeric() || c == '-' || c == '_')
|
||||
}
|
||||
|
||||
/// Generate error message for invalid session name
|
||||
|
||||
@@ -14,9 +14,9 @@ const DEFAULT_MODEL = "anthropic/claude-haiku-4.5";
|
||||
|
||||
const SYSTEM_PROMPT = `You are a helpful documentation assistant for agent-browser, a headless browser automation CLI designed for AI agents.
|
||||
|
||||
GitHub repository: https://github.com/vercel-labs/agent-browser
|
||||
GitHub repository: https://github.com/leeguooooo/agent-browser
|
||||
Documentation: https://agent-browser.dev
|
||||
npm package: agent-browser
|
||||
npm package: agent-browser-stealth
|
||||
|
||||
You have access to the full agent-browser documentation via the bash and readFile tools. The docs are available as markdown files in the /workspace/ directory.
|
||||
|
||||
|
||||
@@ -6,6 +6,13 @@ export const metadata = pageMetadata("cdp-mode")
|
||||
|
||||
Connect to an existing browser via Chrome DevTools Protocol:
|
||||
|
||||
Default behavior in this fork: when `--cdp` is omitted, agent-browser requires an existing browser at `localhost:9333`. If CDP is unavailable, the command fails fast (no local-launch fallback).
|
||||
|
||||
Project policy:
|
||||
|
||||
- `--profile` / `AGENT_BROWSER_PROFILE` are forbidden
|
||||
- `--channel` / `AGENT_BROWSER_CHANNEL` are forbidden
|
||||
|
||||
```bash
|
||||
# Start Chrome with: google-chrome --remote-debugging-port=9222
|
||||
|
||||
@@ -52,7 +59,7 @@ AGENT_BROWSER_AUTO_CONNECT=1 agent-browser snapshot
|
||||
Auto-connect discovers Chrome by:
|
||||
|
||||
1. Reading Chrome's `DevToolsActivePort` file from the default user data directory
|
||||
2. Falling back to probing common debugging ports (9222, 9229)
|
||||
2. Falling back to probing common debugging ports (9222, 9229, 9333)
|
||||
|
||||
This is useful when:
|
||||
|
||||
@@ -75,6 +82,23 @@ Or set it globally via config or environment variable:
|
||||
AGENT_BROWSER_COLOR_SCHEME=dark agent-browser --cdp 9222 open https://example.com
|
||||
```
|
||||
|
||||
## Stealth behavior
|
||||
|
||||
`--stealth` is enabled by default across connection modes, but capabilities depend on how you connect:
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Connection type</th><th>Stealth capabilities</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td>Local launch</td><td>Chromium launch args + context init scripts</td></tr>
|
||||
<tr><td>CDP / auto-connect</td><td>Context init scripts</td></tr>
|
||||
<tr><td>Cloud providers</td><td>Context init scripts (Kernel may also apply provider-managed stealth)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
Use `--debug` to print the active connection type and applied stealth capabilities.
|
||||
|
||||
## Use cases
|
||||
|
||||
This enables control of:
|
||||
@@ -93,7 +117,6 @@ This enables control of:
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>--session <name></code></td><td>Use isolated session</td></tr>
|
||||
<tr><td><code>--profile <path></code></td><td>Persistent browser profile directory</td></tr>
|
||||
<tr><td><code>-p <provider></code></td><td>Cloud browser provider (<code>browserbase</code>, <code>browseruse</code>, <code>kernel</code>)</td></tr>
|
||||
<tr><td><code>--headers <json></code></td><td>HTTP headers scoped to origin</td></tr>
|
||||
<tr><td><code>--executable-path</code></td><td>Custom browser executable</td></tr>
|
||||
|
||||
@@ -11,9 +11,9 @@ agent-browser open <url> # Navigate (aliases: goto, navigate)
|
||||
agent-browser click <sel> # Click element (--new-tab to open in new tab)
|
||||
agent-browser dblclick <sel> # Double-click
|
||||
agent-browser fill <sel> <text> # Clear and fill
|
||||
agent-browser type <sel> <text> # Type into element
|
||||
agent-browser type <sel> <text> [--delay <ms>] # Type into element
|
||||
agent-browser press <key> # Press key (Enter, Tab, Control+a) (alias: key)
|
||||
agent-browser keyboard type <text> # Type at current focus (no selector needed)
|
||||
agent-browser keyboard type <text> [--delay <ms>] # Type at current focus (no selector needed)
|
||||
agent-browser keyboard inserttext <text> # Insert text without key events
|
||||
agent-browser keydown <key> # Hold key down
|
||||
agent-browser keyup <key> # Release key
|
||||
@@ -32,9 +32,16 @@ agent-browser pdf <path> # Save page as PDF
|
||||
agent-browser snapshot # Accessibility tree with refs
|
||||
agent-browser eval <js> # Run JavaScript
|
||||
agent-browser connect <port|url> # Connect to browser via CDP
|
||||
agent-browser --version # Show CLI version
|
||||
agent-browser close # Close browser (aliases: quit, exit)
|
||||
```
|
||||
|
||||
Fork builds print dual-version metadata with `--version`:
|
||||
|
||||
```bash
|
||||
agent-browser 0.14.0-fork.1 (upstream 0.14.0, fork 1)
|
||||
```
|
||||
|
||||
## Get info
|
||||
|
||||
```bash
|
||||
@@ -95,6 +102,7 @@ agent-browser find nth 2 ".card" hover
|
||||
```bash
|
||||
agent-browser wait <selector> # Wait for element
|
||||
agent-browser wait <ms> # Wait for time
|
||||
agent-browser wait 2000-5000 # Random wait between 2-5 seconds
|
||||
agent-browser wait --text "Welcome" # Wait for text
|
||||
agent-browser wait --url "**/dash" # Wait for URL pattern
|
||||
agent-browser wait --load networkidle # Wait for load state
|
||||
@@ -232,7 +240,6 @@ agent-browser reload # Reload page
|
||||
```bash
|
||||
--session <name> # Isolated browser session
|
||||
--session-name <name> # Auto-save/restore session state (cookies, localStorage)
|
||||
--profile <path> # Persistent browser profile directory
|
||||
--state <path> # Load storage state from JSON file
|
||||
--headers <json> # HTTP headers scoped to URL's origin
|
||||
--executable-path <path> # Custom browser executable
|
||||
@@ -243,6 +250,7 @@ agent-browser reload # Reload page
|
||||
--proxy-bypass <hosts> # Hosts to bypass proxy
|
||||
--ignore-https-errors # Ignore HTTPS certificate errors
|
||||
--allow-file-access # Allow file:// URLs to access local files (Chromium only)
|
||||
--stealth # Stealth mode (always on by default)
|
||||
-p, --provider <name> # Browser provider (ios, browserbase, kernel, browseruse)
|
||||
--device <name> # iOS device name (e.g., "iPhone 15 Pro")
|
||||
--json # JSON output (for scripts)
|
||||
@@ -251,7 +259,7 @@ agent-browser reload # Reload page
|
||||
--headed # Show browser window (not headless)
|
||||
--cdp <port|url> # Connect via Chrome DevTools Protocol (port or WebSocket URL)
|
||||
--auto-connect # Auto-discover and connect to running Chrome
|
||||
--debug # Debug output
|
||||
--debug # Debug output (includes stealth connection type + capabilities)
|
||||
```
|
||||
|
||||
## Command chaining
|
||||
|
||||
@@ -6,6 +6,8 @@ export const metadata = pageMetadata("configuration")
|
||||
|
||||
Create an `agent-browser.json` file to set persistent defaults instead of repeating flags on every command.
|
||||
|
||||
In this fork, default launch behavior requires a resident browser at `localhost:9333` (CDP). If unavailable, commands fail fast instead of launching a managed browser.
|
||||
|
||||
## Config File Locations
|
||||
|
||||
agent-browser checks two locations, merged in priority order:
|
||||
@@ -37,7 +39,6 @@ AGENT_BROWSER_CONFIG=./ci-config.json agent-browser open example.com
|
||||
{
|
||||
"headed": true,
|
||||
"proxy": "http://localhost:8080",
|
||||
"profile": "./browser-data",
|
||||
"userAgent": "my-agent/1.0",
|
||||
"ignoreHttpsErrors": true
|
||||
}
|
||||
@@ -60,7 +61,6 @@ Every CLI flag can be set in the config file using its camelCase equivalent:
|
||||
<tr><td><code>sessionName</code></td><td><code>--session-name</code></td><td>string</td></tr>
|
||||
<tr><td><code>executablePath</code></td><td><code>--executable-path</code></td><td>string</td></tr>
|
||||
<tr><td><code>extensions</code></td><td><code>--extension</code></td><td>string[]</td></tr>
|
||||
<tr><td><code>profile</code></td><td><code>--profile</code></td><td>string</td></tr>
|
||||
<tr><td><code>state</code></td><td><code>--state</code></td><td>string</td></tr>
|
||||
<tr><td><code>proxy</code></td><td><code>--proxy</code></td><td>string</td></tr>
|
||||
<tr><td><code>proxyBypass</code></td><td><code>--proxy-bypass</code></td><td>string</td></tr>
|
||||
@@ -84,7 +84,7 @@ Every CLI flag can be set in the config file using its camelCase equivalent:
|
||||
```json
|
||||
{
|
||||
"headed": true,
|
||||
"profile": "./browser-data"
|
||||
"sessionName": "local-dev"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export const metadata = pageMetadata("installation")
|
||||
Installs the native Rust binary for maximum performance:
|
||||
|
||||
```bash
|
||||
npm install -g agent-browser
|
||||
npm install -g agent-browser-stealth
|
||||
agent-browser install # Download Chromium
|
||||
```
|
||||
|
||||
@@ -20,8 +20,8 @@ This is the fastest option -- commands run through the native Rust CLI directly
|
||||
Run directly with `npx` if you want to try it without installing globally:
|
||||
|
||||
```bash
|
||||
npx agent-browser install # Download Chromium (first time only)
|
||||
npx agent-browser open example.com
|
||||
npx agent-browser-stealth install # Download Chromium (first time only)
|
||||
npx agent-browser-stealth open example.com
|
||||
```
|
||||
|
||||
> **Note:** `npx` routes through Node.js before reaching the Rust CLI, so it is noticeably slower than a global install. For regular use, install globally.
|
||||
@@ -31,14 +31,14 @@ npx agent-browser open example.com
|
||||
For projects that want to pin the version in `package.json`:
|
||||
|
||||
```bash
|
||||
npm install agent-browser
|
||||
npx agent-browser install
|
||||
npm install agent-browser-stealth
|
||||
npx agent-browser-stealth install
|
||||
```
|
||||
|
||||
Then use via `npx` or `package.json` scripts:
|
||||
|
||||
```bash
|
||||
npx agent-browser open example.com
|
||||
npx agent-browser-stealth open example.com
|
||||
```
|
||||
|
||||
## Homebrew (macOS)
|
||||
@@ -51,7 +51,7 @@ agent-browser install # Download Chromium
|
||||
## From source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/vercel-labs/agent-browser
|
||||
git clone https://github.com/leeguooooo/agent-browser
|
||||
cd agent-browser
|
||||
pnpm install
|
||||
pnpm build
|
||||
@@ -60,6 +60,15 @@ pnpm build:native
|
||||
pnpm link --global
|
||||
```
|
||||
|
||||
## Fork versioning
|
||||
|
||||
Fork releases use a dual-version format:
|
||||
|
||||
- `<upstream>-fork.<fork>`
|
||||
- Example: `0.14.0-fork.1`
|
||||
|
||||
`agent-browser --version` prints the full version and also shows upstream and fork parts for fork builds.
|
||||
|
||||
## Linux dependencies
|
||||
|
||||
On Linux, install system dependencies:
|
||||
@@ -89,7 +98,7 @@ AGENT_BROWSER_EXECUTABLE_PATH=/path/to/chromium agent-browser open example.com
|
||||
|
||||
```typescript
|
||||
import chromium from '@sparticuz/chromium';
|
||||
import { BrowserManager } from 'agent-browser';
|
||||
import { BrowserManager } from 'agent-browser-stealth';
|
||||
|
||||
export async function handler() {
|
||||
const browser = new BrowserManager();
|
||||
@@ -110,7 +119,7 @@ agent-browser works with any AI agent out of the box. For richer context:
|
||||
Install the skill for your AI coding assistant:
|
||||
|
||||
```bash
|
||||
npx skills add vercel-labs/agent-browser
|
||||
npx skills add leeguooooo/agent-browser
|
||||
```
|
||||
|
||||
This works with Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, Goose, OpenCode, and Windsurf. The skill is fetched from the repository and stays up to date automatically.
|
||||
|
||||
@@ -7,11 +7,11 @@ export const metadata = pageMetadata("")
|
||||
Browser automation CLI designed for AI agents. Compact text output minimizes context usage. Fast Rust CLI with Node.js fallback.
|
||||
|
||||
```bash
|
||||
npm install -g agent-browser # all platforms (fastest, native Rust CLI)
|
||||
npm install -g agent-browser-stealth # all platforms (fastest, native Rust CLI)
|
||||
brew install agent-browser # macOS
|
||||
|
||||
# or try without installing
|
||||
npx agent-browser open example.com
|
||||
npx agent-browser-stealth open example.com
|
||||
```
|
||||
|
||||
## Features
|
||||
@@ -22,6 +22,8 @@ npx agent-browser open example.com
|
||||
- **Complete** - 50+ commands for navigation, forms, screenshots, network, storage
|
||||
- **Sessions** - Multiple isolated browser instances with separate auth
|
||||
- **Cross-platform** - macOS, Linux, Windows with native binaries
|
||||
- **Auto region detection** - Locale, timezone, and Accept-Language automatically match the target site's TLD
|
||||
- **Captcha auto-retry** - Detects captcha/verification pages and retries with randomized backoff
|
||||
|
||||
## Works with
|
||||
|
||||
|
||||
@@ -34,29 +34,6 @@ Each session has its own:
|
||||
- Navigation history
|
||||
- Authentication state
|
||||
|
||||
## Persistent profiles
|
||||
|
||||
By default, browser state is lost when the browser closes. Use `--profile` to persist state across restarts:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
The profile directory stores:
|
||||
|
||||
- Cookies and localStorage
|
||||
- IndexedDB data
|
||||
- Service workers
|
||||
- Browser cache
|
||||
- Login sessions
|
||||
|
||||
## Session persistence
|
||||
|
||||
Use `--session-name` to automatically save and restore cookies and localStorage across browser restarts:
|
||||
|
||||
@@ -176,7 +176,7 @@ Send input events to control the browser remotely.
|
||||
For advanced use, control streaming directly via the TypeScript API:
|
||||
|
||||
```typescript
|
||||
import { BrowserManager } from 'agent-browser';
|
||||
import { BrowserManager } from 'agent-browser-stealth';
|
||||
|
||||
const browser = new BrowserManager();
|
||||
await browser.launch({ headless: true });
|
||||
|
||||
@@ -53,7 +53,7 @@ export function Header() {
|
||||
</div>
|
||||
<nav className="flex items-center gap-4">
|
||||
<a
|
||||
href="https://github.com/vercel-labs/agent-browser"
|
||||
href="https://github.com/leeguooooo/agent-browser"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hidden sm:flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
@@ -69,7 +69,7 @@ export function Header() {
|
||||
<span>14k</span>
|
||||
</a>
|
||||
<a
|
||||
href="https://www.npmjs.com/package/agent-browser"
|
||||
href="https://www.npmjs.com/package/agent-browser-stealth"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hidden sm:block text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
|
||||
+12
-6
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "agent-browser",
|
||||
"version": "0.14.0",
|
||||
"description": "Headless browser automation CLI for AI agents",
|
||||
"name": "agent-browser-stealth",
|
||||
"version": "0.14.0-fork.3",
|
||||
"description": "Stealth browser automation CLI for AI agents with anti-bot evasions",
|
||||
"type": "module",
|
||||
"main": "dist/daemon.js",
|
||||
"files": [
|
||||
@@ -11,6 +11,7 @@
|
||||
"skills"
|
||||
],
|
||||
"bin": {
|
||||
"agent-browser-stealth": "./bin/agent-browser.js",
|
||||
"agent-browser": "./bin/agent-browser.js"
|
||||
},
|
||||
"scripts": {
|
||||
@@ -33,6 +34,8 @@
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"postinstall": "node scripts/postinstall.js",
|
||||
"sync:upstream": "bash scripts/sync-upstream.sh",
|
||||
"sync:upstream:push": "bash scripts/sync-upstream.sh --push",
|
||||
"changeset": "changeset",
|
||||
"ci:version": "changeset version && pnpm run version:sync && pnpm install --no-frozen-lockfile",
|
||||
"ci:publish": "pnpm run version:sync && pnpm run build && changeset publish"
|
||||
@@ -41,6 +44,9 @@
|
||||
"browser",
|
||||
"automation",
|
||||
"headless",
|
||||
"stealth",
|
||||
"anti-bot",
|
||||
"anti-detection",
|
||||
"playwright",
|
||||
"cli",
|
||||
"agent"
|
||||
@@ -48,12 +54,12 @@
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vercel-labs/agent-browser.git"
|
||||
"url": "git+https://github.com/leeguooooo/agent-browser.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vercel-labs/agent-browser/issues"
|
||||
"url": "https://github.com/leeguooooo/agent-browser/issues"
|
||||
},
|
||||
"homepage": "https://github.com/vercel-labs/agent-browser#readme",
|
||||
"homepage": "https://github.com/leeguooooo/agent-browser#readme",
|
||||
"dependencies": {
|
||||
"node-simctl": "^7.4.0",
|
||||
"playwright-core": "^1.57.0",
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* End-to-end check for CreepJS headless/stealth indicators.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/check-creepjs-headless.js
|
||||
* node scripts/check-creepjs-headless.js --compare-stealth
|
||||
* node scripts/check-creepjs-headless.js --binary ./cli/target/release/agent-browser
|
||||
*/
|
||||
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = join(__dirname, '..');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const getArgValue = (name, fallback) => {
|
||||
const index = args.indexOf(name);
|
||||
if (index === -1 || index + 1 >= args.length) return fallback;
|
||||
return args[index + 1];
|
||||
};
|
||||
|
||||
const binary = getArgValue('--binary', join(rootDir, 'cli', 'target', 'release', 'agent-browser'));
|
||||
const sessionPrefix = getArgValue('--session-prefix', 'creepjs-e2e');
|
||||
const compareStealth = args.includes('--compare-stealth');
|
||||
const targetUrl = getArgValue('--url', 'https://abrahamjuliot.github.io/creepjs/');
|
||||
|
||||
const extractionScript = `(() => {
|
||||
const headless = globalThis.Fingerprint?.headless ?? null;
|
||||
const toNumber = (value) => (typeof value === 'number' ? value : null);
|
||||
return {
|
||||
found: !!headless,
|
||||
metrics: headless ? {
|
||||
chromium: !!headless.chromium,
|
||||
likeHeadless: toNumber(headless.likeHeadlessRating),
|
||||
headless: toNumber(headless.headlessRating),
|
||||
stealth: toNumber(headless.stealthRating),
|
||||
raw: headless,
|
||||
} : null,
|
||||
navigator: {
|
||||
userAgent: navigator.userAgent,
|
||||
userAgentData: navigator.userAgentData ? navigator.userAgentData.toJSON?.() ?? null : null,
|
||||
language: navigator.language,
|
||||
languages: navigator.languages,
|
||||
platform: navigator.platform,
|
||||
webdriver: navigator.webdriver,
|
||||
webdriverInNavigator: ('webdriver' in navigator),
|
||||
},
|
||||
window: {
|
||||
innerWidth: window.innerWidth,
|
||||
innerHeight: window.innerHeight,
|
||||
outerWidth: window.outerWidth,
|
||||
outerHeight: window.outerHeight,
|
||||
screenX: window.screenX,
|
||||
screenY: window.screenY,
|
||||
},
|
||||
intl: {
|
||||
locale: Intl.DateTimeFormat().resolvedOptions().locale,
|
||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
},
|
||||
};
|
||||
})()`;
|
||||
|
||||
function runCommand(commandArgs, options = {}) {
|
||||
const result = spawnSync(binary, commandArgs, { encoding: 'utf8' });
|
||||
if (result.status !== 0 && !options.allowFailure) {
|
||||
const stderr = (result.stderr || '').trim();
|
||||
const stdout = (result.stdout || '').trim();
|
||||
throw new Error(
|
||||
`Command failed: ${binary} ${commandArgs.join(' ')}\n` +
|
||||
`${stderr || stdout || `exit code ${result.status}`}`
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function withSessionArgs(session, stealth) {
|
||||
const base = ['--session', session];
|
||||
if (stealth === false) {
|
||||
base.push('--stealth', 'false');
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function runSingleCheck({ stealth, runId }) {
|
||||
const session = `${sessionPrefix}-${runId}-${stealth ? 'stealth-on' : 'stealth-off'}`;
|
||||
|
||||
runCommand([...withSessionArgs(session, stealth), 'close'], { allowFailure: true });
|
||||
|
||||
try {
|
||||
runCommand([...withSessionArgs(session, stealth), 'open', targetUrl]);
|
||||
runCommand([
|
||||
...withSessionArgs(session, stealth),
|
||||
'wait',
|
||||
'--fn',
|
||||
'!!(window.Fingerprint && window.Fingerprint.headless)',
|
||||
]);
|
||||
runCommand([...withSessionArgs(session, stealth), 'wait', '2000']);
|
||||
|
||||
const evalResult = runCommand([
|
||||
...withSessionArgs(session, stealth),
|
||||
'eval',
|
||||
'--json',
|
||||
extractionScript,
|
||||
]);
|
||||
|
||||
const payload = JSON.parse(evalResult.stdout);
|
||||
return {
|
||||
session,
|
||||
stealth,
|
||||
url: targetUrl,
|
||||
extracted: payload?.data?.result ?? null,
|
||||
};
|
||||
} finally {
|
||||
runCommand([...withSessionArgs(session, stealth), 'close'], { allowFailure: true });
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const runId = Date.now();
|
||||
const checks = compareStealth ? [true, false] : [true];
|
||||
const results = checks.map((stealth) => runSingleCheck({ stealth, runId }));
|
||||
|
||||
const output = {
|
||||
binary,
|
||||
compareStealth,
|
||||
timestamp: new Date().toISOString(),
|
||||
results,
|
||||
};
|
||||
|
||||
console.log(JSON.stringify(output, null, 2));
|
||||
}
|
||||
|
||||
main();
|
||||
Executable
+112
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* End-to-end check for bot.sannysoft.com WebDriver (New) result.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/check-sannysoft-webdriver.js
|
||||
* node scripts/check-sannysoft-webdriver.js --compare-stealth
|
||||
* node scripts/check-sannysoft-webdriver.js --binary ./cli/target/release/agent-browser
|
||||
*/
|
||||
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = join(__dirname, '..');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const getArgValue = (name, fallback) => {
|
||||
const index = args.indexOf(name);
|
||||
if (index === -1 || index + 1 >= args.length) return fallback;
|
||||
return args[index + 1];
|
||||
};
|
||||
|
||||
const binary = getArgValue('--binary', join(rootDir, 'cli', 'target', 'release', 'agent-browser'));
|
||||
const sessionPrefix = getArgValue('--session-prefix', 'botcheck-e2e');
|
||||
const compareStealth = args.includes('--compare-stealth');
|
||||
const targetUrl = getArgValue('--url', 'https://bot.sannysoft.com');
|
||||
|
||||
const extractionScript = `(() => {
|
||||
const normalize = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
||||
const rows = Array.from(document.querySelectorAll('tr'));
|
||||
const exact = rows.find((tr) => normalize(tr.cells?.[0]?.textContent).toLowerCase() === 'webdriver (new)');
|
||||
const fallback = exact || rows.find((tr) => normalize(tr.cells?.[0]?.textContent).toLowerCase().includes('webdriver'));
|
||||
return {
|
||||
found: !!fallback,
|
||||
label: fallback ? normalize(fallback.cells?.[0]?.textContent) : null,
|
||||
valueText: fallback ? normalize(fallback.cells?.[1]?.textContent) : null,
|
||||
statusText: fallback ? normalize(fallback.textContent) : null,
|
||||
navigatorWebdriver: navigator.webdriver,
|
||||
webdriverInNavigator: ('webdriver' in navigator),
|
||||
};
|
||||
})()`;
|
||||
|
||||
function runCommand(commandArgs, options = {}) {
|
||||
const result = spawnSync(binary, commandArgs, { encoding: 'utf8' });
|
||||
if (result.status !== 0 && !options.allowFailure) {
|
||||
const stderr = (result.stderr || '').trim();
|
||||
const stdout = (result.stdout || '').trim();
|
||||
throw new Error(
|
||||
`Command failed: ${binary} ${commandArgs.join(' ')}\n` +
|
||||
`${stderr || stdout || `exit code ${result.status}`}`
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function withSessionArgs(session, stealth) {
|
||||
const base = ['--session', session];
|
||||
if (stealth === false) {
|
||||
base.push('--stealth', 'false');
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function runSingleCheck({ stealth, runId }) {
|
||||
const session = `${sessionPrefix}-${runId}-${stealth ? 'stealth-on' : 'stealth-off'}`;
|
||||
|
||||
// Best-effort cleanup in case previous run left state behind.
|
||||
runCommand([...withSessionArgs(session, stealth), 'close'], { allowFailure: true });
|
||||
|
||||
try {
|
||||
runCommand([...withSessionArgs(session, stealth), 'open', targetUrl]);
|
||||
runCommand([...withSessionArgs(session, stealth), 'wait', '--load', 'networkidle']);
|
||||
runCommand([...withSessionArgs(session, stealth), 'wait', '5000']);
|
||||
|
||||
const evalResult = runCommand([
|
||||
...withSessionArgs(session, stealth),
|
||||
'eval',
|
||||
'--json',
|
||||
extractionScript,
|
||||
]);
|
||||
|
||||
const payload = JSON.parse(evalResult.stdout);
|
||||
return {
|
||||
session,
|
||||
stealth,
|
||||
url: targetUrl,
|
||||
extracted: payload?.data?.result ?? null,
|
||||
};
|
||||
} finally {
|
||||
runCommand([...withSessionArgs(session, stealth), 'close'], { allowFailure: true });
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const runId = Date.now();
|
||||
const checks = compareStealth ? [true, false] : [true];
|
||||
const results = checks.map((stealth) => runSingleCheck({ stealth, runId }));
|
||||
|
||||
const output = {
|
||||
binary,
|
||||
compareStealth,
|
||||
timestamp: new Date().toISOString(),
|
||||
results,
|
||||
};
|
||||
|
||||
console.log(JSON.stringify(output, null, 2));
|
||||
}
|
||||
|
||||
main();
|
||||
+83
-43
@@ -9,7 +9,7 @@
|
||||
* - Mac/Linux: Replaces symlink to point to native binary
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, chmodSync, createWriteStream, unlinkSync, writeFileSync, symlinkSync, lstatSync } from 'fs';
|
||||
import { existsSync, mkdirSync, chmodSync, createWriteStream, unlinkSync, writeFileSync, symlinkSync, lstatSync, readFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { platform, arch } from 'os';
|
||||
@@ -27,15 +27,41 @@ const binaryName = `agent-browser-${platformKey}${ext}`;
|
||||
const binaryPath = join(binDir, binaryName);
|
||||
|
||||
// Package info
|
||||
const packageJson = JSON.parse(
|
||||
(await import('fs')).readFileSync(join(projectRoot, 'package.json'), 'utf8')
|
||||
);
|
||||
const packageJson = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
|
||||
const version = packageJson.version;
|
||||
const packageName = packageJson.name;
|
||||
const binCommands = getBinCommands(packageJson);
|
||||
|
||||
// GitHub release URL
|
||||
const GITHUB_REPO = 'vercel-labs/agent-browser';
|
||||
const GITHUB_REPO = getGitHubRepoFromPackage(packageJson);
|
||||
const DOWNLOAD_URL = `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${binaryName}`;
|
||||
|
||||
function getGitHubRepoFromPackage(pkg) {
|
||||
const repo = pkg?.repository;
|
||||
const repoUrl = typeof repo === 'string' ? repo : repo?.url;
|
||||
|
||||
if (typeof repoUrl === 'string') {
|
||||
const match = repoUrl.match(/github\.com[:/]([^/]+\/[^/.]+)(?:\.git)?$/i);
|
||||
if (match?.[1]) {
|
||||
return match[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for legacy package metadata
|
||||
return 'vercel-labs/agent-browser';
|
||||
}
|
||||
|
||||
function getBinCommands(pkg) {
|
||||
const bin = pkg?.bin;
|
||||
if (typeof bin === 'string') {
|
||||
return [pkg.name.replace(/^@[^/]+\//, '')];
|
||||
}
|
||||
if (bin && typeof bin === 'object') {
|
||||
return Object.keys(bin);
|
||||
}
|
||||
return ['agent-browser'];
|
||||
}
|
||||
|
||||
async function downloadFile(url, dest) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const file = createWriteStream(dest);
|
||||
@@ -107,7 +133,7 @@ async function main() {
|
||||
console.log('');
|
||||
console.log('To build the native binary locally:');
|
||||
console.log(' 1. Install Rust: https://rustup.rs');
|
||||
console.log(' 2. Run: npm run build:native');
|
||||
console.log(' 2. Run: pnpm run build:native');
|
||||
}
|
||||
|
||||
// On global installs, fix npm's bin entry to use native binary directly
|
||||
@@ -157,27 +183,34 @@ async function fixUnixSymlink() {
|
||||
return; // npm not available
|
||||
}
|
||||
|
||||
const symlinkPath = join(npmBinDir, 'agent-browser');
|
||||
let optimized = false;
|
||||
for (const commandName of binCommands) {
|
||||
const symlinkPath = join(npmBinDir, commandName);
|
||||
|
||||
// Check if symlink exists (indicates global install)
|
||||
try {
|
||||
const stat = lstatSync(symlinkPath);
|
||||
if (!stat.isSymbolicLink()) {
|
||||
return; // Not a symlink, don't touch it
|
||||
// Check if symlink exists (indicates global install)
|
||||
try {
|
||||
const stat = lstatSync(symlinkPath);
|
||||
if (!stat.isSymbolicLink()) {
|
||||
continue; // Not a symlink, don't touch it
|
||||
}
|
||||
} catch {
|
||||
continue; // Symlink doesn't exist, not a global install
|
||||
}
|
||||
|
||||
// Replace symlink to point directly to native binary
|
||||
try {
|
||||
unlinkSync(symlinkPath);
|
||||
symlinkSync(binaryPath, symlinkPath);
|
||||
optimized = true;
|
||||
} catch (err) {
|
||||
// Permission error or other issue - not critical, JS wrapper still works
|
||||
console.log(`⚠ Could not optimize symlink (${commandName}): ${err.message}`);
|
||||
console.log(' CLI will work via Node.js wrapper (slightly slower startup)');
|
||||
}
|
||||
} catch {
|
||||
return; // Symlink doesn't exist, not a global install
|
||||
}
|
||||
|
||||
// Replace symlink to point directly to native binary
|
||||
try {
|
||||
unlinkSync(symlinkPath);
|
||||
symlinkSync(binaryPath, symlinkPath);
|
||||
if (optimized) {
|
||||
console.log('✓ Optimized: symlink points to native binary (zero overhead)');
|
||||
} catch (err) {
|
||||
// Permission error or other issue - not critical, JS wrapper still works
|
||||
console.log(`⚠ Could not optimize symlink: ${err.message}`);
|
||||
console.log(' CLI will work via Node.js wrapper (slightly slower startup)');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,25 +228,28 @@ async function fixWindowsShims() {
|
||||
return; // Not a global install or npm not available
|
||||
}
|
||||
|
||||
// The shims are in the npm prefix directory (not prefix/bin on Windows)
|
||||
const cmdShim = join(npmBinDir, 'agent-browser.cmd');
|
||||
const ps1Shim = join(npmBinDir, 'agent-browser.ps1');
|
||||
|
||||
// Only fix if shims exist (indicates global install)
|
||||
if (!existsSync(cmdShim)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Path to native binary relative to npm prefix
|
||||
const relativeBinaryPath = 'node_modules\\agent-browser\\bin\\agent-browser-win32-x64.exe';
|
||||
const packagePath = packageName.replace(/\//g, '\\');
|
||||
const relativeBinaryPath = `node_modules\\${packagePath}\\bin\\${binaryName}`;
|
||||
let optimized = false;
|
||||
|
||||
try {
|
||||
// Overwrite .cmd shim
|
||||
const cmdContent = `@ECHO off\r\n"%~dp0${relativeBinaryPath}" %*\r\n`;
|
||||
writeFileSync(cmdShim, cmdContent);
|
||||
for (const commandName of binCommands) {
|
||||
// The shims are in the npm prefix directory (not prefix/bin on Windows)
|
||||
const cmdShim = join(npmBinDir, `${commandName}.cmd`);
|
||||
const ps1Shim = join(npmBinDir, `${commandName}.ps1`);
|
||||
|
||||
// Overwrite .ps1 shim
|
||||
const ps1Content = `#!/usr/bin/env pwsh
|
||||
// Only fix if shims exist (indicates global install)
|
||||
if (!existsSync(cmdShim)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
// Overwrite .cmd shim
|
||||
const cmdContent = `@ECHO off\r\n"%~dp0${relativeBinaryPath}" %*\r\n`;
|
||||
writeFileSync(cmdShim, cmdContent);
|
||||
|
||||
// Overwrite .ps1 shim
|
||||
const ps1Content = `#!/usr/bin/env pwsh
|
||||
$basedir = Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
$exe = ""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
@@ -222,13 +258,17 @@ if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
& "$basedir/${relativeBinaryPath.replace(/\\/g, '/')}" $args
|
||||
exit $LASTEXITCODE
|
||||
`;
|
||||
writeFileSync(ps1Shim, ps1Content);
|
||||
writeFileSync(ps1Shim, ps1Content);
|
||||
optimized = true;
|
||||
} catch (err) {
|
||||
// Permission error or other issue - not critical, JS wrapper still works
|
||||
console.log(`⚠ Could not optimize shims (${commandName}): ${err.message}`);
|
||||
console.log(' CLI will work via Node.js wrapper (slightly slower startup)');
|
||||
}
|
||||
}
|
||||
|
||||
if (optimized) {
|
||||
console.log('✓ Optimized: shims point to native binary (zero overhead)');
|
||||
} catch (err) {
|
||||
// Permission error or other issue - not critical, JS wrapper still works
|
||||
console.log(`⚠ Could not optimize shims: ${err.message}`);
|
||||
console.log(' CLI will work via Node.js wrapper (slightly slower startup)');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Executable
+142
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
UPSTREAM_REMOTE="upstream"
|
||||
UPSTREAM_BRANCH="main"
|
||||
BASE_BRANCH="main"
|
||||
TRACK_BRANCH="upstream-main"
|
||||
SYNC_BRANCH=""
|
||||
PUSH_BRANCH=false
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Synchronize upstream changes into a dedicated sync branch.
|
||||
|
||||
Usage:
|
||||
./scripts/sync-upstream.sh [options]
|
||||
|
||||
Options:
|
||||
--push Push the created sync branch to origin
|
||||
--upstream-remote <name> Upstream remote name (default: upstream)
|
||||
--upstream-branch <name> Upstream branch to sync from (default: main)
|
||||
--base-branch <name> Local base branch for sync branch (default: main)
|
||||
--track-branch <name> Local branch tracking upstream (default: upstream-main)
|
||||
--sync-branch <name> Explicit sync branch name (default: sync/YYYY-MM-DD)
|
||||
-h, --help Show this help message
|
||||
EOF
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--push)
|
||||
PUSH_BRANCH=true
|
||||
shift
|
||||
;;
|
||||
--upstream-remote)
|
||||
UPSTREAM_REMOTE="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--upstream-branch)
|
||||
UPSTREAM_BRANCH="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--base-branch)
|
||||
BASE_BRANCH="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--track-branch)
|
||||
TRACK_BRANCH="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--sync-branch)
|
||||
SYNC_BRANCH="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1" >&2
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
for var_name in UPSTREAM_REMOTE UPSTREAM_BRANCH BASE_BRANCH TRACK_BRANCH; do
|
||||
if [[ -z "${!var_name}" ]]; then
|
||||
echo "Error: ${var_name} cannot be empty." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ -n "$(git status --porcelain)" ]]; then
|
||||
echo "Error: working tree is not clean. Commit or stash changes first." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! git remote get-url "$UPSTREAM_REMOTE" >/dev/null 2>&1; then
|
||||
echo "Error: remote '$UPSTREAM_REMOTE' does not exist." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Fetching upstream branch: ${UPSTREAM_REMOTE}/${UPSTREAM_BRANCH}"
|
||||
git fetch "$UPSTREAM_REMOTE" "$UPSTREAM_BRANCH"
|
||||
|
||||
if git show-ref --verify --quiet "refs/heads/$TRACK_BRANCH"; then
|
||||
echo "Updating local track branch: $TRACK_BRANCH"
|
||||
git switch "$TRACK_BRANCH" >/dev/null
|
||||
git merge --ff-only "${UPSTREAM_REMOTE}/${UPSTREAM_BRANCH}"
|
||||
else
|
||||
echo "Creating local track branch: $TRACK_BRANCH"
|
||||
git branch "$TRACK_BRANCH" "${UPSTREAM_REMOTE}/${UPSTREAM_BRANCH}"
|
||||
fi
|
||||
|
||||
echo "Switching to base branch: $BASE_BRANCH"
|
||||
git switch "$BASE_BRANCH" >/dev/null
|
||||
|
||||
if git show-ref --verify --quiet "refs/remotes/origin/$BASE_BRANCH"; then
|
||||
echo "Fast-forwarding ${BASE_BRANCH} from origin/${BASE_BRANCH}"
|
||||
git fetch origin "$BASE_BRANCH"
|
||||
git merge --ff-only "origin/${BASE_BRANCH}"
|
||||
fi
|
||||
|
||||
if [[ -z "$SYNC_BRANCH" ]]; then
|
||||
SYNC_BRANCH="sync/$(date +%F)"
|
||||
fi
|
||||
|
||||
if git show-ref --verify --quiet "refs/heads/$SYNC_BRANCH"; then
|
||||
suffix=1
|
||||
while git show-ref --verify --quiet "refs/heads/${SYNC_BRANCH}-${suffix}"; do
|
||||
suffix=$((suffix + 1))
|
||||
done
|
||||
SYNC_BRANCH="${SYNC_BRANCH}-${suffix}"
|
||||
fi
|
||||
|
||||
echo "Creating sync branch: $SYNC_BRANCH"
|
||||
git switch -c "$SYNC_BRANCH" "$BASE_BRANCH" >/dev/null
|
||||
|
||||
merge_message="chore(sync): merge ${UPSTREAM_REMOTE}/${UPSTREAM_BRANCH} into ${BASE_BRANCH}"
|
||||
echo "Merging $TRACK_BRANCH into $SYNC_BRANCH"
|
||||
if ! git merge --no-ff "$TRACK_BRANCH" -m "$merge_message"; then
|
||||
echo ""
|
||||
echo "Merge conflict detected. Resolve conflicts, then run:"
|
||||
echo " git add <resolved-files>"
|
||||
echo " git commit"
|
||||
if [[ "$PUSH_BRANCH" == true ]]; then
|
||||
echo " git push -u origin $SYNC_BRANCH"
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Upstream merge completed on branch: $SYNC_BRANCH"
|
||||
|
||||
if [[ "$PUSH_BRANCH" == true ]]; then
|
||||
echo "Pushing branch to origin: $SYNC_BRANCH"
|
||||
git push -u origin "$SYNC_BRANCH"
|
||||
echo "Done. Open a PR: ${SYNC_BRANCH} -> ${BASE_BRANCH}"
|
||||
else
|
||||
echo "Branch is local only. Push when ready:"
|
||||
echo " git push -u origin $SYNC_BRANCH"
|
||||
fi
|
||||
+21
-3
@@ -20,13 +20,31 @@ const packageJson = JSON.parse(
|
||||
);
|
||||
const version = packageJson.version;
|
||||
|
||||
console.log(`Syncing version ${version} to all config files...`);
|
||||
function parseForkVersion(raw) {
|
||||
const match = raw.match(/^([0-9]+\.[0-9]+\.[0-9]+)-fork\.([A-Za-z0-9.-]+)$/);
|
||||
if (!match) return null;
|
||||
return {
|
||||
upstream: match[1],
|
||||
fork: match[2],
|
||||
};
|
||||
}
|
||||
|
||||
const forkVersion = parseForkVersion(version);
|
||||
if (forkVersion) {
|
||||
console.log(
|
||||
`Syncing version ${version} (upstream=${forkVersion.upstream}, fork=${forkVersion.fork}) to all config files...`
|
||||
);
|
||||
} else {
|
||||
console.log(`Syncing version ${version} to all config files...`);
|
||||
}
|
||||
|
||||
// Update Cargo.toml
|
||||
const cargoTomlPath = join(cliDir, "Cargo.toml");
|
||||
let cargoToml = readFileSync(cargoTomlPath, "utf-8");
|
||||
const cargoVersionRegex = /^version\s*=\s*"[^"]*"/m;
|
||||
const newCargoVersion = `version = "${version}"`;
|
||||
const cargoNameMatch = cargoToml.match(/^name\s*=\s*"([^"]+)"/m);
|
||||
const cargoPackageName = cargoNameMatch?.[1] ?? "agent-browser-stealth";
|
||||
|
||||
let cargoTomlUpdated = false;
|
||||
if (cargoVersionRegex.test(cargoToml)) {
|
||||
@@ -47,7 +65,7 @@ if (cargoVersionRegex.test(cargoToml)) {
|
||||
// Update Cargo.lock to match Cargo.toml
|
||||
if (cargoTomlUpdated) {
|
||||
try {
|
||||
execSync("cargo update -p agent-browser --offline", {
|
||||
execSync(`cargo update -p ${cargoPackageName} --offline`, {
|
||||
cwd: cliDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
@@ -55,7 +73,7 @@ if (cargoTomlUpdated) {
|
||||
} catch {
|
||||
// --offline may fail if package not in cache, try without it
|
||||
try {
|
||||
execSync("cargo update -p agent-browser", {
|
||||
execSync(`cargo update -p ${cargoPackageName}`, {
|
||||
cwd: cliDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
---
|
||||
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:*)
|
||||
allowed-tools: Bash(npx agent-browser-stealth:*), Bash(npx agent-browser:*), Bash(agent-browser:*)
|
||||
---
|
||||
|
||||
# Browser Automation with agent-browser
|
||||
|
||||
Install package: `npm install -g agent-browser-stealth` (CLI command remains `agent-browser` for compatibility).
|
||||
|
||||
## Core Workflow
|
||||
|
||||
Every browser automation follows this pattern:
|
||||
@@ -50,6 +52,7 @@ agent-browser open https://example.com && agent-browser wait --load networkidle
|
||||
# Navigation
|
||||
agent-browser open <url> # Navigate (aliases: goto, navigate)
|
||||
agent-browser close # Close browser
|
||||
agent-browser --version # Show CLI version (fork builds include upstream/fork)
|
||||
|
||||
# Snapshot
|
||||
agent-browser snapshot -i # Interactive elements with refs (recommended)
|
||||
@@ -60,11 +63,11 @@ agent-browser snapshot -s "#selector" # Scope to CSS selector
|
||||
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 type @e2 "text" --delay 120 # Type without clearing (human-like pacing)
|
||||
agent-browser select @e1 "option" # Select dropdown option
|
||||
agent-browser check @e1 # Check checkbox
|
||||
agent-browser press Enter # Press key
|
||||
agent-browser keyboard type "text" # Type at current focus (no selector)
|
||||
agent-browser keyboard type "text" --delay 90 # Type at current focus (no selector)
|
||||
agent-browser keyboard inserttext "text" # Insert without key events
|
||||
agent-browser scroll down 500 # Scroll page
|
||||
|
||||
@@ -78,6 +81,7 @@ 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
|
||||
agent-browser wait 2000-5000 # Random wait between 2-5 seconds
|
||||
|
||||
# Capture
|
||||
agent-browser screenshot # Screenshot to temp dir
|
||||
@@ -175,6 +179,8 @@ agent-browser session list
|
||||
|
||||
### Connect to Existing Chrome
|
||||
|
||||
By default in this fork, commands without `--cdp` require an existing browser at `localhost:9333`. If CDP is unavailable, the command fails fast (no automatic local browser launch).
|
||||
|
||||
```bash
|
||||
# Auto-discover running Chrome with remote debugging enabled
|
||||
agent-browser --auto-connect open https://example.com
|
||||
@@ -216,6 +222,30 @@ agent-browser --allow-file-access open file:///path/to/page.html
|
||||
agent-browser screenshot output.png
|
||||
```
|
||||
|
||||
### Project Policy
|
||||
|
||||
- `--profile` / `AGENT_BROWSER_PROFILE` are forbidden
|
||||
- `--channel` / `AGENT_BROWSER_CHANNEL` are forbidden
|
||||
- Use existing browser sessions (default CDP `localhost:9333`) or pass `--cdp` explicitly
|
||||
|
||||
### Stealth Mode (Always On)
|
||||
|
||||
Stealth is always active -- no flags needed. All sessions automatically apply anti-detection patches (navigator.webdriver removal, UA override, plugin injection, WebGL masking, humanized interactions, etc.).
|
||||
|
||||
Chromium launches in managed mode use Chrome channel by default for a genuine browser binary fingerprint.
|
||||
|
||||
For best results against strong bot detection, use `--headed` and `--session-name`.
|
||||
|
||||
### Auto Region Detection
|
||||
|
||||
The browser automatically detects the target site's region from the URL TLD and sets matching locale, timezone, and Accept-Language headers. For example, navigating to `shopee.tw` sets locale `zh-TW` and timezone `Asia/Taipei`. This reduces server-side risk scoring from region-signal mismatches.
|
||||
|
||||
Override: `AGENT_BROWSER_LOCALE`, `AGENT_BROWSER_TIMEZONE` env vars.
|
||||
|
||||
### Captcha Detection & Auto-Retry
|
||||
|
||||
When a navigation lands on a captcha/verification page, the browser automatically retries up to 2 times with randomized backoff (3-7s). If detection persists, a warning is shown suggesting `--headed` mode or `--session-name` persistence.
|
||||
|
||||
### iOS Simulator (Mobile Safari)
|
||||
|
||||
```bash
|
||||
@@ -287,10 +317,23 @@ agent-browser wait --fn "document.readyState === 'complete'"
|
||||
|
||||
# Wait a fixed duration (milliseconds) as a last resort
|
||||
agent-browser wait 5000
|
||||
|
||||
# Random wait between 2-5 seconds (useful for anti-detection)
|
||||
agent-browser wait 2000-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`.
|
||||
|
||||
### Humanized Interactions
|
||||
|
||||
agent-browser automatically humanizes interactions to avoid behavioral detection:
|
||||
|
||||
- **Randomized typing**: `type --delay` varies each keystroke delay by +-40%
|
||||
- **Random wait ranges**: `wait 2000-5000` pauses for a random duration in that range
|
||||
- **Bezier curve mouse**: Before every `click`, the mouse moves along a natural-looking curve
|
||||
|
||||
These behaviors are always active. For sensitive sites, combine with `--headed` and `--session-name` for best results.
|
||||
|
||||
## Session Management and Cleanup
|
||||
|
||||
When running multiple agents or automations concurrently, always use named sessions to avoid conflicts:
|
||||
@@ -394,8 +437,7 @@ Create `agent-browser.json` in the project root for persistent settings:
|
||||
```json
|
||||
{
|
||||
"headed": true,
|
||||
"proxy": "http://localhost:8080",
|
||||
"profile": "./browser-data"
|
||||
"proxy": "http://localhost:8080"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+135
-9
@@ -517,7 +517,10 @@ async function handleLaunch(
|
||||
browser: BrowserManager
|
||||
): Promise<Response> {
|
||||
await browser.launch(command);
|
||||
return successResponse(command.id, { launched: true });
|
||||
return successResponse(command.id, {
|
||||
launched: true,
|
||||
stealth: browser.getStealthStatus(command.browser ?? 'chromium'),
|
||||
});
|
||||
}
|
||||
|
||||
async function handleNavigate(
|
||||
@@ -526,21 +529,113 @@ async function handleNavigate(
|
||||
): Promise<Response<NavigateData>> {
|
||||
const page = browser.getPage();
|
||||
|
||||
// Set target URL for region auto-detection (locale/timezone)
|
||||
await browser.setTargetUrl(command.url);
|
||||
|
||||
// If headers are provided, set up scoped headers for this origin
|
||||
if (command.headers && Object.keys(command.headers).length > 0) {
|
||||
await browser.setScopedHeaders(command.url, command.headers);
|
||||
}
|
||||
|
||||
// Humanized navigation pacing: random short delay before navigating
|
||||
const pace = 300 + Math.random() * 700;
|
||||
await page.waitForTimeout(Math.round(pace));
|
||||
|
||||
await page.goto(command.url, {
|
||||
waitUntil: command.waitUntil ?? 'load',
|
||||
});
|
||||
|
||||
// Detect captcha/verification pages and retry with backoff
|
||||
const finalUrl = page.url();
|
||||
const title = await page.title();
|
||||
const captchaDetected = isCaptchaPage(finalUrl, title);
|
||||
|
||||
if (captchaDetected) {
|
||||
const maxRetries = 2;
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
const backoff = 3000 + Math.random() * 4000;
|
||||
await page.waitForTimeout(Math.round(backoff));
|
||||
await page.goto(command.url, {
|
||||
waitUntil: command.waitUntil ?? 'load',
|
||||
});
|
||||
const retryUrl = page.url();
|
||||
const retryTitle = await page.title();
|
||||
if (!isCaptchaPage(retryUrl, retryTitle)) {
|
||||
return successResponse(command.id, {
|
||||
url: retryUrl,
|
||||
title: retryTitle,
|
||||
});
|
||||
}
|
||||
}
|
||||
// All retries exhausted -- return the page as-is with a warning
|
||||
return successResponse(command.id, {
|
||||
url: page.url(),
|
||||
title: await page.title(),
|
||||
warning:
|
||||
'Captcha/verification page detected. Try --headed mode or use --session-name for state persistence.',
|
||||
} as NavigateData);
|
||||
}
|
||||
|
||||
return successResponse(command.id, {
|
||||
url: page.url(),
|
||||
title: await page.title(),
|
||||
url: finalUrl,
|
||||
title,
|
||||
});
|
||||
}
|
||||
|
||||
function isCaptchaPage(url: string, title: string): boolean {
|
||||
const lowerUrl = url.toLowerCase();
|
||||
const lowerTitle = title.toLowerCase();
|
||||
const captchaPatterns = [
|
||||
'/verify/captcha',
|
||||
'/captcha',
|
||||
'/challenge',
|
||||
'scene=crawler',
|
||||
'scene=anti_bot',
|
||||
'recaptcha',
|
||||
'hcaptcha',
|
||||
];
|
||||
const titlePatterns = [
|
||||
'verify',
|
||||
'captcha',
|
||||
'challenge',
|
||||
'attention required',
|
||||
'just a moment',
|
||||
'checking your browser',
|
||||
'access denied',
|
||||
'驗證',
|
||||
'验证',
|
||||
'人机验证',
|
||||
];
|
||||
return (
|
||||
captchaPatterns.some((p) => lowerUrl.includes(p)) ||
|
||||
titlePatterns.some((p) => lowerTitle.includes(p))
|
||||
);
|
||||
}
|
||||
|
||||
function bezierPoint(t: number, p0: number, p1: number, p2: number, p3: number): number {
|
||||
const u = 1 - t;
|
||||
return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3;
|
||||
}
|
||||
|
||||
async function humanMouseMove(page: Page, toX: number, toY: number): Promise<void> {
|
||||
const viewport = page.viewportSize();
|
||||
const fromX = viewport ? Math.random() * viewport.width * 0.3 : 100;
|
||||
const fromY = viewport ? Math.random() * viewport.height * 0.3 : 100;
|
||||
|
||||
const cp1x = fromX + (toX - fromX) * (0.2 + Math.random() * 0.3);
|
||||
const cp1y = fromY + (Math.random() - 0.5) * 200;
|
||||
const cp2x = fromX + (toX - fromX) * (0.5 + Math.random() * 0.3);
|
||||
const cp2y = toY + (Math.random() - 0.5) * 200;
|
||||
|
||||
const steps = 15 + Math.floor(Math.random() * 15);
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const t = i / steps;
|
||||
const x = bezierPoint(t, fromX, cp1x, cp2x, toX);
|
||||
const y = bezierPoint(t, fromY, cp1y, cp2y, toY);
|
||||
await page.mouse.move(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleClick(command: ClickCommand, browser: BrowserManager): Promise<Response> {
|
||||
// Support both refs (@e1) and regular selectors
|
||||
const locator = browser.getLocator(command.selector);
|
||||
@@ -572,6 +667,14 @@ async function handleClick(command: ClickCommand, browser: BrowserManager): Prom
|
||||
});
|
||||
}
|
||||
|
||||
// Human-like: move mouse along a Bezier curve before clicking
|
||||
const box = await locator.boundingBox();
|
||||
if (box) {
|
||||
const targetX = box.x + box.width * (0.3 + Math.random() * 0.4);
|
||||
const targetY = box.y + box.height * (0.3 + Math.random() * 0.4);
|
||||
await humanMouseMove(browser.getPage(), targetX, targetY);
|
||||
}
|
||||
|
||||
await locator.click({
|
||||
button: command.button,
|
||||
clickCount: command.clickCount,
|
||||
@@ -592,9 +695,18 @@ async function handleType(command: TypeCommand, browser: BrowserManager): Promis
|
||||
await locator.fill('');
|
||||
}
|
||||
|
||||
await locator.pressSequentially(command.text, {
|
||||
delay: command.delay,
|
||||
});
|
||||
if (command.delay) {
|
||||
// Humanized: type char-by-char with randomized delay (+-40%)
|
||||
await locator.focus();
|
||||
const page = browser.getPage();
|
||||
for (const char of command.text) {
|
||||
const jitter = command.delay * (0.6 + Math.random() * 0.8);
|
||||
await page.keyboard.type(char, { delay: 0 });
|
||||
await page.waitForTimeout(jitter);
|
||||
}
|
||||
} else {
|
||||
await locator.pressSequentially(command.text, {});
|
||||
}
|
||||
} catch (error) {
|
||||
throw toAIFriendlyError(error, command.selector);
|
||||
}
|
||||
@@ -870,7 +982,11 @@ async function handleWait(command: WaitCommand, browser: BrowserManager): Promis
|
||||
timeout: command.timeout,
|
||||
});
|
||||
} else if (command.timeout) {
|
||||
await page.waitForTimeout(command.timeout);
|
||||
// Random range: wait between [timeout, timeoutMax]
|
||||
const min = command.timeout;
|
||||
const max = command.timeoutMax ?? min;
|
||||
const delay = max > min ? min + Math.random() * (max - min) : min;
|
||||
await page.waitForTimeout(Math.round(delay));
|
||||
} else {
|
||||
// Default: wait for load state
|
||||
await page.waitForLoadState('load');
|
||||
@@ -1897,9 +2013,19 @@ async function handleKeyboard(
|
||||
const sub = command.subaction ?? 'press';
|
||||
|
||||
switch (sub) {
|
||||
case 'type':
|
||||
await page.keyboard.type(command.text ?? '', { delay: command.delay });
|
||||
case 'type': {
|
||||
const text = command.text ?? '';
|
||||
if (command.delay) {
|
||||
for (const char of text) {
|
||||
const jitter = command.delay * (0.6 + Math.random() * 0.8);
|
||||
await page.keyboard.type(char, { delay: 0 });
|
||||
await page.waitForTimeout(jitter);
|
||||
}
|
||||
} else {
|
||||
await page.keyboard.type(text);
|
||||
}
|
||||
return successResponse(command.id, { typed: true, text: command.text });
|
||||
}
|
||||
case 'press':
|
||||
await page.keyboard.press(command.keys ?? '');
|
||||
return successResponse(command.id, { pressed: command.keys });
|
||||
|
||||
+136
-4
@@ -53,6 +53,78 @@ describe('BrowserManager', () => {
|
||||
expect(newBrowser.getBrowser()).toBeNull();
|
||||
await newBrowser.close();
|
||||
});
|
||||
|
||||
it('should report local stealth policy capabilities', async () => {
|
||||
const testBrowser = new BrowserManager();
|
||||
await testBrowser.launch({ headless: true, stealth: true });
|
||||
|
||||
const status = testBrowser.getStealthStatus('chromium');
|
||||
expect(status.enabled).toBe(true);
|
||||
expect(status.connectionKind).toBe('local');
|
||||
expect(status.capabilities).toContain('chromium-launch-args');
|
||||
expect(status.capabilities).toContain('context-init-scripts');
|
||||
|
||||
await testBrowser.close();
|
||||
});
|
||||
|
||||
it('should apply init-script stealth policy for CDP connections', async () => {
|
||||
const addInitScript = vi.fn().mockResolvedValue(undefined);
|
||||
const mockPage = { url: () => 'http://example.com', on: vi.fn(), isClosed: () => false };
|
||||
const mockContext = {
|
||||
pages: () => [mockPage],
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript,
|
||||
};
|
||||
const mockBrowser = {
|
||||
contexts: () => [mockContext],
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
isConnected: vi.fn(() => true),
|
||||
};
|
||||
const spy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
const cdpBrowser = new BrowserManager();
|
||||
await cdpBrowser.launch({ cdpPort: 9222, stealth: true });
|
||||
|
||||
expect(addInitScript).toHaveBeenCalledTimes(1);
|
||||
const status = cdpBrowser.getStealthStatus();
|
||||
expect(status.enabled).toBe(true);
|
||||
expect(status.connectionKind).toBe('cdp');
|
||||
expect(status.capabilities).toContain('context-init-scripts');
|
||||
expect(status.capabilities).not.toContain('chromium-launch-args');
|
||||
|
||||
await cdpBrowser.close();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should disable stealth capabilities when launch stealth is false in CDP mode', async () => {
|
||||
const addInitScript = vi.fn().mockResolvedValue(undefined);
|
||||
const mockPage = { url: () => 'http://example.com', on: vi.fn(), isClosed: () => false };
|
||||
const mockContext = {
|
||||
pages: () => [mockPage],
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript,
|
||||
};
|
||||
const mockBrowser = {
|
||||
contexts: () => [mockContext],
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
isConnected: vi.fn(() => true),
|
||||
};
|
||||
const spy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
const cdpBrowser = new BrowserManager();
|
||||
await cdpBrowser.launch({ cdpPort: 9222, stealth: false });
|
||||
|
||||
expect(addInitScript).not.toHaveBeenCalled();
|
||||
const status = cdpBrowser.getStealthStatus();
|
||||
expect(status.enabled).toBe(false);
|
||||
expect(status.connectionKind).toBe('cdp');
|
||||
expect(status.capabilities).toEqual([]);
|
||||
|
||||
await cdpBrowser.close();
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('stale session recovery (all pages closed)', () => {
|
||||
@@ -854,15 +926,16 @@ describe('BrowserManager', () => {
|
||||
contexts: () => [
|
||||
{
|
||||
pages: () => [
|
||||
{ url: () => 'http://example.com', on: vi.fn() },
|
||||
{ url: () => '', on: vi.fn() }, // This page should be filtered out
|
||||
{ url: () => 'http://anothersite.com', on: vi.fn() },
|
||||
{ url: () => 'http://example.com', on: vi.fn(), isClosed: () => false },
|
||||
{ url: () => '', on: vi.fn(), isClosed: () => false }, // This page should be filtered out
|
||||
{ url: () => 'http://anothersite.com', on: vi.fn(), isClosed: () => false },
|
||||
],
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
],
|
||||
close: vi.fn(),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const spy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
@@ -878,6 +951,65 @@ describe('BrowserManager', () => {
|
||||
expect(urls).toContain('http://example.com');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should ignore omnibox popup pages during CDP connection', async () => {
|
||||
const mockBrowser = {
|
||||
contexts: () => [
|
||||
{
|
||||
pages: () => [
|
||||
{
|
||||
url: () => 'chrome://omnibox-popup.top-chrome/',
|
||||
on: vi.fn(),
|
||||
isClosed: () => false,
|
||||
},
|
||||
{ url: () => 'http://example.com', on: vi.fn(), isClosed: () => false },
|
||||
],
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
],
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const spy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
const cdpBrowser = new BrowserManager();
|
||||
await cdpBrowser.launch({ cdpPort: 9222 });
|
||||
|
||||
expect(cdpBrowser.getPages().length).toBe(1);
|
||||
expect(cdpBrowser.getPages()[0]?.url()).toBe('http://example.com');
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should create a fallback page when CDP has only internal pages', async () => {
|
||||
const newPage = { url: () => 'about:blank', on: vi.fn(), isClosed: () => false };
|
||||
const context = {
|
||||
pages: () => [
|
||||
{
|
||||
url: () => 'chrome://omnibox-popup.top-chrome/omnibox_popup_aim.html',
|
||||
on: vi.fn(),
|
||||
isClosed: () => false,
|
||||
},
|
||||
],
|
||||
newPage: vi.fn().mockResolvedValue(newPage),
|
||||
on: vi.fn(),
|
||||
setDefaultTimeout: vi.fn(),
|
||||
addInitScript: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const mockBrowser = {
|
||||
contexts: () => [context],
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const spy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
|
||||
|
||||
const cdpBrowser = new BrowserManager();
|
||||
await cdpBrowser.launch({ cdpPort: 9222 });
|
||||
|
||||
expect(context.newPage).toHaveBeenCalledTimes(1);
|
||||
expect(cdpBrowser.getPages().length).toBe(1);
|
||||
expect(cdpBrowser.getPages()[0]?.url()).toBe('about:blank');
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('screencast', () => {
|
||||
|
||||
+510
-46
@@ -27,6 +27,12 @@ import {
|
||||
decryptData,
|
||||
ENCRYPTION_KEY_ENV,
|
||||
} from './state-utils.js';
|
||||
import {
|
||||
STEALTH_CHROMIUM_ARGS,
|
||||
applyStealthScripts,
|
||||
applyBrowserLevelStealth,
|
||||
type StealthScriptOptions,
|
||||
} from './stealth.js';
|
||||
|
||||
/**
|
||||
* Returns the default Playwright timeout in milliseconds for standard operations.
|
||||
@@ -89,6 +95,38 @@ interface PageError {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
type BrowserType = NonNullable<LaunchCommand['browser']>;
|
||||
type StealthConnectionKind =
|
||||
| 'local'
|
||||
| 'cdp'
|
||||
| 'provider-browserbase'
|
||||
| 'provider-browseruse'
|
||||
| 'provider-kernel';
|
||||
|
||||
interface StealthPolicy {
|
||||
enabled: boolean;
|
||||
connectionKind: StealthConnectionKind;
|
||||
applyChromiumArgs: boolean;
|
||||
applyInitScripts: boolean;
|
||||
providerManaged: boolean;
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
export interface StealthStatus {
|
||||
enabled: boolean;
|
||||
connectionKind: StealthConnectionKind;
|
||||
capabilities: string[];
|
||||
providerManaged: boolean;
|
||||
}
|
||||
|
||||
interface StealthContextDefaults {
|
||||
locale?: string;
|
||||
timezoneId?: string;
|
||||
extraHTTPHeaders?: Record<string, string>;
|
||||
}
|
||||
|
||||
const IGNORED_CDP_PAGE_URL_PREFIXES = ['chrome://omnibox-popup.top-chrome/'];
|
||||
|
||||
/**
|
||||
* Manages the Playwright browser lifecycle with multiple tabs/windows
|
||||
*/
|
||||
@@ -116,6 +154,12 @@ export class BrowserManager {
|
||||
private lastSnapshot: string = '';
|
||||
private scopedHeaderRoutes: Map<string, (route: Route) => Promise<void>> = new Map();
|
||||
private colorScheme: 'light' | 'dark' | 'no-preference' | null = null;
|
||||
private stealthEnabled: boolean = true;
|
||||
private stealthConnectionKind: StealthConnectionKind = 'local';
|
||||
private contextLocale: string | undefined = undefined;
|
||||
private contextTimezoneId: string | undefined = undefined;
|
||||
private contextHeaders: Record<string, string> | undefined = undefined;
|
||||
private contextUserAgent: string | undefined = undefined;
|
||||
|
||||
/**
|
||||
* Set the persistent color scheme preference.
|
||||
@@ -125,6 +169,286 @@ export class BrowserManager {
|
||||
this.colorScheme = scheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Centralized stealth policy so launch mode semantics stay consistent.
|
||||
* Local Chromium gets args + init scripts; CDP/providers get init scripts only.
|
||||
*/
|
||||
private getStealthPolicy(browserType: BrowserType = 'chromium'): StealthPolicy {
|
||||
const applyChromiumArgs = this.stealthConnectionKind === 'local' && browserType === 'chromium';
|
||||
const applyInitScripts = true;
|
||||
const providerManaged = this.stealthConnectionKind === 'provider-kernel';
|
||||
const capabilities: string[] = [];
|
||||
|
||||
if (applyChromiumArgs) {
|
||||
capabilities.push('chromium-launch-args');
|
||||
}
|
||||
if (applyInitScripts) {
|
||||
capabilities.push('context-init-scripts');
|
||||
}
|
||||
if (providerManaged) {
|
||||
capabilities.push('provider-managed-stealth');
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
connectionKind: this.stealthConnectionKind,
|
||||
applyChromiumArgs,
|
||||
applyInitScripts,
|
||||
providerManaged,
|
||||
capabilities,
|
||||
};
|
||||
}
|
||||
|
||||
private logStealthPolicy(phase: string, browserType: BrowserType = 'chromium'): void {
|
||||
if (process.env.AGENT_BROWSER_DEBUG !== '1') return;
|
||||
const policy = this.getStealthPolicy(browserType);
|
||||
const capabilities = policy.capabilities.length > 0 ? policy.capabilities.join(', ') : 'none';
|
||||
console.error(
|
||||
`[DEBUG] Stealth ${phase}: enabled=${policy.enabled} connection=${policy.connectionKind} capabilities=${capabilities}`
|
||||
);
|
||||
}
|
||||
|
||||
getStealthStatus(browserType: BrowserType = 'chromium'): StealthStatus {
|
||||
const policy = this.getStealthPolicy(browserType);
|
||||
return {
|
||||
enabled: policy.enabled,
|
||||
connectionKind: policy.connectionKind,
|
||||
capabilities: policy.capabilities,
|
||||
providerManaged: policy.providerManaged,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeLocaleTag(locale?: string): string | undefined {
|
||||
if (!locale) return undefined;
|
||||
const cleaned = locale.trim().split(',')[0]?.split(';')[0]?.replace(/_/g, '-');
|
||||
if (!cleaned) return undefined;
|
||||
try {
|
||||
return new Intl.Locale(cleaned).toString();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private buildAcceptLanguageHeader(locale: string): string {
|
||||
const baseLanguage = locale.split('-')[0];
|
||||
if (!baseLanguage || baseLanguage === locale) {
|
||||
return `${locale};q=0.9`;
|
||||
}
|
||||
return `${locale},${baseLanguage};q=0.9`;
|
||||
}
|
||||
|
||||
private getHeaderValue(
|
||||
headers: Record<string, string> | undefined,
|
||||
name: string
|
||||
): string | undefined {
|
||||
if (!headers) return undefined;
|
||||
const target = name.toLowerCase();
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (key.toLowerCase() === target) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// TLD -> {locale, timezone} mapping for automatic region consistency
|
||||
private static readonly TLD_REGION_MAP: Record<string, { locale: string; timezone: string }> = {
|
||||
tw: { locale: 'zh-TW', timezone: 'Asia/Taipei' },
|
||||
cn: { locale: 'zh-CN', timezone: 'Asia/Shanghai' },
|
||||
hk: { locale: 'zh-HK', timezone: 'Asia/Hong_Kong' },
|
||||
jp: { locale: 'ja-JP', timezone: 'Asia/Tokyo' },
|
||||
kr: { locale: 'ko-KR', timezone: 'Asia/Seoul' },
|
||||
th: { locale: 'th-TH', timezone: 'Asia/Bangkok' },
|
||||
vn: { locale: 'vi-VN', timezone: 'Asia/Ho_Chi_Minh' },
|
||||
sg: { locale: 'en-SG', timezone: 'Asia/Singapore' },
|
||||
my: { locale: 'ms-MY', timezone: 'Asia/Kuala_Lumpur' },
|
||||
id: { locale: 'id-ID', timezone: 'Asia/Jakarta' },
|
||||
ph: { locale: 'en-PH', timezone: 'Asia/Manila' },
|
||||
br: { locale: 'pt-BR', timezone: 'America/Sao_Paulo' },
|
||||
mx: { locale: 'es-MX', timezone: 'America/Mexico_City' },
|
||||
ar: { locale: 'es-AR', timezone: 'America/Argentina/Buenos_Aires' },
|
||||
de: { locale: 'de-DE', timezone: 'Europe/Berlin' },
|
||||
fr: { locale: 'fr-FR', timezone: 'Europe/Paris' },
|
||||
uk: { locale: 'en-GB', timezone: 'Europe/London' },
|
||||
ru: { locale: 'ru-RU', timezone: 'Europe/Moscow' },
|
||||
in: { locale: 'hi-IN', timezone: 'Asia/Kolkata' },
|
||||
au: { locale: 'en-AU', timezone: 'Australia/Sydney' },
|
||||
};
|
||||
|
||||
// Target URL set during navigation, used for region auto-detection
|
||||
private targetUrl: string | undefined = undefined;
|
||||
|
||||
/**
|
||||
* Set the target URL for region auto-detection.
|
||||
* Called from navigate/open commands so locale/timezone can adapt.
|
||||
* Applies CDP overrides to align locale/timezone with the target site's region.
|
||||
*/
|
||||
async setTargetUrl(url: string): Promise<void> {
|
||||
this.targetUrl = url;
|
||||
const region = this.getRegionFromUrl(url);
|
||||
if (!region) return;
|
||||
|
||||
// Skip if user has explicitly set locale/timezone via env
|
||||
const envLocale = process.env.AGENT_BROWSER_LOCALE;
|
||||
const envTimezone = process.env.AGENT_BROWSER_TIMEZONE || process.env.TZ;
|
||||
|
||||
try {
|
||||
const page = this.getPage();
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
|
||||
if (!envTimezone) {
|
||||
await cdp
|
||||
.send('Emulation.setTimezoneOverride', { timezoneId: region.timezone })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
if (!envLocale) {
|
||||
await cdp.send('Emulation.setLocaleOverride', { locale: region.locale }).catch(() => {});
|
||||
// Update Accept-Language header to match
|
||||
const langHeader = this.buildAcceptLanguageHeader(region.locale);
|
||||
const context = page.context();
|
||||
const currentHeaders = this.contextHeaders ?? {};
|
||||
await context.setExtraHTTPHeaders({ ...currentHeaders, 'Accept-Language': langHeader });
|
||||
}
|
||||
|
||||
await cdp.detach().catch(() => {});
|
||||
} catch {
|
||||
// CDP not available (non-Chromium), skip dynamic override
|
||||
}
|
||||
}
|
||||
|
||||
private getRegionFromUrl(url?: string): { locale: string; timezone: string } | undefined {
|
||||
if (!url) return undefined;
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
const parts = hostname.split('.');
|
||||
const tld = parts[parts.length - 1];
|
||||
// Check compound TLDs like co.th, com.tw, co.id
|
||||
const secondLevel = parts.length >= 2 ? parts[parts.length - 2] : '';
|
||||
const compoundTld = `${secondLevel}.${tld}`;
|
||||
|
||||
// Try compound first (e.g., "co.th" -> "th", "com.tw" -> "tw")
|
||||
const compoundMatch = BrowserManager.TLD_REGION_MAP[tld];
|
||||
if (
|
||||
compoundMatch &&
|
||||
(secondLevel === 'co' ||
|
||||
secondLevel === 'com' ||
|
||||
secondLevel === 'or' ||
|
||||
secondLevel === 'org')
|
||||
) {
|
||||
return compoundMatch;
|
||||
}
|
||||
// Then direct TLD
|
||||
if (BrowserManager.TLD_REGION_MAP[tld]) {
|
||||
return BrowserManager.TLD_REGION_MAP[tld];
|
||||
}
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveStealthLocale(headers?: Record<string, string>): string {
|
||||
const headerLocale = this.getHeaderValue(headers, 'accept-language');
|
||||
const normalizedHeaderLocale = this.normalizeLocaleTag(headerLocale);
|
||||
if (normalizedHeaderLocale) return normalizedHeaderLocale;
|
||||
|
||||
// Explicit env var takes priority
|
||||
const envLocale = this.normalizeLocaleTag(process.env.AGENT_BROWSER_LOCALE);
|
||||
if (envLocale) return envLocale;
|
||||
|
||||
// Auto-detect from target URL TLD
|
||||
const urlRegion = this.getRegionFromUrl(this.targetUrl);
|
||||
if (urlRegion) return urlRegion.locale;
|
||||
|
||||
const candidates = [
|
||||
process.env.LC_ALL,
|
||||
process.env.LC_MESSAGES,
|
||||
process.env.LANG,
|
||||
Intl.DateTimeFormat().resolvedOptions().locale,
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const normalized = this.normalizeLocaleTag(candidate);
|
||||
if (normalized) return normalized;
|
||||
}
|
||||
return 'en-US';
|
||||
}
|
||||
|
||||
private resolveStealthTimezoneId(): string | undefined {
|
||||
// Explicit env var takes priority
|
||||
const envTz = process.env.AGENT_BROWSER_TIMEZONE?.trim() || process.env.TZ?.trim();
|
||||
if (envTz && (envTz === 'UTC' || envTz.includes('/'))) return envTz;
|
||||
|
||||
// Auto-detect from target URL TLD
|
||||
const urlRegion = this.getRegionFromUrl(this.targetUrl);
|
||||
if (urlRegion) return urlRegion.timezone;
|
||||
|
||||
const systemTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
if (systemTz) return systemTz;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private buildStealthContextDefaults(
|
||||
policy: StealthPolicy,
|
||||
headers?: Record<string, string>
|
||||
): StealthContextDefaults {
|
||||
if (!policy.enabled) {
|
||||
return { extraHTTPHeaders: headers };
|
||||
}
|
||||
|
||||
const locale = this.resolveStealthLocale(headers);
|
||||
const timezoneId = this.resolveStealthTimezoneId();
|
||||
const hasAcceptLanguage = this.getHeaderValue(headers, 'accept-language') !== undefined;
|
||||
const extraHTTPHeaders = hasAcceptLanguage
|
||||
? headers
|
||||
: {
|
||||
...(headers ?? {}),
|
||||
'Accept-Language': this.buildAcceptLanguageHeader(locale),
|
||||
};
|
||||
|
||||
return {
|
||||
locale,
|
||||
timezoneId,
|
||||
extraHTTPHeaders,
|
||||
};
|
||||
}
|
||||
|
||||
private extractChromiumVersion(versionText: string): string | undefined {
|
||||
const match = versionText.match(/(\d+\.\d+\.\d+\.\d+)/);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
private buildStealthChromiumUserAgent(chromeVersion: string): string {
|
||||
const platform = os.platform();
|
||||
let osToken = 'X11; Linux x86_64';
|
||||
if (platform === 'darwin') {
|
||||
osToken = 'Macintosh; Intel Mac OS X 10_15_7';
|
||||
} else if (platform === 'win32') {
|
||||
osToken = 'Windows NT 10.0; Win64; x64';
|
||||
}
|
||||
return (
|
||||
`Mozilla/5.0 (${osToken}) AppleWebKit/537.36 ` +
|
||||
`(KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`
|
||||
);
|
||||
}
|
||||
|
||||
private getStealthUserAgentVersionHint(): string | undefined {
|
||||
const deviceUA = devices['Desktop Chrome']?.userAgent;
|
||||
if (!deviceUA) return undefined;
|
||||
return this.extractChromiumVersion(deviceUA);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply context init-script stealth patches when policy allows.
|
||||
*/
|
||||
private async applyStealthIfEnabled(
|
||||
context: BrowserContext,
|
||||
options: StealthScriptOptions = {}
|
||||
): Promise<void> {
|
||||
const policy = this.getStealthPolicy();
|
||||
if (!policy.applyInitScripts) return;
|
||||
await applyStealthScripts(context, options);
|
||||
this.logStealthPolicy('init-script applied');
|
||||
}
|
||||
|
||||
// CDP session for screencast and input injection
|
||||
private cdpSession: CDPSession | null = null;
|
||||
private screencastActive: boolean = false;
|
||||
@@ -265,6 +589,33 @@ export class BrowserManager {
|
||||
return this.pages.length > 0;
|
||||
}
|
||||
|
||||
private getSafePageUrl(page: Page): string {
|
||||
try {
|
||||
return page.url();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
private isIgnoredCDPPageUrl(url: string): boolean {
|
||||
if (!url) return false;
|
||||
const normalizedUrl = url.toLowerCase();
|
||||
return IGNORED_CDP_PAGE_URL_PREFIXES.some((prefix) => normalizedUrl.startsWith(prefix));
|
||||
}
|
||||
|
||||
private isUsableCDPPage(page: Page): boolean {
|
||||
if (page.isClosed()) return false;
|
||||
const url = this.getSafePageUrl(page);
|
||||
if (!url) return false;
|
||||
return !this.isIgnoredCDPPageUrl(url);
|
||||
}
|
||||
|
||||
private collectUsableCDPPages(contexts: BrowserContext[]): Page[] {
|
||||
return contexts
|
||||
.flatMap((context) => context.pages())
|
||||
.filter((page) => this.isUsableCDPPage(page));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure at least one page exists. If the browser is launched but all pages
|
||||
* were closed (stale session), creates a new page on the existing context.
|
||||
@@ -280,8 +631,13 @@ export class BrowserManager {
|
||||
context = this.contexts[this.contexts.length - 1];
|
||||
} else if (this.browser) {
|
||||
context = await this.browser.newContext({
|
||||
...(this.contextHeaders && { extraHTTPHeaders: this.contextHeaders }),
|
||||
...(this.contextUserAgent && { userAgent: this.contextUserAgent }),
|
||||
...(this.contextLocale && { locale: this.contextLocale }),
|
||||
...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
|
||||
...(this.colorScheme && { colorScheme: this.colorScheme }),
|
||||
});
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
@@ -304,6 +660,24 @@ export class BrowserManager {
|
||||
if (this.pages.length === 0) {
|
||||
throw new Error('Browser not launched. Call launch first.');
|
||||
}
|
||||
|
||||
const current = this.pages[this.activePageIndex];
|
||||
if (current && this.isUsableCDPPage(current)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
const usableIndex = this.pages.findIndex((page) => this.isUsableCDPPage(page));
|
||||
if (usableIndex !== -1) {
|
||||
this.activePageIndex = usableIndex;
|
||||
return this.pages[this.activePageIndex];
|
||||
}
|
||||
|
||||
const openIndex = this.pages.findIndex((page) => !page.isClosed());
|
||||
if (openIndex !== -1) {
|
||||
this.activePageIndex = openIndex;
|
||||
return this.pages[this.activePageIndex];
|
||||
}
|
||||
|
||||
return this.pages[this.activePageIndex];
|
||||
}
|
||||
|
||||
@@ -785,7 +1159,7 @@ export class BrowserManager {
|
||||
try {
|
||||
const contexts = this.browser.contexts();
|
||||
if (contexts.length === 0) return false;
|
||||
return contexts.some((context) => context.pages().length > 0);
|
||||
return contexts.some((context) => context.pages().some((page) => this.isUsableCDPPage(page)));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -852,6 +1226,7 @@ export class BrowserManager {
|
||||
* Requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID environment variables.
|
||||
*/
|
||||
private async connectToBrowserbase(): Promise<void> {
|
||||
this.stealthConnectionKind = 'provider-browserbase';
|
||||
const browserbaseApiKey = process.env.BROWSERBASE_API_KEY;
|
||||
const browserbaseProjectId = process.env.BROWSERBASE_PROJECT_ID;
|
||||
|
||||
@@ -889,6 +1264,7 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
const context = contexts[0];
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
const pages = context.pages();
|
||||
const page = pages[0] ?? (await context.newPage());
|
||||
|
||||
@@ -959,6 +1335,7 @@ export class BrowserManager {
|
||||
* Requires KERNEL_API_KEY environment variable.
|
||||
*/
|
||||
private async connectToKernel(): Promise<void> {
|
||||
this.stealthConnectionKind = 'provider-kernel';
|
||||
const kernelApiKey = process.env.KERNEL_API_KEY;
|
||||
if (!kernelApiKey) {
|
||||
throw new Error('KERNEL_API_KEY is required when using kernel as a provider');
|
||||
@@ -1026,9 +1403,11 @@ export class BrowserManager {
|
||||
// Kernel browsers launch with a default context and page
|
||||
if (contexts.length === 0) {
|
||||
context = await browser.newContext();
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
page = await context.newPage();
|
||||
} else {
|
||||
context = contexts[0];
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
const pages = context.pages();
|
||||
page = pages[0] ?? (await context.newPage());
|
||||
}
|
||||
@@ -1055,6 +1434,7 @@ export class BrowserManager {
|
||||
* Requires BROWSER_USE_API_KEY environment variable.
|
||||
*/
|
||||
private async connectToBrowserUse(): Promise<void> {
|
||||
this.stealthConnectionKind = 'provider-browseruse';
|
||||
const browserUseApiKey = process.env.BROWSER_USE_API_KEY;
|
||||
if (!browserUseApiKey) {
|
||||
throw new Error('BROWSER_USE_API_KEY is required when using browseruse as a provider');
|
||||
@@ -1099,9 +1479,11 @@ export class BrowserManager {
|
||||
|
||||
if (contexts.length === 0) {
|
||||
context = await browser.newContext();
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
page = await context.newPage();
|
||||
} else {
|
||||
context = contexts[0];
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
const pages = context.pages();
|
||||
page = pages[0] ?? (await context.newPage());
|
||||
}
|
||||
@@ -1131,23 +1513,12 @@ export class BrowserManager {
|
||||
// Determine CDP endpoint: prefer cdpUrl over cdpPort for flexibility
|
||||
const cdpEndpoint = options.cdpUrl ?? (options.cdpPort ? String(options.cdpPort) : undefined);
|
||||
const hasExtensions = !!options.extensions?.length;
|
||||
const hasProfile = !!options.profile;
|
||||
const hasStorageState = !!options.storageState;
|
||||
|
||||
if (hasExtensions && cdpEndpoint) {
|
||||
throw new Error('Extensions cannot be used with CDP connection');
|
||||
}
|
||||
|
||||
if (hasProfile && cdpEndpoint) {
|
||||
throw new Error('Profile cannot be used with CDP connection');
|
||||
}
|
||||
|
||||
if (hasStorageState && hasProfile) {
|
||||
throw new Error(
|
||||
'Storage state cannot be used with profile (profile is already persistent storage)'
|
||||
);
|
||||
}
|
||||
|
||||
if (hasStorageState && hasExtensions) {
|
||||
throw new Error(
|
||||
'Storage state cannot be used with extensions (extensions require persistent context)'
|
||||
@@ -1172,6 +1543,26 @@ export class BrowserManager {
|
||||
if (options.colorScheme) {
|
||||
this.colorScheme = options.colorScheme;
|
||||
}
|
||||
this.stealthEnabled = true;
|
||||
this.contextLocale = this.resolveStealthLocale(options.headers);
|
||||
this.contextTimezoneId = this.resolveStealthTimezoneId();
|
||||
this.contextHeaders = undefined;
|
||||
this.contextUserAgent = options.userAgent;
|
||||
// -p flag takes precedence over AGENT_BROWSER_PROVIDER.
|
||||
const provider = options.provider ?? process.env.AGENT_BROWSER_PROVIDER;
|
||||
|
||||
if (cdpEndpoint || options.autoConnect) {
|
||||
this.stealthConnectionKind = 'cdp';
|
||||
} else if (provider === 'browserbase') {
|
||||
this.stealthConnectionKind = 'provider-browserbase';
|
||||
} else if (provider === 'browseruse') {
|
||||
this.stealthConnectionKind = 'provider-browseruse';
|
||||
} else if (provider === 'kernel') {
|
||||
this.stealthConnectionKind = 'provider-kernel';
|
||||
} else {
|
||||
this.stealthConnectionKind = 'local';
|
||||
}
|
||||
this.logStealthPolicy('launch policy', options.browser ?? 'chromium');
|
||||
|
||||
if (cdpEndpoint) {
|
||||
await this.connectViaCDP(cdpEndpoint);
|
||||
@@ -1184,8 +1575,6 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
// Cloud browser providers require explicit opt-in via -p flag or AGENT_BROWSER_PROVIDER env var
|
||||
// -p flag takes precedence over env var
|
||||
const provider = options.provider ?? process.env.AGENT_BROWSER_PROVIDER;
|
||||
if (provider === 'browserbase') {
|
||||
await this.connectToBrowserbase();
|
||||
return;
|
||||
@@ -1214,16 +1603,45 @@ export class BrowserManager {
|
||||
const launcher =
|
||||
browserType === 'firefox' ? firefox : browserType === 'webkit' ? webkit : chromium;
|
||||
|
||||
// Build base args array with file access flags if enabled
|
||||
// --allow-file-access-from-files: allows file:// URLs to read other file:// URLs via XHR/fetch
|
||||
// --allow-file-access: allows the browser to access local files in general
|
||||
// Chromium launches always use the Chrome channel unless a custom executable is provided.
|
||||
const chromeChannel =
|
||||
browserType === 'chromium' && !options.executablePath ? 'chrome' : undefined;
|
||||
|
||||
const stealthPolicy = this.getStealthPolicy(browserType);
|
||||
const contextDefaults = this.buildStealthContextDefaults(stealthPolicy, options.headers);
|
||||
const extraHTTPHeaders = contextDefaults.extraHTTPHeaders;
|
||||
this.contextLocale = contextDefaults.locale;
|
||||
this.contextTimezoneId = contextDefaults.timezoneId;
|
||||
this.contextHeaders = contextDefaults.extraHTTPHeaders;
|
||||
|
||||
let contextUserAgent = options.userAgent;
|
||||
if (!contextUserAgent && stealthPolicy.enabled && browserType === 'chromium') {
|
||||
const versionHint = this.getStealthUserAgentVersionHint();
|
||||
if (versionHint) {
|
||||
contextUserAgent = this.buildStealthChromiumUserAgent(versionHint);
|
||||
}
|
||||
}
|
||||
this.contextUserAgent = contextUserAgent;
|
||||
|
||||
// Build base args array with file access flags and stealth args when policy allows.
|
||||
const fileAccessArgs = options.allowFileAccess
|
||||
? ['--allow-file-access-from-files', '--allow-file-access']
|
||||
: [];
|
||||
const stealthArgs = stealthPolicy.applyChromiumArgs ? STEALTH_CHROMIUM_ARGS : [];
|
||||
const hasUserAgentArg = options.args?.some((arg) => arg.startsWith('--user-agent='));
|
||||
const launchUserAgentArgs =
|
||||
!hasUserAgentArg &&
|
||||
!options.userAgent &&
|
||||
stealthPolicy.enabled &&
|
||||
browserType === 'chromium' &&
|
||||
contextUserAgent
|
||||
? [`--user-agent=${contextUserAgent}`]
|
||||
: [];
|
||||
const implicitArgs = [...fileAccessArgs, ...stealthArgs, ...launchUserAgentArgs];
|
||||
const baseArgs = options.args
|
||||
? [...fileAccessArgs, ...options.args]
|
||||
: fileAccessArgs.length > 0
|
||||
? fileAccessArgs
|
||||
? [...implicitArgs, ...options.args]
|
||||
: implicitArgs.length > 0
|
||||
? implicitArgs
|
||||
: undefined;
|
||||
|
||||
// Auto-detect args that control window size and disable viewport emulation
|
||||
@@ -1251,41 +1669,41 @@ export class BrowserManager {
|
||||
{
|
||||
headless: false,
|
||||
executablePath: options.executablePath,
|
||||
...(chromeChannel && { channel: chromeChannel }),
|
||||
args: allArgs,
|
||||
viewport,
|
||||
extraHTTPHeaders: options.headers,
|
||||
userAgent: options.userAgent,
|
||||
extraHTTPHeaders,
|
||||
userAgent: contextUserAgent,
|
||||
...(this.contextLocale && { locale: this.contextLocale }),
|
||||
...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
|
||||
...(options.proxy && { proxy: options.proxy }),
|
||||
ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
|
||||
...(this.colorScheme && { colorScheme: this.colorScheme }),
|
||||
}
|
||||
);
|
||||
this.isPersistentContext = true;
|
||||
} else if (hasProfile) {
|
||||
// Profile uses persistent context for durable cookies/storage
|
||||
// Expand ~ to home directory since it won't be shell-expanded
|
||||
const profilePath = options.profile!.replace(/^~\//, os.homedir() + '/');
|
||||
context = await launcher.launchPersistentContext(profilePath, {
|
||||
headless: options.headless ?? true,
|
||||
executablePath: options.executablePath,
|
||||
args: baseArgs,
|
||||
viewport,
|
||||
extraHTTPHeaders: options.headers,
|
||||
userAgent: options.userAgent,
|
||||
...(options.proxy && { proxy: options.proxy }),
|
||||
ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
|
||||
...(this.colorScheme && { colorScheme: this.colorScheme }),
|
||||
});
|
||||
this.isPersistentContext = true;
|
||||
} else {
|
||||
// Regular ephemeral browser
|
||||
this.browser = await launcher.launch({
|
||||
headless: options.headless ?? true,
|
||||
headless: options.headless ?? false,
|
||||
executablePath: options.executablePath,
|
||||
...(chromeChannel && { channel: chromeChannel }),
|
||||
args: baseArgs,
|
||||
});
|
||||
this.cdpEndpoint = null;
|
||||
|
||||
if (stealthPolicy.enabled && browserType === 'chromium') {
|
||||
await applyBrowserLevelStealth(this.browser);
|
||||
}
|
||||
|
||||
if (!options.userAgent && stealthPolicy.enabled && browserType === 'chromium') {
|
||||
const runtimeVersion = this.extractChromiumVersion(this.browser.version());
|
||||
if (runtimeVersion) {
|
||||
contextUserAgent = this.buildStealthChromiumUserAgent(runtimeVersion);
|
||||
this.contextUserAgent = contextUserAgent;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for auto-load state file (supports encrypted files)
|
||||
let storageState:
|
||||
| string
|
||||
@@ -1355,15 +1773,19 @@ export class BrowserManager {
|
||||
|
||||
context = await this.browser.newContext({
|
||||
viewport,
|
||||
extraHTTPHeaders: options.headers,
|
||||
userAgent: options.userAgent,
|
||||
extraHTTPHeaders,
|
||||
userAgent: contextUserAgent,
|
||||
storageState,
|
||||
...(this.contextLocale && { locale: this.contextLocale }),
|
||||
...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
|
||||
...(options.proxy && { proxy: options.proxy }),
|
||||
ignoreHTTPSErrors: options.ignoreHTTPSErrors ?? false,
|
||||
...(this.colorScheme && { colorScheme: this.colorScheme }),
|
||||
});
|
||||
}
|
||||
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
@@ -1385,6 +1807,7 @@ export class BrowserManager {
|
||||
cdpEndpoint: string | undefined,
|
||||
options?: { timeout?: number }
|
||||
): Promise<void> {
|
||||
this.stealthConnectionKind = 'cdp';
|
||||
if (!cdpEndpoint) {
|
||||
throw new Error('CDP endpoint is required for CDP connection');
|
||||
}
|
||||
@@ -1427,11 +1850,32 @@ export class BrowserManager {
|
||||
throw new Error('No browser context found. Make sure the app has an open window.');
|
||||
}
|
||||
|
||||
// Filter out pages with empty URLs, which can cause Playwright to hang
|
||||
const allPages = contexts.flatMap((context) => context.pages()).filter((page) => page.url());
|
||||
let allPages = this.collectUsableCDPPages(contexts);
|
||||
|
||||
if (allPages.length === 0) {
|
||||
throw new Error('No page found. Make sure the app has loaded content.');
|
||||
// Some Chrome instances (especially with custom UI pages) expose only internal/transient
|
||||
// pages over CDP. Create a fresh page so commands always have a stable target.
|
||||
let fallbackPage: Page | null = null;
|
||||
for (const context of contexts) {
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
if (!fallbackPage) {
|
||||
fallbackPage = page;
|
||||
}
|
||||
if (this.isUsableCDPPage(page)) {
|
||||
fallbackPage = page;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Try next context
|
||||
}
|
||||
}
|
||||
|
||||
if (!fallbackPage) {
|
||||
throw new Error('No page found. Make sure the app has loaded content.');
|
||||
}
|
||||
|
||||
allPages = [fallbackPage];
|
||||
}
|
||||
|
||||
// All validation passed - commit state
|
||||
@@ -1439,6 +1883,7 @@ export class BrowserManager {
|
||||
this.cdpEndpoint = cdpEndpoint;
|
||||
|
||||
for (const context of contexts) {
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
context.setDefaultTimeout(10000);
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
@@ -1535,7 +1980,7 @@ export class BrowserManager {
|
||||
* Discovery strategy:
|
||||
* 1. Read DevToolsActivePort from Chrome's default user data directories
|
||||
* 2. If found, connect using the port and WebSocket path from that file
|
||||
* 3. If not found, probe common debugging ports (9222, 9229)
|
||||
* 3. If not found, probe common debugging ports (9222, 9229, 9333)
|
||||
* 4. If a port responds, connect via CDP
|
||||
*/
|
||||
private async autoConnectViaCDP(): Promise<void> {
|
||||
@@ -1570,7 +2015,7 @@ export class BrowserManager {
|
||||
}
|
||||
|
||||
// Strategy 2: Probe common debugging ports
|
||||
const commonPorts = [9222, 9229];
|
||||
const commonPorts = [9222, 9229, 9333];
|
||||
for (const port of commonPorts) {
|
||||
const wsUrl = await this.probeDebugPort(port);
|
||||
if (wsUrl) {
|
||||
@@ -1626,6 +2071,9 @@ export class BrowserManager {
|
||||
const index = this.pages.indexOf(page);
|
||||
if (index !== -1) {
|
||||
this.pages.splice(index, 1);
|
||||
if (index < this.activePageIndex) {
|
||||
this.activePageIndex--;
|
||||
}
|
||||
if (this.activePageIndex >= this.pages.length) {
|
||||
this.activePageIndex = Math.max(0, this.pages.length - 1);
|
||||
}
|
||||
@@ -1639,6 +2087,11 @@ export class BrowserManager {
|
||||
*/
|
||||
private setupContextTracking(context: BrowserContext): void {
|
||||
context.on('page', (page) => {
|
||||
const pageUrl = this.getSafePageUrl(page);
|
||||
if (this.isIgnoredCDPPageUrl(pageUrl)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only add if not already tracked (avoids duplicates when newTab() creates pages)
|
||||
if (!this.pages.includes(page)) {
|
||||
this.pages.push(page);
|
||||
@@ -1694,8 +2147,13 @@ export class BrowserManager {
|
||||
|
||||
const context = await this.browser.newContext({
|
||||
viewport: viewport === undefined ? { width: 1280, height: 720 } : viewport,
|
||||
...(this.contextHeaders && { extraHTTPHeaders: this.contextHeaders }),
|
||||
...(this.contextUserAgent && { userAgent: this.contextUserAgent }),
|
||||
...(this.contextLocale && { locale: this.contextLocale }),
|
||||
...(this.contextTimezoneId && { timezoneId: this.contextTimezoneId }),
|
||||
...(this.colorScheme && { colorScheme: this.colorScheme }),
|
||||
});
|
||||
await this.applyStealthIfEnabled(context, { locale: this.contextLocale });
|
||||
context.setDefaultTimeout(getDefaultTimeout());
|
||||
this.contexts.push(context);
|
||||
this.setupContextTracking(context);
|
||||
@@ -2435,6 +2893,12 @@ export class BrowserManager {
|
||||
this.isPersistentContext = false;
|
||||
this.activePageIndex = 0;
|
||||
this.colorScheme = null;
|
||||
this.stealthEnabled = true;
|
||||
this.stealthConnectionKind = 'local';
|
||||
this.contextLocale = undefined;
|
||||
this.contextTimezoneId = undefined;
|
||||
this.contextHeaders = undefined;
|
||||
this.contextUserAgent = undefined;
|
||||
this.refMap = {};
|
||||
this.lastSnapshot = '';
|
||||
this.frameCallback = null;
|
||||
|
||||
+40
-5
@@ -405,7 +405,9 @@ export async function startDaemon(options?: {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Auto-launch if not already launched and this isn't a launch/close/state_load command
|
||||
// Auto-launch if not already launched and this isn't a launch/close/state_load command.
|
||||
// Default behavior for this fork: first try attaching to a resident Chrome on CDP :9333,
|
||||
// then fall back to launching a local Playwright browser if CDP is unavailable.
|
||||
if (
|
||||
!manager.isLaunched() &&
|
||||
parseResult.command.action !== 'launch' &&
|
||||
@@ -450,29 +452,62 @@ export async function startDaemon(options?: {
|
||||
|
||||
const ignoreHTTPSErrors = process.env.AGENT_BROWSER_IGNORE_HTTPS_ERRORS === '1';
|
||||
const allowFileAccess = process.env.AGENT_BROWSER_ALLOW_FILE_ACCESS === '1';
|
||||
// Stealth is always enabled in agent-browser-stealth
|
||||
const colorSchemeEnv = process.env.AGENT_BROWSER_COLOR_SCHEME;
|
||||
const colorScheme =
|
||||
const colorScheme: 'dark' | 'light' | 'no-preference' | undefined =
|
||||
colorSchemeEnv === 'dark' ||
|
||||
colorSchemeEnv === 'light' ||
|
||||
colorSchemeEnv === 'no-preference'
|
||||
? colorSchemeEnv
|
||||
: undefined;
|
||||
await manager.launch({
|
||||
const launchOptions = {
|
||||
id: 'auto',
|
||||
action: 'launch' as const,
|
||||
headless: process.env.AGENT_BROWSER_HEADED !== '1',
|
||||
executablePath: process.env.AGENT_BROWSER_EXECUTABLE_PATH,
|
||||
extensions: extensions,
|
||||
profile: process.env.AGENT_BROWSER_PROFILE,
|
||||
storageState: process.env.AGENT_BROWSER_STATE,
|
||||
args,
|
||||
userAgent: process.env.AGENT_BROWSER_USER_AGENT,
|
||||
proxy,
|
||||
ignoreHTTPSErrors: ignoreHTTPSErrors,
|
||||
allowFileAccess: allowFileAccess,
|
||||
|
||||
colorScheme,
|
||||
autoStateFilePath: getSessionAutoStatePath(),
|
||||
});
|
||||
};
|
||||
|
||||
let launchedViaDefaultCdp = false;
|
||||
try {
|
||||
// Keep default CDP attempt minimal. Launch-only options like extensions
|
||||
// are incompatible with CDP and can cause a false-negative fallback.
|
||||
const cdpLaunchOptions = {
|
||||
id: launchOptions.id,
|
||||
action: launchOptions.action,
|
||||
cdpPort: 9333,
|
||||
ignoreHTTPSErrors: launchOptions.ignoreHTTPSErrors,
|
||||
colorScheme: launchOptions.colorScheme,
|
||||
userAgent: launchOptions.userAgent,
|
||||
};
|
||||
await manager.launch({
|
||||
...cdpLaunchOptions,
|
||||
});
|
||||
launchedViaDefaultCdp = true;
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
console.error('[DEBUG] Auto-launch connected via default CDP port 9333');
|
||||
}
|
||||
} catch (error) {
|
||||
if (process.env.AGENT_BROWSER_DEBUG === '1') {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(
|
||||
`[DEBUG] Default CDP port 9333 unavailable, falling back to local launch: ${message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!launchedViaDefaultCdp) {
|
||||
await manager.launch(launchOptions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,19 @@ import { parseCommand } from './protocol.js';
|
||||
const cmd = (obj: object) => JSON.stringify(obj);
|
||||
|
||||
describe('parseCommand', () => {
|
||||
describe('launch', () => {
|
||||
it('should parse launch command with stealth flag', () => {
|
||||
const result = parseCommand(
|
||||
cmd({ id: '1', action: 'launch', headless: false, stealth: true })
|
||||
);
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.command.action).toBe('launch');
|
||||
expect(result.command.stealth).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('navigation', () => {
|
||||
it('should parse navigate command', () => {
|
||||
const result = parseCommand(cmd({ id: '1', action: 'navigate', url: 'https://example.com' }));
|
||||
|
||||
+1
-1
@@ -50,7 +50,6 @@ const launchSchema = baseCommandSchema.extend({
|
||||
ignoreHTTPSErrors: z.boolean().optional(),
|
||||
allowFileAccess: z.boolean().optional(),
|
||||
colorScheme: z.enum(['light', 'dark', 'no-preference']).optional(),
|
||||
profile: z.string().optional(),
|
||||
storageState: z.string().optional(),
|
||||
});
|
||||
|
||||
@@ -809,6 +808,7 @@ const waitSchema = baseCommandSchema.extend({
|
||||
action: z.literal('wait'),
|
||||
selector: z.string().min(1).optional(),
|
||||
timeout: z.number().positive().optional(),
|
||||
timeoutMax: z.number().positive().optional(),
|
||||
state: z.enum(['attached', 'detached', 'visible', 'hidden']).optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { BrowserManager } from './browser.js';
|
||||
|
||||
async function readWebdriverSignals(browser: BrowserManager): Promise<{
|
||||
value: boolean | undefined;
|
||||
inNavigator: boolean;
|
||||
ownNavigator: boolean;
|
||||
ownPrototype: boolean;
|
||||
}> {
|
||||
const page = browser.getPage();
|
||||
await page.goto('about:blank');
|
||||
return page.evaluate(() => {
|
||||
const prototype = Object.getPrototypeOf(navigator);
|
||||
return {
|
||||
value: navigator.webdriver,
|
||||
inNavigator: 'webdriver' in navigator,
|
||||
ownNavigator: Object.prototype.hasOwnProperty.call(navigator, 'webdriver'),
|
||||
ownPrototype: Object.prototype.hasOwnProperty.call(prototype, 'webdriver'),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe('Stealth mode', () => {
|
||||
let browser: BrowserManager;
|
||||
|
||||
afterEach(async () => {
|
||||
if (browser?.isLaunched()) {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('removes navigator.webdriver when stealth is enabled', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const signals = await readWebdriverSignals(browser);
|
||||
expect(signals.value).toBeUndefined();
|
||||
expect(signals.inNavigator).toBe(false);
|
||||
expect(signals.ownNavigator).toBe(false);
|
||||
expect(signals.ownPrototype).toBe(false);
|
||||
});
|
||||
|
||||
it('applies stealth patches to contexts created by newWindow', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
await browser.newWindow();
|
||||
|
||||
const signals = await readWebdriverSignals(browser);
|
||||
expect(signals.value).toBeUndefined();
|
||||
expect(signals.inNavigator).toBe(false);
|
||||
expect(signals.ownNavigator).toBe(false);
|
||||
expect(signals.ownPrototype).toBe(false);
|
||||
});
|
||||
|
||||
it('aligns navigator language with AGENT_BROWSER_LOCALE', async () => {
|
||||
const previousLocale = process.env.AGENT_BROWSER_LOCALE;
|
||||
process.env.AGENT_BROWSER_LOCALE = 'fr-FR';
|
||||
|
||||
try {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const languageSignals = await browser.getPage().evaluate(() => ({
|
||||
language: navigator.language,
|
||||
languages: navigator.languages,
|
||||
}));
|
||||
|
||||
expect(languageSignals.language).toBe('fr-FR');
|
||||
expect(languageSignals.languages).toEqual(['fr-FR', 'fr']);
|
||||
} finally {
|
||||
if (previousLocale === undefined) {
|
||||
delete process.env.AGENT_BROWSER_LOCALE;
|
||||
} else {
|
||||
process.env.AGENT_BROWSER_LOCALE = previousLocale;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps worker and page userAgent free of HeadlessChrome tokens', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const userAgentSignals = await browser.getPage().evaluate(async () => {
|
||||
const pageUA = navigator.userAgent;
|
||||
const workerUA = await new Promise<string>((resolve) => {
|
||||
const source = 'postMessage(navigator.userAgent);';
|
||||
const blob = new Blob([source], { type: 'application/javascript' });
|
||||
const worker = new Worker(URL.createObjectURL(blob));
|
||||
worker.onmessage = (event) => resolve(String(event.data));
|
||||
});
|
||||
return { pageUA, workerUA };
|
||||
});
|
||||
|
||||
expect(userAgentSignals.pageUA).not.toContain('HeadlessChrome');
|
||||
expect(userAgentSignals.workerUA).not.toContain('HeadlessChrome');
|
||||
});
|
||||
|
||||
it('neutralizes the css webdriver heuristic probe', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const signals = await browser.getPage().evaluate(() => ({
|
||||
probe: CSS.supports('border-end-end-radius: initial'),
|
||||
baseline: CSS.supports('display: block'),
|
||||
webdriver: navigator.webdriver,
|
||||
inNavigator: 'webdriver' in navigator,
|
||||
}));
|
||||
|
||||
expect(signals.probe).toBe(false);
|
||||
expect(signals.baseline).toBe(true);
|
||||
expect(signals.webdriver).toBeUndefined();
|
||||
expect(signals.inNavigator).toBe(false);
|
||||
});
|
||||
|
||||
it('neutralizes creepjs prefers-color-scheme light probe', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const signals = await browser.getPage().evaluate(() => {
|
||||
const node = document.createElement('div');
|
||||
node.setAttribute('style', 'background-color: ActiveText');
|
||||
document.body.appendChild(node);
|
||||
const activeTextColor = getComputedStyle(node).backgroundColor;
|
||||
node.remove();
|
||||
|
||||
return {
|
||||
activeTextColor,
|
||||
prefersLight: matchMedia('(prefers-color-scheme: light)').matches,
|
||||
prefersDark: matchMedia('(prefers-color-scheme: dark)').matches,
|
||||
};
|
||||
});
|
||||
|
||||
expect(signals.activeTextColor).not.toBe('rgb(255, 0, 0)');
|
||||
expect(signals.prefersLight).toBe(false);
|
||||
expect(typeof signals.prefersDark).toBe('boolean');
|
||||
});
|
||||
|
||||
it('exposes realistic mimeTypes/pdf/share signals', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const signals = await browser.getPage().evaluate(() => ({
|
||||
mimeTypesLength: navigator.mimeTypes ? navigator.mimeTypes.length : 0,
|
||||
pdfViewerEnabled: navigator.pdfViewerEnabled,
|
||||
hasShare: typeof navigator.share === 'function',
|
||||
hasCanShare: typeof navigator.canShare === 'function',
|
||||
hasConnectionDownlinkMax:
|
||||
!!navigator.connection && typeof navigator.connection.downlinkMax === 'number',
|
||||
hasConnectionDownlinkMaxOnProto:
|
||||
!!navigator.connection && 'downlinkMax' in Object.getPrototypeOf(navigator.connection),
|
||||
}));
|
||||
|
||||
expect(signals.mimeTypesLength).toBeGreaterThan(0);
|
||||
expect(signals.pdfViewerEnabled).toBe(true);
|
||||
expect(signals.hasShare).toBe(true);
|
||||
expect(signals.hasCanShare).toBe(true);
|
||||
expect(signals.hasConnectionDownlinkMax).toBe(true);
|
||||
expect(signals.hasConnectionDownlinkMaxOnProto).toBe(true);
|
||||
});
|
||||
|
||||
it('exposes contacts manager and content index APIs', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const signals = await browser.getPage().evaluate(() => ({
|
||||
hasContacts: 'contacts' in navigator,
|
||||
contactsManagerCtor: typeof (window as any).ContactsManager === 'function',
|
||||
hasContentIndexCtor: typeof (window as any).ContentIndex === 'function',
|
||||
hasServiceWorkerRegistration: typeof ServiceWorkerRegistration !== 'undefined',
|
||||
hasContentIndexOnSWR:
|
||||
typeof ServiceWorkerRegistration !== 'undefined' &&
|
||||
('contentIndex' in ServiceWorkerRegistration.prototype ||
|
||||
'index' in ServiceWorkerRegistration.prototype),
|
||||
notificationPermission: typeof Notification !== 'undefined' ? Notification.permission : null,
|
||||
screenMatchesViewport:
|
||||
screen.width === window.innerWidth && screen.height === window.innerHeight,
|
||||
}));
|
||||
|
||||
expect(signals.hasContacts).toBe(true);
|
||||
expect(signals.contactsManagerCtor).toBe(true);
|
||||
expect(signals.hasContentIndexCtor).toBe(true);
|
||||
if (signals.hasServiceWorkerRegistration) {
|
||||
expect(signals.hasContentIndexOnSWR).toBe(true);
|
||||
}
|
||||
expect(signals.notificationPermission).toBe('default');
|
||||
expect(signals.screenMatchesViewport).toBe(false);
|
||||
});
|
||||
|
||||
it('exposes downlinkMax inside dedicated workers', async () => {
|
||||
browser = new BrowserManager();
|
||||
await browser.launch({ headless: true, stealth: true });
|
||||
|
||||
const workerSignals = await browser.getPage().evaluate(async () => {
|
||||
return new Promise<{
|
||||
hasConnection: boolean;
|
||||
hasDownlinkMax: boolean;
|
||||
hasDownlinkMaxOnProto: boolean;
|
||||
downlinkMax: unknown;
|
||||
}>((resolve) => {
|
||||
const source =
|
||||
"postMessage({hasConnection: !!navigator.connection, hasDownlinkMax: navigator.connection ? ('downlinkMax' in navigator.connection) : false, hasDownlinkMaxOnProto: navigator.connection ? ('downlinkMax' in Object.getPrototypeOf(navigator.connection)) : false, downlinkMax: navigator.connection && navigator.connection.downlinkMax});";
|
||||
const blob = new Blob([source], { type: 'application/javascript' });
|
||||
const worker = new Worker(URL.createObjectURL(blob));
|
||||
worker.onmessage = (event) => resolve(event.data);
|
||||
});
|
||||
});
|
||||
|
||||
expect(workerSignals.hasConnection).toBe(true);
|
||||
expect(workerSignals.hasDownlinkMax).toBe(true);
|
||||
expect(workerSignals.hasDownlinkMaxOnProto).toBe(true);
|
||||
expect(typeof workerSignals.downlinkMax).toBe('number');
|
||||
});
|
||||
});
|
||||
+1138
File diff suppressed because it is too large
Load Diff
+2
-1
@@ -18,7 +18,6 @@ export interface LaunchCommand extends BaseCommand {
|
||||
cdpUrl?: string;
|
||||
autoConnect?: boolean; // Auto-discover and connect to running Chrome via DevToolsActivePort
|
||||
extensions?: string[];
|
||||
profile?: string; // Path to persistent browser profile directory
|
||||
storageState?: string; // Path to storage state JSON file
|
||||
proxy?: {
|
||||
server: string;
|
||||
@@ -828,6 +827,7 @@ export interface WaitCommand extends BaseCommand {
|
||||
action: 'wait';
|
||||
selector?: string;
|
||||
timeout?: number;
|
||||
timeoutMax?: number; // When set with timeout, waits a random duration in [timeout, timeoutMax]
|
||||
state?: 'attached' | 'detached' | 'visible' | 'hidden';
|
||||
}
|
||||
|
||||
@@ -1072,6 +1072,7 @@ export type Response<T = unknown> = SuccessResponse<T> | ErrorResponse;
|
||||
export interface NavigateData {
|
||||
url: string;
|
||||
title: string;
|
||||
warning?: string;
|
||||
}
|
||||
|
||||
export interface Annotation {
|
||||
|
||||
Reference in New Issue
Block a user