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,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: "" };
@@ -1,63 +1,83 @@
1
1
  import { fetch as undiciFetch, ProxyAgent } from "undici";
2
2
  import { resolveProxyForUrl } from "./proxy-settings.js";
3
+ import { AGENTROAM_VERSION } from "../platform-packages.js";
4
+ import { withAbortSignal } from "../abort.js";
3
5
  export async function waitForPublicReadiness(publicUrl, options = {}) {
4
6
  const timeoutMs = options.timeoutMs ?? 30_000;
5
7
  const intervalMs = options.intervalMs ?? 750;
6
8
  const endpoint = new URL("/api/web-auth/status", `${publicUrl.replace(/\/$/, "")}/`);
7
- let proxyFetch = null;
9
+ const deadline = Date.now() + timeoutMs;
10
+ const controller = new AbortController();
11
+ let lastFailure = "no response";
12
+ const timer = setTimeout(() => {
13
+ const detail = lastFailure === "no response" ? "request timed out" : `${lastFailure} (request timed out)`;
14
+ controller.abort(new Error(`public tunnel not ready: ${detail}`));
15
+ }, timeoutMs);
16
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
17
+ const connection = { proxy: null };
8
18
  let fetchImpl = options.fetchImpl;
9
- if (!fetchImpl) {
10
- const proxyResolver = options.proxyResolver ?? resolveProxyForUrl;
11
- const proxyUrl = await proxyResolver(endpoint).catch(() => null);
12
- if (proxyUrl)
13
- proxyFetch = (options.proxyFetchFactory ?? createProxyFetch)(proxyUrl);
14
- fetchImpl = proxyFetch?.fetch ?? fetch;
15
- }
16
19
  try {
17
- const deadline = Date.now() + timeoutMs;
18
- let lastFailure = "no response";
19
- while (Date.now() <= deadline) {
20
- if (options.signal?.aborted)
21
- throw new Error("public tunnel readiness aborted");
22
- try {
23
- const response = await fetchImpl(endpoint, {
24
- cache: "no-store",
25
- headers: { "user-agent": "agentroam-readiness/0.2.0-preview.8" },
26
- signal: options.signal,
27
- });
28
- if (response.ok) {
29
- let body;
30
- try {
31
- body = (await response.json());
32
- }
33
- catch {
20
+ await withAbortSignal(async () => {
21
+ if (!fetchImpl) {
22
+ const proxyResolver = options.proxyResolver ?? resolveProxyForUrl;
23
+ const proxyUrl = await proxyResolver(endpoint).catch(() => null);
24
+ signal.throwIfAborted();
25
+ if (proxyUrl)
26
+ connection.proxy = (options.proxyFetchFactory ?? createProxyFetch)(proxyUrl);
27
+ fetchImpl = connection.proxy?.fetch ?? fetch;
28
+ }
29
+ while (Date.now() <= deadline) {
30
+ signal.throwIfAborted();
31
+ try {
32
+ const response = await fetchImpl(endpoint, {
33
+ cache: "no-store",
34
+ headers: { "user-agent": `agentroam-readiness/${AGENTROAM_VERSION}` },
35
+ signal,
36
+ });
37
+ if (response.ok) {
38
+ let body;
39
+ try {
40
+ body = (await response.json());
41
+ }
42
+ catch {
43
+ throw new FatalReadinessError("HTTP 200 with invalid auth status JSON");
44
+ }
45
+ signal.throwIfAborted();
46
+ if (typeof body.authenticated === "boolean" && typeof body.needsSetup === "boolean")
47
+ return;
34
48
  throw new FatalReadinessError("HTTP 200 with invalid auth status JSON");
35
49
  }
36
- if (typeof body.authenticated === "boolean" && typeof body.needsSetup === "boolean")
37
- return;
38
- throw new FatalReadinessError("HTTP 200 with invalid auth status JSON");
50
+ else {
51
+ lastFailure = `HTTP ${response.status}`;
52
+ void response.body?.cancel().catch(() => { });
53
+ if (![404, 502, 503, 530].includes(response.status))
54
+ throw new FatalReadinessError(lastFailure);
55
+ }
39
56
  }
40
- else {
41
- lastFailure = `HTTP ${response.status}`;
42
- if (![404, 502, 503, 530].includes(response.status))
43
- throw new FatalReadinessError(lastFailure);
57
+ catch (error) {
58
+ if (options.signal?.aborted)
59
+ throw new Error("public tunnel readiness aborted");
60
+ signal.throwIfAborted();
61
+ if (error instanceof FatalReadinessError)
62
+ throw new Error(`public tunnel not ready: ${error.message}`);
63
+ lastFailure = error instanceof Error ? error.message : String(error);
44
64
  }
65
+ if (Date.now() + intervalMs > deadline)
66
+ break;
67
+ await delay(intervalMs, signal);
45
68
  }
46
- catch (error) {
47
- if (options.signal?.aborted)
48
- throw new Error("public tunnel readiness aborted");
49
- if (error instanceof FatalReadinessError)
50
- throw new Error(`public tunnel not ready: ${error.message}`);
51
- lastFailure = error instanceof Error ? error.message : String(error);
52
- }
53
- if (Date.now() + intervalMs > deadline)
54
- break;
55
- await delay(intervalMs, options.signal);
56
- }
57
- throw new Error(`public tunnel not ready: ${lastFailure}`);
69
+ throw new Error(`public tunnel not ready: ${lastFailure}`);
70
+ }, signal);
71
+ }
72
+ catch (error) {
73
+ if (options.signal?.aborted)
74
+ throw new Error("public tunnel readiness aborted");
75
+ throw error;
58
76
  }
59
77
  finally {
60
- await proxyFetch?.close().catch(() => { });
78
+ clearTimeout(timer);
79
+ if (connection.proxy)
80
+ await withAbortSignal(() => connection.proxy.close(), AbortSignal.timeout(3_000)).catch(() => { });
61
81
  }
62
82
  }
63
83
  class FatalReadinessError extends Error {
@@ -67,16 +87,22 @@ function createProxyFetch(proxyUrl) {
67
87
  return {
68
88
  fetch: async (input, init) => (await undiciFetch(input, { ...init, dispatcher })),
69
89
  close: async () => {
70
- await dispatcher.close();
90
+ await dispatcher.destroy();
71
91
  },
72
92
  };
73
93
  }
74
94
  function delay(milliseconds, signal) {
75
95
  return new Promise((resolvePromise, reject) => {
76
- const timer = setTimeout(resolvePromise, milliseconds);
77
- signal?.addEventListener("abort", () => {
96
+ const abort = () => {
78
97
  clearTimeout(timer);
79
- reject(new Error("public tunnel readiness aborted"));
80
- }, { once: true });
98
+ reject(signal?.reason);
99
+ };
100
+ const timer = setTimeout(() => {
101
+ signal?.removeEventListener("abort", abort);
102
+ resolvePromise();
103
+ }, milliseconds);
104
+ signal?.addEventListener("abort", abort, { once: true });
105
+ if (signal?.aborted)
106
+ abort();
81
107
  });
82
108
  }
@@ -1,38 +1,72 @@
1
1
  import { ensureCloudflared } from "../cloudflared/installer.js";
2
2
  import { CloudflareTunnelProvider } from "./cloudflare-provider.js";
3
3
  import { CustomCommandTunnelProvider } from "./custom-command-provider.js";
4
+ import { readDefaultRelayUrl, SelfHostedTunnelProvider } from "./self-hosted-provider.js";
4
5
  import { PinggyTunnelProvider } from "./pinggy-provider.js";
5
6
  import { waitForPublicReadiness } from "./public-readiness.js";
7
+ import { withAbortSignal } from "../abort.js";
8
+ export const RELAY_START_TIMEOUT_MS = 30_000;
9
+ export function resolveRelayProvider(cli, relayUrl) {
10
+ if (cli.relay !== "auto")
11
+ return cli.relay;
12
+ const url = relayUrl === undefined ? cli.relayUrl ?? readDefaultRelayUrl() : relayUrl;
13
+ return url ? "self-hosted" : "cloudflare";
14
+ }
6
15
  export async function selectRelay(options) {
16
+ options.signal.throwIfAborted();
7
17
  if (options.cli.localOnly)
8
18
  return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures: [] };
9
- const providers = options.cli.relay === "auto" ? ["cloudflare", "pinggy"] : [options.cli.relay];
19
+ const { relay, relayUrl: configuredUrl } = options.cli;
20
+ const relayUrl = configuredUrl ?? (relay === "auto" || relay === "self-hosted" ? readDefaultRelayUrl() : null);
21
+ const providerName = resolveRelayProvider(options.cli, relayUrl);
10
22
  const failures = [];
11
23
  const readiness = options.readiness ?? waitForPublicReadiness;
12
- for (const providerName of providers) {
13
- options.onAttempt?.(providerName);
14
- let tunnel = null;
15
- try {
16
- const provider = await createProvider(providerName, options);
17
- tunnel = await provider.start({ localUrl: options.localUrl, signal: options.signal, log: options.log });
18
- await readiness(tunnel.publicUrl, { signal: options.signal });
19
- return { tunnel, publicUrl: tunnel.publicUrl, provider: providerName, failures };
20
- }
21
- catch (error) {
22
- await tunnel?.close().catch(() => { });
23
- const message = error instanceof Error ? error.message : String(error);
24
- failures.push({ provider: providerName, message });
25
- options.onFailure?.(providerName, message);
26
- if (options.signal.aborted)
27
- break;
28
- }
24
+ options.onStage?.("connecting");
25
+ options.onAttempt?.(providerName);
26
+ const attempt = { tunnel: null };
27
+ const deadline = new AbortController();
28
+ const timeoutMs = options.timeoutMs ?? RELAY_START_TIMEOUT_MS;
29
+ const timer = setTimeout(() => deadline.abort(new Error(`relay connection timed out after ${timeoutMs}ms`)), timeoutMs);
30
+ const signal = AbortSignal.any([options.signal, deadline.signal]);
31
+ try {
32
+ return await withAbortSignal(async () => {
33
+ const provider = await createProvider(providerName, options, relayUrl);
34
+ signal.throwIfAborted();
35
+ const handle = await provider.start({ localUrl: options.localUrl, signal, log: options.log });
36
+ if (signal.aborted) {
37
+ void handle.close().catch(() => { });
38
+ signal.throwIfAborted();
39
+ }
40
+ attempt.tunnel = handle;
41
+ options.onStage?.("checking");
42
+ await readiness(handle.publicUrl, { signal });
43
+ signal.throwIfAborted();
44
+ return { tunnel: handle, publicUrl: handle.publicUrl, provider: providerName, failures };
45
+ }, signal);
46
+ }
47
+ catch (error) {
48
+ deadline.abort(error);
49
+ if (attempt.tunnel)
50
+ await withAbortSignal(() => attempt.tunnel.close(), AbortSignal.timeout(3_000)).catch(() => { });
51
+ options.signal.throwIfAborted();
52
+ const message = error instanceof Error ? error.message : String(error);
53
+ failures.push({ provider: providerName, message });
54
+ options.onFailure?.(providerName, message);
55
+ }
56
+ finally {
57
+ clearTimeout(timer);
29
58
  }
30
59
  return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures };
31
60
  }
32
- async function createProvider(name, options) {
61
+ async function createProvider(name, options, relayUrl) {
33
62
  const override = options.providerFactories?.[name];
34
63
  if (override)
35
64
  return await override();
65
+ if (name === "self-hosted") {
66
+ if (!relayUrl)
67
+ throw new Error("自建 HTTPS 入口地址未配置");
68
+ return new SelfHostedTunnelProvider(relayUrl, options.cli.dataDir);
69
+ }
36
70
  if (name === "cloudflare") {
37
71
  const executable = await ensureCloudflared(options.target, options.cli.dataDir);
38
72
  return new CloudflareTunnelProvider(executable);