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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +136 -5
  12. package/dist/cli.js +295 -44
  13. package/dist/cloudflared/bundled-asset.js +3 -2
  14. package/dist/cloudflared/manifest.js +2 -2
  15. package/dist/codex-desktop-command.js +70 -0
  16. package/dist/codex-desktop-force-stop.js +46 -0
  17. package/dist/codex-desktop-idle-guard.js +15 -0
  18. package/dist/codex-desktop-preflight.js +63 -0
  19. package/dist/codex-desktop-probe.js +152 -0
  20. package/dist/codex-desktop-setup.js +154 -0
  21. package/dist/codex-desktop-status.js +85 -0
  22. package/dist/codex-desktop-windows.js +122 -0
  23. package/dist/codex-runtime-manager.js +368 -0
  24. package/dist/codex-sharing.js +155 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +228 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/mesh/mesh-command.js +51 -0
  35. package/dist/mesh/mesh-config.js +95 -0
  36. package/dist/mesh/mesh-payload.js +20 -0
  37. package/dist/mesh/mesh-runtime.js +101 -0
  38. package/dist/native-runtime.js +68 -0
  39. package/dist/network.js +46 -3
  40. package/dist/node-runtime-manager.js +251 -0
  41. package/dist/opencode-runtime-manager.js +260 -0
  42. package/dist/platform-packages.js +18 -5
  43. package/dist/platform.js +6 -4
  44. package/dist/power/sleep-inhibitor.js +161 -0
  45. package/dist/runtime-manager.js +139 -19
  46. package/dist/self-hosted-relay.json +1 -0
  47. package/dist/service/launcher-cleanup.js +79 -0
  48. package/dist/service/macos-launch-agent.js +288 -0
  49. package/dist/service/runtime-state.js +43 -0
  50. package/dist/service/service-command.js +226 -0
  51. package/dist/service/service-controller.js +29 -0
  52. package/dist/service/service-files.js +78 -0
  53. package/dist/service/windows-service-host.js +59 -0
  54. package/dist/service/windows-task-service.js +289 -0
  55. package/dist/startup-lock.js +81 -0
  56. package/dist/tailscale/bundled-asset.js +43 -0
  57. package/dist/tailscale/daemon-manager.js +112 -0
  58. package/dist/tailscale/installer.js +131 -0
  59. package/dist/tailscale/manifest.js +15 -0
  60. package/dist/tailscale/tailnet-cli.js +101 -0
  61. package/dist/todo-mcp-command.js +27 -0
  62. package/dist/tunnel/cloudflare-provider.js +4 -1
  63. package/dist/tunnel/public-readiness.js +76 -50
  64. package/dist/tunnel/relay-orchestrator.js +53 -19
  65. package/dist/tunnel/self-hosted-provider.js +147 -0
  66. package/dist/tunnel/tunnel-controller.js +232 -0
  67. package/dist/unlock-service.js +105 -0
  68. package/dist/update/update-channel.js +38 -0
  69. package/dist/update/update-command.js +97 -0
  70. package/dist/update/update-install.js +34 -0
  71. package/dist/update/update-state.js +43 -0
  72. package/dist/update/update-worker.js +82 -0
  73. package/install/README.md +55 -0
  74. package/install/codex-shared-watchdog.sh +16 -0
  75. package/install/install-agentroam.ps1 +358 -0
  76. package/install/install-agentroam.sh +457 -0
  77. package/install/install-manifest.json +15 -0
  78. package/install/start-codex-desktop-shared.sh +152 -0
  79. package/install/write-relay-default.mjs +6 -0
  80. package/package.json +15 -10
  81. package/dist/args.test.js +0 -27
  82. package/dist/cloudflared/bundled-asset.test.js +0 -76
  83. package/dist/cloudflared/installer.test.js +0 -95
  84. package/dist/native-runtime.test.js +0 -19
  85. package/dist/network.test.js +0 -20
  86. package/dist/pairing.js +0 -2
  87. package/dist/platform-packages.test.js +0 -75
  88. package/dist/platform.test.js +0 -3
  89. package/dist/port.test.js +0 -3
  90. package/dist/process-supervisor.test.js +0 -42
  91. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  92. package/dist/tunnel/pinggy-provider.test.js +0 -40
  93. package/dist/tunnel/proxy-settings.test.js +0 -111
  94. package/dist/tunnel/public-readiness.test.js +0 -104
  95. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -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
+ }
@@ -0,0 +1,260 @@
1
+ import { execFile } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { access, chmod, mkdir, mkdtemp, open, rename, rm, stat } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { delimiter, isAbsolute, relative, resolve, win32 } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { resolveNpmExecutor } from "./codex-runtime-manager.js";
8
+ import { withAbortSignal } from "./abort.js";
9
+ const execFileAsync = promisify(execFile);
10
+ // Default managed installation; compatibility has an independent minimum.
11
+ export const OPENCODE_RUNTIME_VERSION = "1.18.27";
12
+ export const OPENCODE_MINIMUM_VERSION = "1.18.27";
13
+ const OPENCODE_PACKAGE = `opencode-ai@${OPENCODE_RUNTIME_VERSION}`;
14
+ const NPM_REGISTRY = "https://registry.npmjs.org";
15
+ const defaults = {
16
+ accessible,
17
+ async run(command, args, timeoutMs, signal) {
18
+ try {
19
+ const { stdout, stderr } = await execFileAsync(command, args, {
20
+ encoding: "utf8",
21
+ timeout: timeoutMs,
22
+ signal,
23
+ killSignal: "SIGKILL",
24
+ maxBuffer: 4 * 1024 * 1024,
25
+ windowsHide: true,
26
+ });
27
+ return { stdout, stderr };
28
+ }
29
+ catch (error) {
30
+ const value = error;
31
+ throw new Error([value.message, value.stderr, value.stdout].filter(Boolean).join(": "), { cause: error });
32
+ }
33
+ },
34
+ sleep: (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms)),
35
+ now: () => Date.now(),
36
+ };
37
+ export async function resolveOpenCodeRuntime(options) {
38
+ return options.signal
39
+ ? withAbortSignal(() => resolveRuntime(options), options.signal)
40
+ : resolveRuntime(options);
41
+ }
42
+ async function resolveRuntime(options) {
43
+ const environment = options.environment ?? process.env;
44
+ const platform = options.platform ?? process.platform;
45
+ const dependencies = { ...defaults, ...options.dependencies };
46
+ const signal = options.signal;
47
+ if (signal) {
48
+ const run = dependencies.run;
49
+ const sleep = dependencies.sleep;
50
+ dependencies.run = (command, args, timeoutMs) => withAbortSignal(() => run(command, args, timeoutMs, signal), signal);
51
+ dependencies.sleep = (delayMs) => withAbortSignal(() => sleep(delayMs), signal);
52
+ }
53
+ const explicit = environment.AGENT_OPENCODE_BIN?.trim();
54
+ if (explicit) {
55
+ const absolute = platform === "win32" ? win32.isAbsolute(explicit) : isAbsolute(explicit);
56
+ if (!absolute)
57
+ throw new Error("AGENT_OPENCODE_BIN must be an absolute path");
58
+ if (platform === "win32" && /^opencode\.(?:cmd|bat)$/i.test(win32.basename(explicit))) {
59
+ const bundled = await firstCompatible(windowsOpenCodeNpmCandidates(windowsNpmModules(win32.dirname(explicit)), win32.resolve), "explicit", dependencies);
60
+ if (bundled)
61
+ return bundled;
62
+ throw new Error("AGENT_OPENCODE_BIN points to a Windows launcher without a compatible OpenCode executable");
63
+ }
64
+ return validate(explicit, "explicit", dependencies);
65
+ }
66
+ const global = await findGlobal(environment, platform, dependencies);
67
+ if (global)
68
+ return global;
69
+ const managedRoot = resolve(options.dataDir, "runtimes", "opencode", OPENCODE_RUNTIME_VERSION);
70
+ const managed = await validateManaged(managedRoot, platform, dependencies);
71
+ if (managed)
72
+ return managed;
73
+ signal?.throwIfAborted();
74
+ if (options.installIfMissing === false)
75
+ throw new Error("OpenCode is not installed; optional OpenCode sessions are unavailable.");
76
+ options.onProgress?.(`Installing managed OpenCode ${OPENCODE_RUNTIME_VERSION}...`);
77
+ return install({ ...options, environment, platform, dependencies, managedRoot });
78
+ }
79
+ export function parseOpenCodeVersion(output) {
80
+ return output.match(/(?:^|\s)v?((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:\s|$)/)?.[1] ?? null;
81
+ }
82
+ export function managedOpenCodeBinaryCandidates(root, platform) {
83
+ return platform === "win32"
84
+ ? [
85
+ ...windowsOpenCodeNpmCandidates(resolve(root, "node_modules"), resolve),
86
+ resolve(root, "node_modules", ".bin", "opencode.exe"),
87
+ ]
88
+ : [
89
+ resolve(root, "node_modules", "opencode-ai", "bin", "opencode.exe"),
90
+ resolve(root, "node_modules", ".bin", "opencode"),
91
+ ];
92
+ }
93
+ function windowsNpmModules(prefix) {
94
+ return win32.resolve(prefix, win32.basename(prefix).toLowerCase() === ".bin" ? ".." : "node_modules");
95
+ }
96
+ function windowsOpenCodeNpmCandidates(modules, resolvePath) {
97
+ return ["opencode-ai", "opencode-windows-x64-baseline", "opencode-windows-x64"]
98
+ .map(name => resolvePath(modules, name, "bin", "opencode.exe"));
99
+ }
100
+ async function findGlobal(environment, platform, dependencies) {
101
+ const windows = platform === "win32";
102
+ const directories = (environment.PATH ?? environment.Path ?? "").split(windows ? ";" : delimiter).filter(Boolean);
103
+ if (!windows) {
104
+ return firstCompatible(directories.map(dir => resolve(dir, "opencode")), "global", dependencies, true);
105
+ }
106
+ const pathDirs = directories.map(dir => dir.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean);
107
+ const roaming = environment.APPDATA || win32.join(homedir(), "AppData", "Roaming");
108
+ const prefixes = [environment.npm_config_prefix || environment.NPM_CONFIG_PREFIX, win32.join(roaming, "npm")];
109
+ return firstCompatible([
110
+ ...pathDirs.flatMap(dir => [win32.resolve(dir, "opencode.exe"), ...windowsOpenCodeNpmCandidates(windowsNpmModules(dir), win32.resolve)]),
111
+ ...prefixes.filter((dir) => Boolean(dir)).flatMap(dir => windowsOpenCodeNpmCandidates(windowsNpmModules(dir), win32.resolve)),
112
+ ], "global", dependencies);
113
+ }
114
+ async function firstCompatible(candidates, source, dependencies, executable = false) {
115
+ for (const candidate of new Set(candidates)) {
116
+ if (!await dependencies.accessible(candidate, executable))
117
+ continue;
118
+ try {
119
+ return await validate(candidate, source, dependencies);
120
+ }
121
+ catch { /* Keep looking for a compatible install. */ }
122
+ }
123
+ return null;
124
+ }
125
+ async function install(options) {
126
+ const parent = resolve(options.dataDir, "runtimes", "opencode");
127
+ const lockPath = `${options.managedRoot}.lock`;
128
+ await mkdir(parent, { recursive: true });
129
+ const lock = await acquireLock(lockPath, options.managedRoot, options.platform, options.dependencies, options.lockWaitMs ?? 190_000, options.staleLockMs ?? 300_000);
130
+ if (lock.completed)
131
+ return lock.completed;
132
+ let temporary = null;
133
+ try {
134
+ const existing = await validateManaged(options.managedRoot, options.platform, options.dependencies);
135
+ if (existing)
136
+ return existing;
137
+ temporary = await mkdtemp(resolve(parent, `.${OPENCODE_RUNTIME_VERSION}-${process.pid}-`));
138
+ const npm = await resolveNpmExecutor({
139
+ environment: options.environment,
140
+ platform: options.platform,
141
+ nodeExecutable: options.nodeExecutable,
142
+ });
143
+ await options.dependencies.run(npm.command, [
144
+ ...npm.argsPrefix,
145
+ "install",
146
+ "--no-audit",
147
+ "--no-fund",
148
+ `--registry=${NPM_REGISTRY}`,
149
+ "--prefix",
150
+ temporary,
151
+ OPENCODE_PACKAGE,
152
+ ], 180_000);
153
+ const validated = await validateManaged(temporary, options.platform, options.dependencies);
154
+ if (!validated)
155
+ throw new Error(`validation failed after installing ${OPENCODE_PACKAGE}`);
156
+ options.signal?.throwIfAborted();
157
+ await rename(temporary, options.managedRoot);
158
+ temporary = null;
159
+ const activated = await validateManaged(options.managedRoot, options.platform, options.dependencies);
160
+ if (!activated)
161
+ throw new Error("validation failed after activation");
162
+ return activated;
163
+ }
164
+ catch (error) {
165
+ options.signal?.throwIfAborted();
166
+ const concurrent = await validateManaged(options.managedRoot, options.platform, options.dependencies);
167
+ if (concurrent)
168
+ return concurrent;
169
+ throw new Error(`Unable to install managed OpenCode ${OPENCODE_RUNTIME_VERSION}: ${describe(error)}`, { cause: error });
170
+ }
171
+ finally {
172
+ if (temporary)
173
+ await rm(temporary, { recursive: true, force: true });
174
+ await lock.handle.close().catch(() => undefined);
175
+ await rm(lockPath, { force: true });
176
+ }
177
+ }
178
+ async function acquireLock(lockPath, managedRoot, platform, dependencies, waitMs, staleMs) {
179
+ const deadline = dependencies.now() + waitMs;
180
+ while (true) {
181
+ try {
182
+ const handle = await open(lockPath, "wx", 0o600);
183
+ await handle.writeFile(`${process.pid}\n${dependencies.now()}\n`);
184
+ return { handle };
185
+ }
186
+ catch (error) {
187
+ if (error.code !== "EEXIST")
188
+ throw error;
189
+ const completed = await validateManaged(managedRoot, platform, dependencies);
190
+ if (completed)
191
+ return { completed };
192
+ try {
193
+ if (dependencies.now() - (await stat(lockPath)).mtimeMs > staleMs) {
194
+ await rm(lockPath, { force: true });
195
+ continue;
196
+ }
197
+ }
198
+ catch {
199
+ continue;
200
+ }
201
+ if (dependencies.now() >= deadline)
202
+ throw new Error(`Timed out waiting for OpenCode runtime install lock: ${lockPath}`);
203
+ await dependencies.sleep(Math.min(250, Math.max(1, deadline - dependencies.now())));
204
+ }
205
+ }
206
+ }
207
+ async function validateManaged(root, platform, dependencies) {
208
+ for (const executable of managedOpenCodeBinaryCandidates(root, platform)) {
209
+ if (!within(root, executable) || !(await dependencies.accessible(executable)))
210
+ continue;
211
+ try {
212
+ if (platform !== "win32")
213
+ await chmod(executable, 0o755);
214
+ return await validate(executable, "managed", dependencies);
215
+ }
216
+ catch {
217
+ // An unusable launcher may coexist with a working platform binary.
218
+ }
219
+ }
220
+ return null;
221
+ }
222
+ async function validate(executable, source, dependencies) {
223
+ if (!(await dependencies.accessible(executable)))
224
+ throw new Error(`OpenCode executable not found: ${executable}`);
225
+ const result = await dependencies.run(executable, ["--version"], 5_000);
226
+ const version = parseOpenCodeVersion(`${result.stdout}\n${result.stderr}`);
227
+ if (!version)
228
+ throw new Error(`Unable to parse OpenCode version from ${executable}`);
229
+ if (!meetsOpenCodeMinimum(version)) {
230
+ throw new Error(`OpenCode ${version} at ${executable} is incompatible; AgentRoam requires >=${OPENCODE_MINIMUM_VERSION}`);
231
+ }
232
+ await dependencies.run(executable, ["serve", "--help"], 5_000);
233
+ return { executable, version, source };
234
+ }
235
+ // Compare numeric components, so 1.18.100 and 1.19.0 both exceed 1.18.27.
236
+ function meetsOpenCodeMinimum(version) {
237
+ const actual = version.split(".").map(BigInt);
238
+ const minimum = OPENCODE_MINIMUM_VERSION.split(".").map(BigInt);
239
+ for (let index = 0; index < minimum.length; index += 1) {
240
+ if (actual[index] !== minimum[index])
241
+ return actual[index] > minimum[index];
242
+ }
243
+ return true;
244
+ }
245
+ async function accessible(path, executable = false) {
246
+ try {
247
+ await access(path, executable ? constants.X_OK : constants.F_OK);
248
+ return true;
249
+ }
250
+ catch {
251
+ return false;
252
+ }
253
+ }
254
+ function within(root, path) {
255
+ const value = relative(resolve(root), resolve(path));
256
+ return value !== "" && !value.startsWith("..") && !isAbsolute(value);
257
+ }
258
+ function describe(error) {
259
+ return error instanceof Error ? error.message : String(error);
260
+ }