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,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
+ }
@@ -0,0 +1,59 @@
1
+ import { spawn } from "node:child_process";
2
+ import { open, readFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { buildStartArguments } from "./service-controller.js";
6
+ import { ensurePrivateFile, resolveServicePaths } from "./service-files.js";
7
+ export async function runWindowsServiceHost(configPath, dependencies = {}) {
8
+ const config = JSON.parse(await readFile(configPath, "utf8"));
9
+ const paths = resolveServicePaths(undefined, config.dataDir);
10
+ await Promise.all([ensurePrivateFile(paths.stdoutPath), ensurePrivateFile(paths.stderrPath)]);
11
+ const [stdoutHandle, stderrHandle] = await Promise.all([open(paths.stdoutPath, "a"), open(paths.stderrPath, "a")]);
12
+ const [command, ...args] = buildStartArguments(config);
13
+ let child = null;
14
+ const requestStop = () => child?.kill("SIGTERM");
15
+ try {
16
+ child = (dependencies.spawnProcess ?? spawn)(command, args, {
17
+ cwd: config.roots[0],
18
+ env: {
19
+ ...process.env,
20
+ ...(config.environmentPath ? { PATH: config.environmentPath } : {}),
21
+ ...(config.codexPath ? { AGENT_CODEX_BIN: config.codexPath } : {}),
22
+ ...(config.codexHome ? { CODEX_HOME: config.codexHome } : {}),
23
+ AGENTROAM_SERVICE: "1",
24
+ },
25
+ stdio: ["ignore", stdoutHandle.fd, stderrHandle.fd],
26
+ windowsHide: true,
27
+ });
28
+ process.once("SIGINT", requestStop);
29
+ process.once("SIGTERM", requestStop);
30
+ return await waitForExit(child);
31
+ }
32
+ finally {
33
+ process.removeListener("SIGINT", requestStop);
34
+ process.removeListener("SIGTERM", requestStop);
35
+ await Promise.all([stdoutHandle.close(), stderrHandle.close()]);
36
+ }
37
+ }
38
+ function waitForExit(child) {
39
+ return new Promise((resolveExit, rejectExit) => {
40
+ child.once("error", rejectExit);
41
+ child.once("exit", (code, signal) => resolveExit(code ?? (signal ? 1 : 0)));
42
+ });
43
+ }
44
+ const currentFile = fileURLToPath(import.meta.url);
45
+ if (process.argv[1] && resolve(process.argv[1]) === resolve(currentFile)) {
46
+ const configPath = process.argv[2];
47
+ if (!configPath) {
48
+ console.error("AgentRoam Windows service host requires a config path");
49
+ process.exitCode = 2;
50
+ }
51
+ else {
52
+ runWindowsServiceHost(configPath)
53
+ .then((code) => { process.exitCode = code; })
54
+ .catch((error) => {
55
+ console.error(error instanceof Error ? error.message : error);
56
+ process.exitCode = 1;
57
+ });
58
+ }
59
+ }
@@ -0,0 +1,289 @@
1
+ import { constants } from "node:fs";
2
+ import { access, readFile, stat } from "node:fs/promises";
3
+ import { win32 } from "node:path";
4
+ import { WINDOWS_SERVICE_NAME, ensurePrivateDirectory, ensurePrivateFile, readServiceConfig, readServiceState, removeIfExists, resolveServicePaths, writePrivateJson, } from "./service-files.js";
5
+ import { runCommand, } from "./service-controller.js";
6
+ export class WindowsTaskService {
7
+ homeDir;
8
+ runner;
9
+ processExists;
10
+ now;
11
+ readyTimeoutMs;
12
+ stopTimeoutMs;
13
+ pollIntervalMs;
14
+ validate;
15
+ constructor(options = {}) {
16
+ this.homeDir = options.homeDir;
17
+ this.runner = options.runner ?? runCommand;
18
+ this.processExists = options.processExists ?? isProcessRunning;
19
+ this.now = options.now ?? (() => new Date());
20
+ // Leave room for bounded component preparation, local readiness and relay fallback.
21
+ this.readyTimeoutMs = options.readyTimeoutMs ?? 270_000;
22
+ this.stopTimeoutMs = options.stopTimeoutMs ?? 15_000;
23
+ this.pollIntervalMs = options.pollIntervalMs ?? 250;
24
+ this.validate = options.validateConfig ?? validateWindowsConfig;
25
+ }
26
+ async install(config) {
27
+ const hostPath = resolveWindowsServiceHost(config.cliPath);
28
+ await this.validate(config, hostPath);
29
+ const paths = resolveServicePaths(this.homeDir, config.dataDir);
30
+ const previousTask = await this.inspectTask();
31
+ const previousState = await readServiceState(paths);
32
+ await Promise.all([
33
+ ensurePrivateDirectory(paths.controlDir),
34
+ ensurePrivateDirectory(paths.logsDir),
35
+ ensurePrivateFile(paths.stdoutPath),
36
+ ensurePrivateFile(paths.stderrPath),
37
+ ]);
38
+ if (previousTask.running) {
39
+ await this.runRequired(buildStopTaskScript());
40
+ if (previousState?.pid)
41
+ await this.waitForProcessExit(previousState.pid);
42
+ }
43
+ if (previousTask.installed)
44
+ await this.runRequired(buildUnregisterTaskScript());
45
+ await writePrivateJson(paths.configPath, config);
46
+ await Promise.all([removeIfExists(paths.statePath), removeIfExists(paths.urlPath)]);
47
+ await this.runRequired(buildRegisterTaskScript(config, hostPath, paths.configPath));
48
+ await this.runRequired(buildStartTaskScript());
49
+ return {
50
+ paths,
51
+ state: await this.waitForReady(paths),
52
+ definition: WINDOWS_SERVICE_NAME,
53
+ };
54
+ }
55
+ async start() {
56
+ const status = await this.status();
57
+ if (!status.installed)
58
+ throw new Error("AgentRoam service is not installed");
59
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
60
+ if (status.running)
61
+ return this.waitForReady(paths);
62
+ await Promise.all([removeIfExists(paths.statePath), removeIfExists(paths.urlPath)]);
63
+ await this.runRequired(buildStartTaskScript());
64
+ return this.waitForReady(paths, status.state?.pid);
65
+ }
66
+ async stop() {
67
+ const status = await this.status();
68
+ if (!status.installed)
69
+ throw new Error("AgentRoam service is not installed");
70
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
71
+ if (status.running) {
72
+ await this.runRequired(buildStopTaskScript());
73
+ if (status.state?.pid)
74
+ await this.waitForProcessExit(status.state.pid);
75
+ }
76
+ await removeIfExists(paths.urlPath);
77
+ if (status.state) {
78
+ await writePrivateJson(paths.statePath, {
79
+ status: "stopped",
80
+ pid: status.state.pid,
81
+ version: status.state.version,
82
+ startedAt: status.state.startedAt,
83
+ updatedAt: this.now().toISOString(),
84
+ });
85
+ }
86
+ }
87
+ async status() {
88
+ const basePaths = resolveServicePaths(this.homeDir);
89
+ const config = await readServiceConfig(basePaths);
90
+ const paths = resolveServicePaths(this.homeDir, config?.dataDir);
91
+ const task = await this.inspectTask();
92
+ const state = await readServiceState(paths);
93
+ return {
94
+ installed: task.installed,
95
+ loaded: task.installed,
96
+ running: task.running,
97
+ config,
98
+ state: task.running && state && !this.processExists(state.pid) ? null : state,
99
+ definition: WINDOWS_SERVICE_NAME,
100
+ };
101
+ }
102
+ async url() {
103
+ const status = await this.status();
104
+ if (!status.installed)
105
+ throw new Error("AgentRoam service is not installed");
106
+ if (!status.running)
107
+ throw new Error("AgentRoam service is installed but not running");
108
+ if (status.state?.status !== "ready" || !status.state.accessUrl) {
109
+ throw new Error("AgentRoam service is still starting; try again shortly");
110
+ }
111
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
112
+ const value = (await readFile(paths.urlPath, "utf8")).trim();
113
+ if (!value || value !== status.state.accessUrl)
114
+ throw new Error("AgentRoam service URL is unavailable or stale");
115
+ return value;
116
+ }
117
+ async logs(maxBytes = 64 * 1024) {
118
+ const basePaths = resolveServicePaths(this.homeDir);
119
+ const config = await readServiceConfig(basePaths);
120
+ const paths = resolveServicePaths(this.homeDir, config?.dataDir);
121
+ const [stdout, stderr] = await Promise.all([
122
+ readTail(paths.stdoutPath, maxBytes),
123
+ readTail(paths.stderrPath, maxBytes),
124
+ ]);
125
+ return { stdoutPath: paths.stdoutPath, stderrPath: paths.stderrPath, stdout, stderr };
126
+ }
127
+ async restart() {
128
+ const status = await this.status();
129
+ if (!status.installed)
130
+ throw new Error("AgentRoam service is not installed");
131
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
132
+ if (status.running) {
133
+ await this.runRequired(buildStopTaskScript());
134
+ if (status.state?.pid)
135
+ await this.waitForProcessExit(status.state.pid);
136
+ }
137
+ await Promise.all([removeIfExists(paths.statePath), removeIfExists(paths.urlPath)]);
138
+ await this.runRequired(buildStartTaskScript());
139
+ return this.waitForReady(paths, status.state?.pid);
140
+ }
141
+ async uninstall() {
142
+ const status = await this.status();
143
+ const paths = resolveServicePaths(this.homeDir, status.config?.dataDir);
144
+ if (status.running) {
145
+ await this.runRequired(buildStopTaskScript());
146
+ if (status.state?.pid)
147
+ await this.waitForProcessExit(status.state.pid);
148
+ }
149
+ if (status.installed)
150
+ await this.runRequired(buildUnregisterTaskScript());
151
+ await Promise.all([
152
+ removeIfExists(paths.configPath),
153
+ removeIfExists(paths.statePath),
154
+ removeIfExists(paths.urlPath),
155
+ ]);
156
+ return { removed: status.installed || Boolean(status.config), preservedDataDir: paths.dataDir };
157
+ }
158
+ async inspectTask() {
159
+ const result = await this.runPowerShell(buildStatusTaskScript());
160
+ if (result.code !== 0) {
161
+ const detail = result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`;
162
+ throw new Error(`PowerShell task status failed: ${detail}`);
163
+ }
164
+ const line = result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
165
+ if (!line)
166
+ throw new Error("PowerShell task status returned no JSON");
167
+ const value = JSON.parse(line);
168
+ return { installed: value.installed === true, running: value.running === true };
169
+ }
170
+ async runRequired(script) {
171
+ const result = await this.runPowerShell(script);
172
+ if (result.code !== 0) {
173
+ const detail = result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`;
174
+ throw new Error(`PowerShell service command failed: ${detail}`);
175
+ }
176
+ return result;
177
+ }
178
+ runPowerShell(script) {
179
+ return this.runner("powershell.exe", [
180
+ "-NoProfile",
181
+ "-NonInteractive",
182
+ "-ExecutionPolicy", "Bypass",
183
+ "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64"),
184
+ ]);
185
+ }
186
+ async waitForReady(paths, previousPid) {
187
+ const deadline = Date.now() + this.readyTimeoutMs;
188
+ do {
189
+ const state = await readServiceState(paths);
190
+ if (state?.status === "ready" && state.accessUrl && (!previousPid || state.pid !== previousPid)) {
191
+ const task = await this.inspectTask();
192
+ if (task.running && this.processExists(state.pid))
193
+ return state;
194
+ }
195
+ if (Date.now() >= deadline)
196
+ return state?.status === "ready" ? null : state;
197
+ await delay(this.pollIntervalMs);
198
+ } while (true);
199
+ }
200
+ async waitForProcessExit(pid) {
201
+ const deadline = Date.now() + this.stopTimeoutMs;
202
+ while (this.processExists(pid)) {
203
+ if (Date.now() >= deadline)
204
+ throw new Error(`service process ${pid} did not stop after task termination`);
205
+ await delay(this.pollIntervalMs);
206
+ }
207
+ }
208
+ }
209
+ export function resolveWindowsServiceHost(cliPath) {
210
+ return win32.resolve(win32.dirname(cliPath), "..", "dist", "service", "windows-service-host.js");
211
+ }
212
+ export function quoteWindowsCommandLineArgument(value) {
213
+ return `"${value.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\+)$/g, "$1$1")}"`;
214
+ }
215
+ export function buildRegisterTaskScript(config, hostPath, configPath) {
216
+ const argumentsValue = `${quoteWindowsCommandLineArgument(hostPath)} ${quoteWindowsCommandLineArgument(configPath)}`;
217
+ return String.raw `
218
+ $ErrorActionPreference = "Stop"
219
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
220
+ $action = New-ScheduledTaskAction -Execute ${powerShellLiteral(config.nodePath)} -Argument ${powerShellLiteral(argumentsValue)} -WorkingDirectory ${powerShellLiteral(config.roots[0])}
221
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
222
+ $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
223
+ $settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
224
+ Register-ScheduledTask -TaskName ${powerShellLiteral(WINDOWS_SERVICE_NAME)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
225
+ `;
226
+ }
227
+ export function buildStatusTaskScript() {
228
+ return String.raw `
229
+ $ErrorActionPreference = "Stop"
230
+ $task = Get-ScheduledTask -TaskName ${powerShellLiteral(WINDOWS_SERVICE_NAME)} -ErrorAction SilentlyContinue
231
+ if ($null -eq $task) {
232
+ [pscustomobject]@{ installed = $false; running = $false } | ConvertTo-Json -Compress
233
+ } else {
234
+ [pscustomobject]@{ installed = $true; running = ([string]$task.State -eq "Running") } | ConvertTo-Json -Compress
235
+ }
236
+ `;
237
+ }
238
+ function buildStartTaskScript() {
239
+ return `Start-ScheduledTask -TaskName ${powerShellLiteral(WINDOWS_SERVICE_NAME)}\n`;
240
+ }
241
+ function buildStopTaskScript() {
242
+ return `Stop-ScheduledTask -TaskName ${powerShellLiteral(WINDOWS_SERVICE_NAME)}\n`;
243
+ }
244
+ function buildUnregisterTaskScript() {
245
+ return `Unregister-ScheduledTask -TaskName ${powerShellLiteral(WINDOWS_SERVICE_NAME)} -Confirm:$false\n`;
246
+ }
247
+ function powerShellLiteral(value) {
248
+ return `'${value.replace(/'/g, "''")}'`;
249
+ }
250
+ async function validateWindowsConfig(config, hostPath) {
251
+ if (!win32.isAbsolute(config.nodePath) || !win32.isAbsolute(config.cliPath)) {
252
+ throw new Error("AgentRoam service requires absolute Node and CLI paths");
253
+ }
254
+ if (config.cliPath.split(/[\\/]/).includes("_npx")) {
255
+ throw new Error("service install cannot use an npx temporary package; install AgentRoam with the versioned installer first");
256
+ }
257
+ await Promise.all([
258
+ access(config.nodePath, constants.X_OK),
259
+ access(config.cliPath, constants.R_OK),
260
+ access(hostPath, constants.R_OK),
261
+ ...config.roots.map(async (root) => {
262
+ if (!(await stat(root)).isDirectory())
263
+ throw new Error(`service root is not a directory: ${root}`);
264
+ }),
265
+ ]);
266
+ }
267
+ function isProcessRunning(pid) {
268
+ try {
269
+ process.kill(pid, 0);
270
+ return true;
271
+ }
272
+ catch (error) {
273
+ return error.code === "EPERM";
274
+ }
275
+ }
276
+ async function readTail(path, maxBytes) {
277
+ try {
278
+ const value = await readFile(path);
279
+ return value.subarray(Math.max(0, value.length - maxBytes)).toString("utf8");
280
+ }
281
+ catch (error) {
282
+ if (error.code === "ENOENT")
283
+ return "";
284
+ throw error;
285
+ }
286
+ }
287
+ function delay(timeoutMs) {
288
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, timeoutMs));
289
+ }