Compare commits

...
Author SHA1 Message Date
leeguooooo 0a257ad2c1 merge: sync upstream/main into fork main (v0.15.2) 2026-03-03 09:57:17 +09:00
leeguooooo 44c0361fcd Update readme with stealth FAQ 2026-03-02 18:32:28 +09:00
leeguooooo 907ca8c808 Update agent-browser skill installs 2026-03-02 09:38:48 +09:00
leeguooooo 74fda70b67 fix(release): publish correct native version in fork.7 2026-02-28 11:29:21 +09:00
leeguooooo 2a397de59f merge: sync upstream/main into fork main 2026-02-28 11:19:50 +09:00
leeguooooo bf672ee7f9 fix(stealth): avoid matchMedia Illegal invocation
- bind MediaQueryList methods when proxied for prefers-color-scheme light patch

- add regression test for addEventListener/removeEventListener

- bump version to 0.14.0-fork.6 and sync Cargo metadata
2026-02-28 11:17:02 +09:00
leeguooooo 74910cfef1 Merge tag 'v0.15.0' into codex/sync-v0.15.0
v0.15.0

# Conflicts:
#	CHANGELOG.md
#	README.md
#	cli/Cargo.lock
#	cli/Cargo.toml
#	cli/src/commands.rs
#	cli/src/connection.rs
#	cli/src/flags.rs
#	cli/src/main.rs
#	docs/src/app/commands/page.mdx
#	docs/src/app/configuration/page.mdx
#	package.json
#	src/actions.ts
2026-02-27 10:49:55 +09:00
leeguooooo 41830dff71 fix(cookies): require domain and path together when url is absent 2026-02-27 10:49:12 +09:00
leeguooooo e005c7251b feat(stealth): add risk-mode signals and document stealth architecture 2026-02-25 10:27:45 +09:00
leeguooooo 11eab471f1 chore(release): bump version to 0.14.0-fork.4 2026-02-25 10:10:26 +09:00
leeguooooo aa256e30c7 Merge remote-tracking branch 'upstream/main'
# Conflicts:
#	README.md
#	cli/src/connection.rs
#	cli/src/flags.rs
#	cli/src/main.rs
#	src/browser.ts
#	src/protocol.ts
2026-02-25 10:06:20 +09:00
leeguooooo 6f1dd39121 chore(clawhub): 改为本地 pre-push 自动同步 skill 2026-02-24 18:10:05 +09:00
leeguooooo 85d18799a4 feat(skill): 新增 agent-browser-stealth 的 OpenClaw skill 与 ClawHub 自动同步 2026-02-24 18:05:29 +09:00
leeguooooo 43e781a8d3 docs(readme): 精简文档并聚焦反爬能力 2026-02-24 18:00:19 +09:00
leeguooooo 25e8719e51 docs(readme): 补充 --delay 文本转义与 stealth 行为说明 2026-02-24 17:58:13 +09:00
leeguooooo ec011f46ff fix(stealth): 修复 launch 选项与测试基线不一致问题
在 stealth 默认策略下保留自定义 user-agent,不再被 CDP 覆盖。

同步更新 protocol/browser/launch/file-access 相关测试预期,并放宽 browser.test 的 hook 超时以消除偶发超时。
2026-02-24 17:42:12 +09:00
leeguooooo aef8fcc038 ci(release): 修复 OIDC 发布认证链路
移除 setup-node 的 registry-url 注入,避免发布步骤继承无效 NODE_AUTH_TOKEN。

发布前升级 npm 到 v11,使用独立 npmrc 并启用 provenance,以匹配 npm trusted publishing。
2026-02-24 17:24:20 +09:00
leeguooooo 96582b79fd ci(release): 调整 trusted publishing 发布流程
将 changesets/action 改为仅处理 version/PR,不再由其执行 publish。

新增发布前版本检查与独立 pnpm ci:publish 步骤,避免 OIDC 发布在 action 内失败。
2026-02-24 17:20:17 +09:00
leeguooooo 058a286326 chore(release): 发布 0.14.0-fork.3
更新 package.json 版本并写入对应 changelog 条目。
2026-02-24 17:14:06 +09:00
leeguooooo b1f27236d8 fix(cli): 修复 type/keyboard 的 --delay 参数解析
将 --delay <ms> 从输入文本中剥离并写入 delay 字段,避免搜索词混入参数。

同时支持使用 -- 终止参数解析以输入字面量 --delay 文本,并补充回归测试与帮助文档。
2026-02-24 17:13:46 +09:00
leeguooooo a5a9327b7d docs(home): 补充首页能力亮点说明
- 新增自动区域检测能力描述

- 新增验证码自动重试能力描述
2026-02-24 17:06:34 +09:00
leeguooooo 699ccbd3cb feat(cli): 强制使用用户现有浏览器并移除 profile/channel
- 禁用 --profile/AGENT_BROWSER_PROFILE 与 --channel/AGENT_BROWSER_CHANNEL,并给出项目策略提示

- 默认模式强制连接 localhost:9333,连接失败直接报错,不再自动回退新开浏览器

- 同步更新 README、技能文档、docs 与 --help 输出

- 版本升级到 0.14.0-fork.2 并同步 cli/Cargo.toml 与 Cargo.lock
2026-02-24 17:05:11 +09:00
leeguooooo 893ddfd259 feat(cdp): 默认优先连接 9333 常驻 Chrome
- 无显式连接参数时先尝试 CDP 9333,失败后回退本地浏览器启动

- 修复 CDP 页选择稳定性:过滤 omnibox 系统页、无可用页时自动创建 fallback 页

- 调整页面关闭后的 active 索引维护,降低 No page found 问题

- 新增 agent-browser-stealth 二进制入口并保持与 agent-browser 行为一致

- 同步更新 CLI 帮助、README、技能文档与 docs 说明
2026-02-24 16:22:49 +09:00
leeguooooo ea2e93dbba feat(stealth): 优化隐身对抗并引入双版本发布体系
- 将 CreepJS like headless 指标优化到 0%(headless/stealth 维持 0%)

- 新增 ActiveText 与 prefers-color-scheme 探针修复

- 版本号采用 <upstream>-fork.<fork> 格式并在 --version 输出 upstream/fork

- 更新 README、SKILL 与 docs 中的版本体系说明
2026-02-24 15:29:11 +09:00
leeguooooo 4c6afe3e69 docs(config): 移除 --stealth 配置项说明 2026-02-24 14:55:07 +09:00
leeguooooo 9f9a90cf63 docs(cli): 清理过时 stealth 环境变量说明 2026-02-24 14:54:51 +09:00
leeguooooo 0443e4ed7a feat(stealth): 默认开启并收敛 chrome 指纹特征 2026-02-24 14:54:30 +09:00
leeguooooo c5b2292caa feat(stealth): 增强浏览器级 UA 覆盖并修复背景特征 2026-02-24 14:50:03 +09:00
leeguooooo 2ed0c6f8ec feat(stealth): 进一步降低 creepjs like-headless 指标 2026-02-24 14:36:56 +09:00
leeguooooo 3a91aef4c9 feat(stealth): 优化指纹信号并同步文档与包配置 2026-02-24 14:23:59 +09:00
leeguooooo 02ebc9f328 feat(stealth): 增强指纹一致性并新增 creepjs 检测脚本 2026-02-24 14:19:25 +09:00
leeguooooo 955543b757 chore: prepare fork sync and independent release setup 2026-02-24 14:14:50 +09:00
leeguooooo ecad112707 feat(cli): 默认开启 stealth 并支持 wait 区间超时 2026-02-24 12:27:04 +09:00
leeguooooo 8932f28926 fix(stealth): 修复 headed 模式下 stealth 失效并统一策略
- 修复 launch 协议未透传 stealth 导致 --headed 下补丁失效的问题\n- 在 BrowserManager 引入 StealthPolicy,统一 local/CDP/provider 能力决策\n- 增加 launch 返回 stealth 状态并在 --debug 输出连接类型与能力\n- 补充 local/CDP 回归测试与 bot.sannysoft.com 自动检查脚本\n- 同步 README、CLI help、技能文档与 CDP 文档中的 stealth 能力矩阵
2026-02-24 12:18:47 +09:00
44 changed files with 5357 additions and 2709 deletions
+43 -5
View File
@@ -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
@@ -141,8 +142,8 @@ jobs:
needs: build-binaries
runs-on: ubuntu-latest
outputs:
published: ${{ steps.changesets.outputs.published }}
publishedPackages: ${{ steps.changesets.outputs.publishedPackages }}
published: ${{ steps.publish_metadata.outputs.published }}
publishedPackages: ${{ steps.publish_metadata.outputs.publishedPackages }}
steps:
- name: Checkout Repo
uses: actions/checkout@v4
@@ -159,7 +160,6 @@ jobs:
with:
node-version: '22'
cache: pnpm
registry-url: 'https://registry.npmjs.org'
- name: Install Dependencies
run: pnpm install --frozen-lockfile
@@ -214,12 +214,50 @@ jobs:
uses: changesets/action@v1
with:
version: pnpm ci:version
publish: pnpm ci:publish
title: 'chore: version packages'
commit: 'chore: version packages'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_VERCEL_TOKEN_ELEVATED }}
- name: Check if publish is needed
id: publish_check
if: steps.changesets.outputs.hasChangesets == 'false'
run: |
LOCAL_VERSION=$(node -p "require('./package.json').version")
REMOTE_VERSION=$(npm view agent-browser-stealth version 2>/dev/null || echo "")
echo "local_version=$LOCAL_VERSION" >> "$GITHUB_OUTPUT"
echo "remote_version=$REMOTE_VERSION" >> "$GITHUB_OUTPUT"
if [ "$LOCAL_VERSION" != "$REMOTE_VERSION" ]; then
echo "needs_publish=true" >> "$GITHUB_OUTPUT"
else
echo "needs_publish=false" >> "$GITHUB_OUTPUT"
fi
echo "Local: $LOCAL_VERSION"
echo "Remote: ${REMOTE_VERSION:-<none>}"
- name: Publish to npm (trusted publishing)
id: publish_npm
if: steps.changesets.outputs.hasChangesets == 'false' && steps.publish_check.outputs.needs_publish == 'true'
env:
NODE_AUTH_TOKEN: ""
NPM_CONFIG_USERCONFIG: /home/runner/work/_temp/trusted-npmrc
NPM_CONFIG_PROVENANCE: "true"
run: |
npm install -g npm@^11
npm --version
printf "registry=https://registry.npmjs.org/\n" > "$NPM_CONFIG_USERCONFIG"
pnpm ci:publish
- name: Set release outputs
id: publish_metadata
run: |
if [ "${{ steps.publish_npm.outcome }}" = "success" ]; then
echo "published=true" >> "$GITHUB_OUTPUT"
echo "publishedPackages=[{\"name\":\"agent-browser-stealth\",\"version\":\"${{ steps.publish_check.outputs.local_version }}\"}]" >> "$GITHUB_OUTPUT"
else
echo "published=false" >> "$GITHUB_OUTPUT"
echo "publishedPackages=[]" >> "$GITHUB_OUTPUT"
fi
# Create GitHub release with binaries after npm publish
github-release:
+8
View File
@@ -0,0 +1,8 @@
if [ "${SKIP_CLAWHUB_SYNC:-0}" = "1" ]; then
echo "Skipping ClawHub sync (SKIP_CLAWHUB_SYNC=1)"
exit 0
fi
pnpm run clawhub:sync || {
echo "ClawHub sync failed. Push continues. Run 'pnpm run clawhub:sync' manually after fixing login/network."
}
+15 -6
View File
@@ -1,10 +1,17 @@
# agent-browser
## 0.15.2
## 0.15.2-fork.0
### Patch Changes
- 6aea316: Documentation site improvements and internal tooling updates including enhanced code blocks, mobile navigation, and docs chat components. CLI connection and output handling refinements. Skill creator reference documentation and scripts have been reorganized.
- Merge upstream `v0.15.2` updates, including fixes for cookies clear/tab close output, daemon EPERM liveness checks, unnamed element reference matching, and docs/skills refresh.
## 0.15.1-fork.11
### Patch Changes
- Auto-attach existing browser more reliably by trying CDP localhost:9333 first, then falling back to auto-discovery before failing.
Align daemon behavior and user-facing docs/skill guidance with the same attachment policy.
## 0.15.1
@@ -14,11 +21,13 @@
## 0.15.0
### Minor Changes
### Patch Changes
- 2e38882: - Added security hardening: authentication vault, content boundary markers, domain allowlist, action policy, action confirmation, and output length limits.
- Added `--download-path` flag (and `AGENT_BROWSER_DOWNLOAD_PATH` env / `downloadPath` config key) to set a default download directory.
- Added `--selector` flag to `scroll` command for scrolling within specific container elements.
- 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
+181 -1117
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -3,8 +3,8 @@
version = 4
[[package]]
name = "agent-browser"
version = "0.15.2"
name = "agent-browser-stealth"
version = "0.15.2-fork.0"
dependencies = [
"base64",
"dirs",
+11 -3
View File
@@ -1,10 +1,18 @@
[package]
name = "agent-browser"
version = "0.15.2"
name = "agent-browser-stealth"
version = "0.15.2-fork.0"
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"
+221 -184
View File
@@ -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 {
@@ -92,7 +148,6 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
match cmd {
// === Navigation ===
// Maps to "navigate" action in protocol; reflected in ACTION_CATEGORIES in action-policy.ts
"open" | "goto" | "navigate" => {
let url = rest.first().ok_or_else(|| ParseError::MissingArguments {
context: cmd.to_string(),
@@ -114,10 +169,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;
}
@@ -127,6 +184,19 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
nav_cmd["iosDevice"] = json!(device);
}
}
if let Some(ref risk_mode) = flags.risk_mode {
if matches!(risk_mode.as_str(), "off" | "warn" | "block") {
nav_cmd["riskMode"] = json!(risk_mode);
} else {
return Err(ParseError::InvalidValue {
message: format!(
"Invalid --risk-mode value: {} (expected off, warn, or block)",
risk_mode
),
usage: "open <url>",
});
}
}
Ok(nav_cmd)
}
"back" => Ok(json!({ "id": id, "action": "back" })),
@@ -166,9 +236,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 {
@@ -273,14 +352,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(" ");
@@ -290,7 +371,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(),
@@ -425,8 +508,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 {
@@ -435,7 +526,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>",
})
}
}
@@ -564,131 +655,6 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
// === Close ===
"close" | "quit" | "exit" => Ok(json!({ "id": id, "action": "close" })),
// === Authentication Vault ===
"auth" => {
let sub = rest.first().map(|s| s.as_ref());
match sub {
Some("save") => {
let name = rest.get(1).ok_or_else(|| ParseError::MissingArguments {
context: "auth save".to_string(),
usage: "agent-browser auth save <name> --url <url> --username <user> --password <pass>",
})?;
let mut url = None;
let mut username = None;
let mut password = None;
let mut password_stdin = false;
let mut username_selector = None;
let mut password_selector = None;
let mut submit_selector = None;
let mut j = 2;
while j < rest.len() {
match rest[j].as_ref() {
"--url" => { url = rest.get(j + 1).cloned(); j += 1; }
"--username" => { username = rest.get(j + 1).cloned(); j += 1; }
"--password" => { password = rest.get(j + 1).cloned(); j += 1; }
"--password-stdin" => { password_stdin = true; }
"--username-selector" => { username_selector = rest.get(j + 1).cloned(); j += 1; }
"--password-selector" => { password_selector = rest.get(j + 1).cloned(); j += 1; }
"--submit-selector" => { submit_selector = rest.get(j + 1).cloned(); j += 1; }
other => {
if other.starts_with("--") {
return Err(ParseError::InvalidValue {
message: format!("unknown flag '{}' for auth save", other),
usage: "agent-browser auth save <name> --url <url> --username <user> --password <pass>",
});
}
}
}
j += 1;
}
let url_val = url.ok_or_else(|| ParseError::MissingArguments {
context: "auth save".to_string(),
usage: "agent-browser auth save <name> --url <url> --username <user> --password <pass> [--password-stdin]",
})?;
let user_val = username.ok_or_else(|| ParseError::MissingArguments {
context: "auth save".to_string(),
usage: "agent-browser auth save <name> --url <url> --username <user> --password <pass> [--password-stdin]",
})?;
if !password_stdin && password.is_none() {
return Err(ParseError::MissingArguments {
context: "auth save".to_string(),
usage: "agent-browser auth save <name> --url <url> --username <user> --password <pass> [--password-stdin]",
});
}
let mut cmd = json!({
"id": id,
"action": "auth_save",
"name": name,
"url": url_val,
"username": user_val,
});
if password_stdin {
cmd["passwordStdin"] = json!(true);
}
if let Some(pass_val) = password {
cmd["password"] = json!(pass_val);
}
if let Some(us) = username_selector {
cmd["usernameSelector"] = json!(us);
}
if let Some(ps) = password_selector {
cmd["passwordSelector"] = json!(ps);
}
if let Some(ss) = submit_selector {
cmd["submitSelector"] = json!(ss);
}
Ok(cmd)
}
Some("login") => {
let name = rest.get(1).ok_or_else(|| ParseError::MissingArguments {
context: "auth login".to_string(),
usage: "agent-browser auth login <name>",
})?;
Ok(json!({ "id": id, "action": "auth_login", "name": name }))
}
Some("list") => Ok(json!({ "id": id, "action": "auth_list" })),
Some("delete") | Some("remove") => {
let name = rest.get(1).ok_or_else(|| ParseError::MissingArguments {
context: "auth delete".to_string(),
usage: "agent-browser auth delete <name>",
})?;
Ok(json!({ "id": id, "action": "auth_delete", "name": name }))
}
Some("show") => {
let name = rest.get(1).ok_or_else(|| ParseError::MissingArguments {
context: "auth show".to_string(),
usage: "agent-browser auth show <name>",
})?;
Ok(json!({ "id": id, "action": "auth_show", "name": name }))
}
_ => Err(ParseError::UnknownSubcommand {
subcommand: sub.unwrap_or("(none)").to_string(),
valid_options: &["save", "login", "list", "delete", "show"],
}),
}
}
// === Action Confirmation ===
"confirm" => {
let cid = rest.first().ok_or_else(|| ParseError::MissingArguments {
context: "confirm".to_string(),
usage: "agent-browser confirm <confirmation-id>",
})?;
Ok(json!({ "id": id, "action": "confirm", "confirmationId": cid }))
}
"deny" => {
let cid = rest.first().ok_or_else(|| ParseError::MissingArguments {
context: "deny".to_string(),
usage: "agent-browser deny <confirmation-id>",
})?;
Ok(json!({ "id": id, "action": "deny", "confirmationId": cid }))
}
// === Connect (CDP) ===
"connect" => {
let endpoint = rest.first().ok_or_else(|| ParseError::MissingArguments {
@@ -864,6 +830,17 @@ pub fn parse_command(args: &[String], flags: &Flags) -> Result<Value, ParseError
}
}
// Playwright requires either `url` or a complete `domain`+`path` pair.
let has_url = cookie.get("url").is_some();
let has_domain = cookie.get("domain").is_some();
let has_path = cookie.get("path").is_some();
if !has_url && (has_domain != has_path) {
return Err(ParseError::MissingArguments {
context: "cookies set".to_string(),
usage: "When not using --url, you must provide both --domain <domain> and --path <path>",
});
}
Ok(json!({ "id": id, "action": "cookies_set", "cookies": [cookie] }))
}
"clear" => Ok(json!({ "id": id, "action": "cookies_clear" })),
@@ -1093,9 +1070,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;
@@ -1116,7 +1091,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(),
});
}
}
@@ -1170,13 +1147,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(),
@@ -1285,7 +1268,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>",
});
}
@@ -1351,7 +1337,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>",
});
}
@@ -1468,7 +1457,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>",
});
}
@@ -2038,7 +2030,6 @@ mod tests {
executable_path: None,
extensions: Vec::new(),
cdp: None,
profile: None,
state: None,
proxy: None,
proxy_bypass: None,
@@ -2052,7 +2043,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,
@@ -2064,13 +2054,7 @@ mod tests {
annotate: false,
color_scheme: None,
download_path: None,
content_boundaries: false,
max_output: None,
allowed_domains: None,
action_policy: None,
confirm_actions: None,
confirm_interactive: false,
risk_mode: None,
}
}
@@ -2126,28 +2110,34 @@ mod tests {
}
#[test]
fn test_cookies_set_with_domain() {
let cmd = parse_command(
fn test_cookies_set_with_domain_requires_path() {
let result = parse_command(
&args("cookies set mycookie myvalue --domain example.com"),
&default_flags(),
);
assert!(result.is_err());
}
#[test]
fn test_cookies_set_with_path_requires_domain() {
let result = parse_command(
&args("cookies set mycookie myvalue --path /api"),
&default_flags(),
);
assert!(result.is_err());
}
#[test]
fn test_cookies_set_with_domain_and_path() {
let cmd = parse_command(
&args("cookies set mycookie myvalue --domain example.com --path /api"),
&default_flags(),
)
.unwrap();
assert_eq!(cmd["action"], "cookies_set");
assert_eq!(cmd["cookies"][0]["name"], "mycookie");
assert_eq!(cmd["cookies"][0]["value"], "myvalue");
assert_eq!(cmd["cookies"][0]["domain"], "example.com");
}
#[test]
fn test_cookies_set_with_path() {
let cmd = parse_command(
&args("cookies set mycookie myvalue --path /api"),
&default_flags(),
)
.unwrap();
assert_eq!(cmd["action"], "cookies_set");
assert_eq!(cmd["cookies"][0]["name"], "mycookie");
assert_eq!(cmd["cookies"][0]["value"], "myvalue");
assert_eq!(cmd["cookies"][0]["path"], "/api");
}
@@ -2336,6 +2326,14 @@ mod tests {
assert_eq!(cmd["headers"]["Authorization"], "Bearer token");
}
#[test]
fn test_navigate_with_risk_mode() {
let mut flags = default_flags();
flags.risk_mode = Some("block".to_string());
let cmd = parse_command(&args("open https://example.com"), &flags).unwrap();
assert_eq!(cmd["riskMode"], "block");
}
#[test]
fn test_navigate_with_multiple_headers() {
let mut flags = default_flags();
@@ -2470,6 +2468,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();
@@ -2649,6 +2670,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();
@@ -3236,8 +3270,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");
}
@@ -3257,9 +3294,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");
@@ -3307,8 +3346,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);
}
@@ -3352,8 +3390,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);
}
+146 -94
View File
@@ -209,94 +209,24 @@ pub struct DaemonResult {
pub already_running: bool,
}
/// Options forwarded to the daemon process as environment variables.
/// Note: `confirm_interactive` is intentionally absent -- it is a CLI-side
/// UX concern (prompting the user on stdin) and not a daemon configuration.
/// The daemon only needs `confirm_actions` to gate action categories.
pub struct DaemonOptions<'a> {
pub headed: bool,
pub executable_path: Option<&'a str>,
pub extensions: &'a [String],
pub args: Option<&'a str>,
pub user_agent: Option<&'a str>,
pub proxy: Option<&'a str>,
pub proxy_bypass: Option<&'a str>,
pub ignore_https_errors: bool,
pub allow_file_access: bool,
pub profile: Option<&'a str>,
pub state: Option<&'a str>,
pub provider: Option<&'a str>,
pub device: Option<&'a str>,
pub session_name: Option<&'a str>,
pub download_path: Option<&'a str>,
pub allowed_domains: Option<&'a [String]>,
pub action_policy: Option<&'a str>,
pub confirm_actions: Option<&'a str>,
}
fn apply_daemon_env(cmd: &mut Command, session: &str, opts: &DaemonOptions) {
cmd.env("AGENT_BROWSER_DAEMON", "1")
.env("AGENT_BROWSER_SESSION", session);
if opts.headed {
cmd.env("AGENT_BROWSER_HEADED", "1");
}
if let Some(path) = opts.executable_path {
cmd.env("AGENT_BROWSER_EXECUTABLE_PATH", path);
}
if !opts.extensions.is_empty() {
cmd.env("AGENT_BROWSER_EXTENSIONS", opts.extensions.join(","));
}
if let Some(a) = opts.args {
cmd.env("AGENT_BROWSER_ARGS", a);
}
if let Some(ua) = opts.user_agent {
cmd.env("AGENT_BROWSER_USER_AGENT", ua);
}
if let Some(p) = opts.proxy {
cmd.env("AGENT_BROWSER_PROXY", p);
}
if let Some(pb) = opts.proxy_bypass {
cmd.env("AGENT_BROWSER_PROXY_BYPASS", pb);
}
if opts.ignore_https_errors {
cmd.env("AGENT_BROWSER_IGNORE_HTTPS_ERRORS", "1");
}
if opts.allow_file_access {
cmd.env("AGENT_BROWSER_ALLOW_FILE_ACCESS", "1");
}
if let Some(prof) = opts.profile {
cmd.env("AGENT_BROWSER_PROFILE", prof);
}
if let Some(st) = opts.state {
cmd.env("AGENT_BROWSER_STATE", st);
}
if let Some(p) = opts.provider {
cmd.env("AGENT_BROWSER_PROVIDER", p);
}
if let Some(d) = opts.device {
cmd.env("AGENT_BROWSER_IOS_DEVICE", d);
}
if let Some(sn) = opts.session_name {
cmd.env("AGENT_BROWSER_SESSION_NAME", sn);
}
if let Some(dp) = opts.download_path {
cmd.env("AGENT_BROWSER_DOWNLOAD_PATH", dp);
}
if let Some(ad) = opts.allowed_domains {
cmd.env("AGENT_BROWSER_ALLOWED_DOMAINS", ad.join(","));
}
if let Some(ap) = opts.action_policy {
cmd.env("AGENT_BROWSER_ACTION_POLICY", ap);
}
if let Some(ca) = opts.confirm_actions {
cmd.env("AGENT_BROWSER_CONFIRM_ACTIONS", ca);
}
}
#[allow(clippy::too_many_arguments)]
pub fn ensure_daemon(
session: &str,
opts: &DaemonOptions,
headed: bool,
executable_path: Option<&str>,
extensions: &[String],
args: Option<&str>,
user_agent: Option<&str>,
proxy: Option<&str>,
proxy_bypass: Option<&str>,
ignore_https_errors: bool,
allow_file_access: bool,
state: Option<&str>,
provider: Option<&str>,
device: Option<&str>,
session_name: Option<&str>,
debug: bool,
download_path: Option<&str>,
) -> Result<DaemonResult, String> {
// Check if daemon is running AND responsive
if is_daemon_running(session) && daemon_ready(session) {
@@ -381,8 +311,69 @@ pub fn ensure_daemon(
use std::os::unix::process::CommandExt;
let mut cmd = Command::new("node");
cmd.arg(daemon_path);
apply_daemon_env(&mut cmd, session, opts);
cmd.arg(daemon_path)
.env("AGENT_BROWSER_DAEMON", "1")
.env("AGENT_BROWSER_SESSION", session);
if headed {
cmd.env("AGENT_BROWSER_HEADED", "1");
}
if let Some(path) = executable_path {
cmd.env("AGENT_BROWSER_EXECUTABLE_PATH", path);
}
if !extensions.is_empty() {
cmd.env("AGENT_BROWSER_EXTENSIONS", extensions.join(","));
}
if let Some(a) = args {
cmd.env("AGENT_BROWSER_ARGS", a);
}
if let Some(ua) = user_agent {
cmd.env("AGENT_BROWSER_USER_AGENT", ua);
}
if let Some(p) = proxy {
cmd.env("AGENT_BROWSER_PROXY", p);
}
if let Some(pb) = proxy_bypass {
cmd.env("AGENT_BROWSER_PROXY_BYPASS", pb);
}
if ignore_https_errors {
cmd.env("AGENT_BROWSER_IGNORE_HTTPS_ERRORS", "1");
}
if allow_file_access {
cmd.env("AGENT_BROWSER_ALLOW_FILE_ACCESS", "1");
}
if let Some(st) = state {
cmd.env("AGENT_BROWSER_STATE", st);
}
if let Some(p) = provider {
cmd.env("AGENT_BROWSER_PROVIDER", p);
}
if let Some(d) = device {
cmd.env("AGENT_BROWSER_IOS_DEVICE", d);
}
if let Some(sn) = session_name {
cmd.env("AGENT_BROWSER_SESSION_NAME", sn);
}
cmd.env("AGENT_BROWSER_STEALTH", "1");
if debug {
cmd.env("AGENT_BROWSER_DEBUG", "1");
}
if let Some(dp) = download_path {
cmd.env("AGENT_BROWSER_DOWNLOAD_PATH", dp);
}
// Create new process group and session to fully detach
unsafe {
@@ -395,8 +386,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))?;
}
@@ -407,8 +398,69 @@ pub fn ensure_daemon(
// On Windows, call node directly. Command::new handles PATH resolution (node.exe or node.cmd)
// and automatically quotes arguments containing spaces.
let mut cmd = Command::new("node");
cmd.arg(daemon_path);
apply_daemon_env(&mut cmd, session, opts);
cmd.arg(daemon_path)
.env("AGENT_BROWSER_DAEMON", "1")
.env("AGENT_BROWSER_SESSION", session);
if headed {
cmd.env("AGENT_BROWSER_HEADED", "1");
}
if let Some(path) = executable_path {
cmd.env("AGENT_BROWSER_EXECUTABLE_PATH", path);
}
if !extensions.is_empty() {
cmd.env("AGENT_BROWSER_EXTENSIONS", extensions.join(","));
}
if let Some(a) = args {
cmd.env("AGENT_BROWSER_ARGS", a);
}
if let Some(ua) = user_agent {
cmd.env("AGENT_BROWSER_USER_AGENT", ua);
}
if let Some(p) = proxy {
cmd.env("AGENT_BROWSER_PROXY", p);
}
if let Some(pb) = proxy_bypass {
cmd.env("AGENT_BROWSER_PROXY_BYPASS", pb);
}
if ignore_https_errors {
cmd.env("AGENT_BROWSER_IGNORE_HTTPS_ERRORS", "1");
}
if allow_file_access {
cmd.env("AGENT_BROWSER_ALLOW_FILE_ACCESS", "1");
}
if let Some(st) = state {
cmd.env("AGENT_BROWSER_STATE", st);
}
if let Some(p) = provider {
cmd.env("AGENT_BROWSER_PROVIDER", p);
}
if let Some(d) = device {
cmd.env("AGENT_BROWSER_IOS_DEVICE", d);
}
if let Some(sn) = session_name {
cmd.env("AGENT_BROWSER_SESSION_NAME", sn);
}
cmd.env("AGENT_BROWSER_STEALTH", "1");
if debug {
cmd.env("AGENT_BROWSER_DEBUG", "1");
}
if let Some(dp) = download_path {
cmd.env("AGENT_BROWSER_DOWNLOAD_PATH", dp);
}
// CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
@@ -417,8 +469,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))?;
}
+89 -147
View File
@@ -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>,
@@ -35,12 +34,7 @@ pub struct Config {
pub annotate: Option<bool>,
pub color_scheme: Option<String>,
pub download_path: Option<String>,
pub content_boundaries: Option<bool>,
pub max_output: Option<usize>,
pub allowed_domains: Option<Vec<String>>,
pub action_policy: Option<String>,
pub confirm_actions: Option<String>,
pub confirm_interactive: Option<bool>,
pub risk_mode: Option<String>,
}
impl Config {
@@ -60,7 +54,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),
@@ -76,12 +69,7 @@ impl Config {
annotate: other.annotate.or(self.annotate),
color_scheme: other.color_scheme.or(self.color_scheme),
download_path: other.download_path.or(self.download_path),
content_boundaries: other.content_boundaries.or(self.content_boundaries),
max_output: other.max_output.or(self.max_output),
allowed_domains: other.allowed_domains.or(self.allowed_domains),
action_policy: other.action_policy.or(self.action_policy),
confirm_actions: other.confirm_actions.or(self.confirm_actions),
confirm_interactive: other.confirm_interactive.or(self.confirm_interactive),
risk_mode: other.risk_mode.or(self.risk_mode),
}
}
}
@@ -128,11 +116,6 @@ fn parse_bool_arg(args: &[String], i: usize) -> (bool, bool) {
/// Extract --config <path> from args before full flag parsing.
/// Returns `Some(Some(path))` if --config <path> found, `Some(None)` if --config
/// was the last arg with no value, `None` if --config not present.
///
/// Only flags that consume a following argument need to be listed here.
/// Boolean flags (--content-boundaries, --confirm-interactive, etc.) are
/// intentionally absent -- they don't take a value, so they can't cause
/// the next argument to be mis-consumed.
fn extract_config_path(args: &[String]) -> Option<Option<String>> {
const FLAGS_WITH_VALUE: &[&str] = &[
"--session",
@@ -151,11 +134,9 @@ fn extract_config_path(args: &[String]) -> Option<Option<String>> {
"--device",
"--session-name",
"--color-scheme",
"--channel",
"--download-path",
"--max-output",
"--allowed-domains",
"--action-policy",
"--confirm-actions",
"--risk-mode",
];
let mut i = 0;
while i < args.len() {
@@ -180,8 +161,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));
@@ -213,7 +193,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>,
@@ -228,18 +207,14 @@ pub struct Flags {
pub annotate: bool,
pub color_scheme: Option<String>,
pub download_path: Option<String>,
pub content_boundaries: bool,
pub max_output: Option<usize>,
pub allowed_domains: Option<Vec<String>>,
pub action_policy: Option<String>,
pub confirm_actions: Option<String>,
pub confirm_interactive: bool,
/// How verification/captcha detections are handled on navigation:
/// `off` (disable), `warn` (retry and warn), `block` (fail fast).
pub risk_mode: Option<String>,
// Track which launch-time options were explicitly passed via CLI
// (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,
@@ -273,69 +248,55 @@ 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),
download_path: env::var("AGENT_BROWSER_DOWNLOAD_PATH").ok()
.or(config.download_path),
content_boundaries: env_var_is_truthy("AGENT_BROWSER_CONTENT_BOUNDARIES")
|| config.content_boundaries.unwrap_or(false),
max_output: env::var("AGENT_BROWSER_MAX_OUTPUT").ok()
.and_then(|s| s.parse().ok())
.or(config.max_output),
allowed_domains: env::var("AGENT_BROWSER_ALLOWED_DOMAINS").ok()
.map(|s| s.split(',').map(|d| d.trim().to_lowercase()).filter(|d| !d.is_empty()).collect())
.or(config.allowed_domains),
action_policy: env::var("AGENT_BROWSER_ACTION_POLICY").ok()
.or(config.action_policy),
confirm_actions: env::var("AGENT_BROWSER_CONFIRM_ACTIONS").ok()
.or(config.confirm_actions),
confirm_interactive: env_var_is_truthy("AGENT_BROWSER_CONFIRM_INTERACTIVE")
|| config.confirm_interactive.unwrap_or(false),
risk_mode: env::var("AGENT_BROWSER_RISK_MODE")
.ok()
.or(config.risk_mode)
.map(|s| s.to_ascii_lowercase()),
cli_executable_path: false,
cli_extensions: false,
cli_profile: false,
cli_state: false,
cli_args: false,
cli_user_agent: false,
@@ -352,22 +313,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) {
@@ -401,13 +370,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());
@@ -452,13 +414,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) {
@@ -469,7 +435,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) {
@@ -481,7 +449,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) {
@@ -496,44 +466,12 @@ pub fn parse_flags(args: &[String]) -> Flags {
i += 1;
}
}
"--content-boundaries" => {
let (val, consumed) = parse_bool_arg(args, i);
flags.content_boundaries = val;
if consumed { i += 1; }
}
"--max-output" => {
"--risk-mode" => {
if let Some(s) = args.get(i + 1) {
if let Ok(n) = s.parse::<usize>() {
flags.max_output = Some(n);
}
flags.risk_mode = Some(s.to_ascii_lowercase());
i += 1;
}
}
"--allowed-domains" => {
if let Some(s) = args.get(i + 1) {
flags.allowed_domains = Some(
s.split(',').map(|d| d.trim().to_lowercase()).filter(|d| !d.is_empty()).collect()
);
i += 1;
}
}
"--action-policy" => {
if let Some(s) = args.get(i + 1) {
flags.action_policy = Some(s.clone());
i += 1;
}
}
"--confirm-actions" => {
if let Some(s) = args.get(i + 1) {
flags.confirm_actions = Some(s.clone());
i += 1;
}
}
"--confirm-interactive" => {
let (val, consumed) = parse_bool_arg(args, i);
flags.confirm_interactive = val;
if consumed { i += 1; }
}
"--config" => {
// Already handled by load_config(); skip the value
i += 1;
@@ -559,8 +497,6 @@ pub fn clean_args(args: &[String]) -> Vec<String> {
"--allow-file-access",
"--auto-connect",
"--annotate",
"--content-boundaries",
"--confirm-interactive",
];
// Global flags that always take a value (need to skip the next arg too)
const GLOBAL_FLAGS_WITH_VALUE: &[&str] = &[
@@ -569,7 +505,6 @@ pub fn clean_args(args: &[String]) -> Vec<String> {
"--executable-path",
"--cdp",
"--extension",
"--profile",
"--state",
"--proxy",
"--proxy-bypass",
@@ -581,10 +516,7 @@ pub fn clean_args(args: &[String]) -> Vec<String> {
"--session-name",
"--color-scheme",
"--download-path",
"--max-output",
"--allowed-domains",
"--action-policy",
"--confirm-actions",
"--risk-mode",
"--config",
];
@@ -756,12 +688,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"));
@@ -788,13 +714,24 @@ mod tests {
assert!(!flags.cli_download_path);
}
#[test]
fn test_parse_risk_mode_flag() {
let flags = parse_flags(&args("--risk-mode block open example.com"));
assert_eq!(flags.risk_mode.as_deref(), Some("block"));
}
#[test]
fn test_clean_args_removes_risk_mode() {
let cleaned = clean_args(&args("--risk-mode warn open example.com"));
assert_eq!(cleaned, vec!["open", "example.com"]);
}
#[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);
@@ -813,7 +750,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",
@@ -825,7 +761,8 @@ mod tests {
"allowFileAccess": true,
"cdp": "9222",
"autoConnect": true,
"headers": "{\"Auth\":\"token\"}"
"headers": "{\"Auth\":\"token\"}",
"riskMode": "block"
}"#;
let config: Config = serde_json::from_str(json).unwrap();
assert_eq!(config.headed, Some(true));
@@ -835,8 +772,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"));
@@ -849,6 +788,7 @@ mod tests {
assert_eq!(config.cdp.as_deref(), Some("9222"));
assert_eq!(config.auto_connect, Some(true));
assert_eq!(config.headers.as_deref(), Some("{\"Auth\":\"token\"}"));
assert_eq!(config.risk_mode.as_deref(), Some("block"));
}
#[test]
@@ -882,7 +822,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 {
@@ -893,7 +832,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
}
@@ -1144,7 +1082,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()
])
);
}
+178 -247
View File
@@ -17,108 +17,10 @@ use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};
use commands::{gen_id, parse_command, ParseError};
use connection::{ensure_daemon, get_socket_dir, send_command, DaemonOptions};
use connection::{ensure_daemon, get_socket_dir, send_command};
use flags::{clean_args, parse_flags};
use install::run_install;
use output::{print_command_help, print_help, print_response_with_opts, print_version, OutputOptions};
use std::path::PathBuf;
use std::process::Command as ProcessCommand;
/// Run a local auth command (auth_save/list/show/delete) via node auth-cli.js.
/// These commands don't need a browser, so we handle them directly to avoid
/// sending passwords through the daemon's Unix socket channel.
fn run_auth_cli(cmd: &serde_json::Value, json_mode: bool) -> ! {
let exe_path = env::current_exe().unwrap_or_default();
let exe_path = exe_path.canonicalize().unwrap_or(exe_path);
let exe_dir = exe_path.parent().unwrap_or(std::path::Path::new("."));
let mut script_paths = vec![
exe_dir.join("auth-cli.js"),
exe_dir.join("../dist/auth-cli.js"),
PathBuf::from("dist/auth-cli.js"),
];
if let Ok(home) = env::var("AGENT_BROWSER_HOME") {
let home_path = PathBuf::from(&home);
script_paths.insert(0, home_path.join("dist/auth-cli.js"));
script_paths.insert(1, home_path.join("auth-cli.js"));
}
let script_path = match script_paths.iter().find(|p| p.exists()) {
Some(p) => p.clone(),
None => {
if json_mode {
println!(r#"{{"success":false,"error":"auth-cli.js not found"}}"#);
} else {
eprintln!(
"{} auth-cli.js not found. Set AGENT_BROWSER_HOME or run from project directory.",
color::error_indicator()
);
}
exit(1);
}
};
let cmd_json = serde_json::to_string(cmd).unwrap_or_default();
match ProcessCommand::new("node")
.arg(&script_path)
.arg(&cmd_json)
.output()
{
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.is_empty() {
eprint!("{}", stderr);
}
let stdout = String::from_utf8_lossy(&output.stdout);
let stdout = stdout.trim();
if stdout.is_empty() {
if json_mode {
println!(r#"{{"success":false,"error":"No response from auth-cli"}}"#);
} else {
eprintln!("{} No response from auth-cli", color::error_indicator());
}
exit(1);
}
if json_mode {
println!("{}", stdout);
} else {
// Parse the JSON response and use the standard output formatter
match serde_json::from_str::<connection::Response>(stdout) {
Ok(resp) => {
let action = cmd.get("action").and_then(|v| v.as_str());
let opts = OutputOptions {
json: false,
content_boundaries: false,
max_output: None,
};
print_response_with_opts(&resp, action, &opts);
if !resp.success {
exit(1);
}
}
Err(_) => {
println!("{}", stdout);
}
}
}
exit(output.status.code().unwrap_or(0));
}
Err(e) => {
if json_mode {
println!(r#"{{"success":false,"error":"Failed to run auth-cli: {}"}}"#, e);
} else {
eprintln!("{} Failed to run auth-cli: {}", color::error_indicator(), e);
}
exit(1);
}
}
}
use output::{print_command_help, print_help, print_response, print_version};
fn parse_proxy(proxy_str: &str) -> serde_json::Value {
let Some(protocol_end) = proxy_str.find("://") else {
@@ -255,6 +157,62 @@ fn main() {
return;
}
if let Some(ref risk_mode) = flags.risk_mode {
if !matches!(risk_mode.as_str(), "off" | "warn" | "block") {
let msg = format!(
"Invalid --risk-mode value: {} (expected off, warn, or block)",
risk_mode
);
if flags.json {
println!(r#"{{"success":false,"error":"{}"}}"#, msg);
} else {
eprintln!("{} {}", color::error_indicator(), msg);
}
exit(1);
}
}
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;
@@ -273,7 +231,7 @@ fn main() {
return;
}
let mut cmd = match parse_command(&clean, &flags) {
let cmd = match parse_command(&clean, &flags) {
Ok(c) => c,
Err(e) => {
if flags.json {
@@ -296,38 +254,6 @@ fn main() {
}
};
// Handle --password-stdin for auth save
if cmd.get("action").and_then(|v| v.as_str()) == Some("auth_save") {
if cmd.get("password").is_some() {
eprintln!(
"{} Passwords on the command line may be visible in process listings and shell history. Use --password-stdin instead.",
color::warning_indicator()
);
}
if cmd.get("passwordStdin").and_then(|v| v.as_bool()).unwrap_or(false) {
let mut pass = String::new();
if std::io::stdin().read_line(&mut pass).is_err() || pass.is_empty() {
eprintln!("{} Failed to read password from stdin", color::error_indicator());
exit(1);
}
let pass = pass.trim_end_matches('\n').trim_end_matches('\r');
if pass.is_empty() {
eprintln!("{} Password from stdin is empty", color::error_indicator());
exit(1);
}
cmd["password"] = json!(pass);
cmd.as_object_mut().unwrap().remove("passwordStdin");
}
}
// Handle local auth commands without starting the daemon.
// These don't need a browser, so we avoid sending passwords through the socket.
if let Some(action) = cmd.get("action").and_then(|v| v.as_str()) {
if matches!(action, "auth_save" | "auth_list" | "auth_show" | "auth_delete") {
run_auth_cli(&cmd, flags.json);
}
}
// Validate session name before starting daemon
if let Some(ref name) = flags.session_name {
if !validation::is_valid_session_name(name) {
@@ -344,27 +270,24 @@ fn main() {
}
}
let daemon_opts = DaemonOptions {
headed: flags.headed,
executable_path: flags.executable_path.as_deref(),
extensions: &flags.extensions,
args: flags.args.as_deref(),
user_agent: flags.user_agent.as_deref(),
proxy: flags.proxy.as_deref(),
proxy_bypass: flags.proxy_bypass.as_deref(),
ignore_https_errors: flags.ignore_https_errors,
allow_file_access: flags.allow_file_access,
profile: flags.profile.as_deref(),
state: flags.state.as_deref(),
provider: flags.provider.as_deref(),
device: flags.device.as_deref(),
session_name: flags.session_name.as_deref(),
download_path: flags.download_path.as_deref(),
allowed_domains: flags.allowed_domains.as_deref(),
action_policy: flags.action_policy.as_deref(),
confirm_actions: flags.confirm_actions.as_deref(),
};
let daemon_result = match ensure_daemon(&flags.session, &daemon_opts) {
let daemon_result = match ensure_daemon(
&flags.session,
flags.headed,
flags.executable_path.as_deref(),
&flags.extensions,
flags.args.as_deref(),
flags.user_agent.as_deref(),
flags.proxy.as_deref(),
flags.proxy_bypass.as_deref(),
flags.ignore_https_errors,
flags.allow_file_access,
flags.state.as_deref(),
flags.provider.as_deref(),
flags.device.as_deref(),
flags.session_name.as_deref(),
flags.debug,
flags.download_path.as_deref(),
) {
Ok(result) => result,
Err(e) => {
if flags.json {
@@ -391,11 +314,6 @@ fn main() {
} else {
None
},
if flags.cli_profile {
Some("--profile")
} else {
None
},
if flags.cli_state {
Some("--state")
} else {
@@ -485,6 +403,8 @@ fn main() {
exit(1);
}
let mut attached_to_existing_browser = false;
// Auto-connect to existing browser
if flags.auto_connect {
let mut launch_cmd = json!({
@@ -522,6 +442,8 @@ fn main() {
}
exit(1);
}
attached_to_existing_browser = true;
}
// Connect via CDP if --cdp flag is set
@@ -612,6 +534,8 @@ fn main() {
}
exit(1);
}
attached_to_existing_browser = true;
}
// Launch with cloud provider if -p flag is set
@@ -626,38 +550,103 @@ 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 should attach to an existing browser.
// Try CDP :9333 first, then fall back to auto-connect discovery.
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();
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) {
attached_to_existing_browser = resp.success;
}
if !attached_to_existing_browser {
let mut auto_connect_cmd = json!({
"id": gen_id(),
"action": "launch",
"autoConnect": true
});
if let Some(ref cs) = flags.color_scheme {
auto_connect_cmd["colorScheme"] = json!(cs);
}
if let Ok(resp) = send_command(auto_connect_cmd, &flags.session) {
attached_to_existing_browser = resp.success;
}
}
}
if can_try_default_cdp && !attached_to_existing_browser {
let msg = "Project policy requires using your existing browser. Could not connect to CDP at localhost:9333 and auto-discovery also failed. Start Chrome with remote debugging (for example, --remote-debugging-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.download_path.is_some())
&& flags.cdp.is_none()
&& flags.provider.is_none()
&& !attached_to_existing_browser
{
let mut launch_cmd = json!({
"id": gen_id(),
@@ -674,11 +663,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));
@@ -725,22 +709,21 @@ fn main() {
launch_cmd["downloadPath"] = json!(dp);
}
if let Some(ref domains) = flags.allowed_domains {
launch_cmd["allowedDomains"] = json!(domains);
}
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 {
@@ -754,67 +737,15 @@ fn main() {
}
exit(1);
}
Ok(_) => {
// Launch succeeded
}
}
}
let output_opts = OutputOptions {
json: flags.json,
content_boundaries: flags.content_boundaries,
max_output: flags.max_output,
};
match send_command(cmd.clone(), &flags.session) {
Ok(resp) => {
let success = resp.success;
// Handle interactive confirmation
if flags.confirm_interactive {
if let Some(data) = &resp.data {
if data.get("confirmation_required").and_then(|v| v.as_bool()).unwrap_or(false) {
let desc = data.get("description").and_then(|v| v.as_str()).unwrap_or("unknown action");
let category = data.get("category").and_then(|v| v.as_str()).unwrap_or("");
let cid = data.get("confirmation_id").and_then(|v| v.as_str()).unwrap_or("");
eprintln!("[agent-browser] Action requires confirmation:");
eprintln!(" {}: {}", category, desc);
eprint!(" Allow? [y/N]: ");
let mut input = String::new();
let approved = if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
std::io::stdin().read_line(&mut input).is_ok()
&& matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
} else {
false
};
let confirm_cmd = if approved {
json!({ "id": gen_id(), "action": "confirm", "confirmationId": cid })
} else {
json!({ "id": gen_id(), "action": "deny", "confirmationId": cid })
};
match send_command(confirm_cmd, &flags.session) {
Ok(r) => {
if !approved {
eprintln!("{} Action denied", color::error_indicator());
exit(1);
}
print_response_with_opts(&r, None, &output_opts);
}
Err(e) => {
eprintln!("{} {}", color::error_indicator(), e);
exit(1);
}
}
return;
}
}
}
// Extract action for context-specific output handling
let action = cmd.get("action").and_then(|v| v.as_str());
print_response_with_opts(&resp, action, &output_opts);
print_response(&resp, flags.json, action);
if !success {
exit(1);
}
+1
View File
@@ -0,0 +1 @@
include!("main.rs");
+144 -39
View File
@@ -96,6 +96,36 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
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);
}
if let Some(risk_signals) = data.get("riskSignals").and_then(|v| v.as_array()) {
for signal in risk_signals {
let code = signal
.get("code")
.and_then(|v| v.as_str())
.unwrap_or("unknown_risk");
let source = signal.get("source").and_then(|v| v.as_str()).unwrap_or("unknown");
let evidence = signal
.get("evidence")
.and_then(|v| v.as_str())
.unwrap_or("-");
let confidence = signal.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0);
println!(
"{} risk-signal code={} source={} evidence={} confidence={:.2}",
color::warning_indicator(),
code,
source,
evidence,
confidence
);
}
}
if let Some(warnings) = data.get("warnings").and_then(|v| v.as_array()) {
for warning in warnings.iter().filter_map(|v| v.as_str()) {
println!("{} {}", color::warning_indicator(), warning);
}
}
return;
}
println!("{}", url);
@@ -113,15 +143,11 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
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);
}
@@ -404,11 +430,7 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
}
_ => {
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());
}
@@ -591,7 +613,10 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
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 {
@@ -599,7 +624,11 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
};
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;
@@ -609,13 +638,22 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
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;
}
@@ -623,7 +661,10 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
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);
@@ -633,7 +674,11 @@ pub fn print_response_with_opts(resp: &Response, action: Option<&str>, opts: &Ou
// 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;
}
@@ -747,10 +792,12 @@ Global Options:
--json Output as JSON
--session <name> Use specific session
--headers <json> Set HTTP headers (scoped to this origin)
--risk-mode <mode> Risk handling for verify/captcha pages: off, warn, block
--headed Show browser window
Examples:
agent-browser open example.com
agent-browser --risk-mode block open example.com
agent-browser open https://github.com
agent-browser open localhost:3000
agent-browser open api.example.com --headers '{"Authorization": "Bearer token"}'
@@ -876,10 +923,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
@@ -887,7 +935,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.)
@@ -1118,7 +1168,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)
@@ -1131,6 +1181,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"
@@ -1196,13 +1247,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
@@ -1219,6 +1271,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"
@@ -1608,8 +1661,8 @@ Operations:
Cookie Set Options:
--url <url> URL for the cookie (allows setting before page load)
--domain <domain> Cookie domain (e.g., ".example.com")
--path <path> Cookie path (e.g., "/api")
--domain <domain> Cookie domain (use with --path, e.g., ".example.com")
--path <path> Cookie path (use with --domain, e.g., "/api")
--httpOnly Set HttpOnly flag (prevents JavaScript access)
--secure Set Secure flag (HTTPS only)
--sameSite <Strict|Lax|None> SameSite policy
@@ -1617,6 +1670,7 @@ Cookie Set Options:
Note: If --url, --domain, and --path are all omitted, the cookie will be set
for the current page URL.
When --url is omitted, --domain and --path must be provided together.
Global Options:
--json Output as JSON
@@ -2233,10 +2287,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
@@ -2248,7 +2302,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)
@@ -2331,7 +2385,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)
@@ -2353,8 +2406,10 @@ 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: try localhost:9333 first, then auto-discovery (no managed local-launch fallback)
--color-scheme <scheme> Color scheme: dark, light, no-preference (or AGENT_BROWSER_COLOR_SCHEME)
--download-path <path> Default download directory (or AGENT_BROWSER_DOWNLOAD_PATH)
--risk-mode <mode> Verify/captcha handling: off, warn, block (or AGENT_BROWSER_RISK_MODE)
--session-name <name> Auto-save/restore session state (cookies, localStorage)
--content-boundaries Wrap page output in boundary markers (or AGENT_BROWSER_CONTENT_BOUNDARIES)
--max-output <chars> Truncate page output to N chars (or AGENT_BROWSER_MAX_OUTPUT)
@@ -2364,7 +2419,12 @@ Options:
--confirm-interactive Interactive confirmation prompts; auto-denies if stdin is not a TTY (or AGENT_BROWSER_CONFIRM_INTERACTIVE)
--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
Auto-attach existing browser (prefer CDP localhost:9333, then auto-discovery), or pass --cdp explicitly
Configuration:
agent-browser looks for agent-browser.json in these locations (lowest to highest priority):
@@ -2383,7 +2443,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)
@@ -2402,8 +2462,12 @@ 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_DOWNLOAD_PATH Default download directory for browser downloads
AGENT_BROWSER_RISK_MODE Verify/captcha handling mode (off, warn, block)
AGENT_BROWSER_DEFAULT_TIMEOUT Default Playwright timeout in ms (default: 25000)
AGENT_BROWSER_SESSION_NAME Auto-save/load state persistence name
AGENT_BROWSER_STATE_EXPIRE_DAYS Auto-delete saved states older than N days (default: 30)
@@ -2419,11 +2483,11 @@ Environment:
AGENT_BROWSER_CONFIRM_INTERACTIVE Enable interactive confirmation prompts
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
@@ -2438,7 +2502,7 @@ 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 --risk-mode block open example.com # Block on verification/captcha pages
agent-browser --session-name myapp open example.com # Auto-save/restore state
Command Chaining:
@@ -2458,6 +2522,15 @@ iOS Simulator (requires Xcode and Appium):
);
}
pub fn print_response(resp: &Response, json: bool, action: Option<&str>) {
let opts = OutputOptions {
json,
content_boundaries: false,
max_output: None,
};
print_response_with_opts(resp, action, &opts);
}
fn print_snapshot_diff(data: &serde_json::Map<String, serde_json::Value>) {
let changed = data
.get("changed")
@@ -2494,10 +2567,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())
@@ -2508,7 +2578,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",
@@ -2519,7 +2592,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())
@@ -2531,6 +2607,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);
}
}
+4 -1
View File
@@ -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
+2 -2
View File
@@ -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.
+150 -22
View File
@@ -1,11 +1,18 @@
import { pageMetadata } from "@/lib/page-metadata"
import { pageMetadata } from '@/lib/page-metadata';
export const metadata = pageMetadata("cdp-mode")
export const metadata = pageMetadata('cdp-mode');
# CDP Mode
Connect to an existing browser via Chrome DevTools Protocol:
Default behavior in this fork: when `--cdp` is omitted, agent-browser auto-attaches to an existing browser by trying `localhost:9333` first, then auto-discovery. If both fail, the command exits (no managed 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,35 @@ 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:
@@ -89,27 +125,119 @@ This enables control of:
<table>
<thead>
<tr><th>Option</th><th>Description</th></tr>
<tr>
<th>Option</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr><td><code>--session &lt;name&gt;</code></td><td>Use isolated session</td></tr>
<tr><td><code>--profile &lt;path&gt;</code></td><td>Persistent browser profile directory</td></tr>
<tr><td><code>-p &lt;provider&gt;</code></td><td>Cloud browser provider (<code>browserbase</code>, <code>browseruse</code>, <code>kernel</code>)</td></tr>
<tr><td><code>--headers &lt;json&gt;</code></td><td>HTTP headers scoped to origin</td></tr>
<tr><td><code>--executable-path</code></td><td>Custom browser executable</td></tr>
<tr><td><code>--args &lt;args&gt;</code></td><td>Browser launch args (comma-separated)</td></tr>
<tr><td><code>--user-agent &lt;ua&gt;</code></td><td>Custom User-Agent string</td></tr>
<tr><td><code>--proxy &lt;url&gt;</code></td><td>Proxy server URL</td></tr>
<tr><td><code>--proxy-bypass &lt;hosts&gt;</code></td><td>Hosts to bypass proxy</td></tr>
<tr><td><code>--json</code></td><td>JSON output for scripts</td></tr>
<tr><td><code>--full, -f</code></td><td>Full page screenshot</td></tr>
<tr><td><code>--name, -n</code></td><td>Locator name filter</td></tr>
<tr><td><code>--exact</code></td><td>Exact text match</td></tr>
<tr><td><code>--headed</code></td><td>Show browser window</td></tr>
<tr><td><code>{"--cdp <port|url>"}</code></td><td>CDP connection (port or WebSocket URL)</td></tr>
<tr><td><code>--auto-connect</code></td><td>Auto-discover and connect to running Chrome</td></tr>
<tr><td><code>--color-scheme &lt;scheme&gt;</code></td><td>Persistent color scheme (<code>dark</code>, <code>light</code>, <code>no-preference</code>)</td></tr>
<tr><td><code>--debug</code></td><td>Debug output</td></tr>
<tr>
<td>
<code>--session &lt;name&gt;</code>
</td>
<td>Use isolated session</td>
</tr>
<tr>
<td>
<code>-p &lt;provider&gt;</code>
</td>
<td>
Cloud browser provider (<code>browserbase</code>, <code>browseruse</code>,{' '}
<code>kernel</code>)
</td>
</tr>
<tr>
<td>
<code>--headers &lt;json&gt;</code>
</td>
<td>HTTP headers scoped to origin</td>
</tr>
<tr>
<td>
<code>--executable-path</code>
</td>
<td>Custom browser executable</td>
</tr>
<tr>
<td>
<code>--args &lt;args&gt;</code>
</td>
<td>Browser launch args (comma-separated)</td>
</tr>
<tr>
<td>
<code>--user-agent &lt;ua&gt;</code>
</td>
<td>Custom User-Agent string</td>
</tr>
<tr>
<td>
<code>--proxy &lt;url&gt;</code>
</td>
<td>Proxy server URL</td>
</tr>
<tr>
<td>
<code>--proxy-bypass &lt;hosts&gt;</code>
</td>
<td>Hosts to bypass proxy</td>
</tr>
<tr>
<td>
<code>--json</code>
</td>
<td>JSON output for scripts</td>
</tr>
<tr>
<td>
<code>--full, -f</code>
</td>
<td>Full page screenshot</td>
</tr>
<tr>
<td>
<code>--name, -n</code>
</td>
<td>Locator name filter</td>
</tr>
<tr>
<td>
<code>--exact</code>
</td>
<td>Exact text match</td>
</tr>
<tr>
<td>
<code>--headed</code>
</td>
<td>Show browser window</td>
</tr>
<tr>
<td>
<code>{'--cdp <port|url>'}</code>
</td>
<td>CDP connection (port or WebSocket URL)</td>
</tr>
<tr>
<td>
<code>--auto-connect</code>
</td>
<td>Auto-discover and connect to running Chrome</td>
</tr>
<tr>
<td>
<code>--color-scheme &lt;scheme&gt;</code>
</td>
<td>
Persistent color scheme (<code>dark</code>, <code>light</code>, <code>no-preference</code>)
</td>
</tr>
<tr>
<td>
<code>--debug</code>
</td>
<td>Debug output</td>
</tr>
</tbody>
</table>
+33 -58
View File
@@ -1,6 +1,6 @@
import { pageMetadata } from "@/lib/page-metadata"
import { pageMetadata } from '@/lib/page-metadata';
export const metadata = pageMetadata("commands")
export const metadata = pageMetadata('commands');
# Commands
@@ -8,12 +8,13 @@ export const metadata = pageMetadata("commands")
```bash
agent-browser open <url> # Navigate (aliases: goto, navigate)
agent-browser --risk-mode block open <url> # Block when verification/captcha interstitial is detected
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 +33,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 +103,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
@@ -102,6 +111,16 @@ agent-browser wait --fn "condition" # Wait for JS condition
agent-browser wait --download [path] # Wait for download
```
## Risk Mode
Control how `open`/`navigate` handles verification or captcha interstitials:
```bash
agent-browser --risk-mode warn open https://example.com # default: retry and warn with riskSignals
agent-browser --risk-mode block open https://example.com # fail fast on detection
agent-browser --risk-mode off open https://example.com # disable detection/retry
```
## Downloads
```bash
@@ -153,6 +172,14 @@ agent-browser storage local clear # Clear all
agent-browser storage session # Same for sessionStorage
```
For `cookies set`, use one of these patterns:
- `--url <url>`
- `--domain <domain> --path <path>`
- omit all three to scope from the current page URL
When `--url` is omitted, `--domain` and `--path` must be provided together.
## Network
```bash
@@ -201,49 +228,6 @@ agent-browser errors --clear # Clear error log
agent-browser highlight <sel> # Highlight element
```
## Auth vault
```bash
agent-browser auth save <name> [opts] # Save auth profile
agent-browser auth login <name> # Login using saved credentials
agent-browser auth list # List saved profiles (names and URLs only)
agent-browser auth show <name> # Show profile metadata (no passwords)
agent-browser auth delete <name> # Delete a saved profile
```
Save options:
- `--url <url>` -- login page URL (required)
- `--username <user>` -- username (required)
- `--password <pass>` -- password (required unless `--password-stdin`)
- `--password-stdin` -- read password from stdin (recommended to avoid shell history exposure)
- `--username-selector <sel>` -- custom CSS selector for username field
- `--password-selector <sel>` -- custom CSS selector for password field
- `--submit-selector <sel>` -- custom CSS selector for submit button
```bash
echo "pass" | agent-browser auth save github --url https://github.com/login --username user --password-stdin
agent-browser auth login github
agent-browser auth list
```
## Confirmation
When `--confirm-actions` is set, certain action categories return a `confirmation_required` response instead of executing immediately. Use `confirm` or `deny` to approve or reject the action.
```bash
agent-browser confirm <confirmation-id> # Approve a pending action
agent-browser deny <confirmation-id> # Deny a pending action
```
Pending confirmations auto-deny after 60 seconds.
```bash
agent-browser --confirm-actions eval,download eval "document.title"
# Returns confirmation_required with ID
agent-browser confirm c_8f3a1234
```
## State management
```bash
@@ -277,7 +261,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
@@ -288,6 +271,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)
@@ -296,16 +280,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
--color-scheme <scheme> # Color scheme: dark, light, no-preference
--download-path <path> # Default download directory
--content-boundaries # Wrap page output in boundary markers for LLM safety
--max-output <chars> # Truncate page output to N characters
--allowed-domains <list> # Comma-separated allowed domain patterns
--action-policy <path> # Path to action policy JSON file
--confirm-actions <list> # Action categories requiring confirmation
--confirm-interactive # Interactive confirmation prompts (auto-denies if stdin is not a TTY)
--config <path> # Use a custom config file
--debug # Debug output
--debug # Debug output (includes stealth connection type + capabilities)
```
## Command chaining
+372 -70
View File
@@ -1,24 +1,52 @@
import { pageMetadata } from "@/lib/page-metadata"
import { pageMetadata } from '@/lib/page-metadata';
export const metadata = pageMetadata("configuration")
export const metadata = pageMetadata('configuration');
# Configuration
Create an `agent-browser.json` file to set persistent defaults instead of repeating flags on every command.
In this fork, default launch behavior auto-attaches to an existing browser by trying `localhost:9333` (CDP) first, then auto-discovery. If both fail, commands exit instead of launching a managed browser.
## Config File Locations
agent-browser checks two locations, merged in priority order:
<table>
<thead>
<tr><th>Priority</th><th>Location</th><th>Scope</th></tr>
<tr>
<th>Priority</th>
<th>Location</th>
<th>Scope</th>
</tr>
</thead>
<tbody>
<tr><td>1 (lowest)</td><td><code>~/.agent-browser/config.json</code></td><td>User-level defaults</td></tr>
<tr><td>2</td><td><code>./agent-browser.json</code></td><td>Project-level overrides</td></tr>
<tr><td>3</td><td><code>AGENT_BROWSER_*</code> env vars</td><td>Override config values</td></tr>
<tr><td>4 (highest)</td><td>CLI flags</td><td>Override everything</td></tr>
<tr>
<td>1 (lowest)</td>
<td>
<code>~/.agent-browser/config.json</code>
</td>
<td>User-level defaults</td>
</tr>
<tr>
<td>2</td>
<td>
<code>./agent-browser.json</code>
</td>
<td>Project-level overrides</td>
</tr>
<tr>
<td>3</td>
<td>
<code>AGENT_BROWSER_*</code> env vars
</td>
<td>Override config values</td>
</tr>
<tr>
<td>4 (highest)</td>
<td>CLI flags</td>
<td>Override everything</td>
</tr>
</tbody>
</table>
@@ -37,7 +65,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
}
@@ -49,41 +76,229 @@ Every CLI flag can be set in the config file using its camelCase equivalent:
<table>
<thead>
<tr><th>Config Key</th><th>CLI Flag</th><th>Type</th></tr>
<tr>
<th>Config Key</th>
<th>CLI Flag</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr><td><code>headed</code></td><td><code>--headed</code></td><td>boolean</td></tr>
<tr><td><code>json</code></td><td><code>--json</code></td><td>boolean</td></tr>
<tr><td><code>full</code></td><td><code>--full, -f</code></td><td>boolean</td></tr>
<tr><td><code>debug</code></td><td><code>--debug</code></td><td>boolean</td></tr>
<tr><td><code>session</code></td><td><code>--session</code></td><td>string</td></tr>
<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>
<tr><td><code>args</code></td><td><code>--args</code></td><td>string</td></tr>
<tr><td><code>userAgent</code></td><td><code>--user-agent</code></td><td>string</td></tr>
<tr><td><code>provider</code></td><td><code>-p, --provider</code></td><td>string</td></tr>
<tr><td><code>device</code></td><td><code>--device</code></td><td>string</td></tr>
<tr><td><code>ignoreHttpsErrors</code></td><td><code>--ignore-https-errors</code></td><td>boolean</td></tr>
<tr><td><code>allowFileAccess</code></td><td><code>--allow-file-access</code></td><td>boolean</td></tr>
<tr><td><code>cdp</code></td><td><code>--cdp</code></td><td>string</td></tr>
<tr><td><code>autoConnect</code></td><td><code>--auto-connect</code></td><td>boolean</td></tr>
<tr><td><code>colorScheme</code></td><td><code>--color-scheme</code></td><td>string (<code>dark</code>, <code>light</code>, <code>no-preference</code>)</td></tr>
<tr><td><code>downloadPath</code></td><td><code>--download-path</code></td><td>string</td></tr>
<tr><td><code>contentBoundaries</code></td><td><code>--content-boundaries</code></td><td>boolean</td></tr>
<tr><td><code>maxOutput</code></td><td><code>--max-output</code></td><td>number</td></tr>
<tr><td><code>allowedDomains</code></td><td><code>--allowed-domains</code></td><td>string[]</td></tr>
<tr><td><code>actionPolicy</code></td><td><code>--action-policy</code></td><td>string</td></tr>
<tr><td><code>confirmActions</code></td><td><code>--confirm-actions</code></td><td>string</td></tr>
<tr><td><code>confirmInteractive</code></td><td><code>--confirm-interactive</code></td><td>boolean</td></tr>
<tr><td><code>headers</code></td><td><code>--headers</code></td><td>string (JSON)</td></tr>
<tr>
<td>
<code>headed</code>
</td>
<td>
<code>--headed</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>json</code>
</td>
<td>
<code>--json</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>full</code>
</td>
<td>
<code>--full, -f</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>debug</code>
</td>
<td>
<code>--debug</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>session</code>
</td>
<td>
<code>--session</code>
</td>
<td>string</td>
</tr>
<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>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>
<tr>
<td>
<code>args</code>
</td>
<td>
<code>--args</code>
</td>
<td>string</td>
</tr>
<tr>
<td>
<code>userAgent</code>
</td>
<td>
<code>--user-agent</code>
</td>
<td>string</td>
</tr>
<tr>
<td>
<code>provider</code>
</td>
<td>
<code>-p, --provider</code>
</td>
<td>string</td>
</tr>
<tr>
<td>
<code>device</code>
</td>
<td>
<code>--device</code>
</td>
<td>string</td>
</tr>
<tr>
<td>
<code>ignoreHttpsErrors</code>
</td>
<td>
<code>--ignore-https-errors</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>allowFileAccess</code>
</td>
<td>
<code>--allow-file-access</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>cdp</code>
</td>
<td>
<code>--cdp</code>
</td>
<td>string</td>
</tr>
<tr>
<td>
<code>autoConnect</code>
</td>
<td>
<code>--auto-connect</code>
</td>
<td>boolean</td>
</tr>
<tr>
<td>
<code>colorScheme</code>
</td>
<td>
<code>--color-scheme</code>
</td>
<td>
string (<code>dark</code>, <code>light</code>, <code>no-preference</code>)
</td>
</tr>
<tr>
<td>
<code>downloadPath</code>
</td>
<td>
<code>--download-path</code>
</td>
<td>string</td>
</tr>
<tr>
<td>
<code>riskMode</code>
</td>
<td>
<code>--risk-mode</code>
</td>
<td>
string (<code>off</code>, <code>warn</code>, <code>block</code>)
</td>
</tr>
<tr>
<td>
<code>headers</code>
</td>
<td>
<code>--headers</code>
</td>
<td>string (JSON)</td>
</tr>
</tbody>
</table>
`riskMode` defaults to `warn` when unset.
## Common Configurations
### Local Development
@@ -91,7 +306,7 @@ Every CLI flag can be set in the config file using its camelCase equivalent:
```json
{
"headed": true,
"profile": "./browser-data"
"sessionName": "local-dev"
}
```
@@ -123,17 +338,6 @@ Every CLI flag can be set in the config file using its camelCase equivalent:
}
```
### AI Agent Security
```json
{
"contentBoundaries": true,
"maxOutput": 50000,
"allowedDomains": ["your-app.com", "*.your-app.com"],
"actionPolicy": "./policy.json"
}
```
## Overriding Boolean Options
Boolean flags accept an optional `true`/`false` value to override config settings:
@@ -149,7 +353,7 @@ agent-browser --headed open example.com # same as --headed true
agent-browser --headed true open example.com # explicit
```
This applies to all boolean flags: `--headed`, `--debug`, `--json`, `--ignore-https-errors`, `--allow-file-access`, `--auto-connect`, `--content-boundaries`, `--confirm-interactive`.
This applies to all boolean flags: `--headed`, `--debug`, `--json`, `--ignore-https-errors`, `--allow-file-access`, `--auto-connect`.
## Extensions Merging
@@ -163,27 +367,125 @@ These environment variables configure additional daemon and runtime behavior:
<table>
<thead>
<tr><th>Variable</th><th>Description</th><th>Default</th></tr>
<tr>
<th>Variable</th>
<th>Description</th>
<th>Default</th>
</tr>
</thead>
<tbody>
<tr><td><code>AGENT_BROWSER_AUTO_CONNECT</code></td><td>Auto-discover and connect to a running Chrome instance.</td><td>(disabled)</td></tr>
<tr><td><code>AGENT_BROWSER_ALLOW_FILE_ACCESS</code></td><td>Allow <code>file://</code> URLs to access local files.</td><td>(disabled)</td></tr>
<tr><td><code>AGENT_BROWSER_COLOR_SCHEME</code></td><td>Color scheme preference (<code>dark</code>, <code>light</code>, <code>no-preference</code>).</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_DOWNLOAD_PATH</code></td><td>Default directory for browser downloads.</td><td>(temp directory)</td></tr>
<tr><td><code>AGENT_BROWSER_DEFAULT_TIMEOUT</code></td><td>Default Playwright timeout in ms. Keep below 30000 to avoid IPC timeouts.</td><td><code>25000</code></td></tr>
<tr><td><code>AGENT_BROWSER_SESSION_NAME</code></td><td>Auto-save/load state persistence name.</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_STATE_EXPIRE_DAYS</code></td><td>Auto-delete saved session states older than N days.</td><td><code>30</code></td></tr>
<tr><td><code>AGENT_BROWSER_ENCRYPTION_KEY</code></td><td>64-char hex key for AES-256-GCM session encryption.</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_STREAM_PORT</code></td><td>Enable WebSocket streaming on the specified port (e.g., <code>9223</code>).</td><td>(disabled)</td></tr>
<tr><td><code>AGENT_BROWSER_IOS_DEVICE</code></td><td>Default iOS device name for the <code>ios</code> provider.</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_IOS_UDID</code></td><td>Default iOS device UDID for the <code>ios</code> provider.</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_DEBUG</code></td><td>Enable debug output (<code>1</code> to enable).</td><td>(disabled)</td></tr>
<tr><td><code>AGENT_BROWSER_CONTENT_BOUNDARIES</code></td><td>Wrap page output in boundary markers for LLM safety.</td><td>(disabled)</td></tr>
<tr><td><code>AGENT_BROWSER_MAX_OUTPUT</code></td><td>Max characters for page output (truncates beyond limit).</td><td>(unlimited)</td></tr>
<tr><td><code>AGENT_BROWSER_ALLOWED_DOMAINS</code></td><td>Comma-separated allowed domain patterns (e.g., <code>example.com,*.example.com</code>).</td><td>(unrestricted)</td></tr>
<tr><td><code>AGENT_BROWSER_ACTION_POLICY</code></td><td>Path to action policy JSON file.</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_CONFIRM_ACTIONS</code></td><td>Comma-separated action categories requiring confirmation.</td><td>(none)</td></tr>
<tr><td><code>AGENT_BROWSER_CONFIRM_INTERACTIVE</code></td><td>Enable interactive confirmation prompts (auto-denies if stdin is not a TTY).</td><td>(disabled)</td></tr>
<tr>
<td>
<code>AGENT_BROWSER_AUTO_CONNECT</code>
</td>
<td>Auto-discover and connect to a running Chrome instance.</td>
<td>(disabled)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_ALLOW_FILE_ACCESS</code>
</td>
<td>
Allow <code>file://</code> URLs to access local files.
</td>
<td>(disabled)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_COLOR_SCHEME</code>
</td>
<td>
Color scheme preference (<code>dark</code>, <code>light</code>, <code>no-preference</code>).
</td>
<td>(none)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_DOWNLOAD_PATH</code>
</td>
<td>Default directory for browser downloads.</td>
<td>(temp directory)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_RISK_MODE</code>
</td>
<td>
Verification/captcha handling mode (<code>off</code>, <code>warn</code>, <code>block</code>
).
</td>
<td>
<code>warn</code>
</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_DEFAULT_TIMEOUT</code>
</td>
<td>Default Playwright timeout in ms. Keep below 30000 to avoid IPC timeouts.</td>
<td>
<code>25000</code>
</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_SESSION_NAME</code>
</td>
<td>Auto-save/load state persistence name.</td>
<td>(none)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_STATE_EXPIRE_DAYS</code>
</td>
<td>Auto-delete saved session states older than N days.</td>
<td>
<code>30</code>
</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_ENCRYPTION_KEY</code>
</td>
<td>64-char hex key for AES-256-GCM session encryption.</td>
<td>(none)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_STREAM_PORT</code>
</td>
<td>
Enable WebSocket streaming on the specified port (e.g., <code>9223</code>).
</td>
<td>(disabled)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_IOS_DEVICE</code>
</td>
<td>
Default iOS device name for the <code>ios</code> provider.
</td>
<td>(none)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_IOS_UDID</code>
</td>
<td>
Default iOS device UDID for the <code>ios</code> provider.
</td>
<td>(none)</td>
</tr>
<tr>
<td>
<code>AGENT_BROWSER_DEBUG</code>
</td>
<td>
Enable debug output (<code>1</code> to enable).
</td>
<td>(disabled)</td>
</tr>
</tbody>
</table>
+18 -9
View File
@@ -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.
+4 -2
View File
@@ -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
-23
View File
@@ -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:
+1 -1
View File
@@ -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 });
+2 -2
View File
@@ -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="flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-900 transition-colors dark:text-neutral-400 dark:hover:text-neutral-100"
@@ -69,7 +69,7 @@ export function Header() {
<span>16k</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="text-sm text-neutral-500 hover:text-neutral-900 transition-colors dark:text-neutral-400 dark:hover:text-neutral-100"
+15 -7
View File
@@ -1,7 +1,7 @@
{
"name": "agent-browser",
"version": "0.15.2",
"description": "Headless browser automation CLI for AI agents",
"name": "agent-browser-stealth",
"version": "0.15.2-fork.0",
"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": {
@@ -34,14 +35,21 @@
"test:watch": "vitest",
"test:e2e:dogfood": "vitest run test/e2e/dogfood.eval.ts",
"postinstall": "node scripts/postinstall.js",
"verify:native-version": "node scripts/verify-native-version.js",
"clawhub:sync": "bash scripts/clawhub-sync.sh",
"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"
"ci:publish": "pnpm run version:sync && pnpm run build && pnpm run build:native && pnpm run verify:native-version && changeset publish"
},
"keywords": [
"browser",
"automation",
"headless",
"stealth",
"anti-bot",
"anti-detection",
"playwright",
"cli",
"agent"
@@ -49,12 +57,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",
+137
View File
@@ -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();
+112
View File
@@ -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();
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT_DIR"
SKILL_NAME="agent-browser-stealth"
if ! command -v pnpm >/dev/null 2>&1; then
echo "pnpm is required for ClawHub sync"
exit 1
fi
if [ ! -f "skills/${SKILL_NAME}/SKILL.md" ]; then
echo "Missing skill file: skills/${SKILL_NAME}/SKILL.md"
exit 1
fi
# Sync only this fork-owned skill to avoid permission errors on other skills.
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
mkdir -p "$TMP_DIR/skills"
cp -R "skills/${SKILL_NAME}" "$TMP_DIR/skills/${SKILL_NAME}"
echo "Syncing local skill '${SKILL_NAME}' to ClawHub..."
cd "$TMP_DIR"
pnpm dlx clawhub@latest sync --all --root ./skills
echo "ClawHub sync completed."
+83 -43
View File
@@ -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)');
}
}
+142
View File
@@ -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
View File
@@ -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",
});
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env node
/**
* Verifies that the bundled native binary version matches package.json version.
* This prevents publishing npm tarballs where package version and native binary
* version drift (e.g. package is fork.8 but binary still reports fork.7).
*/
import { existsSync, readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { arch, platform } from 'os';
import { execFileSync } from 'child_process';
const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = join(__dirname, '..');
const pkg = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
const expectedVersion = pkg.version;
const ext = platform() === 'win32' ? '.exe' : '';
const platformBinary = join(projectRoot, 'bin', `agent-browser-${platform()}-${arch()}${ext}`);
if (!existsSync(platformBinary)) {
console.error(`Error: native binary not found for current platform: ${platformBinary}`);
console.error('Run `pnpm run build:native` before publishing.');
process.exit(1);
}
let versionOutput = '';
try {
versionOutput = execFileSync(platformBinary, ['--version'], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
}).trim();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Error: failed to execute native binary --version: ${message}`);
process.exit(1);
}
if (!versionOutput.includes(expectedVersion)) {
console.error(`Version mismatch: package.json=${expectedVersion}, native='${versionOutput}'.`);
console.error('Run `pnpm run build:native` and retry publishing.');
process.exit(1);
}
console.log(`✓ Native binary version matches package.json (${expectedVersion})`);
+127
View File
@@ -0,0 +1,127 @@
---
name: agent-browser-stealth
description: Stealth-first browser automation for OpenClaw using agent-browser-stealth. Use when tasks involve bot-protected websites, anti-fingerprint evasion, captcha-prone flows, login persistence, region-sensitive targets (e.g., Shopee/TikTok/e-commerce), or any request to automate web actions with lower detection risk.
homepage: https://github.com/leeguooooo/agent-browser
---
# agent-browser-stealth for OpenClaw
Use this skill when the task needs web automation and anti-bot stability.
## What this skill prioritizes
- Use `agent-browser` CLI from `agent-browser-stealth` package
- Prefer stealth-safe interaction patterns over brittle one-shot scripts
- Keep command flow deterministic: `open -> snapshot -> act -> re-snapshot`
- Minimize bot signals with humanized pacing and stable session reuse
## Install and baseline
```bash
pnpm add -g agent-browser-stealth
agent-browser install
agent-browser --version
```
If default CDP mode is used in your environment, the CLI first tries `localhost:9333` and then auto-discovery. You can still pass `--cdp` / `--auto-connect` explicitly when needed.
## Standard execution workflow
```bash
agent-browser open <url>
agent-browser wait --load networkidle
agent-browser snapshot -i
# choose refs (@e1, @e2, ...)
agent-browser click @eN
agent-browser fill @eM "..."
agent-browser snapshot -i
```
Use refs (`@e1`) from snapshot output whenever possible.
## Anti-bot operating rules
1. Prefer headed mode for sensitive targets:
```bash
agent-browser --headed --session-name shop open https://example.com
```
2. Reuse session state to avoid repeated cold-start fingerprints:
```bash
agent-browser --session-name shop open https://example.com
```
3. Keep interactions human-like:
```bash
agent-browser type @e2 "query" --delay 120
agent-browser wait 1200-2600
```
4. For contenteditable editors, use keyboard mode:
```bash
agent-browser click "[contenteditable='true']"
agent-browser keyboard type "Hello world" --delay 90
```
5. If text must literally include `--delay`, stop arg parsing with `--`:
```bash
agent-browser type @e2 -- "--delay 120"
agent-browser keyboard type -- "--delay 120"
```
## Region-sensitive websites
For region-bound sites, open target domain directly and let locale/timezone alignment apply.
```bash
agent-browser open https://shopee.tw
```
Only override locale/timezone when explicitly required by the task.
## Recovery patterns
If blocked or unstable:
1. Retry with `--headed`.
2. Reuse `--session-name`.
3. Slow down action cadence (`wait`, `type --delay`).
4. Re-open page and regenerate refs with `snapshot -i`.
## Minimal recipes
Login flow:
```bash
agent-browser --session-name account open https://example.com/login
agent-browser snapshot -i
agent-browser fill @e1 "$USERNAME"
agent-browser fill @e2 "$PASSWORD"
agent-browser click @e3
agent-browser wait --url "**/dashboard"
```
Search and capture:
```bash
agent-browser open https://example.com
agent-browser snapshot -i
agent-browser type @e2 "iphone" --delay 120
agent-browser press Enter
agent-browser wait --load networkidle
agent-browser screenshot result.png
```
## Output expectations for OpenClaw
When using this skill, return:
- Exact commands executed
- Key page state changes (URL/title/important element text)
- Any anti-bot signal encountered and mitigation used
- Next safe action
+98 -19
View File
@@ -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: `pnpm add -g agent-browser-stealth` (CLI command remains `agent-browser` for compatibility). If global install is unavailable in your environment, use `pnpm dlx agent-browser-stealth <command>` for one-off runs.
## Core Workflow
Every browser automation follows this pattern:
@@ -49,7 +51,9 @@ agent-browser open https://example.com && agent-browser wait --load networkidle
```bash
# Navigation
agent-browser open <url> # Navigate (aliases: goto, navigate)
agent-browser --risk-mode block open <url> # Block if verification/captcha interstitial is detected
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 +64,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
agent-browser scroll down 500 --selector "div.content" # Scroll within a specific container
@@ -79,6 +83,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
# Downloads
agent-browser download @e1 ./file.pdf # Click element to trigger download
@@ -148,6 +153,20 @@ agent-browser state load auth.json
agent-browser open https://app.example.com/dashboard
```
### Cookie Injection for Auth Callbacks
```bash
# Before navigation: set by URL
agent-browser cookies set session_id "abc123" --url https://app.example.com/api/auth/sso/callback
# Explicit domain/path pair (must be provided together)
agent-browser cookies set auth_token "xyz789" --domain .example.com --path /api
# Or navigate first and rely on current URL
agent-browser open https://app.example.com/api/auth/sso/callback
agent-browser cookies set callback_token "token123"
```
### Session Persistence
```bash
@@ -197,6 +216,12 @@ agent-browser session list
### Connect to Existing Chrome
By default in this fork, commands without `--cdp` auto-attach to your existing browser with this order:
1. Try CDP at `localhost:9333`
2. If unavailable, fall back to `--auto-connect`-style discovery
3. If both fail, exit with guidance (no automatic managed local browser launch on this path)
```bash
# Auto-discover running Chrome with remote debugging enabled
agent-browser --auto-connect open https://example.com
@@ -204,6 +229,9 @@ agent-browser --auto-connect snapshot
# Or with explicit CDP port
agent-browser --cdp 9222 snapshot
# Debug auto-attach behavior
agent-browser --debug snapshot
```
### Color Scheme (Dark Mode)
@@ -238,6 +266,42 @@ 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 attach path: CDP `localhost:9333` then auto-discovery) 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, behavior is controlled by `--risk-mode` (or `AGENT_BROWSER_RISK_MODE`):
- `warn` (default): retry up to 2 times with randomized backoff (3-7s), then return warning plus structured `riskSignals`
- `block`: fail fast once a risk interstitial is detected
- `off`: disable this detection/retry path
Examples:
```bash
agent-browser --risk-mode warn open https://example.com
agent-browser --risk-mode block open https://example.com
AGENT_BROWSER_RISK_MODE=off agent-browser open https://example.com
```
### iOS Simulator (Mobile Safari)
```bash
@@ -300,8 +364,9 @@ export AGENT_BROWSER_ACTION_POLICY=./policy.json
```
Example `policy.json`:
```json
{"default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"]}
{ "default": "deny", "allow": ["navigate", "snapshot", "click", "scroll", "wait", "get"] }
```
Auth vault operations (`auth login`, etc.) bypass action policy but domain allowlist still applies.
@@ -359,10 +424,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:
@@ -413,6 +491,7 @@ agent-browser click @e2 # Click using ref from annotated screenshot
```
Use annotated screenshots when:
- The page has unlabeled icon buttons or visual-only elements
- You need to verify visual layout or styling
- Canvas or chart elements are present (invisible to text snapshots)
@@ -455,6 +534,7 @@ agent-browser eval -b "$(echo -n 'Array.from(document.querySelectorAll("a")).map
**Why this matters:** When the shell processes your command, inner double quotes, `!` characters (history expansion), backticks, and `$()` can all corrupt the JavaScript before it reaches agent-browser. The `--stdin` and `-b` flags bypass shell interpretation entirely.
**Rules of thumb:**
- Single-line, no nested quotes -> regular `eval 'expression'` with single quotes is fine
- Nested quotes, arrow functions, template literals, or multiline -> use `eval --stdin <<'EVALEOF'`
- Programmatic/generated scripts -> use `eval -b` with base64
@@ -466,8 +546,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"
}
```
@@ -475,23 +554,23 @@ Priority (lowest to highest): `~/.agent-browser/config.json` < `./agent-browser.
## Deep-Dive Documentation
| Reference | When to Use |
|-----------|-------------|
| [references/commands.md](references/commands.md) | Full command reference with all options |
| [references/snapshot-refs.md](references/snapshot-refs.md) | Ref lifecycle, invalidation rules, troubleshooting |
| Reference | When to Use |
| -------------------------------------------------------------------- | --------------------------------------------------------- |
| [references/commands.md](references/commands.md) | Full command reference with all options |
| [references/snapshot-refs.md](references/snapshot-refs.md) | Ref lifecycle, invalidation rules, troubleshooting |
| [references/session-management.md](references/session-management.md) | Parallel sessions, state persistence, concurrent scraping |
| [references/authentication.md](references/authentication.md) | Login flows, OAuth, 2FA handling, state reuse |
| [references/video-recording.md](references/video-recording.md) | Recording workflows for debugging and documentation |
| [references/profiling.md](references/profiling.md) | Chrome DevTools profiling for performance analysis |
| [references/proxy-support.md](references/proxy-support.md) | Proxy configuration, geo-testing, rotating proxies |
| [references/authentication.md](references/authentication.md) | Login flows, OAuth, 2FA handling, state reuse |
| [references/video-recording.md](references/video-recording.md) | Recording workflows for debugging and documentation |
| [references/profiling.md](references/profiling.md) | Chrome DevTools profiling for performance analysis |
| [references/proxy-support.md](references/proxy-support.md) | Proxy configuration, geo-testing, rotating proxies |
## Ready-to-Use Templates
| Template | Description |
|----------|-------------|
| [templates/form-automation.sh](templates/form-automation.sh) | Form filling with validation |
| [templates/authenticated-session.sh](templates/authenticated-session.sh) | Login once, reuse state |
| [templates/capture-workflow.sh](templates/capture-workflow.sh) | Content extraction with screenshots |
| Template | Description |
| ------------------------------------------------------------------------ | ----------------------------------- |
| [templates/form-automation.sh](templates/form-automation.sh) | Form filling with validation |
| [templates/authenticated-session.sh](templates/authenticated-session.sh) | Login once, reuse state |
| [templates/capture-workflow.sh](templates/capture-workflow.sh) | Content extraction with screenshots |
```bash
./templates/form-automation.sh https://example.com/form
+20 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { toAIFriendlyError } from './actions.js';
import { detectRiskSignals, toAIFriendlyError } from './actions.js';
describe('toAIFriendlyError', () => {
describe('element blocked by overlay', () => {
@@ -37,3 +37,22 @@ describe('toAIFriendlyError', () => {
});
});
});
describe('detectRiskSignals', () => {
it('should detect verification patterns from URL and title', () => {
const signals = detectRiskSignals(
'https://example.com/verify/captcha?scene=anti_bot',
'Just a moment...'
);
expect(signals.length).toBeGreaterThan(0);
expect(signals.some((s) => s.source === 'url' && s.code === 'captcha_interstitial')).toBe(true);
expect(
signals.some((s) => s.source === 'title' && s.code === 'verification_interstitial')
).toBe(true);
});
it('should return empty array for normal pages', () => {
const signals = detectRiskSignals('https://example.com/dashboard', 'Dashboard');
expect(signals).toEqual([]);
});
});
+482 -523
View File
File diff suppressed because it is too large Load Diff
+273 -6
View File
@@ -9,11 +9,11 @@ describe('BrowserManager', () => {
beforeAll(async () => {
browser = new BrowserManager();
await browser.launch({ headless: true });
});
}, 30000);
afterAll(async () => {
await browser.close();
});
}, 30000);
describe('launch and close', () => {
it('should report as launched', () => {
@@ -53,6 +53,213 @@ describe('BrowserManager', () => {
expect(newBrowser.getBrowser()).toBeNull();
await newBrowser.close();
});
it('should switch from local session when auto-connect is explicitly requested', async () => {
const testBrowser = new BrowserManager();
await testBrowser.launch({ id: 'test', action: 'launch', headless: true });
const closeSpy = vi.spyOn(testBrowser, 'close');
const autoConnectSpy = vi
.spyOn(testBrowser as any, 'autoConnectViaCDP')
.mockResolvedValue(undefined);
await testBrowser.launch({ id: 'test', action: 'launch', autoConnect: true });
expect(closeSpy).toHaveBeenCalledTimes(1);
expect(autoConnectSpy).toHaveBeenCalledTimes(1);
autoConnectSpy.mockRestore();
closeSpy.mockRestore();
await testBrowser.close();
});
it('should not relaunch when already connected via healthy CDP and auto-connect is requested', 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 connectSpy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
const cdpBrowser = new BrowserManager();
await cdpBrowser.launch({ id: 'test', action: 'launch', cdpPort: 9222 });
expect(connectSpy).toHaveBeenCalledTimes(1);
const closeSpy = vi.spyOn(cdpBrowser, 'close');
await cdpBrowser.launch({ id: 'test', action: 'launch', autoConnect: true });
expect(closeSpy).not.toHaveBeenCalled();
expect(connectSpy).toHaveBeenCalledTimes(1);
closeSpy.mockRestore();
await cdpBrowser.close();
connectSpy.mockRestore();
});
it('should report local stealth policy capabilities', async () => {
const testBrowser = new BrowserManager();
await testBrowser.launch({ headless: 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 });
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 reject CDP endpoints with only blank pages when meaningful tabs are required', async () => {
const mockPage = { url: () => 'about:blank', on: vi.fn(), isClosed: () => false };
const mockContext = {
pages: () => [mockPage],
on: vi.fn(),
setDefaultTimeout: vi.fn(),
addInitScript: vi.fn().mockResolvedValue(undefined),
};
const mockBrowser = {
contexts: () => [mockContext],
close: vi.fn().mockResolvedValue(undefined),
isConnected: vi.fn(() => true),
};
const connectSpy = vi.spyOn(chromium, 'connectOverCDP').mockResolvedValue(mockBrowser as any);
const cdpBrowser = new BrowserManager();
await expect(
(cdpBrowser as any).connectViaCDP('9222', {
allowCreatePageFallback: false,
requireMeaningfulPage: true,
})
).rejects.toThrow('No existing user tabs found on this CDP endpoint.');
expect(mockBrowser.close).toHaveBeenCalledTimes(1);
connectSpy.mockRestore();
});
it('should skip auto-connect candidates without user tabs and continue discovery', async () => {
const cdpBrowser = new BrowserManager();
const dirsSpy = vi
.spyOn(cdpBrowser as any, 'getChromeUserDataDirs')
.mockReturnValue(['/tmp/chrome-a', '/tmp/chrome-b']);
const activePortSpy = vi.spyOn(cdpBrowser as any, 'readDevToolsActivePort');
activePortSpy
.mockReturnValueOnce({ port: 9222, wsPath: '/devtools/browser/a' })
.mockReturnValueOnce({ port: 9333, wsPath: '/devtools/browser/b' });
const probeSpy = vi.spyOn(cdpBrowser as any, 'probeDebugPort');
probeSpy
.mockResolvedValueOnce('ws://127.0.0.1:9222/devtools/browser/a')
.mockResolvedValueOnce('ws://127.0.0.1:9333/devtools/browser/b');
const connectViaCDPSpy = vi.spyOn(cdpBrowser as any, 'connectViaCDP');
connectViaCDPSpy
.mockRejectedValueOnce(new Error('No existing user tabs found on this CDP endpoint.'))
.mockResolvedValueOnce(undefined);
await (cdpBrowser as any).autoConnectViaCDP();
expect(connectViaCDPSpy).toHaveBeenCalledTimes(2);
expect(connectViaCDPSpy.mock.calls[0][1]).toMatchObject({
allowCreatePageFallback: false,
requireMeaningfulPage: true,
});
expect(connectViaCDPSpy.mock.calls[1][1]).toMatchObject({
allowCreatePageFallback: false,
requireMeaningfulPage: true,
});
dirsSpy.mockRestore();
activePortSpy.mockRestore();
probeSpy.mockRestore();
connectViaCDPSpy.mockRestore();
});
it('should prefer port 9333 before DevToolsActivePort discovery in auto-connect', async () => {
const cdpBrowser = new BrowserManager();
const probeSpy = vi.spyOn(cdpBrowser as any, 'probeDebugPort');
probeSpy.mockResolvedValueOnce('ws://127.0.0.1:9333/devtools/browser/preferred');
const connectViaCDPSpy = vi
.spyOn(cdpBrowser as any, 'connectViaCDP')
.mockResolvedValue(undefined);
const dirsSpy = vi.spyOn(cdpBrowser as any, 'getChromeUserDataDirs');
await (cdpBrowser as any).autoConnectViaCDP();
expect(probeSpy).toHaveBeenCalledWith(9333);
expect(connectViaCDPSpy).toHaveBeenCalledTimes(1);
expect(connectViaCDPSpy.mock.calls[0][0]).toContain('9333');
expect(dirsSpy).not.toHaveBeenCalled();
probeSpy.mockRestore();
connectViaCDPSpy.mockRestore();
dirsSpy.mockRestore();
});
it('should ignore legacy stealth=false and keep CDP stealth capabilities enabled', 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).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();
});
});
describe('stale session recovery (all pages closed)', () => {
@@ -878,15 +1085,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);
@@ -902,6 +1110,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', () => {
+638 -53
View File
@@ -28,6 +28,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.
@@ -90,6 +96,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
*/
@@ -117,6 +155,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;
private downloadPath: string | null = null;
private allowedDomains: string[] = [];
@@ -128,6 +172,289 @@ 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,
userAgent: this.contextUserAgent,
});
this.logStealthPolicy('init-script applied');
}
// CDP session for screencast and input injection
private cdpSession: CDPSession | null = null;
private screencastActive: boolean = false;
@@ -321,6 +648,43 @@ 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 isMeaningfulCDPPage(page: Page): boolean {
if (page.isClosed()) return false;
const url = this.getSafePageUrl(page).trim().toLowerCase();
if (!url) return false;
if (url === 'about:blank' || url.startsWith('about:blank#')) return false;
if (url === 'chrome://newtab/' || url.startsWith('chrome://newtab')) return false;
if (url === 'chrome://new-tab-page/' || url.startsWith('chrome://new-tab-page')) 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.
@@ -336,8 +700,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);
@@ -361,6 +730,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];
}
@@ -842,7 +1229,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;
}
@@ -909,6 +1296,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;
@@ -946,6 +1334,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());
@@ -1018,6 +1407,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');
@@ -1085,9 +1475,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());
}
@@ -1116,6 +1508,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');
@@ -1160,9 +1553,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());
}
@@ -1194,23 +1589,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)'
@@ -1218,7 +1602,13 @@ export class BrowserManager {
}
if (this.isLaunched()) {
// Explicit --auto-connect should switch away from managed/local/provider sessions
// so commands always target a discovered user browser.
const shouldSwitchToAutoConnect =
!!options.autoConnect &&
(this.cdpEndpoint === null || this.stealthConnectionKind !== 'cdp');
const needsRelaunch =
shouldSwitchToAutoConnect ||
(!cdpEndpoint && !options.autoConnect && this.cdpEndpoint !== null) ||
(!!cdpEndpoint && this.needsCdpReconnect(cdpEndpoint)) ||
(!!options.autoConnect && !this.isCdpConnectionAlive());
@@ -1235,6 +1625,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 (options.downloadPath) {
this.downloadPath = options.downloadPath;
@@ -1267,8 +1677,7 @@ 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;
// -p flag takes precedence over AGENT_BROWSER_PROVIDER.
if (this.downloadPath && provider) {
const warning =
"--download-path is ignored when using a cloud provider (downloads use the remote browser's configuration)";
@@ -1320,16 +1729,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
@@ -1357,10 +1795,13 @@ 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 }),
@@ -1368,33 +1809,31 @@ export class BrowserManager {
}
);
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.downloadPath && { downloadsPath: this.downloadPath }),
});
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.downloadPath && { downloadsPath: this.downloadPath }),
});
this.cdpEndpoint = null;
if (stealthPolicy.enabled && browserType === 'chromium') {
await applyBrowserLevelStealth(this.browser, {
userAgent: contextUserAgent,
});
}
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
@@ -1464,15 +1903,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);
@@ -1494,8 +1937,13 @@ export class BrowserManager {
*/
private async connectViaCDP(
cdpEndpoint: string | undefined,
options?: { timeout?: number }
options?: {
timeout?: number;
allowCreatePageFallback?: boolean;
requireMeaningfulPage?: boolean;
}
): Promise<void> {
this.stealthConnectionKind = 'cdp';
if (!cdpEndpoint) {
throw new Error('CDP endpoint is required for CDP connection');
}
@@ -1538,11 +1986,44 @@ 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);
const allowCreatePageFallback = options?.allowCreatePageFallback ?? true;
if (allPages.length === 0) {
throw new Error('No page found. Make sure the app has loaded content.');
if (!allowCreatePageFallback) {
throw new Error('No existing user tabs found on this CDP endpoint.');
}
// 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];
}
if (options?.requireMeaningfulPage) {
const meaningfulPages = allPages.filter((page) => this.isMeaningfulCDPPage(page));
if (meaningfulPages.length === 0) {
throw new Error('No existing user tabs found on this CDP endpoint.');
}
allPages = meaningfulPages;
}
// All validation passed - commit state
@@ -1550,6 +2031,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);
@@ -1649,10 +2131,39 @@ 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> {
let sawEndpointWithoutUserTabs = false;
// Strategy 0: Prefer project-default resident CDP port first.
// This keeps user + agent on the same browser session when 9333 is available.
{
const wsUrl = await this.probeDebugPort(9333);
if (wsUrl) {
try {
await this.connectViaCDP(wsUrl, {
allowCreatePageFallback: false,
requireMeaningfulPage: true,
});
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes('No existing user tabs found on this CDP endpoint')) {
sawEndpointWithoutUserTabs = true;
if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(
`[DEBUG] Skipping preferred CDP endpoint without user tabs (${wsUrl}): ${message}`
);
}
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(`[DEBUG] Failed preferred CDP candidate (${wsUrl}): ${message}`);
}
}
}
}
// Strategy 1: Check DevToolsActivePort files
const userDataDirs = this.getChromeUserDataDirs();
for (const dir of userDataDirs) {
@@ -1661,8 +2172,25 @@ export class BrowserManager {
// Try HTTP discovery first (works with --remote-debugging-port mode)
const wsUrl = await this.probeDebugPort(activePort.port);
if (wsUrl) {
await this.connectViaCDP(wsUrl);
return;
try {
await this.connectViaCDP(wsUrl, {
allowCreatePageFallback: false,
requireMeaningfulPage: true,
});
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes('No existing user tabs found on this CDP endpoint')) {
sawEndpointWithoutUserTabs = true;
if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(
`[DEBUG] Skipping CDP endpoint without user tabs (${wsUrl}): ${message}`
);
}
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(`[DEBUG] Failed CDP candidate (${wsUrl}): ${message}`);
}
}
}
// HTTP probe failed -- Chrome M144+ chrome://inspect remote debugging uses a
// WebSocket-only server with no HTTP endpoints. Connect using the WebSocket
@@ -1675,9 +2203,24 @@ export class BrowserManager {
`attempting direct WebSocket connection to ${directWsUrl}`
);
}
await this.connectViaCDP(directWsUrl, { timeout: 60_000 });
await this.connectViaCDP(directWsUrl, {
timeout: 60_000,
allowCreatePageFallback: false,
requireMeaningfulPage: true,
});
return;
} catch {
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes('No existing user tabs found on this CDP endpoint')) {
sawEndpointWithoutUserTabs = true;
if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(
`[DEBUG] Skipping CDP endpoint without user tabs (${directWsUrl}): ${message}`
);
}
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(`[DEBUG] Failed CDP candidate (${directWsUrl}): ${message}`);
}
// Direct WebSocket also failed, try next directory
}
}
@@ -1688,11 +2231,34 @@ export class BrowserManager {
for (const port of commonPorts) {
const wsUrl = await this.probeDebugPort(port);
if (wsUrl) {
await this.connectViaCDP(wsUrl);
return;
try {
await this.connectViaCDP(wsUrl, {
allowCreatePageFallback: false,
requireMeaningfulPage: true,
});
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes('No existing user tabs found on this CDP endpoint')) {
sawEndpointWithoutUserTabs = true;
if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(
`[DEBUG] Skipping CDP endpoint without user tabs (${wsUrl}): ${message}`
);
}
} else if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error(`[DEBUG] Failed CDP candidate (${wsUrl}): ${message}`);
}
}
}
}
if (sawEndpointWithoutUserTabs) {
throw new Error(
'Found CDP endpoints, but none exposed existing user tabs. Ensure you are attaching to the same Chrome instance/profile you are using manually.'
);
}
// Nothing found
const platform = os.platform();
let hint: string;
@@ -1740,6 +2306,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);
}
@@ -1753,6 +2322,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);
@@ -1808,8 +2382,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);
@@ -2550,6 +3129,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;
+64 -9
View File
@@ -5,7 +5,7 @@ import * as os from 'os';
import { BrowserManager } from './browser.js';
import { IOSManager } from './ios-manager.js';
import { parseCommand, serializeResponse, errorResponse } from './protocol.js';
import { executeCommand, initActionPolicy } from './actions.js';
import { executeCommand } from './actions.js';
import { executeIOSCommand } from './ios-actions.js';
import { StreamServer } from './stream-server.js';
import {
@@ -338,9 +338,6 @@ export async function startDaemon(options?: {
// Clean up expired state files on startup
runCleanupExpiredStates();
// Initialize action policy enforcement
initActionPolicy();
// Determine provider from options or environment
const provider = options?.provider ?? process.env.AGENT_BROWSER_PROVIDER;
const isIOS = provider === 'ios';
@@ -413,7 +410,8 @@ 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: attach to an existing browser only.
if (
!manager.isLaunched() &&
parseResult.command.action !== 'launch' &&
@@ -458,29 +456,86 @@ 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 attachedToExistingBrowser = false;
try {
// Keep default CDP attempt minimal. Launch-only options like extensions
// are incompatible with CDP and can cause false-negative attach failures.
const cdpLaunchOptions = {
id: launchOptions.id,
action: launchOptions.action,
cdpPort: 9333,
ignoreHTTPSErrors: launchOptions.ignoreHTTPSErrors,
colorScheme: launchOptions.colorScheme,
userAgent: launchOptions.userAgent,
};
await manager.launch({
...cdpLaunchOptions,
});
attachedToExistingBrowser = 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, trying auto-connect discovery: ${message}`
);
}
}
if (!attachedToExistingBrowser) {
try {
await manager.launch({
id: launchOptions.id,
action: launchOptions.action,
autoConnect: true,
ignoreHTTPSErrors: launchOptions.ignoreHTTPSErrors,
colorScheme: launchOptions.colorScheme,
userAgent: launchOptions.userAgent,
});
attachedToExistingBrowser = true;
if (process.env.AGENT_BROWSER_DEBUG === '1') {
console.error('[DEBUG] Auto-launch connected via auto-connect discovery');
}
} catch (error) {
if (process.env.AGENT_BROWSER_DEBUG === '1') {
const message = error instanceof Error ? error.message : String(error);
console.error(`[DEBUG] Auto-connect discovery failed: ${message}`);
}
}
}
if (!attachedToExistingBrowser) {
throw new Error(
'Project policy requires using your existing browser. Could not connect to CDP at localhost:9333 and auto-discovery also failed.'
);
}
}
}
+40
View File
@@ -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 and ignore legacy 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 as any).stealth).toBeUndefined();
}
});
});
describe('navigation', () => {
it('should parse navigate command', () => {
const result = parseCommand(cmd({ id: '1', action: 'navigate', url: 'https://example.com' }));
@@ -31,11 +44,38 @@ describe('parseCommand', () => {
}
});
it('should parse navigate with riskMode', () => {
const result = parseCommand(
cmd({
id: '1',
action: 'navigate',
url: 'https://example.com',
riskMode: 'block',
})
);
expect(result.success).toBe(true);
if (result.success) {
expect(result.command.riskMode).toBe('block');
}
});
it('should reject navigate without url', () => {
const result = parseCommand(cmd({ id: '1', action: 'navigate' }));
expect(result.success).toBe(false);
});
it('should reject navigate with invalid riskMode', () => {
const result = parseCommand(
cmd({
id: '1',
action: 'navigate',
url: 'https://example.com',
riskMode: 'invalid',
})
);
expect(result.success).toBe(false);
});
it('should parse back command', () => {
const result = parseCommand(cmd({ id: '1', action: 'back' }));
expect(result.success).toBe(true);
+2 -1
View File
@@ -51,7 +51,6 @@ const launchSchema = baseCommandSchema.extend({
allowFileAccess: z.boolean().optional(),
colorScheme: z.enum(['light', 'dark', 'no-preference']).optional(),
downloadPath: z.string().optional(),
profile: z.string().optional(),
storageState: z.string().optional(),
allowedDomains: z.array(z.string()).optional(),
actionPolicy: z.string().optional(),
@@ -63,6 +62,7 @@ const navigateSchema = baseCommandSchema.extend({
url: z.string().min(1),
waitUntil: z.enum(['load', 'domcontentloaded', 'networkidle']).optional(),
headers: z.record(z.string()).optional(),
riskMode: z.enum(['off', 'warn', 'block']).optional(),
});
const clickSchema = baseCommandSchema.extend({
@@ -813,6 +813,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(),
});
+225
View File
@@ -0,0 +1,225 @@
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,
lightListenerCalls: (() => {
try {
const mql = matchMedia('(prefers-color-scheme: light)');
const handler = () => {};
mql.addEventListener('change', handler);
mql.removeEventListener('change', handler);
return 'ok';
} catch (error) {
return String(error);
}
})(),
};
});
expect(signals.activeTextColor).not.toBe('rgb(255, 0, 0)');
expect(signals.prefersLight).toBe(false);
expect(typeof signals.prefersDark).toBe('boolean');
expect(signals.lightListenerCalls).toBe('ok');
});
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');
});
});
+1154
View File
File diff suppressed because it is too large Load Diff
+15 -1
View File
@@ -6,6 +6,15 @@ export interface BaseCommand {
action: string;
}
export type RiskMode = 'off' | 'warn' | 'block';
export interface RiskSignal {
code: string;
source: 'url' | 'title';
evidence: string;
confidence: number;
}
// Action-specific command types
export interface LaunchCommand extends BaseCommand {
action: 'launch';
@@ -18,7 +27,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;
@@ -45,6 +53,8 @@ export interface NavigateCommand extends BaseCommand {
url: string;
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
headers?: Record<string, string>;
// off: skip detection/retry, warn: retry then return warning+riskSignals, block: fail fast
riskMode?: RiskMode;
}
export interface ClickCommand extends BaseCommand {
@@ -832,6 +842,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';
}
@@ -1123,6 +1134,9 @@ export type Response<T = unknown> = SuccessResponse<T> | ErrorResponse;
export interface NavigateData {
url: string;
title: string;
warning?: string;
// Structured evidence emitted when verification/captcha patterns are detected.
riskSignals?: RiskSignal[];
}
export interface Annotation {
+2 -2
View File
@@ -146,9 +146,9 @@ describe('File Access (Issue #345)', () => {
const content = await page.locator('h1').textContent();
expect(content).toBe('Test File Access');
// Verify webdriver is hidden (from custom arg)
// Verify webdriver is hidden under stealth defaults
const webdriver = await page.evaluate(() => navigator.webdriver);
expect(webdriver).toBe(false);
expect(webdriver).toBeUndefined();
});
});
});
+7 -7
View File
@@ -11,7 +11,7 @@ describe('Launch Options', () => {
});
describe('browser args', () => {
it('should launch with custom args to disable webdriver detection', async () => {
it('should keep webdriver undefined with custom args under stealth defaults', async () => {
browser = new BrowserManager();
await browser.launch({
headless: true,
@@ -21,9 +21,9 @@ describe('Launch Options', () => {
const page = browser.getPage();
await page.goto('about:blank');
// Check that navigator.webdriver is false
// Under stealth defaults, webdriver is hidden (undefined)
const webdriver = await page.evaluate(() => navigator.webdriver);
expect(webdriver).toBe(false);
expect(webdriver).toBeUndefined();
});
it('should launch with multiple args', async () => {
@@ -39,7 +39,7 @@ describe('Launch Options', () => {
expect(browser.isLaunched()).toBe(true);
});
it('should launch without args (default behavior)', async () => {
it('should launch without args and keep webdriver hidden by default', async () => {
browser = new BrowserManager();
await browser.launch({
headless: true,
@@ -48,9 +48,9 @@ describe('Launch Options', () => {
const page = browser.getPage();
await page.goto('about:blank');
// Default Playwright behavior - webdriver is true
// Stealth default behavior - webdriver is hidden
const webdriver = await page.evaluate(() => navigator.webdriver);
expect(webdriver).toBe(true);
expect(webdriver).toBeUndefined();
});
});
@@ -152,7 +152,7 @@ describe('Launch Options', () => {
// Verify webdriver is hidden
const webdriver = await page.evaluate(() => navigator.webdriver);
expect(webdriver).toBe(false);
expect(webdriver).toBeUndefined();
});
});
});