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,95 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { link, readFile, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writePrivateJson } from "../service/service-files.js";
5
+ const DEFAULT_CONTROL_PLANE = "https://headscale.kaiwuyouwei.com";
6
+ const SECRET = /^[A-Za-z0-9_-]{43}$/;
7
+ function configPath(dataDir) {
8
+ return join(dataDir, "mesh", "control-plane.json");
9
+ }
10
+ export async function saveMeshEnvironment(dataDir, env) {
11
+ const url = env.AGENT_HEADSCALE_URL?.trim();
12
+ const apiKey = env.AGENT_HEADSCALE_API_KEY?.trim();
13
+ const code = env.AGENTROAM_MESH_ACTIVATION_CODE?.trim();
14
+ if (code) {
15
+ if (apiKey || env.AGENTROAM_MESH_CREDENTIAL)
16
+ throw new Error("组网激活码不能与其他组网凭据同时使用");
17
+ await activateMesh(dataDir, url ?? DEFAULT_CONTROL_PLANE, code);
18
+ return;
19
+ }
20
+ if (!url && !apiKey)
21
+ return;
22
+ if (!url || !apiKey)
23
+ throw new Error("请同时设置 AGENT_HEADSCALE_URL 和 AGENT_HEADSCALE_API_KEY");
24
+ await writePrivateJson(configPath(dataDir), { url, apiKey });
25
+ }
26
+ /** Keep the same credential after a lost activation response. The code itself is never stored. */
27
+ async function activateMesh(dataDir, url, code) {
28
+ const plane = new URL(url);
29
+ if (plane.protocol !== "https:" || plane.username || plane.password || plane.pathname !== "/" || plane.search || plane.hash) {
30
+ throw new Error("组网激活需要 HTTPS 控制面地址");
31
+ }
32
+ if (!SECRET.test(code))
33
+ throw new Error("无效的组网激活码");
34
+ const path = configPath(dataDir);
35
+ if (!await readMeshConfig(dataDir)) {
36
+ const temporary = `${path}.${randomBytes(8).toString("hex")}.pending`;
37
+ await writePrivateJson(temporary, { url: plane.origin, credential: randomBytes(32).toString("base64url") });
38
+ try {
39
+ await link(temporary, path);
40
+ }
41
+ catch (error) {
42
+ if (error.code !== "EEXIST")
43
+ throw error;
44
+ }
45
+ finally {
46
+ await rm(temporary, { force: true });
47
+ }
48
+ }
49
+ const config = await readMeshConfig(dataDir);
50
+ if (config?.url !== plane.origin || !config.credential)
51
+ throw new Error("此数据目录已有其他组网配置");
52
+ if (config.activated)
53
+ return;
54
+ const response = await fetch(new URL("/agentroam-enrollment/v1/activate", plane), {
55
+ method: "POST",
56
+ headers: { authorization: `Bearer ${config.credential}`, "content-type": "application/json" },
57
+ body: JSON.stringify({ code }),
58
+ redirect: "error", signal: AbortSignal.timeout(10_000),
59
+ });
60
+ if (!response.ok) {
61
+ if ([400, 403].includes(response.status)) {
62
+ throw new Error("组网激活码已失效、无效或已被另一台设备使用");
63
+ }
64
+ throw new Error(`组网激活失败 (HTTP ${response.status})`);
65
+ }
66
+ await writePrivateJson(path, { ...config, activated: true });
67
+ }
68
+ async function readMeshConfig(dataDir) {
69
+ const raw = await readFile(configPath(dataDir), "utf8").catch(error => {
70
+ if (error.code === "ENOENT")
71
+ return null;
72
+ throw error;
73
+ });
74
+ if (raw === null)
75
+ return null;
76
+ try {
77
+ const config = JSON.parse(raw);
78
+ if (typeof config?.url === "string" && (typeof config.apiKey === "string" || (typeof config.credential === "string" && SECRET.test(config.credential))))
79
+ return config;
80
+ }
81
+ catch { /* Report a malformed private config without its contents. */ }
82
+ throw new Error("无法读取组网控制面配置");
83
+ }
84
+ export async function loadMeshEnvironment(dataDir, env) {
85
+ if (env.AGENTROAM_MESH_ACTIVATION_CODE?.trim())
86
+ await saveMeshEnvironment(dataDir, env);
87
+ else if (env.AGENT_HEADSCALE_URL !== undefined || env.AGENT_HEADSCALE_API_KEY !== undefined || env.AGENTROAM_MESH_CREDENTIAL !== undefined)
88
+ return {};
89
+ const config = await readMeshConfig(dataDir);
90
+ if (config?.apiKey)
91
+ return { AGENT_HEADSCALE_URL: config.url, AGENT_HEADSCALE_API_KEY: config.apiKey };
92
+ if (config?.activated && config.credential)
93
+ return { AGENT_HEADSCALE_URL: config.url, AGENTROAM_MESH_CREDENTIAL: config.credential };
94
+ return {};
95
+ }
@@ -0,0 +1,20 @@
1
+ import { hostname } from "node:os";
2
+ /**
3
+ * 纯函数层(无子进程、无二维码依赖),便于在 CLI 之外复用与单测:
4
+ * 机器标识、扫码载荷、本机服务地址发现。
5
+ */
6
+ /** 机器标识:与 headscale user 命名一一对应(agentroam-<id>)。 */
7
+ export function meshMachineId(host = hostname()) {
8
+ return host.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32).replace(/-+$/g, "") || "local";
9
+ }
10
+ /** 手机扫码载荷:JSON,官方客户端 M2 手工输入,M3 内嵌客户端直接解析。 */
11
+ export function meshQrPayload(input) {
12
+ return JSON.stringify({
13
+ type: "agentroam-mesh",
14
+ version: 1,
15
+ loginServer: input.loginServer,
16
+ authkey: input.authkey,
17
+ ...(input.accessUrl ? { accessUrl: input.accessUrl } : {}),
18
+ ...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),
19
+ });
20
+ }
@@ -0,0 +1,101 @@
1
+ import { isIPv4 } from "node:net";
2
+ import { localServiceRequest } from "../local-service-request.js";
3
+ import { TailscaleDaemon } from "../tailscale/daemon-manager.js";
4
+ import { ensureTailscaleBinaries } from "../tailscale/installer.js";
5
+ import { readTailscaleStatus, tailscaleLogout, tailscaleServe, tailscaleServeReset, tailscaleUp } from "../tailscale/tailnet-cli.js";
6
+ import { meshMachineId } from "./mesh-payload.js";
7
+ export function createMeshRuntime({ dataDir, localUrl, target, log }) {
8
+ const controller = new AbortController();
9
+ const { signal } = controller;
10
+ let daemon;
11
+ let pending = Promise.resolve();
12
+ const request = (action, body) => localServiceRequest(dataDir, `/api/mesh/${action}`, body === undefined
13
+ ? { signal } : { signal, method: "POST", body, timeoutMs: 60_000 });
14
+ async function apply(action, requestedName, automatic = false) {
15
+ signal.throwIfAborted();
16
+ const state = await request("status");
17
+ if (!state.configured) {
18
+ if (automatic)
19
+ return;
20
+ throw new Error("请先用激活码配置组网并重启 AgentRoam");
21
+ }
22
+ if (automatic && state.phase === "offboarded")
23
+ return;
24
+ if (action === "offboard" && state.phase === "offboarded")
25
+ return;
26
+ try {
27
+ const binaries = await ensureTailscaleBinaries(target, dataDir);
28
+ signal.throwIfAborted();
29
+ daemon ??= new TailscaleDaemon({ dataDir, tailscaledPath: binaries.tailscaled, signal, onLog: log });
30
+ const cli = { tailscalePath: binaries.tailscale, socketPath: daemon.socketPath(), signal };
31
+ const runtime = await daemon.ensureRunning(binaries.tailscale);
32
+ const isRunning = runtime.status.backendState === "Running";
33
+ if (isRunning && runtime.status.controlPlaneUrl !== state.controlPlaneUrl) {
34
+ throw new Error("已加入的控制面与当前配置不同,请先恢复原配置并退出组网");
35
+ }
36
+ if (action === "offboard") {
37
+ try {
38
+ await tailscaleServeReset(cli);
39
+ if (isRunning)
40
+ await tailscaleLogout(cli);
41
+ await request("admin/left", {});
42
+ }
43
+ finally {
44
+ await daemon.stop();
45
+ }
46
+ return;
47
+ }
48
+ const name = requestedName ?? meshMachineId(runtime.status.hostname ?? undefined);
49
+ if (!isRunning) {
50
+ const issued = await request("admin/key", { device: "desktop", nodeName: name });
51
+ await tailscaleUp(cli, { loginServer: issued.loginServer, authKey: issued.authkey, hostname: name, stateDir: runtime.stateDir });
52
+ }
53
+ const status = await readTailscaleStatus(cli);
54
+ const tailnetIPv4 = status.tailscaleIPs.find(ip => {
55
+ if (!isIPv4(ip))
56
+ return false;
57
+ const [network, subnet] = ip.split(".").map(Number);
58
+ return network === 100 && subnet >= 64 && subnet <= 127;
59
+ });
60
+ if (status.backendState !== "Running" || !tailnetIPv4)
61
+ throw new Error("入网未完成,未获得组网 IPv4 地址");
62
+ if (!status.dnsName)
63
+ throw new Error("Headscale 未提供 MagicDNS 地址,请检查控制面配置");
64
+ await tailscaleServe(cli, localUrl);
65
+ await request("admin/report", { hostname: status.hostname ? meshMachineId(status.hostname) : name, tailnetIPv4, dnsName: status.dnsName });
66
+ }
67
+ catch (error) {
68
+ if (!signal.aborted) {
69
+ const message = error instanceof Error ? error.message : String(error);
70
+ await request("admin/error", { message }).catch(() => { });
71
+ }
72
+ throw error;
73
+ }
74
+ }
75
+ return {
76
+ run(action, name, automatic = false) {
77
+ const operation = pending.then(() => apply(action, name, automatic));
78
+ pending = operation.catch(() => { });
79
+ return operation;
80
+ },
81
+ async close() {
82
+ controller.abort();
83
+ await daemon?.stop();
84
+ await pending;
85
+ },
86
+ };
87
+ }
88
+ export function attachMeshControl(child, runtime) {
89
+ const receive = (message) => {
90
+ if (message?.type !== "agentroam:mesh-run" || typeof message.id !== "string" ||
91
+ (message.action !== "onboard" && message.action !== "offboard"))
92
+ return;
93
+ const reply = (error) => {
94
+ if (child.connected)
95
+ child.send({ type: "agentroam:mesh-result", id: message.id, error }, () => { });
96
+ };
97
+ void runtime.run(message.action, message.name).then(() => reply(), error => reply(error instanceof Error ? error.message : String(error)));
98
+ };
99
+ child.on("message", receive);
100
+ return () => child.off("message", receive);
101
+ }
@@ -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,60 @@
1
1
  import { networkInterfaces } from "node:os";
2
- export function findLanUrl(port, interfaces = networkInterfaces()) {
2
+ import { createSocket } from "node:dgram";
3
+ export function pairingNetworkRoutes(interfaces = networkInterfaces()) {
4
+ const choices = new Map();
5
+ for (const [interfaceName, entries] of Object.entries(interfaces)) {
6
+ for (const entry of entries ?? []) {
7
+ if (entry.family !== "IPv4" || entry.internal || choices.has(entry.address))
8
+ continue;
9
+ const { address } = entry;
10
+ const [first, second] = address.split(".").map(Number);
11
+ const kind = first === 100 && second >= 64 && second <= 127 ? "tailscale" : isPrivateIpv4(address) ? "lan" : "vpn";
12
+ choices.set(address, { id: address, kind, address, interfaceName });
13
+ }
14
+ }
15
+ return [...choices.values()];
16
+ }
17
+ export function findLanUrl(port, interfaces = networkInterfaces(), routedAddress) {
3
18
  const addresses = Object.values(interfaces)
4
19
  .flatMap((entries) => entries ?? [])
5
20
  .filter((entry) => entry.family === "IPv4" && !entry.internal)
6
21
  .map((entry) => entry.address);
7
- const address = addresses.find(isPrivateIpv4) ?? addresses[0];
22
+ const address = routedAddress && addresses.includes(routedAddress) && isPrivateIpv4(routedAddress)
23
+ ? routedAddress : addresses.find(isPreferredLanIpv4);
8
24
  return address ? `http://${address}:${port}` : null;
9
25
  }
26
+ /** UDP connect selects the OS route without sending a packet to the destination. */
27
+ export async function findRoutedLanUrl(port) {
28
+ const routedAddress = await new Promise((done) => {
29
+ const socket = createSocket("udp4");
30
+ let settled = false;
31
+ const finish = (address) => {
32
+ if (settled)
33
+ return;
34
+ settled = true;
35
+ clearTimeout(timer);
36
+ try {
37
+ socket.close();
38
+ }
39
+ catch { /* A failed bind may leave no socket to close. */ }
40
+ done(address);
41
+ };
42
+ const timer = setTimeout(() => finish(null), 1_000);
43
+ socket.once("error", () => finish(null));
44
+ socket.connect(53, "1.1.1.1", () => { if (!settled)
45
+ finish(socket.address().address); });
46
+ });
47
+ return findLanUrl(port, networkInterfaces(), routedAddress);
48
+ }
10
49
  function isPrivateIpv4(address) {
50
+ const parts = address.split(".").map(Number);
51
+ return isPreferredLanIpv4(address) || (parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
52
+ && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31);
53
+ }
54
+ function isPreferredLanIpv4(address) {
11
55
  const parts = address.split(".").map(Number);
12
56
  if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255))
13
57
  return false;
14
58
  return parts[0] === 10 ||
15
- (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
16
59
  (parts[0] === 192 && parts[1] === 168);
17
60
  }
@@ -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
+ }