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
@@ -0,0 +1,288 @@
1
+ import { constants } from "node:fs";
2
+ import { access, chmod, mkdir, readFile, rename, stat } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { SERVICE_LABEL, ensurePrivateDirectory, ensurePrivateFile, readServiceConfig, readServiceState, removeIfExists, resolveServicePaths, writePrivateJson, } from "./service-files.js";
5
+ import { buildStartArguments, runCommand, } from "./service-controller.js";
6
+ export { buildStartArguments } from "./service-controller.js";
7
+ export class MacLaunchAgent {
8
+ homeDir;
9
+ uid;
10
+ runner;
11
+ processExists;
12
+ now;
13
+ readyTimeoutMs;
14
+ stopTimeoutMs;
15
+ pollIntervalMs;
16
+ constructor(options = {}) {
17
+ this.homeDir = options.homeDir;
18
+ this.uid = options.uid ?? process.getuid?.() ?? 0;
19
+ this.runner = options.runner ?? runCommand;
20
+ this.processExists = options.processExists ?? isProcessRunning;
21
+ this.now = options.now ?? (() => new Date());
22
+ // Codex preparation (180s), sharing (10s), local server (20s), relay (30s), plus cleanup.
23
+ this.readyTimeoutMs = options.readyTimeoutMs ?? 270_000;
24
+ this.stopTimeoutMs = options.stopTimeoutMs ?? 15_000;
25
+ this.pollIntervalMs = options.pollIntervalMs ?? 250;
26
+ }
27
+ async install(config) {
28
+ await this.validateConfig(config);
29
+ const paths = resolveServicePaths(this.homeDir, config.dataDir);
30
+ const previousState = await readServiceState(paths);
31
+ await Promise.all([
32
+ mkdir(paths.launchAgentsDir, { recursive: true }),
33
+ ensurePrivateDirectory(paths.controlDir),
34
+ ensurePrivateDirectory(paths.logsDir),
35
+ ]);
36
+ await Promise.all([ensurePrivateFile(paths.stdoutPath), ensurePrivateFile(paths.stderrPath)]);
37
+ const jsonPath = resolve(paths.controlDir, "launch-agent.json.tmp");
38
+ const plistTempPath = resolve(paths.controlDir, "launch-agent.plist.tmp");
39
+ await removeIfExists(plistTempPath);
40
+ await writePrivateJson(jsonPath, buildLaunchAgentPlist(config, paths));
41
+ try {
42
+ await this.runRequired("plutil", ["-convert", "xml1", "-o", plistTempPath, jsonPath]);
43
+ await this.runRequired("plutil", ["-lint", plistTempPath]);
44
+ await chmod(plistTempPath, 0o600);
45
+ if ((await this.inspectJob()).loaded) {
46
+ await this.runRequired("launchctl", ["bootout", this.serviceTarget]);
47
+ await this.waitForServiceExit(previousState?.pid);
48
+ }
49
+ await rename(plistTempPath, paths.plistPath);
50
+ await chmod(paths.plistPath, 0o600);
51
+ await writePrivateJson(paths.configPath, config);
52
+ await Promise.all([removeIfExists(paths.statePath), removeIfExists(paths.urlPath)]);
53
+ await this.bootstrap(paths.plistPath);
54
+ }
55
+ finally {
56
+ await Promise.all([removeIfExists(jsonPath), removeIfExists(plistTempPath)]);
57
+ }
58
+ return { paths, state: await this.waitForReady(paths), definition: paths.plistPath };
59
+ }
60
+ async start() {
61
+ const status = await this.status();
62
+ if (!status.installed)
63
+ throw new Error("AgentRoam service is not installed");
64
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
65
+ if (status.running)
66
+ return this.waitForReady(paths);
67
+ if (status.loaded)
68
+ await this.runRequired("launchctl", ["kickstart", this.serviceTarget]);
69
+ else
70
+ await this.bootstrap(status.definition);
71
+ return this.waitForReady(paths, status.state?.pid);
72
+ }
73
+ async stop() {
74
+ const status = await this.status();
75
+ if (!status.installed)
76
+ throw new Error("AgentRoam service is not installed");
77
+ if (!status.loaded)
78
+ return;
79
+ await this.runRequired("launchctl", ["bootout", this.serviceTarget]);
80
+ if (status.state?.pid)
81
+ await this.waitForProcessExit(status.state.pid);
82
+ }
83
+ async status() {
84
+ const basePaths = resolveServicePaths(this.homeDir);
85
+ const config = await readServiceConfig(basePaths);
86
+ const paths = resolveServicePaths(this.homeDir, config?.dataDir);
87
+ const installed = await pathExists(paths.plistPath);
88
+ const job = installed ? await this.inspectJob() : { loaded: false, running: false, pid: undefined };
89
+ const state = await readServiceState(paths);
90
+ return {
91
+ installed,
92
+ loaded: job.loaded,
93
+ running: job.running,
94
+ config,
95
+ state: job.running && state?.pid !== job.pid ? null : state,
96
+ definition: paths.plistPath,
97
+ };
98
+ }
99
+ async url() {
100
+ const status = await this.status();
101
+ if (!status.installed)
102
+ throw new Error("AgentRoam service is not installed");
103
+ if (!status.running)
104
+ throw new Error("AgentRoam service is installed but not running");
105
+ if (status.state?.status !== "ready" || !status.state.accessUrl) {
106
+ throw new Error("AgentRoam service is still starting; try again shortly");
107
+ }
108
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
109
+ const value = (await readFile(paths.urlPath, "utf8")).trim();
110
+ if (!value || value !== status.state.accessUrl)
111
+ throw new Error("AgentRoam service URL is unavailable or stale");
112
+ return value;
113
+ }
114
+ async logs(maxBytes = 64 * 1024) {
115
+ const basePaths = resolveServicePaths(this.homeDir);
116
+ const config = await readServiceConfig(basePaths);
117
+ const paths = resolveServicePaths(this.homeDir, config?.dataDir);
118
+ const [stdout, stderr] = await Promise.all([
119
+ readTail(paths.stdoutPath, maxBytes),
120
+ readTail(paths.stderrPath, maxBytes),
121
+ ]);
122
+ return { stdoutPath: paths.stdoutPath, stderrPath: paths.stderrPath, stdout, stderr };
123
+ }
124
+ async restart() {
125
+ const status = await this.status();
126
+ if (!status.installed)
127
+ throw new Error("AgentRoam service is not installed");
128
+ if (status.loaded)
129
+ await this.runRequired("launchctl", ["kickstart", "-k", this.serviceTarget]);
130
+ else
131
+ await this.bootstrap(status.definition);
132
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
133
+ return this.waitForReady(paths, status.state?.pid);
134
+ }
135
+ async uninstall() {
136
+ const basePaths = resolveServicePaths(this.homeDir);
137
+ const config = await readServiceConfig(basePaths);
138
+ const paths = resolveServicePaths(this.homeDir, config?.dataDir);
139
+ const installed = await pathExists(paths.plistPath);
140
+ const state = await readServiceState(paths);
141
+ if ((await this.inspectJob()).loaded) {
142
+ await this.runRequired("launchctl", ["bootout", this.serviceTarget]);
143
+ if (state?.pid)
144
+ await this.waitForProcessExit(state.pid);
145
+ }
146
+ await Promise.all([
147
+ removeIfExists(paths.plistPath),
148
+ removeIfExists(paths.configPath),
149
+ removeIfExists(paths.statePath),
150
+ removeIfExists(paths.urlPath),
151
+ ]);
152
+ return { removed: installed || Boolean(config), preservedDataDir: paths.dataDir };
153
+ }
154
+ get domainTarget() {
155
+ return `gui/${this.uid}`;
156
+ }
157
+ get serviceTarget() {
158
+ return `${this.domainTarget}/${SERVICE_LABEL}`;
159
+ }
160
+ async inspectJob() {
161
+ const result = await this.runner("launchctl", ["print", this.serviceTarget]);
162
+ const pid = /\bpid\s*=\s*(\d+)\b/.exec(result.stdout);
163
+ return {
164
+ loaded: result.code === 0,
165
+ running: result.code === 0 && /\bstate\s*=\s*running\b/.test(result.stdout),
166
+ pid: pid ? Number(pid[1]) : undefined,
167
+ };
168
+ }
169
+ async bootstrap(definition) {
170
+ await this.runRequired("launchctl", ["enable", this.serviceTarget]);
171
+ await this.runRequired("launchctl", ["bootstrap", this.domainTarget, definition]);
172
+ }
173
+ async runRequired(command, args) {
174
+ const result = await this.runner(command, args);
175
+ if (result.code !== 0) {
176
+ const detail = result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`;
177
+ throw new Error(`${command} ${args[0] ?? ""} failed: ${detail}`);
178
+ }
179
+ return result;
180
+ }
181
+ async validateConfig(config) {
182
+ if (!config.nodePath.startsWith("/") || !config.cliPath.startsWith("/")) {
183
+ throw new Error("AgentRoam service requires absolute Node and CLI paths");
184
+ }
185
+ if (config.cliPath.split("/").includes("_npx")) {
186
+ throw new Error("service install cannot use an npx temporary package; install AgentRoam with npm install -g first");
187
+ }
188
+ await Promise.all([
189
+ access(config.nodePath, constants.X_OK),
190
+ access(config.cliPath, constants.R_OK),
191
+ ...(config.codexPath ? [access(config.codexPath, constants.X_OK)] : []),
192
+ ...config.roots.map(async (root) => {
193
+ if (!(await stat(root)).isDirectory())
194
+ throw new Error(`service root is not a directory: ${root}`);
195
+ }),
196
+ ]);
197
+ }
198
+ async waitForReady(paths, previousPid) {
199
+ const deadline = Date.now() + this.readyTimeoutMs;
200
+ do {
201
+ const state = await readServiceState(paths);
202
+ if (state?.status === "ready" && state.accessUrl && (!previousPid || state.pid !== previousPid)) {
203
+ const job = await this.inspectJob();
204
+ if (job.running && job.pid === state.pid)
205
+ return state;
206
+ }
207
+ if (Date.now() >= deadline)
208
+ return state?.status === "ready" ? null : state;
209
+ await delay(this.pollIntervalMs);
210
+ } while (true);
211
+ }
212
+ async waitForProcessExit(pid) {
213
+ const deadline = Date.now() + this.stopTimeoutMs;
214
+ while (this.processExists(pid)) {
215
+ if (Date.now() >= deadline)
216
+ throw new Error(`service process ${pid} did not stop after launchctl bootout`);
217
+ await delay(this.pollIntervalMs);
218
+ }
219
+ }
220
+ async waitForServiceExit(pid) {
221
+ const deadline = Date.now() + this.stopTimeoutMs;
222
+ do {
223
+ const processRunning = pid ? this.processExists(pid) : false;
224
+ const job = await this.inspectJob();
225
+ if (!processRunning && !job.loaded)
226
+ return;
227
+ if (Date.now() >= deadline) {
228
+ if (processRunning)
229
+ throw new Error(`service process ${pid} did not stop after launchctl bootout`);
230
+ throw new Error(`service ${SERVICE_LABEL} did not unload after launchctl bootout`);
231
+ }
232
+ await delay(this.pollIntervalMs);
233
+ } while (true);
234
+ }
235
+ }
236
+ export function buildLaunchAgentPlist(config, paths) {
237
+ const environmentVariables = {
238
+ AGENTROAM_SERVICE: "1",
239
+ PATH: config.environmentPath || `${dirname(config.nodePath)}:/usr/bin:/bin:/usr/sbin:/sbin`,
240
+ };
241
+ if (config.codexPath)
242
+ environmentVariables.AGENT_CODEX_BIN = config.codexPath;
243
+ if (config.codexHome)
244
+ environmentVariables.CODEX_HOME = config.codexHome;
245
+ return {
246
+ Label: SERVICE_LABEL,
247
+ ProgramArguments: buildStartArguments(config),
248
+ WorkingDirectory: config.roots[0],
249
+ EnvironmentVariables: environmentVariables,
250
+ RunAtLoad: true,
251
+ KeepAlive: true,
252
+ ThrottleInterval: 5,
253
+ StandardOutPath: paths.stdoutPath,
254
+ StandardErrorPath: paths.stderrPath,
255
+ };
256
+ }
257
+ async function pathExists(path) {
258
+ try {
259
+ await access(path);
260
+ return true;
261
+ }
262
+ catch {
263
+ return false;
264
+ }
265
+ }
266
+ function isProcessRunning(pid) {
267
+ try {
268
+ process.kill(pid, 0);
269
+ return true;
270
+ }
271
+ catch (error) {
272
+ return error.code === "EPERM";
273
+ }
274
+ }
275
+ async function readTail(path, maxBytes) {
276
+ try {
277
+ const value = await readFile(path);
278
+ return value.subarray(Math.max(0, value.length - maxBytes)).toString("utf8");
279
+ }
280
+ catch (error) {
281
+ if (error.code === "ENOENT")
282
+ return "";
283
+ throw error;
284
+ }
285
+ }
286
+ function delay(timeoutMs) {
287
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, timeoutMs));
288
+ }
@@ -0,0 +1,43 @@
1
+ import { readServiceState, removeIfExists, writePrivateJson, writePrivateText, } from "./service-files.js";
2
+ export class ServiceRuntimeReporter {
3
+ paths;
4
+ version;
5
+ pid;
6
+ now;
7
+ startedAt;
8
+ constructor(paths, version, pid = process.pid, now = () => new Date()) {
9
+ this.paths = paths;
10
+ this.version = version;
11
+ this.pid = pid;
12
+ this.now = now;
13
+ this.startedAt = this.now().toISOString();
14
+ }
15
+ async starting() {
16
+ await removeIfExists(this.paths.urlPath);
17
+ await this.write({ status: "starting" });
18
+ }
19
+ async localReady(localUrl) {
20
+ await this.write({ status: "starting", localUrl });
21
+ }
22
+ async ready(ready) {
23
+ await this.write({ status: "ready", ...ready });
24
+ await writePrivateText(this.paths.urlPath, `${ready.accessUrl}\n`);
25
+ }
26
+ async stopped() {
27
+ const current = await readServiceState(this.paths);
28
+ if (!current || current.pid !== this.pid)
29
+ return false;
30
+ await this.write({ status: "stopped" });
31
+ await removeIfExists(this.paths.urlPath);
32
+ return true;
33
+ }
34
+ async write(details) {
35
+ await writePrivateJson(this.paths.statePath, {
36
+ pid: this.pid,
37
+ version: this.version,
38
+ startedAt: this.startedAt,
39
+ updatedAt: this.now().toISOString(),
40
+ ...details,
41
+ });
42
+ }
43
+ }
@@ -0,0 +1,226 @@
1
+ import { saveMeshEnvironment } from "../mesh/mesh-config.js";
2
+ import { printLocalDesktopUrl } from '../local-desktop-url.js';
3
+ import { delimiter, dirname, isAbsolute, resolve, win32 } from "node:path";
4
+ import { resolveCodexRuntime } from "../codex-runtime-manager.js";
5
+ import { detectPlatform } from "../platform.js";
6
+ import { printPairingCode } from "../device-pairing.js";
7
+ import { renderQr } from "../qr.js";
8
+ import { MacLaunchAgent } from "./macos-launch-agent.js";
9
+ import { WindowsTaskService } from "./windows-task-service.js";
10
+ import { assertSupportedNodeVersion } from "../../bin/runtime-policy.mjs";
11
+ import { cleanupOldLaunchers } from "./launcher-cleanup.js";
12
+ import { configureCodexSharing } from "../codex-sharing.js";
13
+ import { setupCodexDesktop } from "../codex-desktop-setup.js";
14
+ import { authorizeRemoteDesktop } from "../desktop-authorization.js";
15
+ import { withCliProgress } from "../../bin/cli-progress.mjs";
16
+ import { withTimeout } from "../abort.js";
17
+ export async function runServiceCommand(options, context) {
18
+ const platform = context.platform ?? process.platform;
19
+ const log = context.log ?? console.log;
20
+ const stdoutIsTTY = context.isTTY ?? process.stdout.isTTY === true;
21
+ const logAccessUrl = async (accessUrl) => {
22
+ log(`Open: ${accessUrl}`);
23
+ if (!options.qr || !stdoutIsTTY)
24
+ return;
25
+ log("");
26
+ log(await renderQr(accessUrl));
27
+ };
28
+ const controller = context.controller ?? context.launchAgent ?? createController(platform, context.homeDir);
29
+ switch (options.serviceAction) {
30
+ case "install": {
31
+ const nodeVersion = context.nodeVersion ?? process.versions.node;
32
+ assertSupportedNodeVersion(nodeVersion);
33
+ const now = context.now?.() ?? new Date();
34
+ const environment = context.environment ?? process.env;
35
+ const environmentPath = buildServiceEnvironmentPath(context.nodePath, environment.PATH ?? environment.Path, platform);
36
+ let codexPath;
37
+ try {
38
+ const codex = await withCliProgress("Checking Codex; the background service installs it if missing", () => withTimeout(signal => (context.codexResolver ?? resolveCodexRuntime)({
39
+ dataDir: options.dataDir,
40
+ target: detectPlatform(platform, context.arch ?? process.arch, nodeVersion),
41
+ environment: { ...environment, PATH: environmentPath },
42
+ platform,
43
+ nodeExecutable: context.nodePath,
44
+ installIfMissing: false,
45
+ signal,
46
+ onProgress: (message) => log(`… ${message}`),
47
+ }), 60_000, "Codex check timed out; the background service will continue checking."));
48
+ codexPath = codex.executable;
49
+ }
50
+ catch (error) {
51
+ log(`Codex will be checked and installed during service startup: ${error instanceof Error ? error.message : error}`);
52
+ }
53
+ const relayUrl = options.relayUrl ?? environment.AGENTROAM_HTTPS_RELAY_URL?.trim();
54
+ const config = {
55
+ version: context.version,
56
+ nodePath: context.nodePath,
57
+ cliPath: context.cliPath,
58
+ environmentPath,
59
+ ...(codexPath ? { codexPath } : {}),
60
+ ...(environment.CODEX_HOME?.trim() ? { codexHome: resolve(environment.CODEX_HOME.trim()) } : {}),
61
+ roots: options.roots,
62
+ port: options.port,
63
+ relay: options.relay,
64
+ tunnelCommand: options.tunnelCommand,
65
+ ...(relayUrl ? { relayUrl } : {}),
66
+ localOnly: options.localOnly,
67
+ dataDir: options.dataDir,
68
+ installedAt: now.toISOString(),
69
+ };
70
+ if (platform === "darwin" && codexPath) {
71
+ try {
72
+ await withTimeout(signal => (context.configureSharing ?? configureCodexSharing)(options, {
73
+ homeDir: context.homeDir, environment: { ...environment, PATH: environmentPath, AGENT_CODEX_BIN: codexPath }, signal,
74
+ }), 10_000, "Codex sharing setup timed out (10 seconds)");
75
+ }
76
+ catch (error) {
77
+ log(`Codex sharing setup incomplete; repair it from the computer menu: ${error instanceof Error ? error.message : error}`);
78
+ }
79
+ }
80
+ await saveMeshEnvironment(options.dataDir, environment);
81
+ const { definition, state } = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.install(config));
82
+ log(`✓ AgentRoam service installed: ${definition}`);
83
+ if (state?.status !== "ready" && state?.localUrl)
84
+ printLocalDesktopUrl(state.localUrl, log, platform);
85
+ requireReadyService(state);
86
+ log(`Open: ${state.accessUrl}`);
87
+ if (state.localUrl)
88
+ printLocalDesktopUrl(state.localUrl, log, platform);
89
+ printLanFallback(state, log);
90
+ if (state?.localUrl && state.status !== "stopped" && (platform === "darwin" || platform === "win32")) {
91
+ if (environment.AGENTROAM_INSTALL_REMOTE_DESKTOP === "skip") {
92
+ log("Remote desktop authorization skipped. Run agentroam desktop authorize later.");
93
+ }
94
+ else {
95
+ try {
96
+ await (context.desktopAuthorization ?? authorizeRemoteDesktop)(options.dataDir, { platform, isTTY: stdoutIsTTY, timeoutMs: 60_000, log });
97
+ }
98
+ catch (error) {
99
+ log(`Remote desktop authorization incomplete: ${error instanceof Error ? error.message : error}`);
100
+ log("Installation continues. Retry with agentroam desktop authorize or the local browser authorization panel.");
101
+ }
102
+ }
103
+ }
104
+ if (platform === "darwin" && !options.desktopSetup)
105
+ log("Codex Desktop sharing: agentroam codex-desktop --setup; preview: agentroam codex-desktop --dry-run.");
106
+ if (state.version === config.version)
107
+ await cleanupOldLaunchers(config, log);
108
+ if (options.desktopSetup && ["darwin", "win32"].includes(platform)) {
109
+ await withCliProgress("Configuring Codex Desktop sharing", () => (context.desktopSetup ?? setupCodexDesktop)(options, { platform, environment, service: config, log }));
110
+ }
111
+ await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, {
112
+ fallbackUrl: state.accessUrl, waitForMesh: Boolean(environment.AGENTROAM_MESH_ACTIVATION_CODE?.trim()),
113
+ qr: options.qr, interactive: stdoutIsTTY,
114
+ });
115
+ return;
116
+ }
117
+ case "start": {
118
+ const state = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.start());
119
+ if (state?.status !== "ready" && state?.localUrl)
120
+ printLocalDesktopUrl(state.localUrl, log, platform);
121
+ requireReadyService(state);
122
+ log(`Open: ${state.accessUrl}`);
123
+ if (state.localUrl)
124
+ printLocalDesktopUrl(state.localUrl, log, platform);
125
+ printLanFallback(state, log);
126
+ log("✓ AgentRoam service started");
127
+ if (options.qr && stdoutIsTTY)
128
+ log(await renderQr(state.accessUrl));
129
+ return;
130
+ }
131
+ case "stop":
132
+ await withCliProgress("Stopping background service", () => controller.stop());
133
+ log("✓ AgentRoam service stopped");
134
+ return;
135
+ case "status": {
136
+ const status = await controller.status();
137
+ if (!status.installed) {
138
+ log("AgentRoam service: not installed");
139
+ return;
140
+ }
141
+ log(`AgentRoam service: ${status.running ? "running" : "installed but stopped"}`);
142
+ if (status.config) {
143
+ log(`Version: ${status.config.version}`);
144
+ log(`Root: ${status.config.roots.join(", ")}`);
145
+ }
146
+ if (status.running && status.state?.status !== "ready" && status.state?.localUrl)
147
+ printLocalDesktopUrl(status.state.localUrl, log, platform);
148
+ if (status.running && status.state?.status === "ready" && status.state.accessUrl) {
149
+ printLanFallback(status.state, log);
150
+ await logAccessUrl(status.state.accessUrl);
151
+ if (status.state.localUrl)
152
+ printLocalDesktopUrl(status.state.localUrl, log, platform);
153
+ }
154
+ return;
155
+ }
156
+ case "url":
157
+ log(await controller.url());
158
+ return;
159
+ case "logs": {
160
+ const logs = await controller.logs();
161
+ log(`stdout: ${logs.stdoutPath}`);
162
+ if (logs.stdout)
163
+ log(logs.stdout.trimEnd());
164
+ log(`stderr: ${logs.stderrPath}`);
165
+ if (logs.stderr)
166
+ log(logs.stderr.trimEnd());
167
+ return;
168
+ }
169
+ case "restart": {
170
+ const state = await withCliProgress("Restarting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.restart());
171
+ if (state?.status !== "ready" && state?.localUrl)
172
+ printLocalDesktopUrl(state.localUrl, log, platform);
173
+ requireReadyService(state);
174
+ log(`Open: ${state.accessUrl}`);
175
+ if (state.localUrl)
176
+ printLocalDesktopUrl(state.localUrl, log, platform);
177
+ printLanFallback(state, log);
178
+ log("✓ AgentRoam service restarted");
179
+ if (options.qr && stdoutIsTTY)
180
+ log(await renderQr(state.accessUrl));
181
+ return;
182
+ }
183
+ case "uninstall": {
184
+ const result = await controller.uninstall();
185
+ log(result.removed ? "✓ AgentRoam service uninstalled" : "AgentRoam service was not installed");
186
+ log(`Application data preserved: ${result.preservedDataDir}`);
187
+ return;
188
+ }
189
+ default:
190
+ throw cliError("service action is required");
191
+ }
192
+ }
193
+ function printLanFallback(state, log) {
194
+ if (state.provider !== "lan")
195
+ return;
196
+ if (state.accessUrl && ["127.0.0.1", "localhost", "[::1]"].includes(new URL(state.accessUrl).hostname)) {
197
+ log("✓ Local access only. Connect to Wi-Fi or Ethernet and restart to enable phone access.");
198
+ return;
199
+ }
200
+ log("✓ Service ready on LAN. Connect your phone to the same network to pair.");
201
+ }
202
+ function requireReadyService(state) {
203
+ if (state?.status !== "ready" || !state.accessUrl) {
204
+ throw Object.assign(new Error(`AgentRoam service is not ready (${state?.status ?? "no state"}). Run agentroam service logs, fix the error, then run agentroam service start and agentroam pair.`), { exitCode: 1 });
205
+ }
206
+ }
207
+ export function buildServiceEnvironmentPath(nodePath, pathValue, platform) {
208
+ const separator = platform === "win32" ? ";" : delimiter;
209
+ const nodeDirectory = platform === "win32" ? win32.dirname(nodePath) : dirname(nodePath);
210
+ const absolute = platform === "win32" ? win32.isAbsolute : isAbsolute;
211
+ const required = platform === "darwin" ? ["/usr/bin", "/bin", "/usr/sbin", "/sbin"] : [];
212
+ const entries = [nodeDirectory, ...(pathValue ?? "").split(separator), ...required]
213
+ .map((entry) => entry.trim())
214
+ .filter((entry) => entry && absolute(entry));
215
+ return [...new Set(entries)].join(separator);
216
+ }
217
+ function createController(platform, homeDir) {
218
+ if (platform === "darwin")
219
+ return new MacLaunchAgent({ homeDir });
220
+ if (platform === "win32")
221
+ return new WindowsTaskService({ homeDir });
222
+ throw cliError(`agentroam service is unavailable on ${platform}; supported platforms are macOS and Windows`);
223
+ }
224
+ function cliError(message) {
225
+ return Object.assign(new Error(message), { exitCode: 2 });
226
+ }
@@ -0,0 +1,29 @@
1
+ import { spawn } from "node:child_process";
2
+ export function buildStartArguments(config) {
3
+ const args = [config.nodePath, config.cliPath, "start"];
4
+ for (const root of config.roots)
5
+ args.push("--root", root);
6
+ if (config.port !== null)
7
+ args.push("--port", String(config.port));
8
+ if (config.localOnly)
9
+ args.push("--local-only");
10
+ else
11
+ args.push("--relay", config.relay);
12
+ if (config.relayUrl)
13
+ args.push("--relay-url", config.relayUrl);
14
+ if (!config.localOnly && config.tunnelCommand)
15
+ args.push("--tunnel-command", config.tunnelCommand);
16
+ args.push("--data-dir", config.dataDir, "--no-qr");
17
+ return args;
18
+ }
19
+ export function runCommand(command, args) {
20
+ return new Promise((resolveResult, reject) => {
21
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
22
+ let stdout = "";
23
+ let stderr = "";
24
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
25
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
26
+ child.once("error", reject);
27
+ child.once("exit", (code) => resolveResult({ code: code ?? 1, stdout, stderr }));
28
+ });
29
+ }
@@ -0,0 +1,78 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { homedir } from "node:os";
3
+ import { dirname, resolve } from "node:path";
4
+ import { chmod, mkdir, open, readFile, rename, rm } from "node:fs/promises";
5
+ export const SERVICE_LABEL = "com.agentroam.service";
6
+ export const WINDOWS_SERVICE_NAME = "AgentRoam";
7
+ export function resolveServicePaths(homeDir = homedir(), dataDir = resolve(homeDir, ".agentroam")) {
8
+ const normalizedHome = resolve(homeDir);
9
+ const normalizedData = resolve(dataDir);
10
+ const launchAgentsDir = resolve(normalizedHome, "Library", "LaunchAgents");
11
+ const controlDir = resolve(normalizedHome, ".agentroam", "service");
12
+ const logsDir = resolve(normalizedData, "logs");
13
+ return {
14
+ homeDir: normalizedHome,
15
+ dataDir: normalizedData,
16
+ launchAgentsDir,
17
+ plistPath: resolve(launchAgentsDir, `${SERVICE_LABEL}.plist`),
18
+ controlDir,
19
+ configPath: resolve(controlDir, "config.json"),
20
+ statePath: resolve(controlDir, "state.json"),
21
+ urlPath: resolve(normalizedData, "tunnel.url"),
22
+ logsDir,
23
+ stdoutPath: resolve(logsDir, "service.stdout.log"),
24
+ stderrPath: resolve(logsDir, "service.stderr.log"),
25
+ };
26
+ }
27
+ export async function ensurePrivateDirectory(path) {
28
+ await mkdir(path, { recursive: true, mode: 0o700 });
29
+ await chmod(path, 0o700);
30
+ }
31
+ export async function ensurePrivateFile(path) {
32
+ await ensurePrivateDirectory(dirname(path));
33
+ const handle = await open(path, "a", 0o600);
34
+ await handle.close();
35
+ await chmod(path, 0o600);
36
+ }
37
+ export async function writePrivateJson(path, value) {
38
+ await writePrivateText(path, `${JSON.stringify(value, null, 2)}\n`);
39
+ }
40
+ export async function writePrivateText(path, value) {
41
+ await ensurePrivateDirectory(dirname(path));
42
+ const temporary = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
43
+ const handle = await open(temporary, "wx", 0o600);
44
+ try {
45
+ await handle.writeFile(value, "utf8");
46
+ await handle.sync();
47
+ }
48
+ finally {
49
+ await handle.close();
50
+ }
51
+ try {
52
+ await rename(temporary, path);
53
+ await chmod(path, 0o600);
54
+ }
55
+ catch (error) {
56
+ await rm(temporary, { force: true });
57
+ throw error;
58
+ }
59
+ }
60
+ export async function readServiceConfig(paths) {
61
+ return readJson(paths.configPath);
62
+ }
63
+ export async function readServiceState(paths) {
64
+ return readJson(paths.statePath);
65
+ }
66
+ export async function removeIfExists(path) {
67
+ await rm(path, { force: true });
68
+ }
69
+ async function readJson(path) {
70
+ try {
71
+ return JSON.parse(await readFile(path, "utf8"));
72
+ }
73
+ catch (error) {
74
+ if (error.code === "ENOENT")
75
+ return null;
76
+ throw error;
77
+ }
78
+ }