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,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
+ }
@@ -0,0 +1,43 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { createRequire } from "node:module";
3
+ import { PLATFORM_DEPENDENCY_VERSIONS } from "../platform-packages.js";
4
+ import { TAILSCALE_PACKAGES } from "./manifest.js";
5
+ export async function resolveBundledTailscale(target, requireFromCli = createRequire(import.meta.url)) {
6
+ const packageName = TAILSCALE_PACKAGES[target];
7
+ if (!packageName)
8
+ return null;
9
+ let manifestPath;
10
+ let assetPath;
11
+ try {
12
+ manifestPath = requireFromCli.resolve(`${packageName}/manifest.json`);
13
+ assetPath = requireFromCli.resolve(`${packageName}/archive`);
14
+ }
15
+ catch (error) {
16
+ if (["MODULE_NOT_FOUND", "ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(error?.code ?? ""))
17
+ return null;
18
+ throw error;
19
+ }
20
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
21
+ const expectedEntries = target === "windows-amd64" ? ["tailscale.exe", "tailscaled.exe"] : ["tailscale", "tailscaled"];
22
+ if (manifest.packageVersion !== PLATFORM_DEPENDENCY_VERSIONS[packageName] ||
23
+ manifest.target !== target ||
24
+ manifest.assetFormat !== "tgz" ||
25
+ typeof manifest.upstreamVersion !== "string" ||
26
+ !Array.isArray(manifest.entries) ||
27
+ manifest.entries.length !== expectedEntries.length ||
28
+ !expectedEntries.every(entry => manifest.entries.includes(entry)) ||
29
+ typeof manifest.size !== "number" ||
30
+ !Number.isSafeInteger(manifest.size) ||
31
+ manifest.size <= 0 ||
32
+ typeof manifest.sha256 !== "string" ||
33
+ !/^[a-f0-9]{64}$/.test(manifest.sha256)) {
34
+ throw new Error(`invalid tailscale platform manifest: ${manifestPath}`);
35
+ }
36
+ return {
37
+ assetPath,
38
+ sha256: manifest.sha256,
39
+ size: manifest.size,
40
+ entries: manifest.entries,
41
+ version: manifest.upstreamVersion,
42
+ };
43
+ }
@@ -0,0 +1,112 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdir } from "node:fs/promises";
4
+ import { resolve } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { readTailscaleStatus } from "./tailnet-cli.js";
7
+ /**
8
+ * tailscaled(userspace 模式)生命周期管理。
9
+ *
10
+ * 复用优先:socket 上已有可用的 tailscaled(例如同机另一个 agentroam 进程已拉起)时
11
+ * 直接复用,绝不启动第二个守护进程争抢 statedir。userspace 模式不需要 root/TUN。
12
+ */
13
+ export class TailscaleDaemon {
14
+ options;
15
+ child = null;
16
+ constructor(options) {
17
+ this.options = options;
18
+ }
19
+ socketPath() {
20
+ if (process.platform === "win32") {
21
+ const id = createHash("sha256").update(this.stateDir().toLowerCase()).digest("hex").slice(0, 24);
22
+ return `\\\\.\\pipe\\agentroam-tailscale-${id}`;
23
+ }
24
+ return resolve(this.stateDir(), "tailscaled.sock");
25
+ }
26
+ stateDir() {
27
+ return resolve(this.options.dataDir, "tailscale");
28
+ }
29
+ /** tailscale CLI 与 tailscaled 同目录、同名去 d(PATH 探测来源同样是成对相邻的)。 */
30
+ cliPath() {
31
+ return this.options.tailscaledPath.replace(/tailscaled(\.exe)?$/, "tailscale$1");
32
+ }
33
+ cliOptionsWith(tailscalePath) {
34
+ return {
35
+ tailscalePath,
36
+ socketPath: this.socketPath(),
37
+ timeoutMs: this.options.timeoutMs,
38
+ spawnImpl: this.options.spawnImpl,
39
+ signal: this.options.signal,
40
+ };
41
+ }
42
+ /** 用给定 tailscale CLI 探活;BackendState=Unknown 且无 100.x 视为未就绪。 */
43
+ async probeStatus(cliPath) {
44
+ try {
45
+ const status = await readTailscaleStatus(this.cliOptionsWith(cliPath));
46
+ if (["Unknown", "NoState", "Starting"].includes(status.backendState))
47
+ return null;
48
+ return status;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ async ensureRunning(tailscalePath) {
55
+ const socketPath = this.socketPath();
56
+ const stateDir = this.stateDir();
57
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
58
+ if (process.platform !== "win32")
59
+ await chmod(stateDir, 0o700);
60
+ const existing = await this.probeStatus(tailscalePath);
61
+ if (existing)
62
+ return { socketPath, stateDir, reused: true, status: existing };
63
+ if (this.child)
64
+ await this.stopChild();
65
+ const log = this.options.onLog ?? (() => { });
66
+ log("Starting tailscaled (userspace)…");
67
+ const spawnImpl = this.options.spawnImpl ?? spawn;
68
+ let startupError;
69
+ const child = spawnImpl(this.options.tailscaledPath, [
70
+ "--tun=userspace-networking", "--port=0",
71
+ ...(process.platform === "win32" ? ["--windows-mode=dev"] : []),
72
+ `--statedir=${stateDir}`,
73
+ `--socket=${socketPath}`,
74
+ ], {
75
+ stdio: ["ignore", "ignore", "pipe"], windowsHide: true,
76
+ env: { ...process.env, AGENT_HEADSCALE_API_KEY: undefined },
77
+ });
78
+ this.child = child;
79
+ child.stderr?.on("data", (chunk) => log(String(chunk).trimEnd()));
80
+ child.once("error", error => { startupError = error; });
81
+ child.once("exit", () => { if (this.child === child)
82
+ this.child = null; });
83
+ const deadline = Date.now() + 15_000;
84
+ while (Date.now() < deadline) {
85
+ this.options.signal?.throwIfAborted();
86
+ if (startupError)
87
+ throw startupError;
88
+ if (this.child === null)
89
+ throw new Error("tailscaled exited during startup");
90
+ const status = await this.probeStatus(tailscalePath);
91
+ if (status)
92
+ return { socketPath, stateDir, reused: false, status };
93
+ await delay(300, undefined, { signal: this.options.signal });
94
+ }
95
+ await this.stopChild();
96
+ throw new Error("tailscaled did not become ready within 15s (check tailscaled availability and statedir permissions)");
97
+ }
98
+ async stop() {
99
+ await this.stopChild();
100
+ }
101
+ async stopChild() {
102
+ const child = this.child;
103
+ this.child = null;
104
+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null)
105
+ return;
106
+ await new Promise((resolveExit) => {
107
+ const timer = setTimeout(() => { child.kill("SIGKILL"); resolveExit(null); }, 3_000);
108
+ child.once("exit", () => { clearTimeout(timer); resolveExit(null); });
109
+ child.kill("SIGTERM");
110
+ });
111
+ }
112
+ }