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,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
+ }
@@ -0,0 +1,131 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { access, chmod, copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { delimiter, resolve } from "node:path";
5
+ import { resolveBundledTailscale } from "./bundled-asset.js";
6
+ import { sha256File } from "../cloudflared/checksum.js";
7
+ /** 归档内固定两个二进制(tailscale CLI + tailscaled 守护进程),安装到 <dataDir>/bin。 */
8
+ export async function ensureTailscaleBinaries(target, dataDir, options = {}) {
9
+ const executableSuffix = target === "windows-amd64" ? ".exe" : "";
10
+ const binDir = resolve(dataDir, "bin");
11
+ const finalPaths = {
12
+ tailscale: resolve(binDir, `tailscale${executableSuffix}`),
13
+ tailscaled: resolve(binDir, `tailscaled${executableSuffix}`),
14
+ };
15
+ await mkdir(binDir, { recursive: true });
16
+ const resolveBundled = options.resolveBundled ?? resolveBundledTailscale;
17
+ const findSystem = options.findSystem ?? findSystemTailscale;
18
+ const failures = [];
19
+ try {
20
+ const bundled = await resolveBundled(target);
21
+ if (bundled) {
22
+ if (await cachedPair(finalPaths, bundled.sha256))
23
+ return finalPaths;
24
+ await installBundledTailscale(bundled, target, binDir, finalPaths);
25
+ return finalPaths;
26
+ }
27
+ failures.push(`platform package missing for ${target}`);
28
+ }
29
+ catch (error) {
30
+ failures.push(describeError(error));
31
+ }
32
+ const system = await findSystem(target);
33
+ if (system)
34
+ return system;
35
+ throw new Error(`tailscale binaries unavailable: ${failures.join("; ")}; install Tailscale (brew install tailscale) or build the platform package`);
36
+ }
37
+ /** macOS/Windows 的 GUI/服务进程 PATH 可能不含 Homebrew,显式探测常见前缀。 */
38
+ export async function findSystemTailscale(target = "darwin-arm64") {
39
+ const platform = target === "windows-amd64" ? "win32" : process.platform;
40
+ const suffix = platform === "win32" ? ".exe" : "";
41
+ const directories = new Set();
42
+ for (const value of (process.env.PATH ?? "").split(delimiter).filter(Boolean))
43
+ directories.add(value);
44
+ if (platform === "darwin")
45
+ directories.add("/opt/homebrew/bin");
46
+ if (platform !== "win32") {
47
+ directories.add("/usr/local/bin");
48
+ directories.add("/usr/bin");
49
+ }
50
+ for (const directory of directories) {
51
+ const pair = {
52
+ tailscale: resolve(directory, `tailscale${suffix}`),
53
+ tailscaled: resolve(directory, `tailscaled${suffix}`),
54
+ };
55
+ if (await bothExecutable(pair))
56
+ return pair;
57
+ }
58
+ return null;
59
+ }
60
+ async function bothExecutable(pair) {
61
+ for (const path of [pair.tailscale, pair.tailscaled]) {
62
+ try {
63
+ await access(path, constants.X_OK);
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ return true;
70
+ }
71
+ async function cachedPair(paths, hash) {
72
+ for (const path of [paths.tailscale, paths.tailscaled]) {
73
+ const marker = `${path}.source.sha256`;
74
+ try {
75
+ if (!(await stat(path)).isFile())
76
+ return false;
77
+ if ((await readFile(marker, "utf8")).trim() !== hash)
78
+ return false;
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
84
+ return true;
85
+ }
86
+ async function installBundledTailscale(asset, target, binDir, finalPaths) {
87
+ const archiveInfo = await stat(asset.assetPath);
88
+ if (!archiveInfo.isFile() || archiveInfo.size !== asset.size)
89
+ throw new Error("bundled tailscale size mismatch");
90
+ if ((await sha256File(asset.assetPath)) !== asset.sha256)
91
+ throw new Error("bundled tailscale checksum mismatch");
92
+ const temporaryDir = resolve(binDir, `.tailscale-${process.pid}-${Date.now()}`);
93
+ await mkdir(temporaryDir, { recursive: true });
94
+ try {
95
+ await extractTgz(asset.assetPath, temporaryDir);
96
+ const entries = (await readdir(temporaryDir)).sort();
97
+ const expected = [...asset.entries].sort();
98
+ if (entries.length !== expected.length || !entries.every((entry, index) => entry === expected[index])) {
99
+ throw new Error(`unexpected bundled tailscale contents: ${entries.join(", ")}`);
100
+ }
101
+ for (const entry of asset.entries) {
102
+ const destination = /^tailscale(?:\.exe)?$/.test(entry) ? finalPaths.tailscale : finalPaths.tailscaled;
103
+ const extracted = resolve(temporaryDir, entry);
104
+ if (!(await stat(extracted)).isFile())
105
+ throw new Error(`bundled tailscale executable missing: ${entry}`);
106
+ if (target !== "windows-amd64")
107
+ await chmod(extracted, 0o755);
108
+ await copyFile(extracted, destination);
109
+ const markerTemp = `${destination}.source.sha256.${process.pid}.tmp`;
110
+ await writeFileAtomic(markerTemp, `${asset.sha256}\n`, `${destination}.source.sha256`);
111
+ }
112
+ }
113
+ finally {
114
+ await rm(temporaryDir, { recursive: true, force: true });
115
+ }
116
+ }
117
+ async function writeFileAtomic(temporary, content, final) {
118
+ await writeFile(temporary, content);
119
+ await rename(temporary, final);
120
+ }
121
+ function describeError(error) {
122
+ const value = error;
123
+ return [value.cause?.code, value.message, value.cause?.message].filter(Boolean).join(": ") || String(error);
124
+ }
125
+ function extractTgz(archive, dir) {
126
+ return new Promise((resolvePromise, reject) => {
127
+ const child = spawn("tar", ["-xzf", archive, "-C", dir], { stdio: "ignore" });
128
+ child.once("exit", (code) => (code === 0 ? resolvePromise() : reject(new Error(`tar exited ${code}`))));
129
+ child.once("error", reject);
130
+ });
131
+ }
@@ -0,0 +1,15 @@
1
+ import { PLATFORM_DEPENDENCY_VERSIONS, requirePlatformPackages } from "../platform-packages.js";
2
+ /**
3
+ * tailscale 平台包(agentroam-tailscale-<target>)由
4
+ * scripts/build-tailscale-platform-package.mjs 在打包期从 tailscale 源码
5
+ * (pinned tag)构建:官方只为 Linux 发布裸 tgz,macOS/Windows 无官方裸二进制分发,
6
+ * 因此归档在打包期生成,运行期缺平台包时回落 PATH 探测(Homebrew / 官方安装)。
7
+ */
8
+ export const TAILSCALE_PACKAGES = {
9
+ "darwin-arm64": requirePlatformPackages("darwin-arm64").tailscale,
10
+ "windows-amd64": requirePlatformPackages("windows-amd64").tailscale,
11
+ };
12
+ export function tailscalePackageVersion(target) {
13
+ const packageName = TAILSCALE_PACKAGES[target];
14
+ return packageName ? PLATFORM_DEPENDENCY_VERSIONS[packageName] : undefined;
15
+ }
@@ -0,0 +1,101 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ export class TailscaleCommandError extends Error {
5
+ result;
6
+ constructor(message, result) {
7
+ super(message);
8
+ this.result = result;
9
+ }
10
+ }
11
+ export async function runTailscaleCommand(options, args) {
12
+ options.signal?.throwIfAborted();
13
+ const timeoutMs = options.timeoutMs ?? 30_000;
14
+ const spawnImpl = options.spawnImpl ?? spawn;
15
+ return await new Promise((resolveCommand, rejectCommand) => {
16
+ const child = spawnImpl(options.tailscalePath, ["--socket", options.socketPath, ...args], {
17
+ stdio: ["ignore", "pipe", "pipe"],
18
+ windowsHide: true,
19
+ signal: options.signal,
20
+ });
21
+ let stdout = "";
22
+ let stderr = "";
23
+ const timer = setTimeout(() => {
24
+ child.kill("SIGKILL");
25
+ rejectCommand(new TailscaleCommandError(`tailscale ${args[0]} timed out after ${timeoutMs}ms`, { stdout, stderr, code: -1 }));
26
+ }, timeoutMs);
27
+ child.stdout?.on("data", (chunk) => { stdout += String(chunk); });
28
+ child.stderr?.on("data", (chunk) => { stderr += String(chunk); });
29
+ child.once("error", (error) => { clearTimeout(timer); rejectCommand(error); });
30
+ child.once("close", (code) => {
31
+ clearTimeout(timer);
32
+ const result = { stdout, stderr, code: code ?? -1 };
33
+ if (code === 0)
34
+ resolveCommand(result);
35
+ else
36
+ rejectCommand(new TailscaleCommandError(`tailscale ${args[0]} exited ${code}: ${stderr.trim() || stdout.trim().slice(0, 400)}`, result));
37
+ });
38
+ });
39
+ }
40
+ /** `tailscale status --json` 在未登录时也可能退出 0,因此按 BackendState 判定而不是只看退出码。 */
41
+ export async function readTailscaleStatus(options) {
42
+ const result = await runTailscaleCommand({ ...options, timeoutMs: options.timeoutMs ?? 8_000 }, ["status", "--json"]);
43
+ let payload;
44
+ try {
45
+ payload = JSON.parse(result.stdout);
46
+ }
47
+ catch {
48
+ throw new TailscaleCommandError("tailscale status --json returned invalid JSON", result);
49
+ }
50
+ const tailscaleIPs = Array.isArray(payload.Self?.TailscaleIPs)
51
+ ? payload.Self?.TailscaleIPs.filter((value) => typeof value === "string") ?? []
52
+ : [];
53
+ const dnsName = typeof payload.Self?.DNSName === "string" && payload.Self.DNSName
54
+ ? payload.Self.DNSName.replace(/\.$/, "")
55
+ : null;
56
+ let controlPlaneUrl = null;
57
+ if (payload.BackendState === "Running") {
58
+ const prefs = await runTailscaleCommand(options, ["debug", "prefs"]);
59
+ const { ControlURL } = JSON.parse(prefs.stdout);
60
+ if (ControlURL)
61
+ controlPlaneUrl = new URL(ControlURL).origin;
62
+ }
63
+ return {
64
+ backendState: typeof payload.BackendState === "string" ? payload.BackendState : "Unknown",
65
+ tailscaleIPs,
66
+ dnsName,
67
+ hostname: typeof payload.Self?.HostName === "string" ? payload.Self.HostName : null,
68
+ controlPlaneUrl,
69
+ };
70
+ }
71
+ /** `tailscale up` 会阻塞到状态收敛;userspace 模式下首联一般数秒内完成。 */
72
+ export async function tailscaleUp(options, config) {
73
+ const directory = await mkdtemp(join(config.stateDir, ".auth-"));
74
+ const keyPath = join(directory, "key");
75
+ try {
76
+ await writeFile(keyPath, config.authKey, { mode: 0o600, flag: "wx" });
77
+ return await runTailscaleCommand({ ...options, timeoutMs: options.timeoutMs ?? 60_000 }, [
78
+ "up", `--login-server=${config.loginServer}`, `--auth-key=file:${keyPath}`,
79
+ `--hostname=${config.hostname}`, "--accept-dns=false", "--timeout=30s",
80
+ ]);
81
+ }
82
+ catch (error) {
83
+ if (error instanceof TailscaleCommandError) {
84
+ throw new Error(error.message.replaceAll(config.authKey, "[redacted]"));
85
+ }
86
+ throw error;
87
+ }
88
+ finally {
89
+ await rm(directory, { recursive: true, force: true });
90
+ }
91
+ }
92
+ export async function tailscaleServe(options, localUrl) {
93
+ // --http=80:headscale 不签发 MagicDNS 节点证书,tailnet 内用 80 端口 HTTP 暴露网关。
94
+ return await runTailscaleCommand(options, ["serve", "--bg", "--http=80", localUrl]);
95
+ }
96
+ export async function tailscaleServeReset(options) {
97
+ return await runTailscaleCommand(options, ["serve", "reset"]);
98
+ }
99
+ export async function tailscaleLogout(options) {
100
+ return await runTailscaleCommand({ ...options, timeoutMs: options.timeoutMs ?? 20_000 }, ["logout"]);
101
+ }
@@ -0,0 +1,27 @@
1
+ import { createRequire } from "node:module";
2
+ import { pathToFileURL, fileURLToPath } from "node:url";
3
+ import { existsSync } from "node:fs";
4
+ import { detectPlatform } from "./platform.js";
5
+ import { resolvePlatformRuntime } from "./platform-packages.js";
6
+ export async function runTodoMcpCommand(argv) {
7
+ const at = argv.indexOf("--service"), serviceId = at >= 0 ? argv[at + 1] : undefined;
8
+ if (!serviceId || serviceId.startsWith("-"))
9
+ throw new Error("Usage: agentroam mcp todo --service <serviceId>");
10
+ let entry;
11
+ const sibling = fileURLToPath(new URL("../../native-runtime/dist/index.js", import.meta.url));
12
+ if (existsSync(sibling))
13
+ entry = sibling;
14
+ else {
15
+ try {
16
+ entry = createRequire(import.meta.url).resolve("@agent/native-runtime");
17
+ }
18
+ catch {
19
+ const { runtimeRoot } = resolvePlatformRuntime(detectPlatform());
20
+ entry = createRequire(`${runtimeRoot}/package.json`).resolve("@agent/native-runtime");
21
+ }
22
+ }
23
+ const runtime = await import(pathToFileURL(entry).href);
24
+ if (typeof runtime.runTodoMcpStdio !== "function")
25
+ throw new Error("Installed runtime lacks Todo MCP support; update the runtime");
26
+ await runtime.runTodoMcpStdio({ serviceId });
27
+ }
@@ -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: "" };