@alicloud/autowonder 0.3.45 → 0.3.47

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,6 +2,21 @@
2
2
 
3
3
  AutoWonder 本地 agent runtime。安装后启动 daemon,持续轮询本地 assignment 队列并执行任务包。
4
4
 
5
+ ## 实时预览 CLI
6
+
7
+ `autowonder preview start/status/stop` 在执行器侧管理专用 WSS 预览中转。本地开发使用 `tnpm link`,
8
+ 不需要发包;完整配置和联调步骤见[实时预览说明](lib/preview/README.md)。
9
+
10
+ ```bash
11
+ npx -y @alicloud/autowonder@0.3.47 preview start --id <binding-id> --port <vite-port> --config <config-json> --json
12
+ npx -y @alicloud/autowonder@0.3.47 preview status --id <binding-id> --json
13
+ npx -y @alicloud/autowonder@0.3.47 preview stop --id <binding-id> --json
14
+ ```
15
+
16
+ 配置文件路径也可由 `AUTOWONDER_PREVIEW_CONFIG` 提供,本机状态目录默认 `~/.autowonder/preview`、
17
+ 可用 `AUTOWONDER_PREVIEW_HOME` 覆盖;配置文件只保存 `tokenEnv` 变量名,执行器 Token 仍从环境注入。
18
+ 通过 `autowonder connect` 启动的 daemon 会对支持自动恢复的会话自动登记预览中转,无需手工 start。
19
+
5
20
  ## PRD 浏览器 MCP
6
21
 
7
22
  Node.js 22+ 的桌面电脑可免全局安装启动(需发布包含该功能的新版本):
@@ -18,10 +33,10 @@ Browser Use 的源码、测试、依赖和发布统一在本 runtime 仓库维
18
33
 
19
34
  ```bash
20
35
  # Qoder CLI(模型使用 provider model ID;Context Window 使用固定档位)
21
- npx -y @alicloud/autowonder@0.3.45 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
36
+ npx -y @alicloud/autowonder@0.3.47 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qoder --model qmodel_latest --reasoning-effort medium --context-window 260000
22
37
 
23
38
  # Qoder CLI CN
24
- npx -y @alicloud/autowonder@0.3.45 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
39
+ npx -y @alicloud/autowonder@0.3.47 connect --ws-url <wss-endpoint> --token <executor-token> --executor-id <executor-id> --provider qodercn
25
40
  ```
26
41
 
27
42
  `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 登录状态。
@@ -217,7 +232,7 @@ mv "$queue/.assignment.tmp" "$queue/assignment.json"
217
232
  也可以直接提交到本地 API:
218
233
 
219
234
  ```bash
220
- npx -y @alicloud/autowonder@0.3.45 dispatch ./assignment.json
235
+ npx -y @alicloud/autowonder@0.3.47 dispatch ./assignment.json
221
236
  ```
222
237
 
223
238
  ## 上传工单附件
@@ -225,7 +240,7 @@ npx -y @alicloud/autowonder@0.3.45 dispatch ./assignment.json
225
240
  把本地需求/设计文档直接上传到工单,避免在会话里传递大文件:
226
241
 
227
242
  ```bash
228
- npx -y @alicloud/autowonder@0.3.45 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
243
+ npx -y @alicloud/autowonder@0.3.47 workitem upload --server-url <autowonder-server-url> --workitem-id <id> --file <filepath-1> --file <filepath-2> --json
229
244
  ```
230
245
 
231
246
  上传令牌通过 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)。
@@ -235,7 +250,7 @@ npx -y @alicloud/autowonder@0.3.45 workitem upload --server-url <autowonder-serv
235
250
  把工单上已有的需求/设计文档下载到本地目录,再用本地文件工具阅读,避免把大文件或二进制附件搬进会话上下文:
236
251
 
237
252
  ```bash
238
- npx -y @alicloud/autowonder@0.3.45 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
253
+ npx -y @alicloud/autowonder@0.3.47 workitem download --server-url <autowonder-server-url> --workitem-id <id> --file <name-or-id> --output-dir <dir> --json
239
254
  ```
240
255
 
241
256
  下载令牌通过 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)。
@@ -245,7 +260,7 @@ npx -y @alicloud/autowonder@0.3.45 workitem download --server-url <autowonder-se
245
260
  把需求/设计文档上传到 7x24 定时任务,用法与工单附件一致(同一套上传令牌与预检规则):
246
261
 
247
262
  ```bash
248
- npx -y @alicloud/autowonder@0.3.45 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
263
+ npx -y @alicloud/autowonder@0.3.47 scheduled-task upload --server-url <autowonder-server-url> --scheduled-task-id <id> --file <filepath-1> --file <filepath-2> --json
249
264
  ```
250
265
 
251
266
  上传令牌同样通过 `autowonder.workitem_cli_upload_token` 签发(令牌为用户级,对当前可修改的任意定时任务生效),经 `--token` 或 `AUTOWONDER_UPLOAD_TOKEN` 传入;退出码约定与 `workitem upload` 相同。
@@ -253,8 +268,8 @@ npx -y @alicloud/autowonder@0.3.45 scheduled-task upload --server-url <autowonde
253
268
  ## 管理 daemon
254
269
 
255
270
  ```bash
256
- npx -y @alicloud/autowonder@0.3.45 status
257
- npx -y @alicloud/autowonder@0.3.45 stop
271
+ npx -y @alicloud/autowonder@0.3.47 status
272
+ npx -y @alicloud/autowonder@0.3.47 stop
258
273
  ```
259
274
 
260
275
  默认 API 是 `http://127.0.0.1:34989`,日志位于 `~/.autowonder/daemon.log`。npm 包不包含任何 agent、MCP 或服务端凭证。
@@ -277,7 +292,7 @@ daemon 内置独立于工作区 GC 的保留清扫:默认每小时运行一次
277
292
  ## 调试
278
293
 
279
294
  ```bash
280
- npx -y @alicloud/autowonder@0.3.45 connect ... --debug
295
+ npx -y @alicloud/autowonder@0.3.47 connect ... --debug
281
296
  ```
282
297
 
283
298
  `--debug` 会让 CLI 以 `AUTOWONDER_DEBUG=1` 启动 daemon,把完整的 daemon 与 agent 活动(runtime 事件流、provider 事件解码、重试退避与会话门等待、空闲时的阻塞点)同时输出到控制台和会话调试日志。调试日志不做脱敏,仅用于本机排障;不传 `--debug` 时该环境变量不会注入。
package/bin/cli.js CHANGED
@@ -491,6 +491,7 @@ async function cmdConnect(args) {
491
491
  AUTOWONDER_EXECUTOR_TOKEN: config.token,
492
492
  AUTOWONDER_EXECUTOR_ID: executorId,
493
493
  AUTOWONDER_MEMORY_MODE: config.memoryMode,
494
+ AUTOWONDER_PREVIEW_CLI: process.env.AUTOWONDER_PREVIEW_CLI || __filename,
494
495
  };
495
496
  if (flags.model) env.AUTOWONDER_MODEL = flags.model;
496
497
  if (flags["reasoning-effort"]) env.AUTOWONDER_REASONING_EFFORT = flags["reasoning-effort"];
@@ -956,6 +957,7 @@ function cmdHelp() {
956
957
  autowonder — local runtime for AI agent dispatch execution
957
958
 
958
959
  Usage:
960
+ autowonder preview start|status|stop [options] Manage a live frontend preview relay
959
961
  autowonder browser [start|install] [options] Start the PRD browser MCP (Node.js 22+)
960
962
  autowonder connect --ws-url <url> --token <token> --executor-id <id> Connect to server and run
961
963
  autowonder start [--provider qoder|qodercn] Start daemon in background
@@ -1079,6 +1081,7 @@ async function main() {
1079
1081
 
1080
1082
  // Browser-only machines do not need daemon/provider setup or global Git changes.
1081
1083
  if (command === "browser") return require("./browser").cmdBrowser(commandArgs);
1084
+ if (command === "preview") return require("../lib/preview").cmdPreview(commandArgs);
1082
1085
  ensureWindowsUTF8();
1083
1086
 
1084
1087
  switch (command) {
@@ -0,0 +1,66 @@
1
+ # 执行器实时预览专用中转
2
+
3
+ Vite 与真实业务后端代理继续运行在执行器上,CLI 主动连接平台 WSS;没有 frp、通用 TCP 隧道或远端静态产物替代。平台入口保持 `/design-preview/<绑定标识>/`。复用现有执行器认证和平台成员/分享授权。
4
+
5
+ ## 配置和使用
6
+
7
+ 非敏感配置文件(运行时不写入 Token):
8
+
9
+ ```json
10
+ {
11
+ "relayUrl": "wss://app.example.com/design-preview-relay/v1/control/design-123",
12
+ "bindingId": "design-123",
13
+ "executorId": 789,
14
+ "auth": { "tokenEnv": "AUTOWONDER_EXECUTOR_TOKEN" }
15
+ }
16
+ ```
17
+
18
+ 平台绑定须准确匹配工作区、需求、会话、sourceKey 和执行器。Token 由安全环境注入,不能放命令参数、Prompt、URL、仓库或日志。只允许 WSS;回环地址开发允许 WS。验证服务器证书,拒绝重定向,不使用 HTTP/SOCKS 代理 agent。
19
+
20
+ ```bash
21
+ # npm/ 下隔离链接,保留其他任务正在用的全局 autowonder。
22
+ npm_config_prefix=/absolute/private/link-prefix tnpm link --ignore-scripts --omit=optional
23
+ export PATH=/absolute/private/link-prefix/bin:$PATH
24
+ # 工程中运行 Vite,登记实际端口。
25
+ pnpm dev:autowonder --base /design-preview/design-123/
26
+ autowonder preview start --id design-123 --port 5173 --config /absolute/private/preview.json --json
27
+ autowonder preview status --id design-123 --json
28
+ autowonder preview stop --id design-123 --json
29
+ ```
30
+
31
+ 配置路径也可由 `AUTOWONDER_PREVIEW_CONFIG` 提供。本地联调使用安装好的 CLI 或隔离链接。
32
+
33
+ 对支持自动恢复的会话,平台通过已认证的执行器连接发出启动请求。通过 `autowonder connect` 启动的 macOS 或 Linux 执行器使用同一安装包的 CLI,并用项目原有的 Vite 配置启动服务。Vite 退出后,执行器优先复用上次的端口。发生端口冲突时,执行器读取 Vite 实际选择的端口,以原绑定重新登记。手工 `preview start` 适用于已经自行启动 Vite 的工程。
34
+
35
+ ## 状态和生命周期
36
+
37
+ READY 表示已收到平台注册确认且登记的本机 Vite 能响应。网络断开为 RECONNECTING,Vite 退出为 LOCAL_SERVICE_UNAVAILABLE,认证失败/绑定冲突为 FAILED;状态命令实时检查本机服务,不能仅凭 PID 显示 READY。平台不可达时 start 等待最多 15 秒,保留重连监督进程并返回真实状态。
38
+
39
+ 相同 ID、配置与 owner 幂等复用。更换实际端口前仅停止所属 ID。默认状态位于 ~/.autowonder/preview;可用 AUTOWONDER_PREVIEW_HOME 指向独立目录。目录 0700、文件 0600;只保存 Token 摘要和本机状态服务密码,不保存执行器 Token。监督进程使用已验证 PID 指纹,避免误杀其他进程。daemon 自动注入 AUTOWONDER_PREVIEW_OWNER_PID,预览跨任务轮次保留,所属 daemon 退出后关闭。独立手工运行应明确 stop;Windows 托管模式仍不支持。
40
+
41
+ CLI 启动独立监督进程,再由它运行转发子进程。子进程崩溃、收到异常终止信号或超过 15 秒没有更新健康状态时,监督进程清理并自动重启,退避最高 5 秒;卡死子进程先终止,2.5 秒后仍未退出才强制结束。明确 stop 会先写停止意图再通知监督进程,确保不会被自动拉起;认证失败和绑定冲突保持 FAILED,不无限重试凭据。执行器身份使用固定 UTC/C locale 的启动时间,避免语言、时区或命令文本变化造成误判;`ps` 超时/错误属于 UNKNOWN,不等同退出。连续 10 秒无法确认身份时暂停转发,确认原执行器仍存活后自动恢复;确认退出或 PID 被复用时结束预览。状态保留最近 12 条脱敏退出/恢复事件和 restartCount,便于追查,而不是无原因地 STOPPED。
42
+
43
+ 启动使用私有 stdin 屏障:父命令先登记新监督进程的真实 PID 和启动指纹,再允许它初始化转发。机器繁忙、Node 加载较慢时,status 返回 RECONNECTING,重复 start 等待/复用同一个进程,不把尚在启动的进程误当成已退出而删除状态。
44
+
45
+ 监督进程本身被 SIGKILL 时,转发子进程每次健康检查都核对实际父进程,发现已被收养便关闭控制连接和数据流后退出,不留下占用绑定的孤儿。此时 status 准确返回 FAILED;再次 start 可回收失效状态并建立新连接,不伪报自动恢复。
46
+
47
+ 每 2 秒探测本机绑定根路径并发送健康报告,确认超过 7 秒失效;重连退避最大 5 秒并带抖动。断线关闭本代次所有 HTTP/HMR 连接,不重放已中断 API。每请求单次密钥数据 WSS,二进制块 64 KiB,帧 128 KiB,最多 24 个并发,块/消息逐个确认,慢流 5 秒确认超时清理;HTTP 空闲 30 秒、最长 10 分钟,请求体最大 32 MiB。只访问 127.0.0.1 的登记端口,不接受平台指定目标;项目自己的 Vite proxy 仍可访问项目配置的真实后端。
48
+
49
+ 重连遇到 409 时,先等待旧连接的 8 秒心跳租约失效;持续冲突超过 10 秒后的下一次尝试才作为其他连接占用而 FAILED。不会抢占仍存活的连接,也不会把半断开的旧连接误判为永久不可恢复。
50
+
51
+ 平台剥离自身 Cookie、Bearer 和代理头;真实业务认证沿用 Vite 工程配置。预览同源脚本仍须可信,不应宣称浏览器登录态隔离。平台多实例必须额外解决连接归属路由,当前实现为单实例注册表。
52
+
53
+ ## 验证
54
+
55
+ ```bash
56
+ node --test npm/test/preview.test.js
57
+ AUTOWONDER_TEST_PREVIEW_CLI=1 go test ./runtime/procreap -run TestPreviewSurvivesRealDispatchReap
58
+ AUTOWONDER_TEST_VITE_PACKAGE=/absolute/project/node_modules/vite go test ./cmd/autowonder-daemon -run TestPrd
59
+ # 主应用先 test-compile 并生成 target/preview-relay-classpath.txt;详情见主应用 docs/prd-preview-relay.md。
60
+ # PATH 必须指向上述 tnpm link。fixture 不使用其他任务的服务。
61
+ PREVIEW_PLATFORM_WORKTREE=/absolute/platform/worktree node scripts/preview-hmr-fixture.cjs /absolute/uxer-fe-template
62
+ ```
63
+
64
+ fixture 复制模板到临时目录,使用生产 Java 中转、新 CLI、真实 Vite/React 和独立 HTTP 后端。打开输出的回环入口,点击进入,计数一次,再在 fixture 输入 update,检查 After HMR、Count 1 和 Vite backend OK;status 输出后端命中计数,stop 释放所属资源。登录/数据库为合成 fixture,完整业务 E2E 另测。
65
+
66
+ 本次仅限本机回环;不部署、不发包,不对外映射办公网。集成 CLI 或使用 WSS 仍须遵守公司安全审批。回环不能证明跨机器、真实 TLS 或公司网络已通过。
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const os = require("os");
6
+ const http = require("http");
7
+ const crypto = require("crypto");
8
+ const { spawn, spawnSync } = require("child_process");
9
+ const hash = (value) => crypto.createHash("sha256").update(value).digest("hex");
10
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
11
+ const root = () => path.resolve(process.env.AUTOWONDER_PREVIEW_HOME || path.join(os.homedir(), ".autowonder", "preview"));
12
+ const quote = (s) => JSON.stringify(String(s));
13
+ function fail(code, message) { const e = new Error(message); e.code = code; throw e; }
14
+ function validId(id) {
15
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$/.test(id || "")) fail("INVALID_ARGUMENT", "--id must contain 1-80 letters, numbers, underscores or hyphens");
16
+ return id;
17
+ }
18
+ const dirFor = (id) => path.join(root(), "sessions", validId(id));
19
+ function privateDir(dir) { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); fs.chmodSync(dir, 0o700); }
20
+ function writeJSON(file, value) {
21
+ const tmp = `${file}.${process.pid}.tmp`;
22
+ fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
23
+ fs.renameSync(tmp, file);
24
+ }
25
+ function readJSON(file) { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } }
26
+ function fingerprint(pid) {
27
+ if (!Number.isSafeInteger(Number(pid)) || Number(pid) < 1) return "";
28
+ const result = process.platform === "win32"
29
+ ? spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `(Get-Process -Id ${Number(pid)} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().Ticks`], { encoding: "utf8", timeout: 3000, windowsHide: true })
30
+ : spawnSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
31
+ encoding: "utf8", timeout: 2000, env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
32
+ });
33
+ return result.status === 0 && result.stdout.trim() ? "v2:" + result.stdout.trim() : "";
34
+ }
35
+ // A failed ps invocation is not evidence that an executor exited. Never reclaim
36
+ // a lock or stop a preview on an inconclusive process lookup.
37
+ function inspectProcess(state, probe = {}) {
38
+ if (!state || !Number.isSafeInteger(state.pid) || state.pid < 1) return "DEAD";
39
+ try { (probe.kill || process.kill)(state.pid, 0); }
40
+ catch (error) { if (error.code === "ESRCH") return "DEAD"; }
41
+ if (!state.fingerprint) return "UNKNOWN";
42
+ let actual;
43
+ if (probe.fingerprint) actual = probe.fingerprint(state.pid);
44
+ else if (state.fingerprint.startsWith("v2:")) actual = fingerprint(state.pid);
45
+ else {
46
+ // Read states created before the stable, locale-independent identity format.
47
+ const result = spawnSync("ps", ["-p", String(state.pid), "-o", "lstart=", "-o", "command="], { encoding: "utf8", timeout: 2000 });
48
+ actual = result.status === 0 ? result.stdout.trim() : "";
49
+ }
50
+ return !actual ? "UNKNOWN" : actual === state.fingerprint ? "MATCH" : "DEAD";
51
+ }
52
+ function owns(state) { return inspectProcess(state) === "MATCH"; }
53
+ async function withLock(name, action) {
54
+ privateDir(root());
55
+ const dir = path.join(root(), `${name}.lock`);
56
+ const until = Date.now() + 45000;
57
+ for (;;) {
58
+ try {
59
+ fs.mkdirSync(dir, { mode: 0o700 });
60
+ writeJSON(path.join(dir, "owner.json"), { pid: process.pid, fingerprint: fingerprint(process.pid) });
61
+ break;
62
+ } catch (e) {
63
+ if (e.code !== "EEXIST") throw e;
64
+ const owner = readJSON(path.join(dir, "owner.json"));
65
+ let age = 0;
66
+ try { age = Date.now() - fs.statSync(dir).mtimeMs; } catch { continue; }
67
+ if ((owner && inspectProcess(owner) === "DEAD") || (!owner && age > 30000)) { fs.rmSync(dir, { recursive: true, force: true }); continue; }
68
+ if (Date.now() >= until) fail("BUSY", "Another preview operation is still running");
69
+ await sleep(100);
70
+ }
71
+ }
72
+ try { return await action(); } finally { fs.rmSync(dir, { recursive: true, force: true }); }
73
+ }
74
+ function port(value, label) {
75
+ if (!/^\d+$/.test(String(value)) || Number(value) < 1 || Number(value) > 65535) fail("INVALID_ARGUMENT", `${label} must be between 1 and 65535`);
76
+ return Number(value);
77
+ }
78
+ function envSecret(name, env) {
79
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name || "") || !env[name] || /[\x00-\x1f\x7f]/.test(env[name])) fail("CONFIGURATION", "A required credential environment variable is missing or invalid");
80
+ return env[name];
81
+ }
82
+ function loadConfig(file, localPort, env = process.env) {
83
+ if (!file) fail("CONFIGURATION", "Provide --config or AUTOWONDER_PREVIEW_CONFIG");
84
+ let input;
85
+ try { input = JSON.parse(fs.readFileSync(path.resolve(file), "utf8")); } catch { fail("CONFIGURATION", "Cannot read preview JSON configuration"); }
86
+ if (!input || typeof input !== "object" || Array.isArray(input)) fail("CONFIGURATION", "Preview configuration must be an object");
87
+ let url;
88
+ try { url = new URL(input.relayUrl); } catch { fail("CONFIGURATION", "relayUrl must be a valid absolute URL"); }
89
+ const loopback = (host) => ["localhost", "127.0.0.1", "[::1]", "::1"].includes(host);
90
+ if (typeof input.bindingId !== "string" || !/^[A-Za-z0-9_-]{1,100}$/.test(input.bindingId) ||
91
+ url.username || url.password || url.pathname !== `/design-preview-relay/v1/control/${input.bindingId}` || url.search || url.hash ||
92
+ !(url.protocol === "wss:" || (url.protocol === "ws:" && loopback(url.hostname))))
93
+ fail("CONFIGURATION", "relayUrl requires WSS and the matching binding control path; loopback WS is allowed for local tests");
94
+ const auth = input.auth;
95
+ if (!auth || typeof auth !== "object") fail("CONFIGURATION", "Configure tokenEnv under auth");
96
+ if (!Number.isSafeInteger(input.executorId) || input.executorId <= 0) fail("CONFIGURATION", "executorId must be a positive integer");
97
+ const secrets = { token: envSecret(auth.tokenEnv, env) };
98
+ const basePath = `/design-preview/${input.bindingId}/`;
99
+ const publicUrl = new URL(basePath, url); publicUrl.protocol = url.protocol === "wss:" ? "https:" : "http:";
100
+ const config = { relayUrl: url.href, bindingId: input.bindingId, executorId: input.executorId,
101
+ basePath, publicUrl: publicUrl.href, localPort: port(localPort, "--port") };
102
+ if (input.healthKey !== undefined) {
103
+ if (typeof input.healthKey !== "string" || !/^[a-f0-9]{48}$/.test(input.healthKey)) fail("CONFIGURATION", "Invalid managed Vite health key");
104
+ config.healthKey = input.healthKey;
105
+ }
106
+ return { ...config, secrets, configHash: hash(JSON.stringify({ ...config, secrets })) };
107
+ }
108
+ function request(url, auth, json = false, headers) {
109
+ return new Promise((resolve) => {
110
+ const req = http.get(url, { auth, headers, timeout: 1500 }, (res) => {
111
+ if (!json) { resolve({ code: res.statusCode, headers: res.headers }); res.destroy(); req.destroy(); return; }
112
+ let body = "";
113
+ res.on("data", (data) => { body += data.toString(); if (body.length > 256 * 1024) { resolve(null); req.destroy(); } });
114
+ res.on("end", () => { try { resolve({ code: res.statusCode, body: json ? JSON.parse(body) : body }); } catch { resolve({ code: res.statusCode }); } });
115
+ res.on("error", () => resolve(null));
116
+ });
117
+ req.on("timeout", () => req.destroy());
118
+ req.on("error", () => resolve(null));
119
+ const deadline = setTimeout(() => { resolve(null); req.destroy(); }, 1500);
120
+ req.on("close", () => clearTimeout(deadline));
121
+ });
122
+ }
123
+ async function localReady(localPort, basePath = "/", healthKey) {
124
+ if (healthKey) {
125
+ const challenge = crypto.randomBytes(16).toString("hex");
126
+ const result = await request(`http://127.0.0.1:${localPort}${basePath}_autowonder/health`, undefined, false,
127
+ { "X-Autowonder-Preview-Challenge": challenge });
128
+ const proof = result?.headers?.["x-autowonder-preview-proof"];
129
+ const expected = crypto.createHmac("sha256", healthKey).update(challenge).digest("hex");
130
+ return result?.code === 204 && typeof proof === "string" && /^[a-f0-9]{64}$/.test(proof) &&
131
+ crypto.timingSafeEqual(Buffer.from(proof, "hex"), Buffer.from(expected, "hex"));
132
+ }
133
+ const result = await request(`http://127.0.0.1:${localPort}${basePath}`, undefined, false, { Accept: "text/html" });
134
+ return Boolean(result && result.code >= 200 && result.code < 400);
135
+ }
136
+ function redact(text, secrets) {
137
+ let result = String(text || "");
138
+ for (const secret of Object.values(secrets || {})) if (secret) result = result.split(secret).join("[redacted]");
139
+ return result.replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/g, "[redacted-url]").slice(-1500);
140
+ }
141
+ async function status(id) {
142
+ const state = readJSON(path.join(dirFor(id), "state.json"));
143
+ if (!state) return { id, status: "STOPPED" };
144
+ const result = { id, status: state.status, url: state.url, port: state.localPort, diagnostic: state.diagnostic || undefined };
145
+ if (state.status === "STOPPED" || state.status === "FAILED") return result;
146
+ if (inspectProcess(state) === "DEAD") return { ...result, status: "FAILED", diagnostic: "Preview supervisor exited; run start to reclaim the session" };
147
+ if (state.owner && inspectProcess(state.owner) === "DEAD") return { ...result, status: "FAILED", diagnostic: "Owning executor has exited" };
148
+ if (!Number.isInteger(state.adminPort)) return { ...result, status: "RECONNECTING", diagnostic: state.diagnostic || "Preview forwarding worker is starting" };
149
+ const admin = await request(`http://127.0.0.1:${state.adminPort}/status`, `preview:${state.adminPassword}`, true);
150
+ if (admin?.code === 200 && admin.body?.status) return { ...result, ...admin.body, id, url: state.url, port: state.localPort };
151
+ return { ...result, status: "RECONNECTING", diagnostic: "Preview supervisor is not responding" };
152
+ }
153
+ async function stopUnlocked(id) {
154
+ const dir = dirFor(id);
155
+ const state = readJSON(path.join(dir, "state.json"));
156
+ if (!state) return { id, status: "STOPPED" };
157
+ if (inspectProcess(state) === "UNKNOWN") fail("BUSY", "Cannot verify preview process identity; state was preserved");
158
+ if (owns(state)) {
159
+ writeJSON(path.join(dir, "stop.json"), { at: new Date().toISOString() });
160
+ process.kill(state.pid, "SIGTERM");
161
+ const deadline = Date.now() + 7000;
162
+ while (inspectProcess(state) !== "DEAD" && Date.now() < deadline) await sleep(100);
163
+ if (inspectProcess(state) !== "DEAD") fail("STOP_FAILED", "Preview supervisor has not exited; its state was preserved");
164
+ }
165
+ fs.rmSync(dir, { recursive: true, force: true });
166
+ return { id, status: "STOPPED" };
167
+ }
168
+ async function start(id, localPort, file) {
169
+ const config = loadConfig(file || process.env.AUTOWONDER_PREVIEW_CONFIG, localPort);
170
+ const ownerPid = process.env.AUTOWONDER_PREVIEW_OWNER_PID;
171
+ const owner = ownerPid ? { pid: Number(ownerPid), fingerprint: fingerprint(Number(ownerPid)) } : null;
172
+ if (owner && !owns(owner)) fail("OWNER_UNAVAILABLE", "The owning executor process is unavailable");
173
+ if (owner && process.platform === "win32") fail("UNSUPPORTED_LIFECYCLE", "Managed preview on Windows requires daemon-owned process launch; use a macOS or Linux executor");
174
+ return withLock(`session-${validId(id)}`, async () => {
175
+ const dir = dirFor(id);
176
+ const previous = readJSON(path.join(dir, "state.json"));
177
+ if (previous && inspectProcess(previous) === "UNKNOWN") fail("BUSY", "Cannot verify existing preview process identity; retry start");
178
+ if (previous && owns(previous)) {
179
+ if (previous.configHash !== config.configHash || JSON.stringify(previous.owner) !== JSON.stringify(owner)) fail("CONFLICT", "Preview id belongs to a different configuration or executor");
180
+ return status(id);
181
+ }
182
+ await stopUnlocked(id);
183
+ if (!await localReady(config.localPort, config.basePath, config.healthKey)) fail("LOCAL_SERVICE_UNAVAILABLE", "Start Vite with the registered base path before opening a preview");
184
+ privateDir(dir);
185
+ const secretEnv = { AW_PREVIEW_TOKEN: config.secrets.token };
186
+ const state = { id, status: "STARTING", configHash: config.configHash, url: config.publicUrl, localPort: config.localPort, owner,
187
+ adminPassword: crypto.randomBytes(24).toString("hex"), config: { ...config, secrets: undefined } };
188
+ writeJSON(path.join(dir, "state.json"), state);
189
+ // This service belongs to the executor, rather than the task that requested it.
190
+ // Keep it out of dispatch-scoped environment/cwd cleanup without changing that cleanup policy.
191
+ const workerEnv = { ...process.env, ...secretEnv };
192
+ delete workerEnv.AUTOWONDER_DISPATCH_ID;
193
+ const child = spawn(process.execPath, [path.join(__dirname, "supervisor.js"), dir], {
194
+ cwd: dir, detached: true, stdio: ["pipe", "ignore", "ignore"], windowsHide: true, env: workerEnv,
195
+ });
196
+ let spawnError = false;
197
+ child.on("error", () => { spawnError = true; });
198
+ child.stdin?.on("error", () => {});
199
+ if (!child.pid) fail("START_FAILED", "Preview supervisor could not be spawned");
200
+ // Publish the actual process identity before releasing the startup barrier.
201
+ // Under load Node initialization can take longer than start's wait deadline;
202
+ // another start/status must never mistake that live process for stale state.
203
+ try {
204
+ state.pid = child.pid; state.fingerprint = fingerprint(child.pid);
205
+ if (!state.fingerprint) fail("START_FAILED", "Cannot verify newly spawned preview process identity");
206
+ writeJSON(path.join(dir, "state.json"), state);
207
+ child.stdin.end("start\n");
208
+ } catch (error) {
209
+ child.kill("SIGTERM"); child.stdin?.destroy(); child.unref();
210
+ throw error;
211
+ }
212
+ child.unref();
213
+ const deadline = Date.now() + 15000;
214
+ while (Date.now() < deadline && !spawnError) {
215
+ const current = readJSON(path.join(dir, "state.json"));
216
+ if (current?.status === "FAILED") fail("START_FAILED", current.diagnostic || "Preview could not start");
217
+ if (current?.pid) {
218
+ const live = await status(id);
219
+ if (live.status === "READY") return live;
220
+ }
221
+ await sleep(150);
222
+ }
223
+ // Keep reconnecting under executor ownership; a temporary platform outage is recoverable.
224
+ return status(id);
225
+ });
226
+ }
227
+
228
+ const HELP = `autowonder preview — 执行器实时前端预览(专用 WSS 中转)
229
+ start --id <id> --port <port> [--config <file>] [--json]
230
+ status --id <id> [--json]
231
+ stop --id <id> [--json]
232
+ 配置路径也可通过 AUTOWONDER_PREVIEW_CONFIG 指定;配置结构见 npm/lib/preview/README.md。
233
+ 本地联调使用 tnpm link 后的 autowonder,不自动安装远端包。`;
234
+ async function cmdPreview(args) {
235
+ const json = args.includes("--json");
236
+ try {
237
+ if (!args.length || args.includes("--help") || args.includes("-h")) { console.log(json ? JSON.stringify({ help: HELP }) : HELP); return; }
238
+ const [command, ...rest] = args;
239
+ if (!["start", "status", "stop"].includes(command)) fail("INVALID_ARGUMENT", "Unknown preview command");
240
+ const flags = {};
241
+ const allowed = command === "start" ? ["id", "port", "config"] : ["id"];
242
+ for (let i = 0; i < rest.length; i++) {
243
+ if (rest[i] === "--json") continue;
244
+ const key = rest[i].slice(2);
245
+ if (!rest[i].startsWith("--") || !allowed.includes(key) || key in flags || !rest[i + 1] || rest[i + 1].startsWith("--")) fail("INVALID_ARGUMENT", "Unknown, duplicate or missing preview argument");
246
+ flags[key] = rest[++i];
247
+ }
248
+ const id = validId(flags.id);
249
+ const result = command === "start" ? await start(id, flags.port, flags.config)
250
+ : command === "stop" ? await withLock(`session-${id}`, () => stopUnlocked(id)) : await status(id);
251
+ console.log(json ? JSON.stringify(result) : `${result.id}: ${result.status}${result.url ? ` ${result.url}` : ""}${result.diagnostic ? ` — ${result.diagnostic}` : ""}`);
252
+ if (result.status === "FAILED") process.exitCode = 1;
253
+ } catch (e) {
254
+ const result = { status: "FAILED", code: e.code || "PREVIEW_ERROR", diagnostic: e.code ? e.message : "Preview operation failed; check configuration, binary and local state permissions" };
255
+ console[json ? "log" : "error"](json ? JSON.stringify(result) : result.diagnostic);
256
+ process.exitCode = 1;
257
+ }
258
+ }
259
+ module.exports = { cmdPreview, start, status, stopUnlocked, loadConfig, localReady, redact, fingerprint, inspectProcess, owns, root, writeJSON, readJSON, withLock, request, quote, sleep, HELP };
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+
3
+ const http = require("http");
4
+ const WebSocket = require("ws");
5
+ const CHUNK = 64 * 1024, FRAME = 128 * 1024, MAX_STREAMS = 24;
6
+ const DROP = new Set(["authorization", "cookie", "host", "connection", "content-length", "proxy-authorization", "proxy-authenticate", "upgrade", "te", "trailer", "transfer-encoding", "keep-alive", "origin", "referer", "forwarded", "sec-websocket-key", "sec-websocket-version", "sec-websocket-extensions", "sec-websocket-protocol"]);
7
+ function headers(input) {
8
+ if (!Array.isArray(input) || input.length > 128) throw new Error("Invalid preview headers");
9
+ const result = {};
10
+ const dynamic = new Set(input.filter(([k]) => String(k).toLowerCase() === "connection").flatMap(([, v]) => String(v).toLowerCase().split(",").map(s => s.trim())));
11
+ for (const [key, value] of input) {
12
+ const lower = String(key).toLowerCase();
13
+ if (!DROP.has(lower) && !dynamic.has(lower) && !lower.startsWith("x-forwarded-") && !lower.startsWith("x-autowonder-")) result[lower] = value;
14
+ }
15
+ result["accept-encoding"] = "identity";
16
+ return result;
17
+ }
18
+ function validPath(value, basePath) {
19
+ if (typeof value !== "string" || value.length > 16384 || !value.startsWith(basePath) || /[\\\x00-\x20\x7f#]/.test(value)) return false;
20
+ const path = value.split("?")[0];
21
+ return !/%(?:2e|2f|5c|25)/i.test(path) && !path.split("/").some(part => part === "." || part === "..");
22
+ }
23
+ function connect(url, extra = {}) {
24
+ // ws uses a direct Node http(s) connection. No proxy agents, redirects or URL credentials.
25
+ return new WebSocket(url, { ...extra, followRedirects: false, handshakeTimeout: 5000, maxPayload: FRAME, perMessageDeflate: false });
26
+ }
27
+ function send(socket, value) {
28
+ return new Promise((resolve, reject) => {
29
+ if (socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > FRAME * 2) return reject(new Error("Preview socket unavailable"));
30
+ const timer = setTimeout(() => { socket.terminate(); reject(new Error("Preview write timed out")); }, 5000);
31
+ socket.send(value, error => { clearTimeout(timer); error ? reject(error) : resolve(); });
32
+ });
33
+ }
34
+ const json = (socket, value) => send(socket, JSON.stringify(value));
35
+
36
+ /** One independently bounded data socket per HTTP request/HMR connection. No platform-selected destination. */
37
+ function serveData(config, control, open, streams) {
38
+ if (!/^[a-f0-9-]{36}$/.test(open.id || "") || !/^[A-Za-z0-9_-]{43}$/.test(open.key || "") || !["http", "ws"].includes(open.kind) || streams.has(open.id)) {
39
+ control.terminate(); return;
40
+ }
41
+ if (streams.size >= MAX_STREAMS) { void json(control, { type: "rejected", id: open.id }).catch(() => control.terminate()); return; }
42
+ const endpoint = new URL(config.relayUrl); endpoint.pathname = `/design-preview-relay/v1/data/${open.id}`;
43
+ const socket = connect(endpoint, { headers: { Authorization: `Bearer ${open.key}` } });
44
+ let local, response, ack, requestEnded = false, started = false, closed = false, received = 0, inputPending = false;
45
+ let idle = Date.now(), outbound = Promise.resolve(), queued = 0;
46
+ const close = () => {
47
+ if (closed) return; closed = true; clearInterval(timer); streams.delete(open.id);
48
+ if (ack) { clearTimeout(ack.timer); ack.reject(new Error("Preview closed")); ack = null; }
49
+ if (local) local instanceof WebSocket ? local.terminate() : local.destroy();
50
+ if (response) response.destroy(); socket.terminate();
51
+ };
52
+ streams.set(open.id, close);
53
+ const timer = setInterval(() => { if (!started || open.kind === "http") if (Date.now() - idle > 30000) close(); }, 1000);
54
+ async function acknowledged(value) {
55
+ if (closed || ack) throw new Error("Invalid preview send state");
56
+ const wait = new Promise((resolve, reject) => {
57
+ ack = { resolve, reject, timer: setTimeout(() => { if (ack) ack.reject(new Error("Preview acknowledgement timed out")); close(); }, 5000) };
58
+ });
59
+ // Attach the rejection before awaiting the socket write.
60
+ await Promise.all([send(socket, value), wait]); idle = Date.now();
61
+ }
62
+ function output(value) {
63
+ // ws messages arrive without stream backpressure; pause the loopback peer until acknowledged.
64
+ if (!local || local.readyState !== WebSocket.OPEN || ++queued > 2) return close();
65
+ local.pause();
66
+ outbound = outbound.then(() => acknowledged(value)).then(() => { queued--; if (!closed && !queued) local.resume(); }).catch(close);
67
+ }
68
+ function rewriteHeaders(res, requestPath) {
69
+ const result = [];
70
+ for (let i = 0; i < res.rawHeaders.length; i += 2) {
71
+ const name = res.rawHeaders[i]; let value = res.rawHeaders[i + 1];
72
+ if (name.toLowerCase() === "location") {
73
+ try {
74
+ const target = new URL(value, `http://127.0.0.1:${config.localPort}${requestPath}`);
75
+ if (!["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || Number(target.port || 80) !== config.localPort) continue;
76
+ value = target.pathname + target.search + target.hash;
77
+ } catch { continue; }
78
+ }
79
+ result.push([name, value]);
80
+ }
81
+ return result;
82
+ }
83
+ async function start(frame) {
84
+ if (started || frame.type !== "request" || frame.kind !== open.kind || !validPath(frame.path, config.basePath)) throw new Error("Invalid preview request");
85
+ started = true;
86
+ const safeHeaders = headers(frame.headers);
87
+ safeHeaders.host = `localhost:${config.localPort}`;
88
+ if (open.kind === "http") {
89
+ if (!["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].includes(frame.method)) throw new Error("Invalid preview method");
90
+ if (!["GET", "HEAD"].includes(frame.method)) safeHeaders["transfer-encoding"] = "chunked";
91
+ local = http.request({ hostname: "127.0.0.1", port: config.localPort, path: frame.path, method: frame.method, headers: safeHeaders, timeout: 30000 }, async res => {
92
+ response = res;
93
+ try {
94
+ await json(socket, { type: "response", status: res.statusCode, headers: rewriteHeaders(res, frame.path) });
95
+ for await (const chunk of res) {
96
+ for (let i = 0; i < chunk.length; i += CHUNK) await acknowledged(chunk.subarray(i, i + CHUNK));
97
+ }
98
+ await json(socket, { type: "end" });
99
+ // Platform closes after consuming end, so it cannot lose a queued final frame.
100
+ } catch { close(); }
101
+ });
102
+ local.on("timeout", close);
103
+ // A backend may reject an upload before consuming it. Preserve its response;
104
+ // response iteration still detects a truncated/failed response independently.
105
+ local.on("error", () => { if (!response) close(); });
106
+ } else {
107
+ local = new WebSocket(`ws://127.0.0.1:${config.localPort}${frame.path}`, "vite-hmr", {
108
+ headers: safeHeaders, followRedirects: false, maxPayload: CHUNK, handshakeTimeout: 5000, perMessageDeflate: false,
109
+ });
110
+ local.once("open", () => { void json(socket, { type: "opened" }).catch(close); });
111
+ local.on("message", (data, binary) => output(binary ? data : JSON.stringify({ type: "text", data: data.toString() })));
112
+ local.on("error", close); local.on("close", close);
113
+ }
114
+ }
115
+ socket.on("message", (data, binary) => {
116
+ idle = Date.now();
117
+ try {
118
+ if (binary) {
119
+ if (!started || inputPending || data.length > CHUNK) return close();
120
+ inputPending = true;
121
+ if (open.kind === "http") {
122
+ received += data.length;
123
+ if (requestEnded || received > 32 * 1024 * 1024) return close();
124
+ if (response && (local.destroyed || local.writableEnded)) {
125
+ inputPending = false; void json(socket, { type: "ack" }).catch(close);
126
+ } else local.write(data, error => {
127
+ inputPending = false;
128
+ if (error && !response) close(); else void json(socket, { type: "ack" }).catch(close);
129
+ });
130
+ } else {
131
+ if (local.readyState !== WebSocket.OPEN) return close();
132
+ local.send(data, { binary: true }, error => { inputPending = false; if (error) close(); else void json(socket, { type: "ack" }).catch(close); });
133
+ }
134
+ return;
135
+ }
136
+ const frame = JSON.parse(data.toString());
137
+ if (frame.type === "ack") {
138
+ if (!ack) return close(); const pending = ack; ack = null; clearTimeout(pending.timer); pending.resolve(); return;
139
+ }
140
+ if (frame.type === "request") { void start(frame).catch(close); return; }
141
+ if (!started) return close();
142
+ if (frame.type === "end" && open.kind === "http" && !requestEnded) { requestEnded = true; local.end(); }
143
+ else if (frame.type === "text" && !inputPending && open.kind === "ws" && local.readyState === WebSocket.OPEN && Buffer.byteLength(frame.data || "") <= CHUNK) {
144
+ inputPending = true;
145
+ local.send(frame.data, error => { inputPending = false; if (error) close(); else void json(socket, { type: "ack" }).catch(close); });
146
+ } else close();
147
+ } catch { close(); }
148
+ });
149
+ socket.on("error", close); socket.on("close", close);
150
+ return close;
151
+ }
152
+ module.exports = { CHUNK, FRAME, MAX_STREAMS, connect, json, serveData, validPath, headers };
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { spawn } = require("child_process");
6
+ const { readJSON, writeJSON, inspectProcess } = require("./index");
7
+
8
+ function run() {
9
+ const dir = process.argv[2], file = path.join(dir, "state.json"), initial = readJSON(file);
10
+ if (!initial || initial.pid !== process.pid || !initial.fingerprint || !process.env.AW_PREVIEW_TOKEN) throw new Error("Invalid preview supervisor state");
11
+ const token = process.env.AW_PREVIEW_TOKEN;
12
+ delete process.env.AW_PREVIEW_TOKEN;
13
+ let child, tick, retry, killTimer, finalStatus, finalReason, closing = false, unknownSince = 0, suspended = false;
14
+ let restartCount = 0, startedAt = 0, backoff = 250;
15
+ const snapshot = () => readJSON(file) || initial;
16
+ const save = (status, reason, extra = {}) => {
17
+ const state = snapshot();
18
+ const events = [...(state.events || []), { at: new Date().toISOString(), reason }].slice(-12);
19
+ writeJSON(file, { ...state, ...extra, status, diagnostic: reason, events, updatedAt: Date.now() });
20
+ };
21
+ writeJSON(file, { ...initial, restartCount: 0, updatedAt: Date.now() });
22
+ const haltChild = () => {
23
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
24
+ const current = child;
25
+ current.kill("SIGTERM");
26
+ killTimer = setTimeout(() => { if (current.exitCode === null && current.signalCode === null) current.kill("SIGKILL"); }, 2500);
27
+ };
28
+ const finish = (status, reason) => {
29
+ if (closing) return;
30
+ closing = true; finalStatus = status; finalReason = reason; clearTimeout(retry); clearInterval(tick);
31
+ try { save(status, reason); } catch {} // Disk failure must not prevent process cleanup.
32
+ haltChild();
33
+ if (!child || child.exitCode !== null || child.signalCode !== null) process.exit(status === "FAILED" ? 1 : 0);
34
+ };
35
+ const launch = () => {
36
+ if (closing || suspended) return;
37
+ if (fs.existsSync(path.join(dir, "stop.json"))) return finish("STOPPED", "EXPLICIT_STOP");
38
+ save("RECONNECTING", restartCount ? "WORKER_RESTARTING" : "STARTING", { restartCount, adminPort: undefined, workerPid: undefined });
39
+ startedAt = Date.now();
40
+ child = spawn(process.execPath, [path.join(__dirname, "worker.js"), dir], {
41
+ cwd: dir, env: { ...process.env, AW_PREVIEW_TOKEN: token }, stdio: "ignore", windowsHide: true,
42
+ });
43
+ child.on("error", () => {});
44
+ child.once("close", (code, signal) => {
45
+ clearTimeout(killTimer); child = undefined;
46
+ if (closing) { try { save(finalStatus, finalReason); } catch {} process.exit(finalStatus === "FAILED" ? 1 : 0); }
47
+ if (snapshot().status === "FAILED") return finish("FAILED", snapshot().diagnostic || "WORKER_FAILED");
48
+ if (suspended) return;
49
+ restartCount++;
50
+ save("RECONNECTING", signal ? `WORKER_SIGNAL_${signal}` : `WORKER_EXIT_${code ?? "SPAWN_ERROR"}`, { restartCount });
51
+ if (Date.now() - startedAt > 30000) backoff = 250;
52
+ retry = setTimeout(launch, backoff); backoff = Math.min(backoff * 2, 5000);
53
+ });
54
+ };
55
+ const check = () => {
56
+ if (closing) return;
57
+ if (fs.existsSync(path.join(dir, "stop.json"))) return finish("STOPPED", "EXPLICIT_STOP");
58
+ const identity = initial.owner ? inspectProcess(initial.owner) : "MATCH";
59
+ if (identity === "DEAD") return finish("STOPPED", "OWNER_EXITED");
60
+ if (identity === "UNKNOWN") {
61
+ if (!unknownSince) unknownSince = Date.now();
62
+ if (Date.now() - unknownSince >= 10000 && !suspended) {
63
+ suspended = true; clearTimeout(retry);
64
+ save("RECONNECTING", "OWNER_IDENTITY_UNAVAILABLE"); haltChild();
65
+ }
66
+ return;
67
+ }
68
+ unknownSince = 0;
69
+ if (suspended) {
70
+ if (child) return;
71
+ suspended = false; launch(); return;
72
+ }
73
+ if (child && Date.now() - startedAt > 15000 && Date.now() - (snapshot().updatedAt || 0) > 15000) {
74
+ save("RECONNECTING", "WORKER_HEARTBEAT_TIMEOUT"); haltChild();
75
+ }
76
+ };
77
+ for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => finish("STOPPED", fs.existsSync(path.join(dir, "stop.json")) ? "EXPLICIT_STOP" : `SUPERVISOR_SIGNAL_${signal}`));
78
+ process.on("uncaughtException", () => finish("FAILED", "SUPERVISOR_INTERNAL_ERROR"));
79
+ tick = setInterval(check, 2000);
80
+ check(); launch();
81
+ }
82
+ let startup = "";
83
+ process.stdin.setEncoding("utf8");
84
+ process.stdin.on("data", chunk => { startup += chunk; if (startup.length > 16) process.exit(1); });
85
+ process.stdin.once("end", () => { if (startup !== "start\n") process.exit(1); run(); });
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+
3
+ const http = require("http");
4
+ const path = require("path");
5
+ const crypto = require("crypto");
6
+ const { writeJSON, readJSON, localReady } = require("./index");
7
+ const { connect, json, serveData } = require("./relay");
8
+ async function run() {
9
+ const dir = process.argv[2], file = path.join(dir, "state.json"), state = readJSON(file);
10
+ if (!state || state.pid !== process.ppid) throw new Error("Invalid preview worker state");
11
+ const config = state.config, token = process.env.AW_PREVIEW_TOKEN;
12
+ delete process.env.AW_PREVIEW_TOKEN;
13
+ if (!token) throw new Error("Preview credential unavailable");
14
+ state.workerPid = process.pid;
15
+ let socket, retry, tick, closing = false, checking = false, lastAck = 0, connected = false, registered = false, terminal = false;
16
+ let backoff = 250, lastHealth = false, conflictSince = 0;
17
+ const streams = new Map();
18
+ const persist = (status, diagnostic) => {
19
+ // Preserve the supervisor's bounded restart/exit history across generations.
20
+ const current = readJSON(file);
21
+ if (current?.workerPid && current.workerPid !== process.pid) return;
22
+ state.status = status; state.diagnostic = diagnostic; state.updatedAt = Date.now();
23
+ state.events = current?.events; state.restartCount = current?.restartCount;
24
+ if (!closing || status === "FAILED") writeJSON(file, state);
25
+ };
26
+ const dropStreams = () => { for (const close of [...streams.values()]) close(); };
27
+ const verifyLocalService = () => localReady(config.localPort, config.basePath, config.healthKey);
28
+ const summary = async () => {
29
+ if (terminal) return { status: "FAILED", diagnostic: state.diagnostic };
30
+ const local = await verifyLocalService();
31
+ if (!local) return { status: "LOCAL_SERVICE_UNAVAILABLE", diagnostic: "Registered local Vite service is unavailable" };
32
+ if (!connected || !registered || Date.now() - lastAck > 7000) return { status: "RECONNECTING", diagnostic: "Waiting for authenticated platform registration" };
33
+ return { status: "READY" };
34
+ };
35
+ const server = http.createServer(async (req, res) => {
36
+ const expected = Buffer.from("Basic " + Buffer.from("preview:" + state.adminPassword).toString("base64"));
37
+ const actual = Buffer.from(req.headers.authorization || "");
38
+ if (actual.length !== expected.length || !crypto.timingSafeEqual(actual, expected)) { res.writeHead(401); res.end(); return; }
39
+ if (req.url !== "/status") { res.writeHead(404); res.end(); return; }
40
+ const live = await summary(); res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(live));
41
+ });
42
+ server.maxConnections = 8; server.requestTimeout = 3000; server.headersTimeout = 3000;
43
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
44
+ state.adminPort = server.address().port; persist("STARTING");
45
+ const finish = (failed = false, diagnostic) => {
46
+ if (closing) return; closing = true; terminal = failed;
47
+ clearTimeout(retry); clearInterval(tick); dropStreams();
48
+ if (socket) socket.terminate();
49
+ if (failed) persist("FAILED", diagnostic);
50
+ server.close(); server.closeAllConnections?.();
51
+ setTimeout(() => process.exit(failed ? 1 : 0), 50);
52
+ };
53
+ const health = async () => {
54
+ if (checking || closing) return; checking = true;
55
+ try {
56
+ // SIGKILL cannot run the supervisor's shutdown handler. An adopted worker
57
+ // must release its platform lease instead of surviving as an orphan.
58
+ if (process.ppid !== state.pid) { finish(); return; }
59
+ const local = await verifyLocalService();
60
+ if (closing) return;
61
+ lastHealth = local;
62
+ if (connected) {
63
+ if (Date.now() - lastAck > 7000) socket.terminate();
64
+ else await json(socket, { type: "health", available: local, port: config.localPort });
65
+ }
66
+ if (!local) dropStreams();
67
+ persist(local && connected && registered && Date.now() - lastAck < 7000 ? "READY" : local ? "RECONNECTING" : "LOCAL_SERVICE_UNAVAILABLE",
68
+ local ? undefined : "Registered local Vite service is unavailable");
69
+ } catch { if (socket) socket.terminate(); }
70
+ finally { checking = false; }
71
+ };
72
+ const dial = () => {
73
+ if (closing) return;
74
+ registered = false; connected = false;
75
+ socket = connect(config.relayUrl, { headers: { Authorization: `Bearer ${token}`, "X-Autowonder-Executor": String(config.executorId) } });
76
+ socket.once("open", () => { connected = true; lastAck = Date.now(); void health(); });
77
+ socket.on("message", (data, binary) => {
78
+ try {
79
+ if (binary) return socket.terminate();
80
+ const frame = JSON.parse(data.toString());
81
+ if (frame.type === "registered") {
82
+ registered = frame.available === true && lastHealth; lastAck = Date.now(); backoff = 250; conflictSince = 0;
83
+ persist(registered ? "READY" : "LOCAL_SERVICE_UNAVAILABLE");
84
+ } else if (frame.type === "cancel" && /^[a-f0-9-]{36}$/.test(frame.id || "")) {
85
+ const close = streams.get(frame.id); if (close) close();
86
+ } else if (frame.type === "open" && registered && Date.now() - lastAck < 7000) {
87
+ if (!config.healthKey) { serveData(config, socket, frame, streams); return; }
88
+ const active = socket;
89
+ void verifyLocalService().then((local) => {
90
+ if (socket !== active || closing) return;
91
+ if (local && registered) serveData(config, active, frame, streams);
92
+ else active.terminate();
93
+ }).catch(() => active.terminate());
94
+ }
95
+ else socket.terminate();
96
+ } catch { socket.terminate(); }
97
+ });
98
+ socket.on("unexpected-response", (_request, res) => {
99
+ res.resume();
100
+ // After a half-open connection the platform may still own the old control
101
+ // generation until its 8-second heartbeat expires. Give that lease time to
102
+ // clear, rather than turning a recoverable disconnect into permanent FAILED.
103
+ if (res.statusCode === 409) {
104
+ if (!conflictSince) conflictSince = Date.now();
105
+ if (Date.now() - conflictSince < 10000) {
106
+ persist("RECONNECTING", "Waiting for the previous platform connection lease to expire");
107
+ socket.terminate(); return;
108
+ }
109
+ }
110
+ if ([401, 403, 404, 409].includes(res.statusCode)) finish(true,
111
+ res.statusCode === 409 ? "Preview binding is already owned by another connection" : res.statusCode === 404 ? "Preview binding is not configured on the platform" : "Preview executor authentication failed");
112
+ else socket.terminate();
113
+ });
114
+ socket.on("error", () => {});
115
+ socket.once("close", () => {
116
+ connected = false; registered = false; dropStreams();
117
+ if (!closing) {
118
+ persist("RECONNECTING", "Platform connection closed; retrying");
119
+ retry = setTimeout(dial, backoff + Math.floor(Math.random() * 250)); backoff = Math.min(backoff * 2, 5000);
120
+ }
121
+ });
122
+ };
123
+ for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => finish());
124
+ tick = setInterval(() => { void health(); }, 2000);
125
+ dial();
126
+ }
127
+ run().catch(() => process.exit(1));
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "@alicloud/autowonder",
3
- "version": "0.3.45",
3
+ "version": "0.3.47",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@alicloud/autowonder",
9
- "version": "0.3.45",
9
+ "version": "0.3.47",
10
10
  "license": "Apache-2.0",
11
+ "dependencies": {
12
+ "ws": "8.23.0"
13
+ },
11
14
  "bin": {
12
15
  "autowonder": "bin/cli.js"
13
16
  },
@@ -1349,6 +1352,27 @@
1349
1352
  "license": "ISC",
1350
1353
  "optional": true
1351
1354
  },
1355
+ "node_modules/ws": {
1356
+ "version": "8.23.0",
1357
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
1358
+ "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
1359
+ "license": "MIT",
1360
+ "engines": {
1361
+ "node": ">=10.0.0"
1362
+ },
1363
+ "peerDependencies": {
1364
+ "bufferutil": "^4.0.1",
1365
+ "utf-8-validate": ">=5.0.2"
1366
+ },
1367
+ "peerDependenciesMeta": {
1368
+ "bufferutil": {
1369
+ "optional": true
1370
+ },
1371
+ "utf-8-validate": {
1372
+ "optional": true
1373
+ }
1374
+ }
1375
+ },
1352
1376
  "node_modules/zod": {
1353
1377
  "version": "4.6.7",
1354
1378
  "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alicloud/autowonder",
3
- "version": "0.3.45",
3
+ "version": "0.3.47",
4
4
  "description": "AutoWonder local runtime — execute AI agent dispatch packages on your machine",
5
5
  "bin": {
6
6
  "autowonder": "bin/cli.js"
@@ -41,6 +41,9 @@
41
41
  "@modelcontextprotocol/sdk": "1.32.2",
42
42
  "playwright": "1.64.0-alpha-1790635538000"
43
43
  },
44
+ "dependencies": {
45
+ "ws": "8.23.0"
46
+ },
44
47
  "scripts": {
45
48
  "prepack": "node scripts/verify-browser-package.js",
46
49
  "build": "./scripts/build-and-publish.sh --build",