agentroam 0.2.0-preview.79 → 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.
package/dist/args.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { homedir } from "node:os";
2
2
  import { resolve } from "node:path";
3
+ import { isIPv4 } from "node:net";
3
4
  export function parseArgs(argv) {
4
5
  const values = [...argv];
5
6
  let command = "start";
@@ -116,6 +117,14 @@ export function parseArgs(argv) {
116
117
  options.desktopSetup = true;
117
118
  else if (arg === "--url" && command === "pair")
118
119
  options.pairingUrl = next();
120
+ else if (arg === "--list-routes" && command === "pair")
121
+ options.pairingListRoutes = true;
122
+ else if (arg === "--via" && command === "pair") {
123
+ const via = next();
124
+ if (!["self-hosted", "cloudflare", "lan", "tailscale", "headscale"].includes(via) && !isIPv4(via))
125
+ throw cliError("pair --via requires self-hosted, cloudflare, lan, tailscale, headscale or a local IPv4 address");
126
+ options.pairingVia = via;
127
+ }
119
128
  else if (arg === "--node-name" && command === "mesh") {
120
129
  const name = next();
121
130
  if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(name))
@@ -170,6 +179,9 @@ export function parseArgs(argv) {
170
179
  }
171
180
  if (options.testNoPairing && (command !== "start" || !options.localOnly || options.tunnelCommand || options.relayUrl || options.relay !== "auto"))
172
181
  throw cliError("--test-no-pairing requires start --local-only and cannot use a tunnel or background service");
182
+ if ((options.pairingVia || options.pairingListRoutes) && (options.pairingUrl || !options.qr || (options.pairingVia && options.pairingListRoutes))) {
183
+ throw cliError("pair --via and --list-routes cannot be combined with each other, --url or --no-qr");
184
+ }
173
185
  if (!options.roots.length)
174
186
  options.roots = [process.cwd()];
175
187
  if (options.relay === "custom" && !options.tunnelCommand)
package/dist/cli.js CHANGED
@@ -8,7 +8,7 @@ import { ensureCloudflared } from "./cloudflared/installer.js";
8
8
  import { resolveCodexRuntime } from "./codex-runtime-manager.js";
9
9
  import { probeSQLiteRuntime, probeTerminalRuntime, repairNativeRuntimePermissions } from "./native-runtime.js";
10
10
  import { findRoutedLanUrl } from "./network.js";
11
- import { installedDataDir, pairingAdmin, printPairingCode, terminalText } from "./device-pairing.js";
11
+ import { installedDataDir, pairingAdmin, printPairingCode, printPairingRoutes, printPairingVia, terminalText } from "./device-pairing.js";
12
12
  import { detectPlatform } from "./platform.js";
13
13
  import { AGENTROAM_VERSION, resolvePlatformRuntime, resolvePlatformTui } from "./platform-packages.js";
14
14
  import { acquireSleepInhibitor } from "./power/sleep-inhibitor.js";
@@ -39,7 +39,10 @@ export async function main(argv) {
39
39
  console.log(`AgentRoam
40
40
  agentroam [start] [--local-only] [--test-no-pairing] [--data-dir PATH]
41
41
  agentroam start --relay self-hosted --relay-url https://connect.example.com
42
- agentroam pair 生成一次性设备配对码
42
+ agentroam pair 生成设备授权,公网连接可用时显示二维码
43
+ agentroam pair --no-qr 生成需由电脑批准的数字配对码
44
+ agentroam pair --list-routes 查看可选配对线路和本机 IP
45
+ agentroam pair --via <线路或 IP> 按所选地址生成扫码授权
43
46
  agentroam pair --url <服务器地址> 生成 App 扫码直连授权(终端显示)
44
47
  agentroam approvals 查看待批准请求和核对短语
45
48
  agentroam approve <请求ID> --phrase <核对短语>
@@ -91,8 +94,14 @@ async function executeCommand(options, argv) {
91
94
  cliErrorLog.installGlobalErrorHandlers();
92
95
  if (["pair", "devices", "revoke", "approvals", "approve", "deny", "lock", "unlock", "audit"].includes(options.command)) {
93
96
  const dataDir = argv.includes("--data-dir") ? options.dataDir : await installedDataDir(options.dataDir);
94
- if (options.command === "pair")
95
- await printPairingCode(dataDir, console.log, { accessUrl: options.pairingUrl, qr: options.qr });
97
+ if (options.command === "pair") {
98
+ if (options.pairingListRoutes)
99
+ await printPairingRoutes(dataDir);
100
+ else if (options.pairingVia)
101
+ await printPairingVia(dataDir, options.pairingVia);
102
+ else
103
+ await printPairingCode(dataDir, console.log, { accessUrl: options.pairingUrl, qr: options.qr });
104
+ }
96
105
  else if (options.command === "approvals") {
97
106
  const { requests, locked } = await pairingAdmin(dataDir, "requests");
98
107
  console.log(locked ? "远程访问已锁定" : requests.length ? requests.map((r) => `${r.id} ${terminalText(r.name)} 核对短语:${r.phrase} 到期 ${new Date(r.expires).toLocaleString()}`).join("\n") : "暂无待授权请求");
@@ -30,6 +30,41 @@ export function pairingQrPayload(accessUrl, grant) {
30
30
  throw new Error("Invalid pairing URL or authorization grant");
31
31
  return `${url.origin}/pair#pair=${grant}`;
32
32
  }
33
+ async function joinedMeshAddress(dataDir) {
34
+ const mesh = await localServiceRequest(dataDir, "/api/mesh/status").catch(() => null);
35
+ return mesh?.phase === "joined" ? mesh.accessUrl : undefined;
36
+ }
37
+ export async function printPairingRoutes(dataDir, log = console.log) {
38
+ const [{ routes }, mesh] = await Promise.all([
39
+ localServiceRequest(dataDir, "/api/desktop/tunnel/routes"), joinedMeshAddress(dataDir),
40
+ ]);
41
+ const labels = {
42
+ "self-hosted": "自建 HTTPS", cloudflare: "Cloudflare", lan: "局域网", tailscale: "Tailscale / 组网地址", vpn: "本机网络地址", headscale: "Headscale",
43
+ };
44
+ log("agentroam pair --via <线路或 IP>");
45
+ for (const route of routes)
46
+ log(` ${route.id} ${labels[route.kind]}${route.interfaceName ? ` · ${terminalText(route.interfaceName)}` : ""}`);
47
+ if (routes.some(route => route.kind === "lan"))
48
+ log(" lan 自动选择局域网地址");
49
+ if (routes.some(route => route.kind === "tailscale"))
50
+ log(" tailscale 自动选择 100.x 组网地址");
51
+ if (mesh)
52
+ log(` headscale ${new URL(mesh).origin}`);
53
+ }
54
+ export async function printPairingVia(dataDir, via, log = console.log) {
55
+ const accessUrl = await withCliProgress("正在准备所选配对线路", async () => {
56
+ if (via === "headscale") {
57
+ const mesh = await joinedMeshAddress(dataDir);
58
+ if (!mesh)
59
+ throw new Error("电脑尚未加入自建 Headscale 组网。");
60
+ return mesh;
61
+ }
62
+ const route = await localServiceRequest(dataDir, `/api/desktop/tunnel/routes?via=${encodeURIComponent(via)}`, { method: "POST", timeoutMs: 40_000 });
63
+ return route.accessUrl;
64
+ });
65
+ log(`Pairing route: ${new URL(accessUrl).origin}`);
66
+ await printPairingQr(dataDir, accessUrl, log);
67
+ }
33
68
  export async function printPairingCode(dataDir, log = console.log, options = {}) {
34
69
  const interactiveQr = (options.qr ?? true) && (options.interactive ?? process.stdout.isTTY);
35
70
  if (interactiveQr && options.accessUrl === undefined) {
package/dist/network.js CHANGED
@@ -1,5 +1,19 @@
1
1
  import { networkInterfaces } from "node:os";
2
2
  import { createSocket } from "node:dgram";
3
+ export function pairingNetworkRoutes(interfaces = networkInterfaces()) {
4
+ const choices = new Map();
5
+ for (const [interfaceName, entries] of Object.entries(interfaces)) {
6
+ for (const entry of entries ?? []) {
7
+ if (entry.family !== "IPv4" || entry.internal || choices.has(entry.address))
8
+ continue;
9
+ const { address } = entry;
10
+ const [first, second] = address.split(".").map(Number);
11
+ const kind = first === 100 && second >= 64 && second <= 127 ? "tailscale" : isPrivateIpv4(address) ? "lan" : "vpn";
12
+ choices.set(address, { id: address, kind, address, interfaceName });
13
+ }
14
+ }
15
+ return [...choices.values()];
16
+ }
3
17
  export function findLanUrl(port, interfaces = networkInterfaces(), routedAddress) {
4
18
  const addresses = Object.values(interfaces)
5
19
  .flatMap((entries) => entries ?? [])
@@ -6,13 +6,19 @@ import { PinggyTunnelProvider } from "./pinggy-provider.js";
6
6
  import { waitForPublicReadiness } from "./public-readiness.js";
7
7
  import { withAbortSignal } from "../abort.js";
8
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
+ }
9
15
  export async function selectRelay(options) {
10
16
  options.signal.throwIfAborted();
11
17
  if (options.cli.localOnly)
12
18
  return { tunnel: null, publicUrl: options.lanUrl, provider: "lan", failures: [] };
13
19
  const { relay, relayUrl: configuredUrl } = options.cli;
14
20
  const relayUrl = configuredUrl ?? (relay === "auto" || relay === "self-hosted" ? readDefaultRelayUrl() : null);
15
- const providerName = relay === "auto" ? (relayUrl ? "self-hosted" : "cloudflare") : relay;
21
+ const providerName = resolveRelayProvider(options.cli, relayUrl);
16
22
  const failures = [];
17
23
  const readiness = options.readiness ?? waitForPublicReadiness;
18
24
  options.onStage?.("connecting");
@@ -1,10 +1,14 @@
1
1
  import { setTimeout as delay } from "node:timers/promises";
2
- import { selectRelay } from "./relay-orchestrator.js";
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";
3
6
  /** Owns only the public route. Server, agents and terminals have a separate lifetime. */
4
7
  export class TunnelController {
5
8
  options;
6
9
  abort = new AbortController();
7
10
  selection = null;
11
+ pairingRelays = new Map();
8
12
  pending = null;
9
13
  stopped = false;
10
14
  observers = new Set();
@@ -17,6 +21,66 @@ export class TunnelController {
17
21
  this.state = { ...this.state, phase: "unsupported", error: "测试模式不支持公网连接,请以正常配对模式启动服务。" };
18
22
  }
19
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
+ }
20
84
  subscribe(listener) {
21
85
  this.observers.add(listener);
22
86
  listener(this.status());
@@ -136,6 +200,8 @@ export class TunnelController {
136
200
  await this.pending;
137
201
  await this.selection?.tunnel?.close().catch(error => this.report(error));
138
202
  this.selection = null;
203
+ await Promise.allSettled([...this.pairingRelays.values()].map(async (relay) => (await relay).tunnel?.close()));
204
+ this.pairingRelays.clear();
139
205
  await this.writes;
140
206
  this.observers.clear();
141
207
  }
@@ -148,6 +214,18 @@ export function attachTunnelControl(child, controller) {
148
214
  const receive = (message) => {
149
215
  if (message?.type === "agentroam:tunnel-connect")
150
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 : "无法准备所选线路。"));
151
229
  };
152
230
  child.on("message", receive);
153
231
  return () => { unsubscribe(); child.removeListener("message", receive); };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentroam",
3
- "version": "0.2.0-preview.79",
3
+ "version": "0.2.0-preview.80",
4
4
  "description": "Zero-install mobile remote terminal and file console",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,14 +27,14 @@
27
27
  "ws": "^8.21.3"
28
28
  },
29
29
  "optionalDependencies": {
30
- "agentroam-runtime-darwin-arm64": "0.2.0-preview.79",
31
- "agentroam-runtime-win32-x64": "0.2.0-preview.79",
30
+ "agentroam-runtime-darwin-arm64": "0.2.0-preview.80",
31
+ "agentroam-runtime-win32-x64": "0.2.0-preview.80",
32
32
  "agentroam-cloudflared-darwin-arm64": "0.2.0-preview.78",
33
33
  "agentroam-cloudflared-win32-x64": "0.2.0-preview.78",
34
34
  "agentroam-tailscale-darwin-arm64": "0.2.0-preview.77",
35
35
  "agentroam-tailscale-win32-x64": "0.2.0-preview.77",
36
- "agentroam-tui-darwin-arm64": "0.2.0-preview.79",
37
- "@caoqu/agentroam-tui-win32-x64": "0.2.0-preview.79"
36
+ "agentroam-tui-darwin-arm64": "0.2.0-preview.80",
37
+ "@caoqu/agentroam-tui-win32-x64": "0.2.0-preview.80"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/node": "^22.0.0",