@alicloud/autowonder 0.3.38 → 0.3.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -9
- package/bin/browser.js +47 -0
- package/bin/cli.js +5 -1
- package/lib/browser/README.md +88 -0
- package/lib/browser/browser.js +62 -0
- package/lib/browser/cli.js +148 -0
- package/lib/browser/gateway.js +46 -0
- package/lib/browser/package.json +4 -0
- package/lib/browser/ui.js +35 -0
- package/npm-shrinkwrap.json +1373 -0
- package/package.json +11 -2
- package/scripts/verify-browser-package.js +23 -0
- package/vendor/autowonder-daemon-darwin-amd64 +0 -0
- package/vendor/autowonder-daemon-darwin-arm64 +0 -0
- package/vendor/autowonder-daemon-linux-amd64 +0 -0
- package/vendor/autowonder-daemon-linux-arm64 +0 -0
- package/vendor/autowonder-daemon-win32-amd64.exe +0 -0
- package/vendor/autowonder-daemon-win32-arm64.exe +0 -0
package/README.md
CHANGED
|
@@ -2,14 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
AutoWonder 本地 agent runtime。安装后启动 daemon,持续轮询本地 assignment 队列并执行任务包。
|
|
4
4
|
|
|
5
|
+
## PRD 浏览器 MCP
|
|
6
|
+
|
|
7
|
+
Node.js 22+ 的桌面电脑可免全局安装启动(需发布包含该功能的新版本):
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx -y @alicloud/autowonder@latest browser
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
自动查找浏览器,缺少时下载 Chromium,并生成、保存 MCP Token。用户在专用浏览器中登录并允许 AI 操作后,将输出的 MCP 地址和 Token 填入 PRD 工作台。默认监听 `0.0.0.0:8931`,自动输出本机 IPv4 地址;跨机器使用不要求指定 `--public-host`,只需执行器能访问对应地址和端口。
|
|
14
|
+
|
|
15
|
+
Browser Use 的源码、测试、依赖和发布统一在本 runtime 仓库维护。详见 [使用与维护说明](lib/browser/README.md)。
|
|
16
|
+
|
|
5
17
|
## 连接 AutoWonder 服务
|
|
6
18
|
|
|
7
19
|
```bash
|
|
8
20
|
# Qoder CLI(模型使用 provider model ID;Context Window 使用固定档位)
|
|
9
|
-
npx -y @alicloud/autowonder@0.3.
|
|
21
|
+
npx -y @alicloud/autowonder@0.3.39 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
|
|
10
22
|
|
|
11
23
|
# Qoder CLI CN
|
|
12
|
-
npx -y @alicloud/autowonder@0.3.
|
|
24
|
+
npx -y @alicloud/autowonder@0.3.39 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
|
|
13
25
|
```
|
|
14
26
|
|
|
15
27
|
`connect` 会安装当前 npm 包内置的 daemon,并使用页面生成的 WebSocket endpoint、Token 和执行器 ID 建立连接。客户端只支持通过 Qoder 系列 CLI 启动(`qoder` 对应 `qodercli`,`qodercn` 对应 `qodercn`),其他 `--provider` 取值会在启动 daemon 前直接报错拦截并提示 `Unsupported provider`。选择 Qoder CLI 或 Qoder CLI CN 时需要 Node.js 20+;runtime 会在缺少对应 CLI 时自动通过 npm 安装,并在尚未登录时打开浏览器登录。runtime 会继承当前用户的 HOME、环境变量和 CLI 登录状态。
|
|
@@ -201,7 +213,7 @@ mv "$queue/.assignment.tmp" "$queue/assignment.json"
|
|
|
201
213
|
也可以直接提交到本地 API:
|
|
202
214
|
|
|
203
215
|
```bash
|
|
204
|
-
npx -y @alicloud/autowonder@0.3.
|
|
216
|
+
npx -y @alicloud/autowonder@0.3.39 dispatch ./assignment.json
|
|
205
217
|
```
|
|
206
218
|
|
|
207
219
|
## 上传工单附件
|
|
@@ -209,7 +221,7 @@ npx -y @alicloud/autowonder@0.3.38 dispatch ./assignment.json
|
|
|
209
221
|
把本地需求/设计文档直接上传到工单,避免在会话里传递大文件:
|
|
210
222
|
|
|
211
223
|
```bash
|
|
212
|
-
npx -y @alicloud/autowonder@0.3.
|
|
224
|
+
npx -y @alicloud/autowonder@0.3.39 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
|
|
213
225
|
```
|
|
214
226
|
|
|
215
227
|
上传令牌通过 MCP 工具 `autowonder.workitem_cli_upload_token` 签发,经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 环境变量传入。`--file` 可重复指定多个文件;`--json` 输出机器可读结果。失败时按错误类型返回不同退出码(401→3、403→4、404→5、409→6、413→7、其他 4xx→8、网络/重定向→9)。
|
|
@@ -219,7 +231,7 @@ npx -y @alicloud/autowonder@0.3.38 workitem upload --server-url <autowonder-serv
|
|
|
219
231
|
把工单上已有的需求/设计文档下载到本地目录,再用本地文件工具阅读,避免把大文件或二进制附件搬进会话上下文:
|
|
220
232
|
|
|
221
233
|
```bash
|
|
222
|
-
npx -y @alicloud/autowonder@0.3.
|
|
234
|
+
npx -y @alicloud/autowonder@0.3.39 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
|
|
223
235
|
```
|
|
224
236
|
|
|
225
237
|
下载令牌通过 MCP 工具 `autowonder.workitem_cli_download_token` 签发(与上传令牌相互独立),经 `--token` 或 `AUTOWONDER_DOWNLOAD_TOKEN` 环境变量传入。`--file` 可重复指定文档名或 artifact id,省略则下载该工单的全部附件;`--output-dir` 默认为当前目录;`--json` 输出机器可读结果,含每个文件的 `id`、`name`、`path`、`size`。退出码约定与 `workitem upload` 相同(401→3、403→4、404→5、409→6、413→7、其他 4xx→8、网络/重定向→9)。
|
|
@@ -229,7 +241,7 @@ npx -y @alicloud/autowonder@0.3.38 workitem download --server-url <autowonder-se
|
|
|
229
241
|
把需求/设计文档上传到 7x24 定时任务,用法与工单附件一致(同一套上传令牌与预检规则):
|
|
230
242
|
|
|
231
243
|
```bash
|
|
232
|
-
npx -y @alicloud/autowonder@0.3.
|
|
244
|
+
npx -y @alicloud/autowonder@0.3.39 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
|
|
233
245
|
```
|
|
234
246
|
|
|
235
247
|
上传令牌同样通过 `autowonder.workitem_cli_upload_token` 签发(令牌为用户级,对当前可修改的任意定时任务生效),经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 传入;退出码约定与 `workitem upload` 相同。
|
|
@@ -237,8 +249,8 @@ npx -y @alicloud/autowonder@0.3.38 scheduled-task upload --server-url <autowonde
|
|
|
237
249
|
## 管理 daemon
|
|
238
250
|
|
|
239
251
|
```bash
|
|
240
|
-
npx -y @alicloud/autowonder@0.3.
|
|
241
|
-
npx -y @alicloud/autowonder@0.3.
|
|
252
|
+
npx -y @alicloud/autowonder@0.3.39 status
|
|
253
|
+
npx -y @alicloud/autowonder@0.3.39 stop
|
|
242
254
|
```
|
|
243
255
|
|
|
244
256
|
默认 API 是 `http://127.0.0.1:34989`,日志位于 `~/.autowonder/daemon.log`。npm 包不包含任何 agent、MCP 或服务端凭证。
|
|
@@ -261,7 +273,7 @@ daemon 内置独立于工作区 GC 的保留清扫:默认每小时运行一次
|
|
|
261
273
|
## 调试
|
|
262
274
|
|
|
263
275
|
```bash
|
|
264
|
-
npx -y @alicloud/autowonder@0.3.
|
|
276
|
+
npx -y @alicloud/autowonder@0.3.39 connect ... --debug
|
|
265
277
|
```
|
|
266
278
|
|
|
267
279
|
`--debug` 会让 CLI 以 `AUTOWONDER_DEBUG=1` 启动 daemon,把完整的 daemon 与 agent 活动(runtime 事件流、provider 事件解码、重试退避与会话门等待、空闲时的阻塞点)同时输出到控制台和会话调试日志。调试日志不做脱敏,仅用于本机排障;不传 `--debug` 时该环境变量不会注入。
|
package/bin/browser.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const HELP = `AutoWonder Browser — Playwright MCP
|
|
4
|
+
Usage:
|
|
5
|
+
autowonder browser [start] [options]
|
|
6
|
+
autowonder browser install
|
|
7
|
+
npx -y @alicloud/autowonder@latest browser
|
|
8
|
+
|
|
9
|
+
Options:
|
|
10
|
+
--host <address> Listen address (default: 0.0.0.0)
|
|
11
|
+
--port <port> MCP port (default: 8931)
|
|
12
|
+
--public-host <host> Advertised host only; does not change binding
|
|
13
|
+
--data-dir <directory> Profile, token and output (default: ~/.auto-wonder-browser)
|
|
14
|
+
--executable-path <path> Use an existing Chrome/Edge/Chromium
|
|
15
|
+
--headless For automated tests; default is a visible browser
|
|
16
|
+
-h, --help Show this help
|
|
17
|
+
|
|
18
|
+
Requires Node.js 22+. No executor connection or model provider is needed.
|
|
19
|
+
AUTOWONDER_BROWSER_TOKEN overrides the automatically generated, persisted token.
|
|
20
|
+
Start paused; log in in the dedicated browser, then click “允许 AI 操作”.
|
|
21
|
+
Copy the MCP URL and raw token into the PRD workspace. Ctrl+C stops the service.
|
|
22
|
+
If no browser is found, start downloads the pinned Chromium automatically.
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
async function cmdBrowser(args) {
|
|
26
|
+
let action = "start";
|
|
27
|
+
if (args[0] && !args[0].startsWith("-")) [action, ...args] = args;
|
|
28
|
+
if (!["start", "install"].includes(action)) throw new Error(`Unknown browser command: ${action}. Use autowonder browser --help`);
|
|
29
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
30
|
+
console.log(HELP);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (Number(process.versions.node.split(".")[0]) < 22) {
|
|
34
|
+
throw new Error("AutoWonder Browser requires Node.js 22 or newer. Existing runtime commands remain available.");
|
|
35
|
+
}
|
|
36
|
+
if (action === "install" && args.length) throw new Error("Usage: autowonder browser install");
|
|
37
|
+
for (const dependency of ["@playwright/mcp/package.json", "@modelcontextprotocol/sdk/client/index.js", "playwright/package.json"]) {
|
|
38
|
+
try { require.resolve(dependency); }
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error("Browser dependencies are missing. Install with Node.js 22+: npm install -g @alicloud/autowonder --include=optional (or retry npx with optional dependencies enabled).");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const { runBrowser } = await import("../lib/browser/cli.js");
|
|
44
|
+
return runBrowser(args, action);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { cmdBrowser };
|
package/bin/cli.js
CHANGED
|
@@ -945,6 +945,7 @@ function cmdHelp() {
|
|
|
945
945
|
autowonder — local runtime for AI agent dispatch execution
|
|
946
946
|
|
|
947
947
|
Usage:
|
|
948
|
+
autowonder browser [start|install] [options] Start the PRD browser MCP (Node.js 22+)
|
|
948
949
|
autowonder connect --ws-url <url> --token <token> --executor-id <id> Connect to server and run
|
|
949
950
|
autowonder start [--provider qoder|qodercn] Start daemon in background
|
|
950
951
|
autowonder stop Stop background daemon
|
|
@@ -1061,11 +1062,14 @@ function ensureWindowsUTF8() {
|
|
|
1061
1062
|
// ─── Main ────────────────────────────────────────────────────────────
|
|
1062
1063
|
|
|
1063
1064
|
async function main() {
|
|
1064
|
-
ensureWindowsUTF8();
|
|
1065
1065
|
const args = process.argv.slice(2);
|
|
1066
1066
|
const command = args[0] || "help";
|
|
1067
1067
|
const commandArgs = args.slice(1);
|
|
1068
1068
|
|
|
1069
|
+
// Browser-only machines do not need daemon/provider setup or global Git changes.
|
|
1070
|
+
if (command === "browser") return require("./browser").cmdBrowser(commandArgs);
|
|
1071
|
+
ensureWindowsUTF8();
|
|
1072
|
+
|
|
1069
1073
|
switch (command) {
|
|
1070
1074
|
case "connect": return cmdConnect(commandArgs);
|
|
1071
1075
|
case "start": return cmdStart(commandArgs);
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# AutoWonder Browser
|
|
2
|
+
|
|
3
|
+
Browser Use is maintained here in the runtime repository and released with the
|
|
4
|
+
`@alicloud/autowonder` npm package. There is no separately versioned browser
|
|
5
|
+
package, Git submodule, private repository download or external source checkout
|
|
6
|
+
in the build/install/run path. Make all browser fixes, tests and documentation
|
|
7
|
+
changes in this repository.
|
|
8
|
+
|
|
9
|
+
Imported from `sdlc-autopilot/auto-wonder-browser-use` commit
|
|
10
|
+
`a4383c05d1f63983f5f97865418eaa0e2a7836fb` on 2026-11-04. The original gateway,
|
|
11
|
+
guide UI, persistent profile/token behavior and MCP integration test are retained.
|
|
12
|
+
The original repository is historical reference only; runtime is the maintained
|
|
13
|
+
source. Archiving that remote repository is a separate administrative action.
|
|
14
|
+
|
|
15
|
+
## Customer quick start
|
|
16
|
+
|
|
17
|
+
On a desktop computer with Node.js 22+, run (after a runtime version containing
|
|
18
|
+
this feature is published):
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npx -y @alicloud/autowonder@latest browser
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This does not require a global installation or executor/model-provider setup.
|
|
25
|
+
npx downloads/caches the npm package. The command uses an available Chromium,
|
|
26
|
+
Chrome or Edge; if none is found it downloads its pinned Chromium. Browser
|
|
27
|
+
downloads do not run during npm install. For a repeatable deployment replace
|
|
28
|
+
`latest` with the released runtime version. To pre-download Chromium:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npx -y @alicloud/autowonder@latest browser install
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`browser start` is an alias for `browser`. `browser --help` lists all options.
|
|
35
|
+
An existing browser can be selected with `--executable-path "/path/to/chrome"`.
|
|
36
|
+
Linux needs a desktop session and the browser's system libraries. Headless mode
|
|
37
|
+
is for automated testing, not the normal human login workflow.
|
|
38
|
+
|
|
39
|
+
1. Open the business website in the dedicated browser and log in manually.
|
|
40
|
+
2. Return to the guide and click **允许 AI 操作**.
|
|
41
|
+
3. In the PRD workspace, add a browser MCP using the printed `/mcp` URL and raw
|
|
42
|
+
token (without a `Bearer` prefix), then check the connection.
|
|
43
|
+
|
|
44
|
+
The command automatically generates the token. No environment configuration is
|
|
45
|
+
needed. The token is saved to `~/.auto-wonder-browser/token` and reused on restart;
|
|
46
|
+
`profile/` stores browser login data and `output/` stores MCP artifacts. The
|
|
47
|
+
optional `AUTOWONDER_BROWSER_TOKEN` environment variable overrides the saved
|
|
48
|
+
token. Keep tokens and profiles private. The business login and MCP token are
|
|
49
|
+
separate credentials. Every restart requires manual AI authorization again.
|
|
50
|
+
|
|
51
|
+
Default binding is **0.0.0.0:8931**. The command prints non-loopback IPv4 addresses;
|
|
52
|
+
choose one reachable from the executor. `--public-host` only overrides the
|
|
53
|
+
advertised address; it does not change binding or open firewalls. No public-host
|
|
54
|
+
flag is required for ordinary cross-machine access. `--host 127.0.0.1` restricts
|
|
55
|
+
the MCP service to the local computer. HTTP is intended for trusted networks;
|
|
56
|
+
use VPN/HTTPS forwarding across untrusted networks. The guide itself is local.
|
|
57
|
+
|
|
58
|
+
Pause AI before manual takeover. Pause rejects new MCP requests (423) but does
|
|
59
|
+
not cancel an in-flight operation. Ctrl+C stops the service. Clients share one
|
|
60
|
+
browser context: use one task at a time, or separate ports and data directories.
|
|
61
|
+
PRD read-only behavior is a task instruction, not a tool-level write barrier.
|
|
62
|
+
Connection checks require AI authorization and do not prove business login or
|
|
63
|
+
end-to-end image delivery.
|
|
64
|
+
|
|
65
|
+
## Maintenance and release
|
|
66
|
+
|
|
67
|
+
- Source: `npm/lib/browser/`; command routing: `npm/bin/browser.js`.
|
|
68
|
+
- Tests: `npm/test/browser/`, `npm/test/browser-command.test.js`,
|
|
69
|
+
`npm/test/browser-package.test.js`.
|
|
70
|
+
- Dependencies are exact optional dependencies in `npm/package.json`, locked in
|
|
71
|
+
`npm/npm-shrinkwrap.json`. They are optional to preserve legacy runtime install
|
|
72
|
+
compatibility; browser execution requires them and Node.js 22+. Do not use
|
|
73
|
+
`--omit=optional` for browser installations. If omitted, reinstall with
|
|
74
|
+
`npm install -g @alicloud/autowonder --include=optional` on Node.js 22+.
|
|
75
|
+
- Upgrade MCP, Playwright and its Chromium revision together and rerun integration
|
|
76
|
+
tests. Do not resolve Playwright through undeclared transitive dependencies.
|
|
77
|
+
- From `npm/`: `npm ci`, `npm test`, `npm run test:browser`, `npm pack`.
|
|
78
|
+
- `prepack` protects both npm pack and npm publish against missing browser source
|
|
79
|
+
or stale dependency metadata. The existing runtime release builds still supply
|
|
80
|
+
daemon binaries; browser-only npm packing does not rebuild them.
|
|
81
|
+
- CI installs the packed artifact in an empty directory and exercises real MCP
|
|
82
|
+
authentication, browser login, screenshots and restart persistence on each OS.
|
|
83
|
+
- Version bumps must update package.json and npm-shrinkwrap.json together (use
|
|
84
|
+
`npm version` in npm/ or regenerate the lock after an automated version edit).
|
|
85
|
+
|
|
86
|
+
Existing runtime commands retain their Node version requirements and do not load
|
|
87
|
+
browser dependencies. No platform API, MCP tool contract or existing capability
|
|
88
|
+
binding is changed by this migration.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { accessSync, constants, statSync } from 'node:fs';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
|
|
7
|
+
function executable(path) {
|
|
8
|
+
try {
|
|
9
|
+
if (!statSync(path).isFile()) return false;
|
|
10
|
+
accessSync(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
|
|
11
|
+
return true;
|
|
12
|
+
} catch { return false; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Prefer the bundled browser; permit a quick start on desktops with Chrome/Edge.
|
|
16
|
+
export function browserExecutable(bundled, explicit) {
|
|
17
|
+
if (explicit) {
|
|
18
|
+
const path = resolve(explicit);
|
|
19
|
+
if (!executable(path)) throw new Error(`Invalid --executable-path: ${path}`);
|
|
20
|
+
return path;
|
|
21
|
+
}
|
|
22
|
+
const candidates = [bundled];
|
|
23
|
+
if (process.platform === 'darwin') candidates.push(
|
|
24
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
25
|
+
join(homedir(), 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'),
|
|
26
|
+
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
|
27
|
+
);
|
|
28
|
+
if (process.platform === 'win32') {
|
|
29
|
+
for (const base of [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].filter(Boolean)) {
|
|
30
|
+
candidates.push(join(base, 'Google/Chrome/Application/chrome.exe'), join(base, 'Microsoft/Edge/Application/msedge.exe'));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (process.platform === 'linux') candidates.push('/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/opt/google/chrome/chrome');
|
|
34
|
+
return candidates.find(path => executable(path));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function installBrowser() {
|
|
38
|
+
const require = createRequire(import.meta.url);
|
|
39
|
+
const cli = join(dirname(require.resolve('playwright/package.json')), 'cli.js');
|
|
40
|
+
console.log('正在下载匹配版本的 Chromium(仅首次使用需要)…');
|
|
41
|
+
await new Promise((resolve, reject) => {
|
|
42
|
+
const child = spawn(process.execPath, [cli, 'install', 'chromium'], { stdio: 'inherit', windowsHide: true });
|
|
43
|
+
const stop = () => child.kill('SIGTERM');
|
|
44
|
+
const cleanup = () => { process.off('SIGINT', stop); process.off('SIGTERM', stop); };
|
|
45
|
+
process.on('SIGINT', stop);
|
|
46
|
+
process.on('SIGTERM', stop);
|
|
47
|
+
child.once('error', error => { cleanup(); reject(error); });
|
|
48
|
+
child.once('exit', (code, signal) => {
|
|
49
|
+
cleanup();
|
|
50
|
+
if (code === 0 && !signal) resolve();
|
|
51
|
+
else reject(new Error('Chromium installation failed or was interrupted. Retry autowonder browser install; check available disk space and network/proxy access.'));
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function ensureBrowser(bundled, explicit) {
|
|
57
|
+
const found = browserExecutable(bundled, explicit);
|
|
58
|
+
if (found) return found;
|
|
59
|
+
await installBrowser();
|
|
60
|
+
if (!executable(bundled)) throw new Error('Chromium was not found after installation. Retry autowonder browser install.');
|
|
61
|
+
return bundled;
|
|
62
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { homedir, networkInterfaces } from 'node:os';
|
|
6
|
+
import { access, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { constants } from 'node:fs';
|
|
8
|
+
import { isIP } from 'node:net';
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
13
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
14
|
+
import { createGateway, listen } from './gateway.js';
|
|
15
|
+
import { createUI } from './ui.js';
|
|
16
|
+
import { ensureBrowser, installBrowser } from './browser.js';
|
|
17
|
+
|
|
18
|
+
export async function runBrowser(argv, action = 'start') {
|
|
19
|
+
const require = createRequire(import.meta.url);
|
|
20
|
+
if (action === 'install') return installBrowser();
|
|
21
|
+
const { values } = parseArgs({ args: argv, options: {
|
|
22
|
+
host: { type: 'string', default: '0.0.0.0' }, port: { type: 'string', default: '8931' },
|
|
23
|
+
'data-dir': { type: 'string', default: join(homedir(), '.auto-wonder-browser') },
|
|
24
|
+
'public-host': { type: 'string' }, 'executable-path': { type: 'string' },
|
|
25
|
+
headless: { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h' },
|
|
26
|
+
} });
|
|
27
|
+
if (values.help) {
|
|
28
|
+
console.log(`AutoWonder Browser — Playwright MCP 启动器
|
|
29
|
+
autowonder browser [--port 8931] [--host 0.0.0.0] [--public-host 内网IP或域名]
|
|
30
|
+
[--data-dir 目录] [--executable-path 浏览器路径] [--headless]
|
|
31
|
+
认证:AUTOWONDER_BROWSER_TOKEN 环境变量;未设置时自动生成并保存。
|
|
32
|
+
默认打开有界面 Chromium 和登录引导页。--headless 仅供测试。`);
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
const port = Number(values.port);
|
|
36
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('port 必须在 1–65535 之间');
|
|
37
|
+
for (const name of ['host', 'public-host']) {
|
|
38
|
+
if (values[name] === undefined) continue;
|
|
39
|
+
const host = values[name];
|
|
40
|
+
if (!isIP(host) && !/^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(host)) {
|
|
41
|
+
throw new Error(`Invalid --${name}: use an IP address or hostname, without scheme, port or path`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (!values['data-dir'].trim()) throw new Error('Invalid --data-dir: directory must not be empty');
|
|
45
|
+
const dataDir = resolve(values['data-dir']);
|
|
46
|
+
// Validate the nearest existing ancestor before downloading or writing state.
|
|
47
|
+
let parent = dataDir;
|
|
48
|
+
while (true) {
|
|
49
|
+
try {
|
|
50
|
+
if (!(await stat(parent)).isDirectory()) throw new Error('Invalid --data-dir: path or ancestor is not a directory');
|
|
51
|
+
await access(parent, constants.W_OK);
|
|
52
|
+
break;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error.code !== 'ENOENT' || dirname(parent) === parent) throw error;
|
|
55
|
+
parent = dirname(parent);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
let token = process.env.AUTOWONDER_BROWSER_TOKEN || undefined;
|
|
59
|
+
if (!token) {
|
|
60
|
+
try { token = (await readFile(join(dataDir, 'token'), 'utf8')).trim(); }
|
|
61
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
62
|
+
}
|
|
63
|
+
function validateToken(value) {
|
|
64
|
+
if (value !== undefined && (value.length < 24 || /\s/.test(value))) throw new Error('Token 至少需要 24 个字符且不能包含空白');
|
|
65
|
+
}
|
|
66
|
+
validateToken(token);
|
|
67
|
+
const preflight = http.createServer();
|
|
68
|
+
await listen(preflight, port, values.host);
|
|
69
|
+
await new Promise(resolve => preflight.close(resolve));
|
|
70
|
+
const state = { ready: false, paused: true };
|
|
71
|
+
let child, client, gateway, ui, stopping = false;
|
|
72
|
+
async function shutdown(code = 0) {
|
|
73
|
+
if (stopping) return;
|
|
74
|
+
stopping = true;
|
|
75
|
+
state.ready = false;
|
|
76
|
+
const force = setTimeout(() => { child?.kill('SIGKILL'); process.exit(code); }, 5000);
|
|
77
|
+
force.unref();
|
|
78
|
+
gateway?.closeAllConnections(); gateway?.close();
|
|
79
|
+
ui?.server.closeAllConnections(); ui?.server.close();
|
|
80
|
+
// Explicit close flushes the profile even on Windows, where SIGTERM is abrupt.
|
|
81
|
+
await client?.callTool({ name: 'browser_close', arguments: {} }).catch(() => {});
|
|
82
|
+
await client?.close().catch(() => {});
|
|
83
|
+
if (child && child.exitCode === null) {
|
|
84
|
+
const exited = new Promise(resolve => child.once('exit', resolve));
|
|
85
|
+
child.kill('SIGTERM');
|
|
86
|
+
await exited;
|
|
87
|
+
}
|
|
88
|
+
clearTimeout(force);
|
|
89
|
+
process.exit(code);
|
|
90
|
+
}
|
|
91
|
+
process.on('SIGINT', () => shutdown());
|
|
92
|
+
process.on('SIGTERM', () => shutdown());
|
|
93
|
+
if (process.send) process.on('message', message => { if (message?.type === 'shutdown') shutdown(); });
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
const playwright = require('playwright');
|
|
97
|
+
const executable = await ensureBrowser(playwright.chromium.executablePath(), values['executable-path']);
|
|
98
|
+
await mkdir(dataDir, { recursive: true, mode: 0o700 });
|
|
99
|
+
if (!token) {
|
|
100
|
+
const tokenPath = join(dataDir, 'token');
|
|
101
|
+
token = randomBytes(32).toString('hex');
|
|
102
|
+
try { await writeFile(tokenPath, token + '\n', { mode: 0o600, flag: 'wx' }); }
|
|
103
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; token = (await readFile(tokenPath, 'utf8')).trim(); }
|
|
104
|
+
}
|
|
105
|
+
validateToken(token);
|
|
106
|
+
const reserve = http.createServer();
|
|
107
|
+
const internalPort = await listen(reserve, 0, '127.0.0.1');
|
|
108
|
+
await new Promise(resolve => reserve.close(resolve));
|
|
109
|
+
const upstream = new URL(`http://127.0.0.1:${internalPort}`);
|
|
110
|
+
gateway = createGateway({ token, upstream, state });
|
|
111
|
+
await listen(gateway, port, values.host);
|
|
112
|
+
ui = createUI(state);
|
|
113
|
+
const uiPort = await listen(ui.server, 0, '127.0.0.1');
|
|
114
|
+
const uiURL = `http://127.0.0.1:${uiPort}${ui.path}`;
|
|
115
|
+
const mcpDir = dirname(require.resolve('@playwright/mcp/package.json'));
|
|
116
|
+
const args = [join(mcpDir, 'cli.js'), '--host', '127.0.0.1', '--port', String(internalPort), '--allowed-hosts', `127.0.0.1:${internalPort}`,
|
|
117
|
+
'--user-data-dir', join(dataDir, 'profile'), '--shared-browser-context', '--idle-timeout', '0',
|
|
118
|
+
'--executable-path', executable,
|
|
119
|
+
'--image-responses', 'allow', '--output-dir', join(dataDir, 'output')];
|
|
120
|
+
if (values.headless) args.push('--headless');
|
|
121
|
+
console.log('正在启动 Playwright MCP 和浏览器…');
|
|
122
|
+
child = spawn(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
123
|
+
let diagnostics = '';
|
|
124
|
+
for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => { diagnostics = (diagnostics + chunk).slice(-6000); });
|
|
125
|
+
child.on('error', error => { console.error(error.message); shutdown(1); });
|
|
126
|
+
child.on('exit', () => { if (!stopping) { console.error('Playwright MCP 已退出:\n' + diagnostics); shutdown(1); } });
|
|
127
|
+
const deadline = Date.now() + 30000;
|
|
128
|
+
while (true) {
|
|
129
|
+
try { await fetch(upstream, { signal: AbortSignal.timeout(500) }); break; }
|
|
130
|
+
catch { if (Date.now() > deadline) throw new Error('MCP 启动超时:' + diagnostics); await new Promise(r => setTimeout(r, 200)); }
|
|
131
|
+
}
|
|
132
|
+
client = new Client({ name: 'autowonder-bootstrap', version: require('../../package.json').version });
|
|
133
|
+
await client.connect(new StreamableHTTPClientTransport(new URL('/mcp', upstream)));
|
|
134
|
+
const opened = await client.callTool({ name: 'browser_navigate', arguments: { url: uiURL } });
|
|
135
|
+
if (opened.isError) throw new Error(JSON.stringify(opened.content));
|
|
136
|
+
state.ready = true;
|
|
137
|
+
const hosts = values['public-host'] ? [values['public-host']] : values.host === '0.0.0.0'
|
|
138
|
+
? [...new Set(Object.values(networkInterfaces()).flat().filter(x => x && x.family === 'IPv4' && !x.internal).map(x => x.address))]
|
|
139
|
+
: [values.host];
|
|
140
|
+
if (!hosts.length) hosts.push('127.0.0.1');
|
|
141
|
+
const endpoint = host => `http://${host.includes(':') && !host.startsWith('[') ? '[' + host + ']' : host}:${port}/mcp`;
|
|
142
|
+
console.log(`\n浏览器已就绪。请在自动打开的引导页中输入网站并登录。\n登录后点击“允许 AI 操作”。\n本机引导页:${uiURL}\n数据目录:${dataDir}\nMCP 地址:\n${hosts.map(endpoint).join('\n')}\n认证 Token:${token}\n\n客户端配置:\n${JSON.stringify({ mcpServers: { 'autowonder-browser': { url: endpoint(hosts[0]), headers: { Authorization: `Bearer ${token}` } } } }, null, 2)}\n\nCtrl+C 停止服务。`);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
console.error(`启动失败:${error.message}\n首次使用请先执行 autowonder browser install;Linux 需要桌面会话及浏览器系统依赖。`);
|
|
145
|
+
await shutdown(1);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
export function createGateway({ token, upstream, state }) {
|
|
5
|
+
return http.createServer((req, res) => {
|
|
6
|
+
const reply = (status, error) => {
|
|
7
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
8
|
+
res.end(JSON.stringify({ error }));
|
|
9
|
+
};
|
|
10
|
+
if (req.url !== '/mcp') return reply(404, 'Not found');
|
|
11
|
+
const actual = Buffer.from(req.headers.authorization || '');
|
|
12
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
13
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
|
14
|
+
res.setHeader('www-authenticate', 'Bearer');
|
|
15
|
+
return reply(401, 'Bearer token required');
|
|
16
|
+
}
|
|
17
|
+
// This endpoint is for MCP clients, not arbitrary web pages.
|
|
18
|
+
if (req.headers.origin) return reply(403, 'Browser-origin requests are not allowed');
|
|
19
|
+
if (!['POST', 'GET', 'DELETE'].includes(req.method)) return reply(405, 'Method not allowed');
|
|
20
|
+
if (!state.ready) return reply(503, 'Browser is starting');
|
|
21
|
+
if (state.paused) return reply(423, 'Paused for manual browser use');
|
|
22
|
+
const headers = { ...req.headers, host: upstream.host };
|
|
23
|
+
delete headers.authorization;
|
|
24
|
+
delete headers.connection;
|
|
25
|
+
const proxy = http.request(new URL('/mcp', upstream), { method: req.method, headers }, response => {
|
|
26
|
+
res.writeHead(response.statusCode, response.headers);
|
|
27
|
+
response.pipe(res);
|
|
28
|
+
response.on('error', () => res.destroy());
|
|
29
|
+
});
|
|
30
|
+
proxy.on('error', () => {
|
|
31
|
+
if (!res.headersSent) reply(502, 'Playwright MCP unavailable');
|
|
32
|
+
else res.destroy();
|
|
33
|
+
});
|
|
34
|
+
req.on('aborted', () => proxy.destroy());
|
|
35
|
+
res.on('close', () => proxy.destroy());
|
|
36
|
+
req.pipe(proxy);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function listen(server, port, host) {
|
|
41
|
+
await new Promise((resolve, reject) => {
|
|
42
|
+
server.once('error', reject);
|
|
43
|
+
server.listen(port, host, () => { server.removeListener('error', reject); resolve(); });
|
|
44
|
+
});
|
|
45
|
+
return server.address().port;
|
|
46
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
export function createUI(state) {
|
|
5
|
+
const path = `/${randomBytes(24).toString('hex')}`;
|
|
6
|
+
const server = http.createServer((req, res) => {
|
|
7
|
+
res.setHeader('cache-control', 'no-store');
|
|
8
|
+
res.setHeader('referrer-policy', 'no-referrer');
|
|
9
|
+
res.setHeader('x-frame-options', 'DENY');
|
|
10
|
+
if (req.headers.host !== `127.0.0.1:${server.address().port}`) { res.writeHead(403); return res.end(); }
|
|
11
|
+
if (req.url === `${path}/state` && req.method === 'POST') {
|
|
12
|
+
if (req.headers.origin !== `http://${req.headers.host}`) { res.writeHead(403); return res.end(); }
|
|
13
|
+
const action = req.headers['x-browser-action'];
|
|
14
|
+
if (!['pause', 'resume'].includes(action)) { res.writeHead(400); return res.end(); }
|
|
15
|
+
state.paused = action === 'pause';
|
|
16
|
+
res.setHeader('content-type', 'application/json');
|
|
17
|
+
return res.end(JSON.stringify({ paused: state.paused }));
|
|
18
|
+
}
|
|
19
|
+
if (req.url !== path || req.method !== 'GET') { res.writeHead(404); return res.end(); }
|
|
20
|
+
res.setHeader('content-type', 'text/html; charset=utf-8');
|
|
21
|
+
res.end(`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>AutoWonder 浏览器</title>
|
|
22
|
+
<style>body{font:16px/1.7 system-ui;background:#f3f5f9;color:#192234;max-width:760px;margin:10vh auto;padding:24px}main{background:white;padding:40px;border-radius:20px;box-shadow:0 16px 60px #19223412}h1{margin-top:0}input{box-sizing:border-box;width:100%;padding:14px;font:inherit;border:1px solid #bbb;border-radius:8px}button{font:inherit;padding:10px 18px;margin:14px 8px 0 0;border:0;border-radius:8px;cursor:pointer;background:#245de8;color:white}.secondary{background:#e8edf8;color:#192234}#status{padding:12px;background:#edf2ff;border-radius:8px}small{color:#576477}</style>
|
|
23
|
+
<main><h1>AutoWonder 浏览器</h1><p>在此浏览器中登录,AI 将复用同一个浏览器和登录信息。</p><p id="status"></p>
|
|
24
|
+
<form id="open"><label for="url">要访问的网站</label><input id="url" type="url" placeholder="https://your-app.example.com" required><button>打开网站并登录</button></form>
|
|
25
|
+
<p>完成登录后,回到本标签页,点击“允许 AI 操作”。</p><button id="resume">允许 AI 操作</button><button class="secondary" id="pause">暂停 AI,人工操作</button>
|
|
26
|
+
<p><small>暂停会拒绝新的 MCP 请求;已开始的操作可能仍在执行,请等待其完成再接管。一次只连接一个任务。不要关闭此引导页,登录页会在新标签中打开。</small></p></main>
|
|
27
|
+
<script>
|
|
28
|
+
let paused=${JSON.stringify(state.paused)};
|
|
29
|
+
function render(){document.querySelector('#status').textContent=paused?'当前:人工模式,远程 MCP 已暂停':'当前:AI 模式,远程 MCP 可用'}render();
|
|
30
|
+
document.querySelector('#open').onsubmit=e=>{e.preventDefault();const url=new URL(document.querySelector('#url').value);if(!['http:','https:'].includes(url.protocol)){alert('只支持 HTTP / HTTPS 地址');return}window.open(url.href,'_blank','noopener,noreferrer')};
|
|
31
|
+
for(const action of ['pause','resume'])document.getElementById(action).onclick=async()=>{try{const r=await fetch(location.pathname+'/state',{method:'POST',headers:{'x-browser-action':action}});if(!r.ok)throw Error('操作失败');paused=(await r.json()).paused;render()}catch(e){alert('服务连接失败,请检查终端')}};
|
|
32
|
+
</script></html>`);
|
|
33
|
+
});
|
|
34
|
+
return { server, path };
|
|
35
|
+
}
|