agentroam 0.2.0-preview.8 → 0.2.0-preview.81

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 +177 -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
@@ -0,0 +1,228 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { openSync } from "node:fs";
4
+ import { ReadStream } from "node:tty";
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { join, resolve } from "node:path";
8
+ import { renderQr } from "./qr.js";
9
+ import { localServiceRequest, LocalServiceHttpError } from "./local-service-request.js";
10
+ import { withCliProgress, withoutCliProgress } from "../bin/cli-progress.mjs";
11
+ /** Resolve a private local descriptor; never send the administrative token to a tunnel URL. */
12
+ export async function pairingAdmin(dataDir, action, body, options = {}) {
13
+ const readOnly = ["devices", "requests", "audit"].includes(action);
14
+ try {
15
+ return await localServiceRequest(dataDir, `/api/pairing/admin/${action}`, {
16
+ ...options, method: readOnly ? "GET" : "POST", ...(readOnly ? {} : { body: body ?? {} }),
17
+ });
18
+ }
19
+ catch (error) {
20
+ if (!(error instanceof LocalServiceHttpError))
21
+ throw error;
22
+ const message = error.status === 423 ? "Remote access is locked. Run agentroam unlock first" : error.status === 410 ? "Request expired or already handled" : error.status === 409 ? "Verification phrase does not match" : `Device authorization failed (HTTP ${error.status})`;
23
+ throw new Error(message);
24
+ }
25
+ }
26
+ export function terminalText(value) { return value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ""); }
27
+ export function pairingQrPayload(accessUrl, grant) {
28
+ const url = new URL(accessUrl);
29
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || !/^[A-Za-z0-9_-]{43}$/.test(grant))
30
+ throw new Error("Invalid pairing URL or authorization grant");
31
+ return `${url.origin}/pair#pair=${grant}`;
32
+ }
33
+ async function joinedMeshAddress(dataDir) {
34
+ const mesh = await localServiceRequest(dataDir, "/api/mesh/status").catch(() => null);
35
+ return mesh?.phase === "joined" ? mesh.accessUrl : undefined;
36
+ }
37
+ export async function printPairingRoutes(dataDir, log = console.log) {
38
+ const [{ routes }, mesh] = await Promise.all([
39
+ localServiceRequest(dataDir, "/api/desktop/tunnel/routes"), joinedMeshAddress(dataDir),
40
+ ]);
41
+ const labels = {
42
+ "self-hosted": "自建 HTTPS", cloudflare: "Cloudflare", lan: "局域网", tailscale: "Tailscale / 组网地址", vpn: "本机网络地址", headscale: "Headscale",
43
+ };
44
+ log("agentroam pair --via <线路或 IP>");
45
+ for (const route of routes)
46
+ log(` ${route.id} ${labels[route.kind]}${route.interfaceName ? ` · ${terminalText(route.interfaceName)}` : ""}`);
47
+ if (routes.some(route => route.kind === "lan"))
48
+ log(" lan 自动选择局域网地址");
49
+ if (routes.some(route => route.kind === "tailscale"))
50
+ log(" tailscale 自动选择 100.x 组网地址");
51
+ if (mesh)
52
+ log(` headscale ${new URL(mesh).origin}`);
53
+ }
54
+ export async function printPairingVia(dataDir, via, log = console.log) {
55
+ const accessUrl = await withCliProgress("正在准备所选配对线路", async () => {
56
+ if (via === "headscale") {
57
+ const mesh = await joinedMeshAddress(dataDir);
58
+ if (!mesh)
59
+ throw new Error("电脑尚未加入自建 Headscale 组网。");
60
+ return mesh;
61
+ }
62
+ const route = await localServiceRequest(dataDir, `/api/desktop/tunnel/routes?via=${encodeURIComponent(via)}`, { method: "POST", timeoutMs: 40_000 });
63
+ return route.accessUrl;
64
+ });
65
+ log(`Pairing route: ${new URL(accessUrl).origin}`);
66
+ await printPairingQr(dataDir, accessUrl, log);
67
+ }
68
+ export async function printPairingCode(dataDir, log = console.log, options = {}) {
69
+ const interactiveQr = (options.qr ?? true) && (options.interactive ?? process.stdout.isTTY);
70
+ if (interactiveQr && options.accessUrl === undefined) {
71
+ const relay = await localServiceRequest(dataDir, "/api/desktop/tunnel", { signal: options.signal }).catch(() => null);
72
+ if (relay?.phase === "ready" && relay.provider === "self-hosted" && relay.accessUrl) {
73
+ await printPairingQr(dataDir, relay.accessUrl, log);
74
+ return;
75
+ }
76
+ }
77
+ const result = await withCliProgress("Generating device pairing code", () => pairingAdmin(dataDir, "code"));
78
+ log(`Pairing code: ${result.code.slice(0, 4)} ${result.code.slice(4)}`);
79
+ log("Valid for 5 minutes, single use. After entering it on your phone, confirm the verification phrase on this computer.");
80
+ if (interactiveQr) {
81
+ const accessUrl = await resolvePairingAccessUrl(dataDir, options);
82
+ if (accessUrl)
83
+ await printPairingQr(dataDir, accessUrl, log);
84
+ else
85
+ log("Generate an app authorization QR code: agentroam pair --url <phone-accessible-server-url>");
86
+ }
87
+ const approvalInput = resolveApprovalInput(options);
88
+ if (approvalInput) {
89
+ await withCliProgress("Waiting for your phone to scan or enter the pairing code", () => watchPairingApproval(dataDir, result.expiresAt, { log, signal: options.signal, input: approvalInput }));
90
+ }
91
+ else
92
+ log("View requests: agentroam approvals; approve: agentroam approve <request-id> --phrase <phone-verification-phrase>");
93
+ }
94
+ async function printPairingQr(dataDir, accessUrl, log) {
95
+ pairingQrPayload(accessUrl, "a".repeat(43));
96
+ const qr = await withCliProgress("Generating phone connection QR code", async () => {
97
+ const { grant } = await pairingAdmin(dataDir, "qr");
98
+ return renderQr(pairingQrPayload(accessUrl, grant));
99
+ });
100
+ log("Scan with your phone to connect (valid for 5 minutes, single use; do not share screenshots):");
101
+ log(qr);
102
+ }
103
+ export async function resolvePairingAccessUrl(dataDir, options = {}) {
104
+ if (options.accessUrl !== undefined)
105
+ return options.accessUrl;
106
+ const readMesh = () => localServiceRequest(dataDir, "/api/mesh/status", { signal: options.signal }).catch(() => null);
107
+ const deadline = Date.now() + 20_000;
108
+ let mesh = await readMesh();
109
+ while (options.waitForMesh && mesh?.phase === "ready" && Date.now() < deadline) {
110
+ await delay(400, undefined, { signal: options.signal });
111
+ mesh = await readMesh();
112
+ }
113
+ if (mesh?.phase === "joined" && mesh.accessUrl)
114
+ return mesh.accessUrl;
115
+ return options.fallbackUrl ?? await readFile(join(dataDir, "tunnel.url"), "utf8").then(value => value.trim(), () => null);
116
+ }
117
+ /** Open the controlling terminal (`/dev/tty`) — the same source install-agentroam.sh reads from. */
118
+ function openControllingTerminal() {
119
+ if (process.platform === "win32")
120
+ return undefined;
121
+ let fd;
122
+ try {
123
+ fd = openSync("/dev/tty", "r");
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ // Use libuv's cancellable TTY handle. A filesystem read on /dev/tty can keep
129
+ // the process alive after destroy(), waiting for one more line of input.
130
+ return new ReadStream(fd);
131
+ }
132
+ /**
133
+ * Pick the stream the approval phrase is read from.
134
+ *
135
+ * Never fall back to `process.stdin` when it is not a TTY: the installer runs as
136
+ * `curl … | sh`, so stdin is *the install script itself*. Reading it consumes
137
+ * the rest of the install, echoes it back to the terminal, and answers the
138
+ * prompt with the next script line instead of the user's "yes" — which silently
139
+ * rejects the device and swallows the remaining install steps.
140
+ */
141
+ export function resolveApprovalInput(context = {}) {
142
+ const stdinIsTTY = context.stdinIsTTY ?? process.stdin.isTTY === true;
143
+ const stdoutIsTTY = context.stdoutIsTTY ?? process.stdout.isTTY === true;
144
+ if (!(context.interactive ?? (stdinIsTTY && stdoutIsTTY)))
145
+ return undefined;
146
+ if (stdinIsTTY)
147
+ return process.stdin;
148
+ return (context.openTerminal ?? openControllingTerminal)();
149
+ }
150
+ /** Watch only while the printed code is usable; approval gets the request's own deadline. */
151
+ export async function watchPairingApproval(dataDir, codeExpiresAt, options = {}) {
152
+ const admin = options.admin ?? pairingAdmin;
153
+ const log = options.log ?? console.log;
154
+ log("Waiting for your phone to connect...");
155
+ while (Date.now() < codeExpiresAt && !options.signal?.aborted) {
156
+ const result = await admin(dataDir, "requests");
157
+ if (result.locked) {
158
+ log("Remote access is locked");
159
+ return;
160
+ }
161
+ if (result.qrClaimed) {
162
+ log("App connected via QR code.");
163
+ return;
164
+ }
165
+ const request = result.requests.find((r) => r.created >= codeExpiresAt - 300_000);
166
+ if (request) {
167
+ log(`New device connection request: ${terminalText(request.name)}`);
168
+ log(`Request ID: ${request.id}`);
169
+ log(`Verification phrase: ${request.phrase}`);
170
+ const confirm = options.confirm ?? ((request, signal) => confirmOnTerminal(request, signal, options.input));
171
+ const approved = await withoutCliProgress(() => confirm(request, options.signal));
172
+ if (options.signal?.aborted)
173
+ return;
174
+ if (Date.now() >= request.expires) {
175
+ log("Authorization request expired. Please pair again.");
176
+ return;
177
+ }
178
+ await admin(dataDir, approved ? "approve" : "deny", { id: request.id, ...(approved ? { phrase: request.phrase } : {}) });
179
+ log(approved ? "Approved. Your phone will connect automatically." : "Device rejected.");
180
+ return;
181
+ }
182
+ try {
183
+ await delay(800, undefined, { signal: options.signal });
184
+ }
185
+ catch {
186
+ return;
187
+ }
188
+ }
189
+ if (!options.signal?.aborted)
190
+ log("Pairing code expired. Run agentroam pair to generate a new code.");
191
+ }
192
+ async function confirmOnTerminal(request, signal, terminal = resolveApprovalInput()) {
193
+ // A piped stdin is the install script, and a closed one can never answer.
194
+ if (!terminal || (terminal === process.stdin && process.stdin.isTTY !== true))
195
+ return false;
196
+ const controller = new AbortController();
197
+ const timer = setTimeout(() => controller.abort(), Math.max(0, request.expires - Date.now()));
198
+ // Read the terminal in canonical mode: the tty echoes the keystrokes itself,
199
+ // so letting readline echo them again would double every character.
200
+ const input = createInterface(terminal === process.stdin
201
+ ? { input: terminal, output: process.stdout }
202
+ : { input: terminal, output: process.stdout, terminal: false });
203
+ input.once("SIGINT", () => controller.abort());
204
+ try {
205
+ const answer = await input.question("Does your phone show the same phrase? Type yes to approve, anything else to reject: ", { signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal });
206
+ return answer.trim().toLowerCase() === "yes";
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ finally {
212
+ clearTimeout(timer);
213
+ input.close();
214
+ }
215
+ }
216
+ export async function installedDataDir(fallback) {
217
+ if (resolve(fallback) !== resolve(homedir(), ".agentroam"))
218
+ return fallback;
219
+ try {
220
+ const config = JSON.parse(await readFile(join(homedir(), ".agentroam", "service", "config.json"), "utf8"));
221
+ return typeof config.dataDir === "string" ? resolve(config.dataDir) : fallback;
222
+ }
223
+ catch (error) {
224
+ if (error.code === "ENOENT")
225
+ return fallback;
226
+ throw error;
227
+ }
228
+ }
@@ -0,0 +1,113 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ // Self-contained daily error log for the CLI process. The CLI cannot depend
4
+ // on @agent/core (it ships as a thin launcher), so this mirrors the exact
5
+ // NDJSON entry format of core's DailyFileLogger
6
+ // (`{ts, level, source, message, error?, data?}`) into `<dataDir>/logs/`.
7
+ // It records uncaughtException / unhandledRejection so launcher failures are
8
+ // strictly persisted, matching the server/desktop log series.
9
+ const LEVELS = new Set(["debug", "info", "warn", "error", "fatal"]);
10
+ function localDateString(date) {
11
+ const y = date.getFullYear();
12
+ const m = String(date.getMonth() + 1).padStart(2, "0");
13
+ const d = String(date.getDate()).padStart(2, "0");
14
+ return `${y}-${m}-${d}`;
15
+ }
16
+ function serializeError(err) {
17
+ if (err === undefined || err === null)
18
+ return undefined;
19
+ if (err instanceof Error) {
20
+ const out = { name: err.name, message: err.message };
21
+ if (err.stack)
22
+ out.stack = err.stack;
23
+ return out;
24
+ }
25
+ if (typeof err === "object") {
26
+ const anyErr = err;
27
+ const out = {
28
+ name: typeof anyErr.name === "string" ? anyErr.name : "NonError",
29
+ message: typeof anyErr.message === "string" ? anyErr.message : String(err),
30
+ };
31
+ if (typeof anyErr.stack === "string")
32
+ out.stack = anyErr.stack;
33
+ return out;
34
+ }
35
+ return { name: "NonError", message: String(err) };
36
+ }
37
+ function safeStringify(value) {
38
+ try {
39
+ return JSON.stringify(value) ?? "null";
40
+ }
41
+ catch {
42
+ return '"[unserializable]"';
43
+ }
44
+ }
45
+ export function createCliErrorLog(logsDir) {
46
+ let reportedWriteFailure = false;
47
+ const write = (line) => {
48
+ try {
49
+ if (!existsSync(logsDir))
50
+ mkdirSync(logsDir, { recursive: true });
51
+ appendFileSync(join(logsDir, `${localDateString(new Date())}.log`), line, "utf8");
52
+ }
53
+ catch {
54
+ if (!reportedWriteFailure) {
55
+ reportedWriteFailure = true;
56
+ try {
57
+ process.stderr.write(`[agentroam] failed to write error log to ${logsDir}; further failures are silent\n`);
58
+ }
59
+ catch { /* stderr gone */ }
60
+ }
61
+ }
62
+ };
63
+ const cleanupOldFiles = () => {
64
+ // 30-day retention, aligned with the core logger default. Best effort.
65
+ try {
66
+ if (!existsSync(logsDir))
67
+ return;
68
+ const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;
69
+ for (const name of readdirSync(logsDir)) {
70
+ if (!/^\d{4}-\d{2}-\d{2}\.log$/.test(name))
71
+ continue;
72
+ const full = join(logsDir, name);
73
+ try {
74
+ if (statSync(full).mtimeMs < cutoff)
75
+ unlinkSync(full);
76
+ }
77
+ catch { /* concurrent removal */ }
78
+ }
79
+ }
80
+ catch { /* best effort */ }
81
+ };
82
+ const log = (level, message, error, data) => {
83
+ if (!LEVELS.has(level))
84
+ level = "error";
85
+ const entry = {
86
+ ts: new Date().toISOString(),
87
+ level,
88
+ source: "cli",
89
+ message: typeof message === "string" ? message.slice(0, 4000) : String(message),
90
+ };
91
+ const serialized = serializeError(error);
92
+ if (serialized)
93
+ entry.error = serialized;
94
+ if (data !== undefined)
95
+ entry.data = data;
96
+ write(`${safeStringify(entry)}\n`);
97
+ };
98
+ return {
99
+ log,
100
+ installGlobalErrorHandlers: (options = {}) => {
101
+ const exitOnUncaughtException = options.exitOnUncaughtException ?? true;
102
+ process.on("uncaughtException", (err) => {
103
+ log("fatal", "uncaughtException", err);
104
+ if (exitOnUncaughtException)
105
+ process.exit(1);
106
+ });
107
+ process.on("unhandledRejection", (reason) => {
108
+ log("error", "unhandledRejection", reason);
109
+ });
110
+ cleanupOldFiles();
111
+ },
112
+ };
113
+ }
@@ -0,0 +1,143 @@
1
+ import { readdir, readFile, mkdir, realpath, rename } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { runCommand } from "./service/service-controller.js";
7
+ import { MacLaunchAgent } from "./service/macos-launch-agent.js";
8
+ import { WindowsTaskService } from "./service/windows-task-service.js";
9
+ function alive(pid) {
10
+ try {
11
+ process.kill(pid, 0);
12
+ return true;
13
+ }
14
+ catch (error) {
15
+ return error.code !== "ESRCH";
16
+ }
17
+ }
18
+ async function processList() {
19
+ if (process.platform === "win32") {
20
+ const result = await runCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress"]);
21
+ if (result.code !== 0)
22
+ throw new Error("无法核验旧 CLI 进程");
23
+ return JSON.parse(result.stdout).map((p) => ({ pid: p.ProcessId, ppid: p.ParentProcessId, command: p.CommandLine ?? "" }));
24
+ }
25
+ const result = await runCommand("ps", ["-axo", "pid=,ppid=,command="]);
26
+ if (result.code !== 0)
27
+ throw new Error("无法核验旧 CLI 进程");
28
+ return result.stdout.split("\n").flatMap(line => {
29
+ const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
30
+ return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }] : [];
31
+ });
32
+ }
33
+ async function stopCli(pid) {
34
+ const service = process.platform === "win32" ? new WindowsTaskService() : new MacLaunchAgent();
35
+ const status = await service.status();
36
+ if (status.running && status.state?.pid === pid) {
37
+ await service.stop();
38
+ return;
39
+ }
40
+ if (process.platform === "win32") {
41
+ const result = await runCommand("taskkill", ["/PID", String(pid), "/T", "/F"]);
42
+ if (result.code !== 0)
43
+ throw new Error("旧 CLI 进程树停止失败");
44
+ }
45
+ else
46
+ process.kill(pid, "SIGTERM");
47
+ }
48
+ async function isPackagedRuntime(command) {
49
+ const match = /(?:^|\s)(?:"([^"]+[\\/]ws-server\.mjs)"|(\S+[\\/]ws-server\.mjs))(?=\s|$)/.exec(command);
50
+ const gateway = match?.[1] ?? match?.[2];
51
+ if (!gateway)
52
+ return false;
53
+ try {
54
+ const path = await realpath(gateway);
55
+ if (!/[\\/]node_modules[\\/]agentroam-runtime-(?:darwin-arm64|win32-x64)[\\/]runtime[\\/]ws-server\.mjs$/.test(path))
56
+ return false;
57
+ const manifest = JSON.parse(await readFile(join(dirname(dirname(path)), "package.json"), "utf8"));
58
+ return ["agentroam-runtime-darwin-arm64", "agentroam-runtime-win32-x64"].includes(manifest.name);
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ }
64
+ /** Authenticate the local server, then verify its CLI parent before sending any signal. */
65
+ export async function stopPreviousInstances(dataDir, log, dependencies = {}) {
66
+ const canonical = await realpath(dataDir);
67
+ const registry = dependencies.registry ?? process.env.AGENTROAM_DISCOVERY_DIR ?? join(homedir(), ".agentroam/services");
68
+ const names = await readdir(registry).catch((error) => { if (error.code === "ENOENT")
69
+ return []; throw error; });
70
+ for (const name of names.filter(name => name.endsWith(".json"))) {
71
+ let d;
72
+ let source;
73
+ const recordPath = join(registry, name);
74
+ try {
75
+ source = await readFile(recordPath, "utf8");
76
+ d = JSON.parse(source);
77
+ if (d.protocol !== 1 || !Number.isSafeInteger(d.pid) || d.pid <= 1 || typeof d.instanceId !== "string" || !/^[a-f0-9]{64}$/.test(d.token))
78
+ continue;
79
+ const actual = await realpath(d.dataDir);
80
+ if (actual !== canonical && actual !== join(canonical, "data"))
81
+ continue;
82
+ const url = new URL(d.url);
83
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || url.pathname !== "/" || url.username || url.password || url.search || url.hash)
84
+ continue;
85
+ }
86
+ catch {
87
+ continue;
88
+ }
89
+ let identity;
90
+ try {
91
+ const response = await (dependencies.request ?? fetch)(new URL("/api/desktop/identity", d.url), { headers: { "x-agentroam-desktop-token": d.token }, redirect: "error", signal: AbortSignal.timeout(1500) });
92
+ if (!response.ok)
93
+ throw new Error("实例认证失败");
94
+ identity = await response.json();
95
+ }
96
+ catch {
97
+ if ((dependencies.alive ?? alive)(d.pid)) {
98
+ const processes = dependencies.processes ?? processList;
99
+ const owner = (await processes()).find(p => p.pid === d.pid);
100
+ // An unavailable gateway may still own live sessions. Only quarantine
101
+ // when the PID demonstrably belongs to a different kind of process.
102
+ if (!owner?.command.trim() || /[\\/]ws-server\.mjs(?:["\s]|$)|[\\/]agentroam[\\/]bin[\\/]agentroam\.mjs(?:["\s]|$)/.test(owner.command)) {
103
+ throw new Error("同一数据目录的旧实例无法核验,请先停止旧实例再重试");
104
+ }
105
+ const current = (await processes()).find(p => p.pid === d.pid);
106
+ if (!current || current.ppid !== owner.ppid || current.command !== owner.command) {
107
+ throw new Error("旧实例身份已变化,请重试");
108
+ }
109
+ if (await readFile(recordPath, "utf8") !== source)
110
+ throw new Error("旧实例记录已变化,请重试");
111
+ const backupDir = join(registry, "stale");
112
+ await mkdir(backupDir, { recursive: true, mode: 0o700 });
113
+ await rename(recordPath, join(backupDir, `${randomUUID()}-${name}`));
114
+ log("检测到旧服务记录的 PID 已被其他进程复用,已备份失效记录,继续启动。");
115
+ }
116
+ continue;
117
+ }
118
+ if (identity.protocol !== 1 || identity.instanceId !== d.instanceId || identity.dataDir !== d.dataDir)
119
+ throw new Error("旧实例身份不匹配,已取消启动");
120
+ const processes = await (dependencies.processes ?? processList)();
121
+ const server = processes.find(p => p.pid === d.pid);
122
+ const parent = processes.find(p => p.pid === server?.ppid);
123
+ const orphan = server && (server.ppid === 1 || !parent) && await isPackagedRuntime(server.command);
124
+ if (!server || server.pid === process.pid || (!orphan && (!parent || parent.pid === process.pid || !/[\\/]ws-server\.mjs(?:["\s]|$)/.test(server.command) || !/[\\/]agentroam[\\/]bin[\\/]agentroam\.mjs(?:["\s]|$)/.test(parent.command)))) {
125
+ throw new Error("同一数据目录已有服务,但无法确认它是可接管的 CLI 实例,请先停止该服务");
126
+ }
127
+ // Re-read the process relationship immediately before stopping, to reject stale PID records.
128
+ const current = await (dependencies.processes ?? processList)();
129
+ if (!current.some(p => p.pid === server.pid && p.ppid === server.ppid && p.command === server.command) || (!orphan && !current.some(p => p.pid === parent.pid && p.command === parent.command)))
130
+ throw new Error("旧实例身份已变化,请重试");
131
+ const targetPid = orphan ? server.pid : parent.pid;
132
+ log(orphan ? "检测到旧 CLI 遗留的服务进程,正在停止…" : "检测到同一数据目录的旧 CLI,正在停止…");
133
+ await (dependencies.stop ?? stopCli)(targetPid);
134
+ const deadline = Date.now() + (dependencies.timeoutMs ?? 15_000);
135
+ while ((dependencies.alive ?? alive)(targetPid) || (dependencies.alive ?? alive)(server.pid)) {
136
+ if (Date.now() >= deadline)
137
+ throw new Error("旧 CLI 尚未退出,已取消新实例启动,请稍后重试");
138
+ await delay(100);
139
+ }
140
+ log("✓ 旧 CLI 已停止,继续启动新实例");
141
+ }
142
+ }
143
+ export { lockInstanceStartup } from "./startup-lock.js";
@@ -0,0 +1,8 @@
1
+ export function printLocalDesktopUrl(localUrl, log = console.log, platform = process.platform) {
2
+ log(`Local-only desktop authorization (open on this computer, not your phone): ${localUrl.replace(/\/$/, '')}/web`);
3
+ log('Authorize again: agentroam desktop authorize. Browser fallback: open the local URL on this computer, pair, then click Remote Authorization (shield icon).');
4
+ if (platform === 'win32')
5
+ log('Click Enable Sharing. Keep Windows signed in and unlocked; UAC secure desktop and administrator windows are not supported.');
6
+ else
7
+ log('Grant Screen Recording and Accessibility permissions when prompted, then click Enable Sharing.');
8
+ }
@@ -0,0 +1,69 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ export class LocalServiceHttpError extends Error {
5
+ status;
6
+ detail;
7
+ constructor(status, detail) {
8
+ super(detail ? `本机服务请求失败 (HTTP ${status}): ${detail}` : `本机服务请求失败 (HTTP ${status})`);
9
+ this.status = status;
10
+ this.detail = detail;
11
+ }
12
+ }
13
+ /** Resolve an identity-checked loopback service; never send its token to a tunnel. */
14
+ export async function localServiceRequest(dataDir, path, options = {}) {
15
+ if (!path.startsWith("/api/"))
16
+ throw new Error("无效的本机服务路径");
17
+ const request = options.request ?? fetch;
18
+ options.signal?.throwIfAborted();
19
+ const requestSignal = (timeoutMs) => options.signal
20
+ ? AbortSignal.any([options.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
21
+ const directory = options.registry ?? process.env.AGENTROAM_DISCOVERY_DIR ?? join(homedir(), ".agentroam", "services");
22
+ const names = await readdir(directory).catch((error) => { if (error.code === "ENOENT")
23
+ return []; throw error; });
24
+ const candidates = [];
25
+ for (const name of names.filter((name) => name.endsWith(".json"))) {
26
+ try {
27
+ const d = JSON.parse(await readFile(join(directory, name), "utf8"));
28
+ const url = new URL(d.url);
29
+ if (d.protocol !== 1 || typeof d.instanceId !== "string" || !Number.isSafeInteger(d.pid) || d.pid <= 0 || ![resolve(dataDir), resolve(dataDir, "data")].includes(d.dataDir) || !/^[a-f0-9]{64}$/.test(d.token))
30
+ continue;
31
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || url.pathname !== "/" || url.username || url.password || url.search || url.hash)
32
+ continue;
33
+ options.signal?.throwIfAborted();
34
+ const response = await request(new URL("/api/desktop/identity", url), { headers: { "x-agentroam-desktop-token": d.token }, redirect: "error", signal: requestSignal(1500) });
35
+ if (!response.ok)
36
+ continue;
37
+ const identity = await response.json();
38
+ if (identity.protocol === 1 && identity.instanceId === d.instanceId && identity.dataDir === d.dataDir)
39
+ candidates.push(d);
40
+ }
41
+ catch {
42
+ options.signal?.throwIfAborted(); /* Stale descriptors are expected after a process crash. */
43
+ }
44
+ }
45
+ options.signal?.throwIfAborted();
46
+ if (candidates.length !== 1)
47
+ throw new Error(candidates.length ? "多个服务使用此数据目录,请先停止多余实例" : "未找到运行中的 AgentRoam 服务,请先启动服务或指定 --data-dir");
48
+ const d = candidates[0];
49
+ const url = new URL(path, d.url);
50
+ if (url.origin !== new URL(d.url).origin)
51
+ throw new Error("无效的本机服务路径");
52
+ const response = await request(url, {
53
+ method: options.method ?? "GET",
54
+ headers: { "x-agentroam-desktop-token": d.token, "content-type": "application/json", origin: new URL(d.url).origin },
55
+ ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
56
+ redirect: "error", signal: requestSignal(options.timeoutMs ?? 5000),
57
+ });
58
+ if (!response.ok) {
59
+ let detail;
60
+ try {
61
+ const body = await response.json();
62
+ if (typeof body.error === "string" && body.error.trim())
63
+ detail = body.error.trim().slice(0, 500);
64
+ }
65
+ catch { /* Preserve the status when the service did not return JSON. */ }
66
+ throw new LocalServiceHttpError(response.status, detail);
67
+ }
68
+ return response.json();
69
+ }
@@ -0,0 +1,51 @@
1
+ import { renderQr } from "../qr.js";
2
+ import { localServiceRequest } from "../local-service-request.js";
3
+ import { meshQrPayload } from "./mesh-payload.js";
4
+ export { meshQrPayload };
5
+ export async function runMeshCommand(options) {
6
+ if (options.action === "status")
7
+ return printStatus(options);
8
+ if (options.action === "nodes")
9
+ return printNodes(options);
10
+ if (options.action === "qr")
11
+ return printJoinQr(options);
12
+ await localServiceRequest(options.dataDir, `/api/mesh/admin/${options.action}`, {
13
+ method: "POST", body: { nodeName: options.nodeName }, timeoutMs: 125_000,
14
+ });
15
+ await printStatus(options);
16
+ }
17
+ async function printStatus(options) {
18
+ const status = await localServiceRequest(options.dataDir, "/api/mesh/status");
19
+ console.log(`控制面:${status.configured ? status.controlPlaneUrl : "未配置(使用一次性激活码启动,或配置自管 Headscale 后重启服务)"}`);
20
+ console.log(`状态:${status.phase}${status.lastError ? `(${status.lastError})` : ""}`);
21
+ if (status.hostname)
22
+ console.log(`设备:${status.hostname}`);
23
+ if (status.tailnetIPv4)
24
+ console.log(`Tailnet IP:${status.tailnetIPv4}`);
25
+ if (status.phase === "joined" && status.dnsName)
26
+ console.log(`网关地址:http://${status.dnsName}`);
27
+ if (status.user)
28
+ console.log(`Headscale 用户:${status.user}`);
29
+ if (status.joinedAt)
30
+ console.log(`入网时间:${new Date(status.joinedAt).toLocaleString()}`);
31
+ }
32
+ async function printNodes(options) {
33
+ const { nodes } = await localServiceRequest(options.dataDir, "/api/mesh/admin/nodes");
34
+ console.log(nodes.length
35
+ ? nodes.map((node) => `${node.id} ${node.name} ${node.user ?? "-"}`).join("\n")
36
+ : "控制面上暂无节点");
37
+ }
38
+ async function printJoinQr(options) {
39
+ const issued = await localServiceRequest(options.dataDir, "/api/mesh/admin/key", {
40
+ method: "POST",
41
+ body: { device: "phone", nodeName: options.nodeName }, timeoutMs: 60_000,
42
+ });
43
+ const payload = meshQrPayload(issued);
44
+ console.log("手机加入组网(一次性,15 分钟内有效;请勿截图分享):");
45
+ if (options.qr !== false && process.stdout.isTTY)
46
+ console.log(await renderQr(payload));
47
+ console.log(`\n控制面地址:${issued.loginServer}`);
48
+ console.log(`认证 key:${issued.authkey}`);
49
+ console.log("在 Tailscale 客户端选择自定义控制面,使用以上认证 key 注册设备。");
50
+ console.log(`入网后生成 AgentRoam App 授权码:agentroam pair`);
51
+ }