@alicloud/autowonder 0.3.38 → 0.3.40

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 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.38 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
21
+ npx -y @alicloud/autowonder@0.3.40 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.38 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
24
+ npx -y @alicloud/autowonder@0.3.40 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.38 dispatch ./assignment.json
216
+ npx -y @alicloud/autowonder@0.3.40 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.38 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
224
+ npx -y @alicloud/autowonder@0.3.40 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.38 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
234
+ npx -y @alicloud/autowonder@0.3.40 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.38 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
244
+ npx -y @alicloud/autowonder@0.3.40 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.38 status
241
- npx -y @alicloud/autowonder@0.3.38 stop
252
+ npx -y @alicloud/autowonder@0.3.40 status
253
+ npx -y @alicloud/autowonder@0.3.40 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.38 connect ... --debug
276
+ npx -y @alicloud/autowonder@0.3.40 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,155 @@
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 { fileURLToPath } from 'node:url';
6
+ import { homedir, networkInterfaces } from 'node:os';
7
+ import { access, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
8
+ import { constants } from 'node:fs';
9
+ import { isIP } from 'node:net';
10
+ import { randomBytes } from 'node:crypto';
11
+ import { spawn } from 'node:child_process';
12
+ import http from 'node:http';
13
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
14
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
15
+ import { createGateway, listen } from './gateway.js';
16
+ import { createUI } from './ui.js';
17
+ import { ensureBrowser, installBrowser } from './browser.js';
18
+
19
+ export async function runBrowser(argv, action = 'start') {
20
+ const require = createRequire(import.meta.url);
21
+ if (action === 'install') return installBrowser();
22
+ const { values } = parseArgs({ args: argv, options: {
23
+ host: { type: 'string', default: '0.0.0.0' }, port: { type: 'string', default: '8931' },
24
+ 'data-dir': { type: 'string', default: join(homedir(), '.auto-wonder-browser') },
25
+ 'public-host': { type: 'string' }, 'executable-path': { type: 'string' },
26
+ headless: { type: 'boolean', default: false }, help: { type: 'boolean', short: 'h' },
27
+ } });
28
+ if (values.help) {
29
+ console.log(`AutoWonder Browser — Playwright MCP 启动器
30
+ autowonder browser [--port 8931] [--host 0.0.0.0] [--public-host 内网IP或域名]
31
+ [--data-dir 目录] [--executable-path 浏览器路径] [--headless]
32
+ 认证:AUTOWONDER_BROWSER_TOKEN 环境变量;未设置时自动生成并保存。
33
+ 默认打开有界面 Chromium 和登录引导页。--headless 仅供测试。`);
34
+ process.exit(0);
35
+ }
36
+ const port = Number(values.port);
37
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('port 必须在 1–65535 之间');
38
+ for (const name of ['host', 'public-host']) {
39
+ if (values[name] === undefined) continue;
40
+ const host = values[name];
41
+ if (!isIP(host) && !/^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(host)) {
42
+ throw new Error(`Invalid --${name}: use an IP address or hostname, without scheme, port or path`);
43
+ }
44
+ }
45
+ if (!values['data-dir'].trim()) throw new Error('Invalid --data-dir: directory must not be empty');
46
+ const dataDir = resolve(values['data-dir']);
47
+ // Validate the nearest existing ancestor before downloading or writing state.
48
+ let parent = dataDir;
49
+ while (true) {
50
+ try {
51
+ if (!(await stat(parent)).isDirectory()) throw new Error('Invalid --data-dir: path or ancestor is not a directory');
52
+ await access(parent, constants.W_OK);
53
+ break;
54
+ } catch (error) {
55
+ if (error.code !== 'ENOENT' || dirname(parent) === parent) throw error;
56
+ parent = dirname(parent);
57
+ }
58
+ }
59
+ let token = process.env.AUTOWONDER_BROWSER_TOKEN || undefined;
60
+ if (!token) {
61
+ try { token = (await readFile(join(dataDir, 'token'), 'utf8')).trim(); }
62
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
63
+ }
64
+ function validateToken(value) {
65
+ if (value !== undefined && (value.length < 24 || /\s/.test(value))) throw new Error('Token 至少需要 24 个字符且不能包含空白');
66
+ }
67
+ validateToken(token);
68
+ const preflight = http.createServer();
69
+ await listen(preflight, port, values.host);
70
+ await new Promise(resolve => preflight.close(resolve));
71
+ const state = { ready: false, paused: true };
72
+ let child, client, gateway, ui, stopping = false;
73
+ async function shutdown(code = 0) {
74
+ if (stopping) return;
75
+ stopping = true;
76
+ state.ready = false;
77
+ // Leave MCP's own 15-second watchdog time to finish before forcing exit.
78
+ const force = setTimeout(() => {
79
+ console.error('Browser shutdown timed out; forcing MCP exit. The profile may not have been saved.');
80
+ child?.kill('SIGKILL');
81
+ process.exit(1);
82
+ }, 20000);
83
+ force.unref();
84
+ gateway?.closeAllConnections(); gateway?.close();
85
+ ui?.server.closeAllConnections(); ui?.server.close();
86
+ // browser_close is rejected for shared contexts; shut down the MCP process
87
+ // cooperatively instead so it closes Chromium and flushes the whole profile.
88
+ await client?.close().catch(() => {});
89
+ if (child && child.exitCode === null) {
90
+ const exited = new Promise(resolve => child.once('exit', resolve));
91
+ child.send({ type: 'shutdown' }, error => {
92
+ if (error && child.exitCode === null) child.kill('SIGTERM');
93
+ });
94
+ await exited;
95
+ }
96
+ clearTimeout(force);
97
+ process.exit(code);
98
+ }
99
+ process.on('SIGINT', () => shutdown());
100
+ process.on('SIGTERM', () => shutdown());
101
+ if (process.send) process.on('message', message => { if (message?.type === 'shutdown') shutdown(); });
102
+
103
+ try {
104
+ const playwright = require('playwright');
105
+ const executable = await ensureBrowser(playwright.chromium.executablePath(), values['executable-path']);
106
+ await mkdir(dataDir, { recursive: true, mode: 0o700 });
107
+ if (!token) {
108
+ const tokenPath = join(dataDir, 'token');
109
+ token = randomBytes(32).toString('hex');
110
+ try { await writeFile(tokenPath, token + '\n', { mode: 0o600, flag: 'wx' }); }
111
+ catch (error) { if (error.code !== 'EEXIST') throw error; token = (await readFile(tokenPath, 'utf8')).trim(); }
112
+ }
113
+ validateToken(token);
114
+ const reserve = http.createServer();
115
+ const internalPort = await listen(reserve, 0, '127.0.0.1');
116
+ await new Promise(resolve => reserve.close(resolve));
117
+ const upstream = new URL(`http://127.0.0.1:${internalPort}`);
118
+ gateway = createGateway({ token, upstream, state });
119
+ await listen(gateway, port, values.host);
120
+ ui = createUI(state);
121
+ const uiPort = await listen(ui.server, 0, '127.0.0.1');
122
+ const uiURL = `http://127.0.0.1:${uiPort}${ui.path}`;
123
+ const args = [fileURLToPath(new URL('./mcp-runner.js', import.meta.url)), '--host', '127.0.0.1', '--port', String(internalPort), '--allowed-hosts', `127.0.0.1:${internalPort}`,
124
+ '--user-data-dir', join(dataDir, 'profile'), '--shared-browser-context', '--idle-timeout', '0',
125
+ '--executable-path', executable,
126
+ '--image-responses', 'allow', '--output-dir', join(dataDir, 'output')];
127
+ if (values.headless) args.push('--headless');
128
+ console.log('正在启动 Playwright MCP 和浏览器…');
129
+ child = spawn(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true });
130
+ let diagnostics = '';
131
+ for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => { diagnostics = (diagnostics + chunk).slice(-6000); });
132
+ child.on('error', error => { console.error(error.message); shutdown(1); });
133
+ child.on('exit', () => { if (!stopping) { console.error('Playwright MCP 已退出:\n' + diagnostics); shutdown(1); } });
134
+ const deadline = Date.now() + 30000;
135
+ while (true) {
136
+ try { await fetch(upstream, { signal: AbortSignal.timeout(500) }); break; }
137
+ catch { if (Date.now() > deadline) throw new Error('MCP 启动超时:' + diagnostics); await new Promise(r => setTimeout(r, 200)); }
138
+ }
139
+ client = new Client({ name: 'autowonder-bootstrap', version: require('../../package.json').version });
140
+ await client.connect(new StreamableHTTPClientTransport(new URL('/mcp', upstream)));
141
+ const opened = await client.callTool({ name: 'browser_navigate', arguments: { url: uiURL } });
142
+ if (opened.isError) throw new Error(JSON.stringify(opened.content));
143
+ state.ready = true;
144
+ const hosts = values['public-host'] ? [values['public-host']] : values.host === '0.0.0.0'
145
+ ? [...new Set(Object.values(networkInterfaces()).flat().filter(x => x && x.family === 'IPv4' && !x.internal).map(x => x.address))]
146
+ : [values.host];
147
+ if (!hosts.length) hosts.push('127.0.0.1');
148
+ const endpoint = host => `http://${host.includes(':') && !host.startsWith('[') ? '[' + host + ']' : host}:${port}/mcp`;
149
+ 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 停止服务。`);
150
+ } catch (error) {
151
+ console.error(`启动失败:${error.message}\n首次使用请先执行 autowonder browser install;Linux 需要桌面会话及浏览器系统依赖。`);
152
+ await shutdown(1);
153
+ }
154
+
155
+ }
@@ -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,18 @@
1
+ // Keep shutdown cooperative on Windows: child.kill('SIGTERM') terminates the
2
+ // process there instead of delivering Playwright MCP's graceful signal handler.
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join } from 'node:path';
5
+
6
+ const require = createRequire(import.meta.url);
7
+ const cli = join(dirname(require.resolve('@playwright/mcp/package.json')), 'cli.js');
8
+ function shutdown() {
9
+ // MCP installs a SIGTERM handler that closes all browser processes and flushes
10
+ // persistent profiles. An early shutdown before it installs has no browser.
11
+ if (!process.emit('SIGTERM')) process.exit(0);
12
+ }
13
+ if (process.send) {
14
+ process.on('message', message => { if (message?.type === 'shutdown') shutdown(); });
15
+ process.on('disconnect', shutdown);
16
+ }
17
+ process.argv[1] = cli;
18
+ require(cli);
@@ -0,0 +1,4 @@
1
+ {
2
+ "private": true,
3
+ "type": "module"
4
+ }
@@ -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
+ }