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
@@ -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);
@@ -0,0 +1,147 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { link, readFile, unlink } from "node:fs/promises";
4
+ import { connect } from "node:net";
5
+ import { join } from "node:path";
6
+ import { WebSocket, createWebSocketStream } from "ws";
7
+ import { writePrivateText } from "../service/service-files.js";
8
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
9
+ export function relayOrigin(value) {
10
+ const url = new URL(value);
11
+ if (url.protocol !== "https:" || url.port || url.username || url.password || url.pathname !== "/" ||
12
+ url.search || url.hash || !/^(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*$/.test(url.hostname)) {
13
+ throw new Error("自建 HTTPS 入口需要一个 HTTPS 域名");
14
+ }
15
+ return url;
16
+ }
17
+ export function readDefaultRelayUrl() {
18
+ const configured = process.env.AGENTROAM_HTTPS_RELAY_URL?.trim();
19
+ if (configured)
20
+ return configured;
21
+ const path = new URL("../self-hosted-relay.json", import.meta.url);
22
+ try {
23
+ const url = JSON.parse(readFileSync(path, "utf8")).url;
24
+ return typeof url === "string" ? url : null;
25
+ }
26
+ catch (error) {
27
+ if (error.code !== "ENOENT")
28
+ throw error;
29
+ return null;
30
+ }
31
+ }
32
+ async function installationToken(dataDir) {
33
+ const path = join(dataDir, "relay", "identity");
34
+ const existing = await readToken(path);
35
+ if (existing)
36
+ return existing;
37
+ const temporary = `${path}.${randomBytes(8).toString("hex")}.pending`;
38
+ await writePrivateText(temporary, randomBytes(32).toString("base64url"));
39
+ try {
40
+ await link(temporary, path);
41
+ }
42
+ catch (error) {
43
+ if (error.code !== "EEXIST")
44
+ throw error;
45
+ }
46
+ finally {
47
+ await unlink(temporary);
48
+ }
49
+ const token = await readToken(path);
50
+ if (!token)
51
+ throw new Error("自建 HTTPS 入口的本机身份未能保存");
52
+ return token;
53
+ }
54
+ async function readToken(path) {
55
+ const token = await readFile(path, "utf8").catch((error) => {
56
+ if (error.code === "ENOENT")
57
+ return null;
58
+ throw error;
59
+ });
60
+ if (token !== null && !tokenPattern.test(token))
61
+ throw new Error("自建 HTTPS 入口的本机身份文件无效");
62
+ return token;
63
+ }
64
+ export class SelfHostedTunnelProvider {
65
+ url;
66
+ dataDir;
67
+ dial;
68
+ constructor(url, dataDir, dial = (url, options) => new WebSocket(url, options)) {
69
+ this.url = url;
70
+ this.dataDir = dataDir;
71
+ this.dial = dial;
72
+ }
73
+ async start({ localUrl, signal }) {
74
+ const root = relayOrigin(this.url);
75
+ const token = await installationToken(this.dataDir);
76
+ const local = new URL(localUrl);
77
+ if (local.protocol !== "http:" || local.hostname !== "127.0.0.1" || !local.port) {
78
+ throw new Error("自建 HTTPS 入口只能转发本机 AgentRoam 服务");
79
+ }
80
+ const name = createHash("sha256").update(token).digest("hex").slice(0, 32);
81
+ const publicUrl = `https://d-${name}.${root.host}`;
82
+ const options = { headers: { authorization: `Bearer ${token}` }, handshakeTimeout: 8_000, maxPayload: 1024 * 1024, perMessageDeflate: false };
83
+ const websocket = (path) => this.dial(new URL(`wss://${root.host}${path}`), options);
84
+ signal.throwIfAborted();
85
+ const control = websocket("/v1/connect");
86
+ const streams = new Set();
87
+ const close = () => {
88
+ control.terminate();
89
+ for (const socket of streams)
90
+ socket.terminate();
91
+ };
92
+ const exited = new Promise((resolve) => {
93
+ control.once("close", code => {
94
+ signal.removeEventListener("abort", close);
95
+ for (const socket of streams)
96
+ socket.terminate();
97
+ resolve({ code, signal: null });
98
+ });
99
+ });
100
+ signal.addEventListener("abort", close, { once: true });
101
+ try {
102
+ await new Promise((resolve, reject) => {
103
+ let ready = false;
104
+ control.on("error", reject);
105
+ void exited.then(() => reject(new Error("自建 HTTPS 入口连接已断开")));
106
+ control.on("message", chunk => {
107
+ try {
108
+ const message = JSON.parse(String(chunk));
109
+ if (!ready && message?.type === "ready" && message.publicUrl === publicUrl) {
110
+ ready = true;
111
+ resolve();
112
+ }
113
+ else if (ready && message?.type === "stream" && /^[a-f0-9]{32}$/.test(message.id) && streams.size < 64) {
114
+ const socket = websocket(`/v1/streams/${message.id}`);
115
+ streams.add(socket);
116
+ socket.once("close", () => streams.delete(socket));
117
+ connectToLoopback(socket, Number(local.port));
118
+ }
119
+ else {
120
+ close();
121
+ }
122
+ }
123
+ catch (error) {
124
+ reject(error);
125
+ close();
126
+ }
127
+ });
128
+ });
129
+ signal.throwIfAborted();
130
+ return { publicUrl, exited, close: async () => { close(); await exited; } };
131
+ }
132
+ catch (error) {
133
+ close();
134
+ throw error;
135
+ }
136
+ }
137
+ }
138
+ function connectToLoopback(socket, port) {
139
+ const stream = createWebSocketStream(socket);
140
+ // The remote can send immediately after the WebSocket handshake. Buffer on
141
+ // the stream until the local service accepts the socket.
142
+ const local = connect({ host: "127.0.0.1", port });
143
+ stream.on("error", () => local.destroy());
144
+ local.on("error", () => stream.destroy());
145
+ stream.once("close", () => local.destroy());
146
+ local.once("connect", () => stream.pipe(local).pipe(stream));
147
+ }
@@ -0,0 +1,232 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { pairingNetworkRoutes } from "../network.js";
3
+ import { waitForPublicReadiness } from "./public-readiness.js";
4
+ import { resolveRelayProvider, selectRelay } from "./relay-orchestrator.js";
5
+ import { readDefaultRelayUrl } from "./self-hosted-provider.js";
6
+ /** Owns only the public route. Server, agents and terminals have a separate lifetime. */
7
+ export class TunnelController {
8
+ options;
9
+ abort = new AbortController();
10
+ selection = null;
11
+ pairingRelays = new Map();
12
+ pending = null;
13
+ stopped = false;
14
+ observers = new Set();
15
+ state;
16
+ writes = Promise.resolve();
17
+ constructor(options) {
18
+ this.options = options;
19
+ this.state = { phase: "idle", mode: "local", provider: "lan", accessUrl: `${options.relay.localUrl}/web` };
20
+ if (options.relay.cli.testNoPairing)
21
+ this.state = { ...this.state, phase: "unsupported", error: "测试模式不支持公网连接,请以正常配对模式启动服务。" };
22
+ }
23
+ status() { return { ...this.state }; }
24
+ pairingRoutes() {
25
+ if (this.stopped || this.state.phase === "unsupported")
26
+ return [];
27
+ const choices = [];
28
+ if (this.options.relay.cli.relayUrl || readDefaultRelayUrl())
29
+ choices.push({ id: "self-hosted", kind: "self-hosted" });
30
+ choices.push({ id: "cloudflare", kind: "cloudflare" });
31
+ return choices.concat((this.options.networkRoutes ?? pairingNetworkRoutes)());
32
+ }
33
+ async pairingUrl(via) {
34
+ if (this.stopped || this.state.phase === "unsupported")
35
+ throw new Error("当前后台不支持切换配对线路。");
36
+ if (via === "self-hosted" || via === "cloudflare")
37
+ return this.publicPairingUrl(via);
38
+ const choices = (this.options.networkRoutes ?? pairingNetworkRoutes)();
39
+ const routedAddress = via === "lan" ? new URL(await this.currentLocalUrl()).hostname : undefined;
40
+ const route = via === "lan"
41
+ ? choices.find(choice => choice.kind === "lan" && choice.address === routedAddress) ?? choices.find(choice => choice.kind === "lan")
42
+ : choices.find(choice => choice.id === via || (via === "tailscale" && choice.kind === "tailscale"));
43
+ if (!route?.address)
44
+ throw new Error("所选网络地址当前不可用,请刷新连接选项。");
45
+ const origin = `http://${route.address}:${this.options.relay.port}`;
46
+ try {
47
+ await (this.options.checkNetworkRoute ?? waitForPublicReadiness)(origin, {
48
+ timeoutMs: 3000, proxyResolver: async () => null, signal: this.abort.signal,
49
+ fetchImpl: (url, init) => fetch(url, { ...init, redirect: "error" }),
50
+ });
51
+ }
52
+ catch {
53
+ throw new Error("无法通过所选 IP 访问本机服务,请检查网络和防火墙。");
54
+ }
55
+ return `${origin}/web`;
56
+ }
57
+ async publicPairingUrl(via) {
58
+ if (via === "self-hosted" && !this.options.relay.cli.relayUrl && !readDefaultRelayUrl())
59
+ throw new Error("自建 HTTPS 入口地址未配置。");
60
+ if (resolveRelayProvider(this.options.relay.cli) === via) {
61
+ const status = await this.connect();
62
+ if (status.provider === via && status.phase === "ready" && status.accessUrl)
63
+ return status.accessUrl;
64
+ throw new Error(status.error || "所选公网线路未连接,请重试。");
65
+ }
66
+ let pending = this.pairingRelays.get(via);
67
+ if (!pending) {
68
+ const start = (this.options.select ?? selectRelay)({
69
+ ...this.options.relay, signal: this.abort.signal, lanUrl: this.options.relay.localUrl,
70
+ cli: { ...this.options.relay.cli, relay: via, localOnly: false }, onAttempt: undefined, onFailure: undefined,
71
+ });
72
+ const clear = () => { if (this.pairingRelays.get(via) === pending)
73
+ this.pairingRelays.delete(via); };
74
+ pending = start.then(result => {
75
+ if (!result.tunnel)
76
+ throw new Error(`${via === "cloudflare" ? "Cloudflare" : "自建 HTTPS"} 未连接,请检查电脑网络后重试。`);
77
+ void result.tunnel.exited.then(clear, clear);
78
+ return result;
79
+ }).catch(error => { clear(); throw error; });
80
+ this.pairingRelays.set(via, pending);
81
+ }
82
+ return `${(await pending).publicUrl}/web`;
83
+ }
84
+ subscribe(listener) {
85
+ this.observers.add(listener);
86
+ listener(this.status());
87
+ return () => this.observers.delete(listener);
88
+ }
89
+ connect(forcePublic = true) {
90
+ if (this.pending)
91
+ return this.pending;
92
+ if (this.stopped || this.state.phase === "ready" || this.state.phase === "unsupported")
93
+ return Promise.resolve(this.status());
94
+ this.set({ ...this.state, phase: "connecting", stage: "connecting", error: undefined });
95
+ this.pending = this.attempt(forcePublic).finally(() => { this.pending = null; });
96
+ return this.pending;
97
+ }
98
+ async attempt(forcePublic) {
99
+ let lanUrl = this.options.relay.localUrl;
100
+ try {
101
+ lanUrl = await this.options.lanUrl();
102
+ if (this.stopped)
103
+ return this.status();
104
+ this.set({ ...this.fallback(lanUrl), phase: "connecting", stage: "connecting" });
105
+ await this.persist();
106
+ const result = await (this.options.select ?? selectRelay)({
107
+ ...this.options.relay, lanUrl, signal: this.abort.signal,
108
+ cli: { ...this.options.relay.cli, localOnly: forcePublic ? false : this.options.relay.cli.localOnly },
109
+ onStage: stage => this.set({ ...this.state, stage }),
110
+ });
111
+ if (this.stopped) {
112
+ await result.tunnel?.close();
113
+ return this.status();
114
+ }
115
+ this.selection = result;
116
+ const error = result.failures.length ? this.failureMessage() : undefined;
117
+ if (!result.tunnel)
118
+ lanUrl = await this.currentLocalUrl();
119
+ if (this.stopped)
120
+ return this.status();
121
+ await this.commit(result.tunnel
122
+ ? { phase: "ready", mode: "public", provider: result.provider, accessUrl: `${result.publicUrl}/web` }
123
+ : { ...this.fallback(lanUrl), phase: error ? "error" : "idle", error });
124
+ if (result.tunnel)
125
+ void result.tunnel.exited.then(() => this.disconnected(result)).catch(error => this.report(error));
126
+ }
127
+ catch (error) {
128
+ if (!this.stopped) {
129
+ this.report(error);
130
+ const current = this.selection;
131
+ this.selection = null;
132
+ await current?.tunnel?.close().catch(error => this.report(error));
133
+ lanUrl = await this.currentLocalUrl();
134
+ if (this.stopped)
135
+ return this.status();
136
+ this.set({ ...this.fallback(lanUrl), phase: "error", error: "公网连接未完成,请检查电脑网络或代理后重试。" });
137
+ await this.persist();
138
+ }
139
+ }
140
+ return this.status();
141
+ }
142
+ failureMessage() {
143
+ return this.state.stage === "checking"
144
+ ? "公网地址可达性检查未通过,请检查电脑网络或代理后重试。"
145
+ : "公网隧道连接失败或超时,请检查电脑网络后重试。";
146
+ }
147
+ fallback(url) {
148
+ return { phase: "idle", mode: url === this.options.relay.localUrl ? "local" : "lan", provider: "lan", accessUrl: `${url}/web` };
149
+ }
150
+ currentLocalUrl() {
151
+ return this.options.lanUrl().catch(() => this.options.relay.localUrl);
152
+ }
153
+ async disconnected(selection) {
154
+ if (this.stopped || this.selection !== selection)
155
+ return;
156
+ this.selection = null;
157
+ const url = await this.currentLocalUrl();
158
+ if (this.stopped)
159
+ return;
160
+ await this.commit({ ...this.fallback(url), phase: "error", error: "公网连接已断开,请重试连接。" });
161
+ if (selection.provider !== "self-hosted")
162
+ return;
163
+ for (const wait of [1000, 2000, 5000]) {
164
+ await delay(wait, undefined, { signal: this.abort.signal }).catch(() => { });
165
+ if (this.stopped || this.state.phase === "ready")
166
+ return;
167
+ if ((await this.connect()).phase === "ready")
168
+ return;
169
+ }
170
+ }
171
+ set(status) {
172
+ this.state = status;
173
+ for (const observer of this.observers)
174
+ observer(this.status());
175
+ }
176
+ persist() {
177
+ const status = this.status();
178
+ const write = this.writes.then(() => this.options.publish(status));
179
+ this.writes = write.catch(error => this.report(error));
180
+ return write;
181
+ }
182
+ async commit(status) {
183
+ const previous = this.state;
184
+ this.state = status;
185
+ try {
186
+ await this.persist();
187
+ }
188
+ catch (error) {
189
+ this.state = previous;
190
+ throw error;
191
+ }
192
+ if (!this.stopped)
193
+ for (const observer of this.observers)
194
+ observer(this.status());
195
+ }
196
+ report(error) { this.options.onError?.(error); }
197
+ async close() {
198
+ this.stopped = true;
199
+ this.abort.abort();
200
+ await this.pending;
201
+ await this.selection?.tunnel?.close().catch(error => this.report(error));
202
+ this.selection = null;
203
+ await Promise.allSettled([...this.pairingRelays.values()].map(async (relay) => (await relay).tunnel?.close()));
204
+ this.pairingRelays.clear();
205
+ await this.writes;
206
+ this.observers.clear();
207
+ }
208
+ }
209
+ export function attachTunnelControl(child, controller) {
210
+ const unsubscribe = controller.subscribe(status => {
211
+ if (child.connected)
212
+ child.send({ type: "agentroam:tunnel-status", status }, () => { });
213
+ });
214
+ const receive = (message) => {
215
+ if (message?.type === "agentroam:tunnel-connect")
216
+ void controller.connect().catch(() => { });
217
+ const request = message;
218
+ if (request?.type !== "agentroam:pairing-route" || typeof request.id !== "string")
219
+ return;
220
+ const id = request.id;
221
+ const reply = (result, error) => {
222
+ if (child.connected)
223
+ child.send({ type: "agentroam:pairing-route-result", id, result, error }, () => { });
224
+ };
225
+ const work = request.route === undefined
226
+ ? Promise.resolve().then(() => ({ routes: controller.pairingRoutes() }))
227
+ : controller.pairingUrl(request.route).then(accessUrl => ({ accessUrl }));
228
+ void work.then(result => reply(result), error => reply(undefined, error instanceof Error ? error.message : "无法准备所选线路。"));
229
+ };
230
+ child.on("message", receive);
231
+ return () => { unsubscribe(); child.removeListener("message", receive); };
232
+ }