agentroam 0.2.0-preview.8 → 0.2.0-preview.80

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.
Files changed (95) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +136 -5
  12. package/dist/cli.js +295 -44
  13. package/dist/cloudflared/bundled-asset.js +3 -2
  14. package/dist/cloudflared/manifest.js +2 -2
  15. package/dist/codex-desktop-command.js +70 -0
  16. package/dist/codex-desktop-force-stop.js +46 -0
  17. package/dist/codex-desktop-idle-guard.js +15 -0
  18. package/dist/codex-desktop-preflight.js +63 -0
  19. package/dist/codex-desktop-probe.js +152 -0
  20. package/dist/codex-desktop-setup.js +154 -0
  21. package/dist/codex-desktop-status.js +85 -0
  22. package/dist/codex-desktop-windows.js +122 -0
  23. package/dist/codex-runtime-manager.js +368 -0
  24. package/dist/codex-sharing.js +155 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +228 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/mesh/mesh-command.js +51 -0
  35. package/dist/mesh/mesh-config.js +95 -0
  36. package/dist/mesh/mesh-payload.js +20 -0
  37. package/dist/mesh/mesh-runtime.js +101 -0
  38. package/dist/native-runtime.js +68 -0
  39. package/dist/network.js +46 -3
  40. package/dist/node-runtime-manager.js +251 -0
  41. package/dist/opencode-runtime-manager.js +260 -0
  42. package/dist/platform-packages.js +18 -5
  43. package/dist/platform.js +6 -4
  44. package/dist/power/sleep-inhibitor.js +161 -0
  45. package/dist/runtime-manager.js +139 -19
  46. package/dist/self-hosted-relay.json +1 -0
  47. package/dist/service/launcher-cleanup.js +79 -0
  48. package/dist/service/macos-launch-agent.js +288 -0
  49. package/dist/service/runtime-state.js +43 -0
  50. package/dist/service/service-command.js +226 -0
  51. package/dist/service/service-controller.js +29 -0
  52. package/dist/service/service-files.js +78 -0
  53. package/dist/service/windows-service-host.js +59 -0
  54. package/dist/service/windows-task-service.js +289 -0
  55. package/dist/startup-lock.js +81 -0
  56. package/dist/tailscale/bundled-asset.js +43 -0
  57. package/dist/tailscale/daemon-manager.js +112 -0
  58. package/dist/tailscale/installer.js +131 -0
  59. package/dist/tailscale/manifest.js +15 -0
  60. package/dist/tailscale/tailnet-cli.js +101 -0
  61. package/dist/todo-mcp-command.js +27 -0
  62. package/dist/tunnel/cloudflare-provider.js +4 -1
  63. package/dist/tunnel/public-readiness.js +76 -50
  64. package/dist/tunnel/relay-orchestrator.js +53 -19
  65. package/dist/tunnel/self-hosted-provider.js +147 -0
  66. package/dist/tunnel/tunnel-controller.js +232 -0
  67. package/dist/unlock-service.js +105 -0
  68. package/dist/update/update-channel.js +38 -0
  69. package/dist/update/update-command.js +97 -0
  70. package/dist/update/update-install.js +34 -0
  71. package/dist/update/update-state.js +43 -0
  72. package/dist/update/update-worker.js +82 -0
  73. package/install/README.md +55 -0
  74. package/install/codex-shared-watchdog.sh +16 -0
  75. package/install/install-agentroam.ps1 +358 -0
  76. package/install/install-agentroam.sh +457 -0
  77. package/install/install-manifest.json +15 -0
  78. package/install/start-codex-desktop-shared.sh +152 -0
  79. package/install/write-relay-default.mjs +6 -0
  80. package/package.json +15 -10
  81. package/dist/args.test.js +0 -27
  82. package/dist/cloudflared/bundled-asset.test.js +0 -76
  83. package/dist/cloudflared/installer.test.js +0 -95
  84. package/dist/native-runtime.test.js +0 -19
  85. package/dist/network.test.js +0 -20
  86. package/dist/pairing.js +0 -2
  87. package/dist/platform-packages.test.js +0 -75
  88. package/dist/platform.test.js +0 -3
  89. package/dist/port.test.js +0 -3
  90. package/dist/process-supervisor.test.js +0 -42
  91. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  92. package/dist/tunnel/pinggy-provider.test.js +0 -40
  93. package/dist/tunnel/proxy-settings.test.js +0 -111
  94. package/dist/tunnel/public-readiness.test.js +0 -104
  95. package/dist/tunnel/relay-orchestrator.test.js +0 -72
package/dist/args.js CHANGED
@@ -1,12 +1,77 @@
1
1
  import { homedir } from "node:os";
2
2
  import { resolve } from "node:path";
3
+ import { isIPv4 } from "node:net";
3
4
  export function parseArgs(argv) {
4
5
  const values = [...argv];
5
6
  let command = "start";
6
- if (values[0] && ["start", "doctor", "version"].includes(values[0]))
7
+ if (values[0] && ["start", "doctor", "version", "service", "unlock-service", "update", "update-worker", "pair", "devices", "revoke", "approvals", "approve", "deny", "lock", "unlock", "audit", "codex-desktop", "desktop", "mesh"].includes(values[0])) {
7
8
  command = values.shift();
9
+ }
10
+ let serviceAction = null;
11
+ let unlockServiceAction = null;
12
+ let desktopAction;
13
+ let meshAction;
14
+ if (command === "mesh") {
15
+ const action = values.shift();
16
+ if (!action || !["status", "onboard", "offboard", "qr", "nodes"].includes(action)) {
17
+ throw cliError("mesh requires status, onboard, offboard, qr, or nodes");
18
+ }
19
+ meshAction = action;
20
+ }
21
+ if (command === "desktop") {
22
+ const action = values.shift();
23
+ if (!action || !["authorize", "status", "disable"].includes(action))
24
+ throw cliError("desktop requires authorize, status, or disable");
25
+ desktopAction = action;
26
+ }
27
+ if (command === "service") {
28
+ const action = values.shift();
29
+ if (!action || !["install", "start", "stop", "status", "url", "logs", "restart", "uninstall"].includes(action)) {
30
+ throw cliError("service requires install, start, stop, status, url, logs, restart, or uninstall");
31
+ }
32
+ serviceAction = action;
33
+ if (serviceAction !== "install" && values.length > 0) {
34
+ throw cliError(`service ${serviceAction} does not accept options`);
35
+ }
36
+ }
37
+ if (command === "unlock-service") {
38
+ const action = values.shift();
39
+ if (!action || !["install", "uninstall", "status"].includes(action) || values.length > 0) {
40
+ throw cliError("unlock-service requires install, uninstall, or status and accepts no options");
41
+ }
42
+ unlockServiceAction = action;
43
+ }
44
+ let revokeDeviceId = null;
45
+ let revokeAll = false;
46
+ if (command === "revoke") {
47
+ const device = values.shift();
48
+ if (device === "--all")
49
+ revokeAll = true;
50
+ else if (device && /^[a-f0-9-]{36}$/.test(device))
51
+ revokeDeviceId = device;
52
+ else
53
+ throw cliError("revoke requires a device ID or --all");
54
+ }
55
+ let approvalRequestId;
56
+ if (command === "approve" || command === "deny") {
57
+ approvalRequestId = values.shift();
58
+ if (!approvalRequestId || !/^[a-f0-9-]{36}$/.test(approvalRequestId))
59
+ throw cliError(`${command} requires a request ID`);
60
+ }
61
+ let updateVersion = null;
62
+ let updateStateFile = null;
63
+ if (command === "update" && values[0] && !values[0].startsWith("--"))
64
+ updateVersion = values.shift();
65
+ if (command === "update-worker") {
66
+ const stateFile = values.shift();
67
+ if (!stateFile || values.length > 0)
68
+ throw cliError("update-worker requires one state file");
69
+ updateStateFile = resolve(stateFile);
70
+ }
8
71
  const options = {
9
72
  command,
73
+ serviceAction,
74
+ unlockServiceAction,
10
75
  roots: [],
11
76
  port: null,
12
77
  relay: "auto",
@@ -14,16 +79,59 @@ export function parseArgs(argv) {
14
79
  localOnly: false,
15
80
  qr: true,
16
81
  dataDir: resolve(homedir(), ".agentroam"),
82
+ ...(command === "revoke" ? { revokeDeviceId, revokeAll } : {}),
83
+ ...(approvalRequestId ? { approvalRequestId } : {}),
84
+ updateVersion,
85
+ updateStateFile,
86
+ ...(desktopAction ? { desktopAction } : {}),
87
+ ...(meshAction ? { meshAction } : {}),
17
88
  };
18
- for (let index = 0; index < values.length; index++) {
89
+ for (let index = 0; index < values.length && command !== "update-worker"; index++) {
19
90
  const arg = values[index];
91
+ if (command === "desktop" && !["--data-dir", "--help", "-h"].includes(arg)) {
92
+ throw cliError("desktop accepts only --data-dir");
93
+ }
94
+ if (command === "mesh" && !["--data-dir", "--node-name", "--no-qr", "--help", "-h"].includes(arg)) {
95
+ throw cliError("mesh accepts only --data-dir, --node-name and --no-qr");
96
+ }
97
+ if (command === "codex-desktop" && !["--restart", "--dry-run", "--setup", "--status", "--repair", "--data-dir", "--help", "-h"].includes(arg)) {
98
+ throw cliError("codex-desktop accepts only --setup, --restart, --dry-run, --status, --repair and --data-dir");
99
+ }
20
100
  const next = () => {
21
101
  const value = values[++index];
22
102
  if (!value)
23
103
  throw cliError(`missing value for ${arg}`);
24
104
  return value;
25
105
  };
26
- if (arg === "--root")
106
+ if (arg === "--restart" && command === "codex-desktop")
107
+ options.desktopRestart = true;
108
+ else if (arg === "--dry-run" && command === "codex-desktop")
109
+ options.desktopDryRun = true;
110
+ else if (arg === "--status" && command === "codex-desktop")
111
+ options.desktopSharingStatus = true;
112
+ else if (arg === "--repair" && command === "codex-desktop")
113
+ options.desktopRepair = true;
114
+ else if (arg === "--setup" && command === "codex-desktop")
115
+ options.desktopSetup = true;
116
+ else if (arg === "--setup-codex-desktop" && command === "service" && serviceAction === "install")
117
+ options.desktopSetup = true;
118
+ else if (arg === "--url" && command === "pair")
119
+ options.pairingUrl = next();
120
+ else if (arg === "--list-routes" && command === "pair")
121
+ options.pairingListRoutes = true;
122
+ else if (arg === "--via" && command === "pair") {
123
+ const via = next();
124
+ if (!["self-hosted", "cloudflare", "lan", "tailscale", "headscale"].includes(via) && !isIPv4(via))
125
+ throw cliError("pair --via requires self-hosted, cloudflare, lan, tailscale, headscale or a local IPv4 address");
126
+ options.pairingVia = via;
127
+ }
128
+ else if (arg === "--node-name" && command === "mesh") {
129
+ const name = next();
130
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(name))
131
+ throw cliError("node name must be 1-63 letters, digits or hyphens and cannot start or end with a hyphen");
132
+ options.meshNodeName = name;
133
+ }
134
+ else if (arg === "--root")
27
135
  options.roots.push(resolve(next()));
28
136
  else if (arg === "--port") {
29
137
  const port = Number(next());
@@ -33,17 +141,23 @@ export function parseArgs(argv) {
33
141
  }
34
142
  else if (arg === "--relay") {
35
143
  const relay = next();
36
- if (!["auto", "cloudflare", "pinggy", "custom"].includes(relay)) {
37
- throw cliError("relay must be auto, cloudflare, pinggy, or custom");
144
+ if (!["auto", "cloudflare", "pinggy", "custom", "self-hosted"].includes(relay)) {
145
+ throw cliError("relay must be auto, cloudflare, pinggy, custom, or self-hosted");
38
146
  }
39
147
  options.relay = relay;
40
148
  }
149
+ else if (arg === "--relay-url")
150
+ options.relayUrl = next();
41
151
  else if (arg === "--tunnel-command")
42
152
  options.tunnelCommand = next();
43
153
  else if (arg === "--data-dir")
44
154
  options.dataDir = resolve(next());
155
+ else if (arg === "--phrase" && command === "approve")
156
+ options.approvalPhrase = next();
45
157
  else if (arg === "--local-only")
46
158
  options.localOnly = true;
159
+ else if (arg === "--test-no-pairing")
160
+ options.testNoPairing = true;
47
161
  else if (arg === "--no-qr")
48
162
  options.qr = false;
49
163
  else if (arg === "--help" || arg === "-h")
@@ -51,6 +165,23 @@ export function parseArgs(argv) {
51
165
  else
52
166
  throw cliError(`unknown argument: ${arg}`);
53
167
  }
168
+ if (command === "approve" && !options.approvalPhrase)
169
+ throw cliError("approve requires --phrase matching the phone");
170
+ if (command === "codex-desktop" && options.desktopSetup && (options.desktopRestart || options.desktopDryRun)) {
171
+ throw cliError("--setup cannot be combined with --restart or --dry-run");
172
+ }
173
+ if (command === "codex-desktop" && (options.desktopSharingStatus || options.desktopRepair)
174
+ && [options.desktopSharingStatus, options.desktopRepair, options.desktopSetup, options.desktopRestart, options.desktopDryRun].filter(Boolean).length !== 1) {
175
+ throw cliError("--status and --repair cannot be combined with other desktop actions");
176
+ }
177
+ if (command === "update" && updateVersion && !/^\d+\.\d+\.\d+$/.test(updateVersion)) {
178
+ throw cliError("update version must be an exact stable X.Y.Z version");
179
+ }
180
+ if (options.testNoPairing && (command !== "start" || !options.localOnly || options.tunnelCommand || options.relayUrl || options.relay !== "auto"))
181
+ throw cliError("--test-no-pairing requires start --local-only and cannot use a tunnel or background service");
182
+ if ((options.pairingVia || options.pairingListRoutes) && (options.pairingUrl || !options.qr || (options.pairingVia && options.pairingListRoutes))) {
183
+ throw cliError("pair --via and --list-routes cannot be combined with each other, --url or --no-qr");
184
+ }
54
185
  if (!options.roots.length)
55
186
  options.roots = [process.cwd()];
56
187
  if (options.relay === "custom" && !options.tunnelCommand)
package/dist/cli.js CHANGED
@@ -1,18 +1,186 @@
1
+ import { printLocalDesktopUrl } from './local-desktop-url.js';
1
2
  import { createRequire } from "node:module";
3
+ import { fileURLToPath } from "node:url";
4
+ import { join } from "node:path";
5
+ import { readFile, rm } from "node:fs/promises";
2
6
  import { parseArgs } from "./args.js";
3
7
  import { ensureCloudflared } from "./cloudflared/installer.js";
4
- import { repairNativeRuntimePermissions } from "./native-runtime.js";
5
- import { findLanUrl } from "./network.js";
6
- import { createPairingSecret } from "./pairing.js";
8
+ import { resolveCodexRuntime } from "./codex-runtime-manager.js";
9
+ import { probeSQLiteRuntime, probeTerminalRuntime, repairNativeRuntimePermissions } from "./native-runtime.js";
10
+ import { findRoutedLanUrl } from "./network.js";
11
+ import { installedDataDir, pairingAdmin, printPairingCode, printPairingRoutes, printPairingVia, terminalText } from "./device-pairing.js";
7
12
  import { detectPlatform } from "./platform.js";
8
13
  import { AGENTROAM_VERSION, resolvePlatformRuntime, resolvePlatformTui } from "./platform-packages.js";
9
- import { renderQr } from "./qr.js";
10
- import { RuntimeManager } from "./runtime-manager.js";
11
- import { selectRelay } from "./tunnel/relay-orchestrator.js";
14
+ import { acquireSleepInhibitor } from "./power/sleep-inhibitor.js";
15
+ import { CODEX_PREPARATION_TIMEOUT_MS, RuntimeManager } from "./runtime-manager.js";
16
+ import { withTimeout } from "./abort.js";
17
+ import { ServiceRuntimeReporter } from "./service/runtime-state.js";
18
+ import { runServiceCommand } from "./service/service-command.js";
19
+ import { resolveServicePaths, writePrivateText } from "./service/service-files.js";
20
+ import { TunnelController, attachTunnelControl } from "./tunnel/tunnel-controller.js";
21
+ import { currentCliPath, startUpdate } from "./update/update-command.js";
22
+ import { runUpdateWorker } from "./update/update-worker.js";
23
+ import { lockInstanceStartup, stopPreviousInstances } from "./instance-takeover.js";
24
+ import { runUnlockServiceCommand } from "./unlock-service.js";
25
+ import { createCliErrorLog } from "./error-log.js";
26
+ import { runCodexDesktopCommand } from "./codex-desktop-command.js";
27
+ import { setupCodexDesktop } from "./codex-desktop-setup.js";
28
+ import { runDesktopCommand } from "./desktop-authorization.js";
29
+ import { runMeshCommand } from "./mesh/mesh-command.js";
30
+ import { attachMeshControl, createMeshRuntime } from "./mesh/mesh-runtime.js";
31
+ import { withCliProgress } from "../bin/cli-progress.mjs";
12
32
  const VERSION = AGENTROAM_VERSION;
13
33
  export async function main(argv) {
34
+ if (argv[0] === "mcp" && argv[1] === "todo") {
35
+ const { runTodoMcpCommand } = await import("./todo-mcp-command.js");
36
+ return runTodoMcpCommand(argv.slice(2));
37
+ }
38
+ if (argv.includes("--help") || argv.includes("-h")) {
39
+ console.log(`AgentRoam
40
+ agentroam [start] [--local-only] [--test-no-pairing] [--data-dir PATH]
41
+ agentroam start --relay self-hosted --relay-url https://connect.example.com
42
+ agentroam pair 生成设备授权,公网连接可用时显示二维码
43
+ agentroam pair --no-qr 生成需由电脑批准的数字配对码
44
+ agentroam pair --list-routes 查看可选配对线路和本机 IP
45
+ agentroam pair --via <线路或 IP> 按所选地址生成扫码授权
46
+ agentroam pair --url <服务器地址> 生成 App 扫码直连授权(终端显示)
47
+ agentroam approvals 查看待批准请求和核对短语
48
+ agentroam approve <请求ID> --phrase <核对短语>
49
+ agentroam deny <请求ID> 拒绝请求
50
+ agentroam lock 紧急锁定全部远程访问
51
+ agentroam unlock 本机解锁(需要重新配对)
52
+ agentroam audit 查看安全审计记录
53
+ agentroam devices 查看已授权设备
54
+ agentroam revoke <设备ID> 移除一台设备
55
+ agentroam revoke --all 全部退出并取消待用配对码
56
+ agentroam service install|start|stop|restart|status|url|logs|uninstall
57
+ 首次启动时通过 AGENTROAM_MESH_ACTIVATION_CODE 提供一次性组网激活码
58
+ agentroam mesh status 查看组网入网状态
59
+ agentroam mesh onboard 加入自建 Headscale 控制面(安装后自动执行)
60
+ agentroam mesh qr 生成手机加入组网的一次性二维码(15 分钟)
61
+ agentroam mesh nodes 查看控制面节点
62
+ agentroam mesh offboard 退出组网并清除本机入网状态
63
+ agentroam desktop authorize 本机弹窗授权远程桌面,无需浏览器;可重复执行
64
+ agentroam desktop status 重新检查远程桌面权限和共享状态
65
+ agentroam desktop disable 关闭远程桌面共享,保留系统权限
66
+ agentroam unlock-service install|uninstall|status 管理 Windows 远程解锁服务(安装时弹出 UAC)
67
+ agentroam codex-desktop [--dry-run] 通过共享后端启动官方 Codex 桌面端(macOS)
68
+ agentroam codex-desktop --restart 退出并重新连接官方桌面端,会中断它的全部运行会话
69
+ agentroam codex-desktop --status 输出实际共享连接状态(JSON)
70
+ agentroam codex-desktop --repair 修复默认共享和自动恢复,保留运行中的桌面任务
71
+ agentroam codex-desktop --setup 空闲桌面自动重新连接;有任务或状态未知时询问是否重启
72
+ agentroam service install --setup-codex-desktop 扫码前配置官方桌面共享连接(macOS)
73
+ 设备命令支持 --data-dir PATH;配对码有效期 5 分钟,设备授权有效期 30 天。`);
74
+ return;
75
+ }
14
76
  const options = parseArgs(argv);
77
+ // Foreground start remains alive after readiness; only its startup stages load.
78
+ if (options.command === "start" || options.command === "update-worker")
79
+ return executeCommand(options, argv);
80
+ const label = options.command === "service" ? `Processing background service: ${options.serviceAction}`
81
+ : options.command === "desktop" ? "Checking remote desktop authorization"
82
+ : options.command === "codex-desktop" ? "Configuring Codex Desktop connection"
83
+ : options.command === "doctor" ? "Checking runtime components"
84
+ : options.command === "update" ? "Checking and preparing updates"
85
+ : options.command === "unlock-service" ? "Configuring Windows unlock service; watch for the administrator prompt"
86
+ : "Processing device authorization";
87
+ await withCliProgress(label, () => executeCommand(options, argv));
88
+ }
89
+ async function executeCommand(options, argv) {
90
+ // CLI 进程自身的按天错误日志:<dataDir>/logs/YYYY-MM-DD.log(NDJSON,与
91
+ // server/desktop 的 core logger 同格式)。uncaughtException 记录后按默认
92
+ // 语义退出(1),unhandledRejection 只记录。
93
+ const cliErrorLog = createCliErrorLog(join(options.dataDir, "logs"));
94
+ cliErrorLog.installGlobalErrorHandlers();
95
+ if (["pair", "devices", "revoke", "approvals", "approve", "deny", "lock", "unlock", "audit"].includes(options.command)) {
96
+ const dataDir = argv.includes("--data-dir") ? options.dataDir : await installedDataDir(options.dataDir);
97
+ if (options.command === "pair") {
98
+ if (options.pairingListRoutes)
99
+ await printPairingRoutes(dataDir);
100
+ else if (options.pairingVia)
101
+ await printPairingVia(dataDir, options.pairingVia);
102
+ else
103
+ await printPairingCode(dataDir, console.log, { accessUrl: options.pairingUrl, qr: options.qr });
104
+ }
105
+ else if (options.command === "approvals") {
106
+ const { requests, locked } = await pairingAdmin(dataDir, "requests");
107
+ console.log(locked ? "远程访问已锁定" : requests.length ? requests.map((r) => `${r.id} ${terminalText(r.name)} 核对短语:${r.phrase} 到期 ${new Date(r.expires).toLocaleString()}`).join("\n") : "暂无待授权请求");
108
+ }
109
+ else if (options.command === "approve" || options.command === "deny") {
110
+ await pairingAdmin(dataDir, options.command, { id: options.approvalRequestId, phrase: options.approvalPhrase });
111
+ console.log(options.command === "approve" ? "已批准,手机将自动进入。" : "已拒绝此设备。");
112
+ }
113
+ else if (options.command === "lock" || options.command === "unlock") {
114
+ await pairingAdmin(dataDir, options.command);
115
+ console.log(options.command === "lock" ? "远程访问已锁定,设备授权和待用配对已取消。已提交的本机任务不会自动终止。" : "远程访问已解锁。旧设备不会恢复授权,请执行 agentroam pair 重新配对。");
116
+ }
117
+ else if (options.command === "audit") {
118
+ const { events } = await pairingAdmin(dataDir, "audit");
119
+ console.log(events.length ? events.map((e) => `${new Date(e.at).toISOString()} ${e.action} ${e.outcome} actor=${e.actor ?? "-"} target=${e.target ?? "-"} count=${e.count}`).join("\n") : "暂无审计记录");
120
+ }
121
+ else if (options.command === "devices") {
122
+ const { devices } = await pairingAdmin(dataDir, "devices");
123
+ console.log(devices.length ? devices.map((d) => `${d.id} ${d.name.replace(/[\x00-\x1f\x7f-\x9f]/g, "")} 最近使用 ${new Date(d.seen).toLocaleString()} 到期 ${new Date(d.expires).toLocaleString()}`).join("\n") : "暂无已授权设备");
124
+ console.log("移除设备:agentroam revoke <设备ID>;全部退出:agentroam revoke --all");
125
+ }
126
+ else {
127
+ const result = await pairingAdmin(dataDir, "revoke", options.revokeAll ? { all: true } : { id: options.revokeDeviceId });
128
+ console.log(`已撤销 ${result.revoked} 台设备的授权`);
129
+ }
130
+ return;
131
+ }
132
+ if (options.command === "update-worker") {
133
+ await runUpdateWorker(options.updateStateFile);
134
+ return;
135
+ }
136
+ if (options.command === "service") {
137
+ await runServiceCommand(options, {
138
+ nodePath: process.execPath,
139
+ cliPath: fileURLToPath(new URL("../bin/agentroam.mjs", import.meta.url)),
140
+ version: VERSION,
141
+ });
142
+ return;
143
+ }
15
144
  const target = detectPlatform();
145
+ if (options.command === "desktop") {
146
+ if (!argv.includes("--data-dir"))
147
+ options.dataDir = await installedDataDir(options.dataDir);
148
+ await runDesktopCommand(options);
149
+ return;
150
+ }
151
+ if (options.command === "mesh") {
152
+ if (!argv.includes("--data-dir"))
153
+ options.dataDir = await installedDataDir(options.dataDir);
154
+ await runMeshCommand({
155
+ action: options.meshAction,
156
+ dataDir: options.dataDir,
157
+ nodeName: options.meshNodeName,
158
+ qr: options.qr,
159
+ });
160
+ return;
161
+ }
162
+ if (options.command === "codex-desktop") {
163
+ if (!argv.includes("--data-dir"))
164
+ options.dataDir = await installedDataDir(options.dataDir);
165
+ if (options.desktopSetup)
166
+ await setupCodexDesktop(options);
167
+ else
168
+ await runCodexDesktopCommand(options);
169
+ return;
170
+ }
171
+ if (options.command === "unlock-service") {
172
+ if (target !== "windows-amd64")
173
+ throw new Error("远程解锁服务仅支持 Windows 10/11 x64");
174
+ await runUnlockServiceCommand(options.unlockServiceAction, resolvePlatformRuntime(target).runtimeRoot);
175
+ return;
176
+ }
177
+ if (options.command === "update") {
178
+ if (target !== "darwin-arm64" && target !== "windows-amd64")
179
+ throw new Error(`updates are unavailable for ${target}`);
180
+ const state = await startUpdate({ currentVersion: VERSION, requestedVersion: options.updateVersion ?? null, dataDir: options.dataDir, target, cliPath: currentCliPath() });
181
+ console.log(`AgentRoam ${state.targetVersion} update started in the background.`);
182
+ return;
183
+ }
16
184
  if (options.command === "version") {
17
185
  console.log(`agentroam ${VERSION}`);
18
186
  return;
@@ -22,69 +190,135 @@ export async function main(argv) {
22
190
  return;
23
191
  }
24
192
  console.log(`AgentRoam ${VERSION}\n✓ Node ${process.versions.node} · ${target}`);
25
- const pairing = createPairingSecret();
193
+ const sleepInhibitor = await withCliProgress("Preparing startup environment", () => acquireSleepInhibitor());
26
194
  const controller = new AbortController();
27
195
  let runtime = null;
28
- let relay = null;
196
+ let tunnel = null;
197
+ let mesh;
198
+ let meshOnboarding;
199
+ let detachMesh;
200
+ let detachTunnel;
29
201
  let closing = false;
30
- const close = async () => {
31
- if (closing)
32
- return;
202
+ let releaseStartup;
203
+ let closePromise;
204
+ let reportedStarting = false;
205
+ const serviceReporter = process.env.AGENTROAM_SERVICE === "1"
206
+ ? new ServiceRuntimeReporter(resolveServicePaths(undefined, options.dataDir), VERSION)
207
+ : null;
208
+ const close = () => {
209
+ if (closePromise)
210
+ return closePromise;
33
211
  closing = true;
34
212
  controller.abort();
35
- await relay?.tunnel?.close().catch(() => { });
36
- await runtime?.close().catch(() => { });
213
+ closePromise = withCliProgress("Stopping local service and connections", async () => {
214
+ detachTunnel?.();
215
+ detachMesh?.();
216
+ await mesh?.close();
217
+ await tunnel?.close().catch(() => { });
218
+ await runtime?.close().catch(() => { });
219
+ });
220
+ return closePromise;
37
221
  };
38
222
  const requestClose = () => void close();
39
223
  process.once("SIGINT", requestClose);
40
224
  process.once("SIGTERM", requestClose);
41
225
  try {
42
- runtime = await new RuntimeManager().start(options, pairing, target);
43
- console.log(`✓ Local server: ${runtime.localUrl}/web`);
44
- const lanUrl = findLanUrl(runtime.port) ?? runtime.localUrl;
45
- relay = await selectRelay({
46
- cli: options,
47
- target,
48
- localUrl: runtime.localUrl,
49
- lanUrl,
50
- port: runtime.port,
51
- signal: controller.signal,
52
- log: (line) => process.stderr.write(`${line}\n`),
53
- onAttempt: (provider) => console.log(`▲ Trying ${providerDisplayName(provider)} relay...`),
54
- onFailure: (provider, message) => console.error(`⚠ ${providerDisplayName(provider)} unavailable: ${message}`),
226
+ releaseStartup = await withCliProgress("Waiting for startup lock", () => lockInstanceStartup(options.dataDir));
227
+ await withCliProgress("Taking over previous instances", () => stopPreviousInstances(options.dataDir, console.log));
228
+ if (controller.signal.aborted)
229
+ return;
230
+ await serviceReporter?.starting();
231
+ reportedStarting = Boolean(serviceReporter);
232
+ runtime = await withCliProgress("Starting local service", () => new RuntimeManager().start(options, target));
233
+ if (controller.signal.aborted) {
234
+ await runtime.close();
235
+ return;
236
+ }
237
+ void runtime.exited.then(() => controller.abort());
238
+ await serviceReporter?.localReady(runtime.localUrl);
239
+ if (!options.testNoPairing) {
240
+ mesh = createMeshRuntime({ dataDir: options.dataDir, localUrl: runtime.localUrl, target });
241
+ detachMesh = attachMeshControl(runtime.process, mesh);
242
+ meshOnboarding = mesh.run("onboard", undefined, true)
243
+ .catch(error => { if (!closing)
244
+ console.error(`⚠ 组网自动入网未完成:${error.message}`); });
245
+ }
246
+ const relayRuntime = runtime;
247
+ tunnel = new TunnelController({
248
+ relay: {
249
+ cli: options, target, localUrl: relayRuntime.localUrl, port: relayRuntime.port,
250
+ log: line => process.stderr.write(`${line}\n`),
251
+ onAttempt: provider => console.log(`▲ Connecting to ${providerDisplayName(provider)} (up to 30s, then LAN fallback)…`),
252
+ onFailure: (provider, message) => console.error(`⚠ ${providerDisplayName(provider)} unavailable: ${message}; falling back to LAN.`),
253
+ },
254
+ lanUrl: async () => await findRoutedLanUrl(relayRuntime.port) ?? relayRuntime.localUrl,
255
+ publish: async (status) => {
256
+ const accessUrl = status.accessUrl;
257
+ if (serviceReporter && status.phase !== "connecting") {
258
+ await serviceReporter.ready({ localUrl: relayRuntime.localUrl, publicUrl: new URL(accessUrl).origin, accessUrl, provider: status.provider });
259
+ }
260
+ else
261
+ await writePrivateText(resolveServicePaths(undefined, options.dataDir).urlPath, `${accessUrl}\n`);
262
+ },
263
+ onError: error => console.error("Tunnel status update failed:", error),
55
264
  });
265
+ detachTunnel = attachTunnelControl(runtime.process, tunnel);
266
+ const relay = await withCliProgress("Preparing phone access", () => tunnel.connect(false));
56
267
  if (controller.signal.aborted)
57
268
  return;
58
- if (relay.provider === "lan") {
59
- if (relay.failures.length > 0)
60
- console.error(` Continuing with local network access: ${relay.publicUrl}/web`);
61
- else
62
- console.log(`✓ Local network: ${relay.publicUrl}/web`);
269
+ if (relay.mode !== "public") {
270
+ console.log(`✓ Local network: ${relay.accessUrl}`);
271
+ console.log(relay.mode === "local" ? "Local access only. Connect to Wi-Fi or Ethernet to enable phone access." : "Connect your phone to the same LAN to use this address or QR code.");
63
272
  }
64
273
  else {
65
- console.log(`✓ ${providerDisplayName(relay.provider)} tunnel ready: ${relay.publicUrl}`);
274
+ console.log(`✓ ${providerDisplayName(relay.provider)} tunnel ready: ${new URL(relay.accessUrl).origin}`);
66
275
  }
67
276
  if (relay.provider === "pinggy") {
68
277
  console.log(" Pinggy free tunnels expire after 60 minutes and use a new hostname each session.");
69
278
  console.log(" The phone browser may show a one-time Pinggy security confirmation before pairing.");
70
279
  }
71
- const accessUrl = `${relay.publicUrl}/web${runtime.needsSetup ? `?pair=${encodeURIComponent(pairing.token)}` : ""}`;
72
- console.log(`\nOpen: ${accessUrl}`);
73
- if (options.qr)
74
- console.log(`\n${await renderQr(accessUrl)}`);
75
- if (runtime.needsSetup)
76
- console.log("First pairing link expires in 5 minutes.");
77
- console.log("Ctrl+C stops the tunnel and local server.");
78
- await Promise.race([runtime.exited, relay.tunnel?.exited ?? new Promise(() => { })]);
280
+ const accessUrl = relay.accessUrl;
281
+ await releaseStartup();
282
+ if (serviceReporter) {
283
+ console.log("✓ Background service URL written to the private state file.");
284
+ }
285
+ else {
286
+ console.log(`\nOpen: ${accessUrl}`);
287
+ printLocalDesktopUrl(runtime.localUrl);
288
+ if (!options.testNoPairing) {
289
+ await meshOnboarding;
290
+ if (controller.signal.aborted)
291
+ return;
292
+ await printPairingCode(options.dataDir, console.log, { signal: controller.signal, fallbackUrl: accessUrl, qr: options.qr });
293
+ }
294
+ console.log("Ctrl+C stops the tunnel and local server.");
295
+ }
296
+ await Promise.race([
297
+ runtime.exited,
298
+ sleepInhibitor.lost.then(async (error) => {
299
+ await new Promise((resolveTurn) => setImmediate(resolveTurn));
300
+ if (!closing)
301
+ throw error;
302
+ }),
303
+ ]);
79
304
  }
80
305
  finally {
81
306
  process.removeListener("SIGINT", requestClose);
82
307
  process.removeListener("SIGTERM", requestClose);
83
308
  await close();
309
+ if (!serviceReporter && tunnel) {
310
+ const urlPath = resolveServicePaths(undefined, options.dataDir).urlPath;
311
+ if (await readFile(urlPath, "utf8").then(value => value.trim() === tunnel.status().accessUrl, () => false))
312
+ await rm(urlPath, { force: true });
313
+ }
314
+ await releaseStartup?.();
315
+ if (reportedStarting)
316
+ await serviceReporter?.stopped().catch(() => { });
317
+ await sleepInhibitor.release();
84
318
  }
85
319
  }
86
320
  async function doctor(target, dataDir) {
87
- console.log(`✓ Node ${process.versions.node}`);
321
+ console.log(`✓ Node ${process.versions.node} · Node-API ${process.versions.napi}`);
88
322
  console.log(`✓ Platform ${target}`);
89
323
  const { runtimeRoot } = resolvePlatformRuntime(target);
90
324
  const runtimeRequire = createRequire(`${runtimeRoot}/package.json`);
@@ -95,9 +329,12 @@ async function doctor(target, dataDir) {
95
329
  catch (error) {
96
330
  reportDoctorFailure(error);
97
331
  }
98
- for (const module of ["node-pty", "better-sqlite3"]) {
332
+ for (const [module, probe] of [
333
+ ["node-pty", probeTerminalRuntime],
334
+ ["better-sqlite3", probeSQLiteRuntime],
335
+ ]) {
99
336
  try {
100
- runtimeRequire(module);
337
+ await withCliProgress(`Checking ${module}`, () => probe(runtimeRequire));
101
338
  console.log(`✓ ${module}`);
102
339
  }
103
340
  catch (error) {
@@ -112,7 +349,19 @@ async function doctor(target, dataDir) {
112
349
  reportDoctorFailure(error, "agent-tui: ");
113
350
  }
114
351
  try {
115
- const executable = await ensureCloudflared(target, dataDir);
352
+ const codex = await withCliProgress("Checking and preparing Codex (up to 180s)", () => withTimeout(signal => resolveCodexRuntime({
353
+ dataDir,
354
+ target,
355
+ signal,
356
+ onProgress: (message) => console.log(`… ${message}`),
357
+ }), CODEX_PREPARATION_TIMEOUT_MS, "Codex preparation timed out (180s); check your network and retry."));
358
+ console.log(`✓ Codex ${codex.version} (${codex.source}) ${codex.executable}`);
359
+ }
360
+ catch (error) {
361
+ reportDoctorFailure(error, "Codex: ");
362
+ }
363
+ try {
364
+ const executable = await withCliProgress("Checking and preparing Cloudflare", () => ensureCloudflared(target, dataDir));
116
365
  console.log(`✓ cloudflared ${executable}`);
117
366
  }
118
367
  catch (error) {
@@ -125,6 +374,8 @@ function reportDoctorFailure(error, prefix = "") {
125
374
  process.exitCode = 1;
126
375
  }
127
376
  function providerDisplayName(provider) {
377
+ if (provider === "self-hosted")
378
+ return "自建 HTTPS";
128
379
  if (provider === "cloudflare")
129
380
  return "Cloudflare";
130
381
  if (provider === "pinggy")
@@ -1,6 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { createRequire } from "node:module";
3
- import { CLOUDFLARED_PACKAGES, CLOUDFLARED_PACKAGE_VERSION } from "./manifest.js";
3
+ import { PLATFORM_DEPENDENCY_VERSIONS } from "../platform-packages.js";
4
+ import { CLOUDFLARED_PACKAGES } from "./manifest.js";
4
5
  export async function resolveBundledCloudflared(target, requireFromCli = createRequire(import.meta.url)) {
5
6
  const packageName = CLOUDFLARED_PACKAGES[target];
6
7
  if (!packageName)
@@ -17,7 +18,7 @@ export async function resolveBundledCloudflared(target, requireFromCli = createR
17
18
  throw error;
18
19
  }
19
20
  const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
20
- if (manifest.packageVersion !== CLOUDFLARED_PACKAGE_VERSION ||
21
+ if (manifest.packageVersion !== PLATFORM_DEPENDENCY_VERSIONS[packageName] ||
21
22
  manifest.target !== target ||
22
23
  (manifest.assetFormat !== "tgz" && manifest.assetFormat !== "executable") ||
23
24
  typeof manifest.upstreamVersion !== "string" ||
@@ -1,6 +1,6 @@
1
- import { AGENTROAM_VERSION, requirePlatformPackages } from "../platform-packages.js";
1
+ import { PLATFORM_DEPENDENCY_VERSIONS, requirePlatformPackages } from "../platform-packages.js";
2
2
  export const CLOUDFLARED_VERSION = "2026.8.2";
3
- export const CLOUDFLARED_PACKAGE_VERSION = AGENTROAM_VERSION;
3
+ export const CLOUDFLARED_PACKAGE_VERSION = PLATFORM_DEPENDENCY_VERSIONS[requirePlatformPackages("darwin-arm64").cloudflared];
4
4
  export const CLOUDFLARED_PACKAGES = {
5
5
  "darwin-arm64": requirePlatformPackages("darwin-arm64").cloudflared,
6
6
  "windows-amd64": requirePlatformPackages("windows-amd64").cloudflared,