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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +61 -15
  2. package/bin/agentroam.mjs +10 -1
  3. package/bin/cli-progress.d.mts +9 -0
  4. package/bin/cli-progress.mjs +65 -0
  5. package/bin/desktop-download.mjs +69 -0
  6. package/bin/node-preflight.mjs +171 -0
  7. package/bin/node-runtime-policy.json +4 -0
  8. package/bin/runtime-policy.d.mts +5 -0
  9. package/bin/runtime-policy.mjs +37 -0
  10. package/dist/abort.js +25 -0
  11. package/dist/args.js +102 -3
  12. package/dist/cli.js +244 -44
  13. package/dist/cloudflared/bundled-asset.js +3 -2
  14. package/dist/cloudflared/manifest.js +2 -2
  15. package/dist/codex-desktop-command.js +70 -0
  16. package/dist/codex-desktop-force-stop.js +46 -0
  17. package/dist/codex-desktop-idle-guard.js +15 -0
  18. package/dist/codex-desktop-preflight.js +63 -0
  19. package/dist/codex-desktop-probe.js +152 -0
  20. package/dist/codex-desktop-setup.js +154 -0
  21. package/dist/codex-desktop-status.js +85 -0
  22. package/dist/codex-desktop-windows.js +122 -0
  23. package/dist/codex-runtime-manager.js +368 -0
  24. package/dist/codex-sharing.js +153 -0
  25. package/dist/codex-windows-backend-host.js +59 -0
  26. package/dist/codex-windows-backend.js +120 -0
  27. package/dist/desktop-authorization-prompt.js +84 -0
  28. package/dist/desktop-authorization.js +161 -0
  29. package/dist/device-pairing.js +170 -0
  30. package/dist/error-log.js +113 -0
  31. package/dist/instance-takeover.js +143 -0
  32. package/dist/local-desktop-url.js +8 -0
  33. package/dist/local-service-request.js +69 -0
  34. package/dist/native-runtime.js +68 -0
  35. package/dist/network.js +32 -3
  36. package/dist/node-runtime-manager.js +251 -0
  37. package/dist/opencode-runtime-manager.js +239 -0
  38. package/dist/platform-packages.js +16 -5
  39. package/dist/platform.js +6 -4
  40. package/dist/power/sleep-inhibitor.js +161 -0
  41. package/dist/runtime-manager.js +130 -19
  42. package/dist/service/launcher-cleanup.js +79 -0
  43. package/dist/service/macos-launch-agent.js +288 -0
  44. package/dist/service/runtime-state.js +43 -0
  45. package/dist/service/service-command.js +219 -0
  46. package/dist/service/service-controller.js +27 -0
  47. package/dist/service/service-files.js +78 -0
  48. package/dist/service/windows-service-host.js +59 -0
  49. package/dist/service/windows-task-service.js +289 -0
  50. package/dist/startup-lock.js +81 -0
  51. package/dist/tunnel/cloudflare-provider.js +4 -1
  52. package/dist/tunnel/public-readiness.js +76 -50
  53. package/dist/tunnel/relay-orchestrator.js +31 -9
  54. package/dist/tunnel/tunnel-controller.js +144 -0
  55. package/dist/unlock-service.js +105 -0
  56. package/dist/update/update-channel.js +38 -0
  57. package/dist/update/update-command.js +96 -0
  58. package/dist/update/update-install.js +34 -0
  59. package/dist/update/update-state.js +43 -0
  60. package/dist/update/update-worker.js +80 -0
  61. package/install/README.md +55 -0
  62. package/install/codex-shared-watchdog.sh +16 -0
  63. package/install/install-agentroam.ps1 +358 -0
  64. package/install/install-agentroam.sh +457 -0
  65. package/install/install-manifest.json +15 -0
  66. package/install/start-codex-desktop-shared.sh +152 -0
  67. package/package.json +13 -10
  68. package/dist/args.test.js +0 -27
  69. package/dist/cloudflared/bundled-asset.test.js +0 -76
  70. package/dist/cloudflared/installer.test.js +0 -95
  71. package/dist/native-runtime.test.js +0 -19
  72. package/dist/network.test.js +0 -20
  73. package/dist/pairing.js +0 -2
  74. package/dist/platform-packages.test.js +0 -75
  75. package/dist/platform.test.js +0 -3
  76. package/dist/port.test.js +0 -3
  77. package/dist/process-supervisor.test.js +0 -42
  78. package/dist/tunnel/cloudflare-provider.test.js +0 -33
  79. package/dist/tunnel/pinggy-provider.test.js +0 -40
  80. package/dist/tunnel/proxy-settings.test.js +0 -111
  81. package/dist/tunnel/public-readiness.test.js +0 -104
  82. package/dist/tunnel/relay-orchestrator.test.js +0 -72
@@ -0,0 +1,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
+ }
@@ -0,0 +1,81 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
3
+ import { createServer } from "node:net";
4
+ import { join, resolve } from "node:path";
5
+ function alive(pid) {
6
+ try {
7
+ process.kill(pid, 0);
8
+ return true;
9
+ }
10
+ catch (error) {
11
+ return error.code !== "ESRCH";
12
+ }
13
+ }
14
+ /** Serialize startup within a data directory; never remove a live owner's lock. */
15
+ export async function lockInstanceStartup(dataDir) {
16
+ await mkdir(dataDir, { recursive: true });
17
+ const path = resolve(await realpath(dataDir), ".cli-start.lock");
18
+ // Task Scheduler can terminate the CLI without running finally. A named pipe
19
+ // is released by Windows even on forced termination; retain the PID marker
20
+ // so older launchers still see an in-progress startup.
21
+ let closePipe;
22
+ const busy = () => new Error("此数据目录已有 CLI 正在启动;请等它完成后重试。");
23
+ if (process.platform === "win32") {
24
+ const pipe = createServer();
25
+ const name = createHash("sha256").update(path.toLowerCase()).digest("hex");
26
+ await new Promise((done, reject) => {
27
+ const onError = (error) => reject(error.code === "EADDRINUSE" ? busy() : error);
28
+ pipe.once("error", onError);
29
+ pipe.listen(`\\\\.\\pipe\\agentroam-startup-${name}`, () => { pipe.removeListener("error", onError); done(); });
30
+ });
31
+ closePipe = () => new Promise((done, reject) => pipe.close(error => error ? reject(error) : done()));
32
+ try {
33
+ const owner = (await readFile(join(path, "pid"), "utf8").catch(error => {
34
+ if (error.code === "ENOENT")
35
+ return null;
36
+ throw error;
37
+ }))?.trim();
38
+ if (owner !== undefined && owner !== null) {
39
+ const pid = Number(owner);
40
+ // Be conservative with corrupt markers and potentially reused live PIDs.
41
+ if (!Number.isSafeInteger(pid) || pid <= 1 || alive(pid))
42
+ throw busy();
43
+ await rm(path, { recursive: true, force: true });
44
+ }
45
+ }
46
+ catch (error) {
47
+ await closePipe();
48
+ throw error;
49
+ }
50
+ }
51
+ try {
52
+ try {
53
+ await mkdir(path, { mode: 0o700 });
54
+ }
55
+ catch (error) {
56
+ if (error.code !== "EEXIST")
57
+ throw error;
58
+ throw new Error("此数据目录已有 CLI 正在启动;请等它完成后重试。若上次异常退出,请确认无启动进程后移除 .cli-start.lock。");
59
+ }
60
+ try {
61
+ await writeFile(join(path, "pid"), String(process.pid), { mode: 0o600 });
62
+ }
63
+ catch (error) {
64
+ await rm(path, { recursive: true, force: true });
65
+ throw error;
66
+ }
67
+ let release;
68
+ return () => release ??= (async () => {
69
+ try {
70
+ await rm(path, { recursive: true, force: true });
71
+ }
72
+ finally {
73
+ await closePipe?.();
74
+ }
75
+ })();
76
+ }
77
+ catch (error) {
78
+ await closePipe?.();
79
+ throw error;
80
+ }
81
+ }
@@ -6,7 +6,7 @@ export class CloudflareTunnelProvider {
6
6
  this.executable = executable;
7
7
  }
8
8
  async start({ localUrl, signal, log }) {
9
- const child = spawn(this.executable, ["tunnel", "--no-autoupdate", "--url", localUrl], {
9
+ const child = spawn(this.executable, buildCloudflaredArguments(localUrl), {
10
10
  stdio: ["ignore", "pipe", "pipe"],
11
11
  windowsHide: true,
12
12
  detached: process.platform !== "win32",
@@ -26,6 +26,9 @@ export class CloudflareTunnelProvider {
26
26
  }
27
27
  }
28
28
  }
29
+ export function buildCloudflaredArguments(localUrl) {
30
+ return ["tunnel", "--no-autoupdate", "--protocol", "http2", "--url", localUrl];
31
+ }
29
32
  export function waitForConnectedUrl(child, log, timeoutMs) {
30
33
  return new Promise((resolvePromise, reject) => {
31
34
  const buffers = { stdout: "", stderr: "" };