agentroam 0.2.0-preview.7 → 0.2.0-preview.71

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 (82) 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 +102 -3
  12. package/dist/cli.js +244 -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 +153 -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 +170 -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/native-runtime.js +68 -0
  35. package/dist/network.js +32 -3
  36. package/dist/node-runtime-manager.js +251 -0
  37. package/dist/opencode-runtime-manager.js +239 -0
  38. package/dist/platform-packages.js +16 -5
  39. package/dist/platform.js +6 -4
  40. package/dist/power/sleep-inhibitor.js +161 -0
  41. package/dist/runtime-manager.js +130 -19
  42. package/dist/service/launcher-cleanup.js +79 -0
  43. package/dist/service/macos-launch-agent.js +288 -0
  44. package/dist/service/runtime-state.js +43 -0
  45. package/dist/service/service-command.js +219 -0
  46. package/dist/service/service-controller.js +27 -0
  47. package/dist/service/service-files.js +78 -0
  48. package/dist/service/windows-service-host.js +59 -0
  49. package/dist/service/windows-task-service.js +289 -0
  50. package/dist/startup-lock.js +81 -0
  51. package/dist/tunnel/cloudflare-provider.js +4 -1
  52. package/dist/tunnel/public-readiness.js +76 -50
  53. package/dist/tunnel/relay-orchestrator.js +31 -9
  54. package/dist/tunnel/tunnel-controller.js +144 -0
  55. package/dist/unlock-service.js +105 -0
  56. package/dist/update/update-channel.js +38 -0
  57. package/dist/update/update-command.js +96 -0
  58. package/dist/update/update-install.js +34 -0
  59. package/dist/update/update-state.js +43 -0
  60. package/dist/update/update-worker.js +80 -0
  61. package/install/README.md +55 -0
  62. package/install/codex-shared-watchdog.sh +16 -0
  63. package/install/install-agentroam.ps1 +358 -0
  64. package/install/install-agentroam.sh +457 -0
  65. package/install/install-manifest.json +15 -0
  66. package/install/start-codex-desktop-shared.sh +152 -0
  67. package/package.json +13 -10
  68. package/dist/args.test.js +0 -27
  69. package/dist/cloudflared/bundled-asset.test.js +0 -76
  70. package/dist/cloudflared/installer.test.js +0 -95
  71. package/dist/native-runtime.test.js +0 -19
  72. package/dist/network.test.js +0 -20
  73. package/dist/pairing.js +0 -2
  74. package/dist/platform-packages.test.js +0 -75
  75. package/dist/platform.test.js +0 -3
  76. package/dist/port.test.js +0 -3
  77. package/dist/process-supervisor.test.js +0 -42
  78. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  79. package/dist/tunnel/pinggy-provider.test.js +0 -40
  80. package/dist/tunnel/proxy-settings.test.js +0 -111
  81. package/dist/tunnel/public-readiness.test.js +0 -104
  82. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -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
+ }
@@ -1,5 +1,73 @@
1
1
  import { chmod } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ const execute = promisify(execFile);
6
+ const WINDOWS_PTY_PROBE = `
7
+ const pty = require(process.argv[1]);
8
+ const marker = "agentroam-runtime-probe";
9
+ const terminal = pty.spawn(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", "echo " + marker], {
10
+ name: "xterm-256color", cols: 80, rows: 24, cwd: process.cwd(), env: process.env,
11
+ });
12
+ let output = "";
13
+ const timer = setTimeout(() => process.exit(1), 5000);
14
+ terminal.onData(chunk => { output = (output + chunk).slice(-4096); });
15
+ terminal.onExit(({ exitCode }) => {
16
+ clearTimeout(timer);
17
+ process.exit(exitCode === 0 && output.includes(marker) ? 0 : 1);
18
+ });
19
+ `;
20
+ export function probeSQLiteRuntime(runtimeRequire) {
21
+ const Database = runtimeRequire("better-sqlite3");
22
+ const database = new Database(":memory:");
23
+ try {
24
+ database.exec("CREATE TABLE runtime_probe (value INTEGER NOT NULL)");
25
+ database.prepare("INSERT INTO runtime_probe VALUES (?)").run(7);
26
+ if (database.prepare("SELECT value FROM runtime_probe").get()?.value !== 7) {
27
+ throw new Error("SQLite runtime query failed");
28
+ }
29
+ }
30
+ finally {
31
+ database.close();
32
+ }
33
+ }
34
+ export async function probeTerminalRuntime(runtimeRequire, platform = process.platform) {
35
+ if (platform === "win32") {
36
+ // ConPTY retains an output worker after shell exit. Keep the probe in an
37
+ // owned child process so terminating it releases all handles together.
38
+ await execute(process.execPath, ["--input-type=commonjs", "-e", WINDOWS_PTY_PROBE, runtimeRequire.resolve("node-pty")], {
39
+ timeout: 10_000, windowsHide: true, maxBuffer: 64 * 1024,
40
+ });
41
+ return;
42
+ }
43
+ const pty = runtimeRequire("node-pty");
44
+ const marker = "agentroam-runtime-probe";
45
+ const terminal = pty.spawn("/bin/sh", ["-c", `printf ${marker}`], {
46
+ name: "xterm-256color", cols: 80, rows: 24, cwd: process.cwd(), env: process.env,
47
+ });
48
+ await new Promise((resolveProbe, rejectProbe) => {
49
+ let output = "";
50
+ const timer = setTimeout(() => {
51
+ dataListener.dispose();
52
+ exitListener.dispose();
53
+ try {
54
+ terminal.kill();
55
+ }
56
+ catch { }
57
+ rejectProbe(new Error("PTY runtime probe timed out"));
58
+ }, 5_000);
59
+ const dataListener = terminal.onData((chunk) => { output = (output + chunk).slice(-4096); });
60
+ const exitListener = terminal.onExit(({ exitCode }) => {
61
+ clearTimeout(timer);
62
+ dataListener.dispose();
63
+ exitListener.dispose();
64
+ if (exitCode === 0 && output.includes(marker))
65
+ resolveProbe();
66
+ else
67
+ rejectProbe(new Error(`PTY runtime probe failed (exit ${exitCode})`));
68
+ });
69
+ });
70
+ }
3
71
  export async function repairNativeRuntimePermissions(runtimeRoot, platform = process.platform, arch = process.arch) {
4
72
  if (platform === "win32")
5
73
  return;
package/dist/network.js CHANGED
@@ -1,17 +1,46 @@
1
1
  import { networkInterfaces } from "node:os";
2
- export function findLanUrl(port, interfaces = networkInterfaces()) {
2
+ import { createSocket } from "node:dgram";
3
+ export function findLanUrl(port, interfaces = networkInterfaces(), routedAddress) {
3
4
  const addresses = Object.values(interfaces)
4
5
  .flatMap((entries) => entries ?? [])
5
6
  .filter((entry) => entry.family === "IPv4" && !entry.internal)
6
7
  .map((entry) => entry.address);
7
- const address = addresses.find(isPrivateIpv4) ?? addresses[0];
8
+ const address = routedAddress && addresses.includes(routedAddress) && isPrivateIpv4(routedAddress)
9
+ ? routedAddress : addresses.find(isPreferredLanIpv4);
8
10
  return address ? `http://${address}:${port}` : null;
9
11
  }
12
+ /** UDP connect selects the OS route without sending a packet to the destination. */
13
+ export async function findRoutedLanUrl(port) {
14
+ const routedAddress = await new Promise((done) => {
15
+ const socket = createSocket("udp4");
16
+ let settled = false;
17
+ const finish = (address) => {
18
+ if (settled)
19
+ return;
20
+ settled = true;
21
+ clearTimeout(timer);
22
+ try {
23
+ socket.close();
24
+ }
25
+ catch { /* A failed bind may leave no socket to close. */ }
26
+ done(address);
27
+ };
28
+ const timer = setTimeout(() => finish(null), 1_000);
29
+ socket.once("error", () => finish(null));
30
+ socket.connect(53, "1.1.1.1", () => { if (!settled)
31
+ finish(socket.address().address); });
32
+ });
33
+ return findLanUrl(port, networkInterfaces(), routedAddress);
34
+ }
10
35
  function isPrivateIpv4(address) {
36
+ const parts = address.split(".").map(Number);
37
+ return isPreferredLanIpv4(address) || (parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
38
+ && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31);
39
+ }
40
+ function isPreferredLanIpv4(address) {
11
41
  const parts = address.split(".").map(Number);
12
42
  if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255))
13
43
  return false;
14
44
  return parts[0] === 10 ||
15
- (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
16
45
  (parts[0] === 192 && parts[1] === 168);
17
46
  }
@@ -0,0 +1,251 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { createReadStream, createWriteStream } from "node:fs";
4
+ import { access, chmod, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, } from "node:fs/promises";
5
+ import { get as httpsGet } from "node:https";
6
+ import { resolve } from "node:path";
7
+ import { pipeline } from "node:stream/promises";
8
+ import { promisify } from "node:util";
9
+ const execFileAsync = promisify(execFile);
10
+ const NODE_DOWNLOAD_BASE_URL = "https://nodejs.org/dist/v22.22.0";
11
+ const DEFAULT_DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
12
+ const DEFAULT_LOCK_WAIT_MS = 12 * 60_000;
13
+ const DEFAULT_STALE_LOCK_MS = 15 * 60_000;
14
+ const MAX_REDIRECTS = 5;
15
+ export const MANAGED_NODE_VERSION = "22.22.0";
16
+ export const NODE_RUNTIME_ASSETS = {
17
+ "darwin-arm64": {
18
+ archive: "node-v22.22.0-darwin-arm64.tar.xz",
19
+ sha256: "2bd596bbfc4a275ceb8721a5954ee97daea5ebe673e96a185ebd732f6fb023ac",
20
+ archiveRoot: "node-v22.22.0-darwin-arm64",
21
+ },
22
+ "windows-amd64": {
23
+ archive: "node-v22.22.0-win-x64.zip",
24
+ sha256: "c97fa376d2becdc8863fcd3ca2dd9a83a9f3468ee7ccf7a6d076ec66a645c77a",
25
+ archiveRoot: "node-v22.22.0-win-x64",
26
+ },
27
+ };
28
+ const defaultDependencies = {
29
+ download: downloadFile,
30
+ sha256: sha256File,
31
+ async run(command, args, timeoutMs) {
32
+ const { stdout, stderr } = await execFileAsync(command, args, {
33
+ encoding: "utf8",
34
+ timeout: timeoutMs,
35
+ maxBuffer: 4 * 1024 * 1024,
36
+ windowsHide: true,
37
+ });
38
+ return { stdout, stderr };
39
+ },
40
+ sleep: (delayMs) => new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs)),
41
+ now: () => Date.now(),
42
+ };
43
+ export function detectNodeRuntimeTarget(platform = process.platform, arch = process.arch) {
44
+ if (platform === "darwin" && arch === "arm64")
45
+ return "darwin-arm64";
46
+ if (platform === "win32" && arch === "x64")
47
+ return "windows-amd64";
48
+ throw Object.assign(new Error(`managed Node.js is unsupported on ${platform}-${arch}`), {
49
+ exitCode: 2,
50
+ });
51
+ }
52
+ export function managedNodeExecutable(dataDir, target) {
53
+ const root = resolve(dataDir, "runtimes", "node", MANAGED_NODE_VERSION);
54
+ return target === "windows-amd64" ? resolve(root, "node.exe") : resolve(root, "bin", "node");
55
+ }
56
+ export function managedNodeNpmCli(dataDir, target) {
57
+ const root = resolve(dataDir, "runtimes", "node", MANAGED_NODE_VERSION);
58
+ return target === "windows-amd64"
59
+ ? resolve(root, "node_modules", "npm", "bin", "npm-cli.js")
60
+ : resolve(root, "lib", "node_modules", "npm", "bin", "npm-cli.js");
61
+ }
62
+ export async function ensureManagedNode(options) {
63
+ const target = options.target ?? detectNodeRuntimeTarget(options.platform, options.arch);
64
+ const dependencies = { ...defaultDependencies, ...options.dependencies };
65
+ const cached = await validateManagedNode(options.dataDir, target, dependencies);
66
+ if (cached)
67
+ return cached;
68
+ const parent = resolve(options.dataDir, "runtimes", "node");
69
+ const runtimeRoot = resolve(parent, MANAGED_NODE_VERSION);
70
+ const lockPath = `${runtimeRoot}.lock`;
71
+ await mkdir(parent, { recursive: true });
72
+ const lock = await acquireLock({
73
+ lockPath,
74
+ dataDir: options.dataDir,
75
+ target,
76
+ dependencies,
77
+ waitMs: options.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS,
78
+ staleMs: options.staleLockMs ?? DEFAULT_STALE_LOCK_MS,
79
+ });
80
+ if (lock.completed)
81
+ return lock.completed;
82
+ let temporaryRoot = null;
83
+ try {
84
+ const afterLock = await validateManagedNode(options.dataDir, target, dependencies);
85
+ if (afterLock)
86
+ return afterLock;
87
+ const asset = NODE_RUNTIME_ASSETS[target];
88
+ temporaryRoot = await mkdtemp(resolve(parent, `.${MANAGED_NODE_VERSION}-${process.pid}-`));
89
+ const archivePath = resolve(temporaryRoot, asset.archive);
90
+ const extractRoot = resolve(temporaryRoot, "extract");
91
+ await mkdir(extractRoot);
92
+ options.onProgress?.(`Downloading Node.js ${MANAGED_NODE_VERSION} for ${target}...`);
93
+ await dependencies.download(`${NODE_DOWNLOAD_BASE_URL}/${asset.archive}`, archivePath, options.downloadTimeoutMs ?? DEFAULT_DOWNLOAD_TIMEOUT_MS);
94
+ const actualSha256 = await dependencies.sha256(archivePath);
95
+ if (actualSha256 !== asset.sha256) {
96
+ throw new Error(`Node.js archive checksum mismatch: expected ${asset.sha256}, got ${actualSha256}`);
97
+ }
98
+ options.onProgress?.(`Extracting Node.js ${MANAGED_NODE_VERSION}...`);
99
+ await extractArchive(target, archivePath, extractRoot, dependencies);
100
+ const entries = await readdir(extractRoot);
101
+ if (entries.length !== 1 || entries[0] !== asset.archiveRoot) {
102
+ throw new Error(`unexpected Node.js archive root: ${entries.join(", ") || "empty archive"}`);
103
+ }
104
+ const extractedRuntime = resolve(extractRoot, asset.archiveRoot);
105
+ const staged = await validateRuntimeRoot(extractedRuntime, target, dependencies);
106
+ if (!staged)
107
+ throw new Error("Node.js runtime validation failed after extraction");
108
+ await rm(runtimeRoot, { recursive: true, force: true });
109
+ await rename(extractedRuntime, runtimeRoot);
110
+ const installed = await validateManagedNode(options.dataDir, target, dependencies);
111
+ if (!installed)
112
+ throw new Error("Node.js runtime validation failed after activation");
113
+ return installed;
114
+ }
115
+ catch (error) {
116
+ const concurrent = await validateManagedNode(options.dataDir, target, dependencies);
117
+ if (concurrent)
118
+ return concurrent;
119
+ throw new Error(`Unable to install managed Node.js ${MANAGED_NODE_VERSION}: ${describeError(error)}`, {
120
+ cause: error,
121
+ });
122
+ }
123
+ finally {
124
+ if (temporaryRoot)
125
+ await rm(temporaryRoot, { recursive: true, force: true });
126
+ await lock.handle.close().catch(() => undefined);
127
+ await releaseOwnedLock(lockPath, lock.token);
128
+ }
129
+ }
130
+ async function validateManagedNode(dataDir, target, dependencies) {
131
+ return validateRuntimeRoot(resolve(dataDir, "runtimes", "node", MANAGED_NODE_VERSION), target, dependencies);
132
+ }
133
+ async function validateRuntimeRoot(runtimeRoot, target, dependencies) {
134
+ const executable = target === "windows-amd64"
135
+ ? resolve(runtimeRoot, "node.exe")
136
+ : resolve(runtimeRoot, "bin", "node");
137
+ const npmCli = target === "windows-amd64"
138
+ ? resolve(runtimeRoot, "node_modules", "npm", "bin", "npm-cli.js")
139
+ : resolve(runtimeRoot, "lib", "node_modules", "npm", "bin", "npm-cli.js");
140
+ if (!(await pathExists(executable)) || !(await pathExists(npmCli)))
141
+ return null;
142
+ try {
143
+ if (target === "darwin-arm64")
144
+ await chmod(executable, 0o755);
145
+ const result = await dependencies.run(executable, ["--version"], 5_000);
146
+ if (`${result.stdout}\n${result.stderr}`.trim() !== `v${MANAGED_NODE_VERSION}`)
147
+ return null;
148
+ return { executable, npmCli, version: MANAGED_NODE_VERSION, source: "managed" };
149
+ }
150
+ catch {
151
+ return null;
152
+ }
153
+ }
154
+ async function extractArchive(target, archivePath, extractRoot, dependencies) {
155
+ if (target === "darwin-arm64") {
156
+ await dependencies.run("/usr/bin/tar", ["-xJf", archivePath, "-C", extractRoot], 120_000);
157
+ return;
158
+ }
159
+ const script = "& { param($archive, $destination) Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }";
160
+ await dependencies.run("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script, archivePath, extractRoot], 120_000);
161
+ }
162
+ async function acquireLock(options) {
163
+ const deadline = options.dependencies.now() + options.waitMs;
164
+ while (true) {
165
+ const token = `${process.pid}:${randomUUID()}`;
166
+ try {
167
+ const handle = await open(options.lockPath, "wx", 0o600);
168
+ await handle.writeFile(`${token}\n${options.dependencies.now()}\n`);
169
+ return { handle, token };
170
+ }
171
+ catch (error) {
172
+ if (error.code !== "EEXIST")
173
+ throw error;
174
+ const completed = await validateManagedNode(options.dataDir, options.target, options.dependencies);
175
+ if (completed)
176
+ return { completed };
177
+ try {
178
+ const details = await stat(options.lockPath);
179
+ if (options.dependencies.now() - details.mtimeMs > options.staleMs) {
180
+ await rm(options.lockPath, { force: true });
181
+ continue;
182
+ }
183
+ }
184
+ catch {
185
+ continue;
186
+ }
187
+ if (options.dependencies.now() >= deadline) {
188
+ throw new Error(`Timed out waiting for Node.js install lock: ${options.lockPath}`);
189
+ }
190
+ await options.dependencies.sleep(Math.min(250, Math.max(1, deadline - options.dependencies.now())));
191
+ }
192
+ }
193
+ }
194
+ async function releaseOwnedLock(lockPath, token) {
195
+ try {
196
+ if ((await readFile(lockPath, "utf8")).split("\n", 1)[0] === token) {
197
+ await rm(lockPath, { force: true });
198
+ }
199
+ }
200
+ catch {
201
+ // A missing or replaced lock no longer belongs to this installer.
202
+ }
203
+ }
204
+ async function downloadFile(url, destination, timeoutMs) {
205
+ await new Promise((resolveDownload, rejectDownload) => {
206
+ const request = (currentUrl, redirects) => {
207
+ const responseRequest = httpsGet(currentUrl, { headers: { "user-agent": "agentroam-node-bootstrap" } }, (response) => {
208
+ const status = response.statusCode ?? 0;
209
+ if (status >= 300 && status < 400 && response.headers.location) {
210
+ response.resume();
211
+ if (redirects >= MAX_REDIRECTS)
212
+ return rejectDownload(new Error("too many Node.js download redirects"));
213
+ const redirectUrl = new URL(response.headers.location, currentUrl);
214
+ if (redirectUrl.protocol !== "https:") {
215
+ rejectDownload(new Error(`refusing non-HTTPS Node.js redirect: ${redirectUrl.protocol}`));
216
+ return;
217
+ }
218
+ request(redirectUrl.toString(), redirects + 1);
219
+ return;
220
+ }
221
+ if (status !== 200) {
222
+ response.resume();
223
+ rejectDownload(new Error(`Node.js download failed: HTTP ${status}`));
224
+ return;
225
+ }
226
+ pipeline(response, createWriteStream(destination, { mode: 0o600 }))
227
+ .then(resolveDownload, rejectDownload);
228
+ });
229
+ responseRequest.setTimeout(timeoutMs, () => responseRequest.destroy(new Error("Node.js download timed out")));
230
+ responseRequest.once("error", rejectDownload);
231
+ };
232
+ request(url, 0);
233
+ });
234
+ }
235
+ async function sha256File(path) {
236
+ const hash = createHash("sha256");
237
+ await pipeline(createReadStream(path), hash);
238
+ return hash.digest("hex");
239
+ }
240
+ async function pathExists(path) {
241
+ try {
242
+ await access(path);
243
+ return true;
244
+ }
245
+ catch {
246
+ return false;
247
+ }
248
+ }
249
+ function describeError(error) {
250
+ return error instanceof Error ? error.message : String(error);
251
+ }