agentroam 0.2.0-preview.78 → 0.2.0-preview.79
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 +24 -4
- package/dist/cli.js +40 -2
- package/dist/codex-sharing.js +5 -3
- package/dist/device-pairing.js +35 -12
- package/dist/mesh/mesh-command.js +51 -0
- package/dist/mesh/mesh-config.js +95 -0
- package/dist/mesh/mesh-payload.js +20 -0
- package/dist/mesh/mesh-runtime.js +101 -0
- package/dist/platform-packages.js +2 -0
- package/dist/runtime-manager.js +10 -1
- package/dist/self-hosted-relay.json +1 -0
- package/dist/service/service-command.js +8 -1
- package/dist/service/service-controller.js +2 -0
- package/dist/tailscale/bundled-asset.js +43 -0
- package/dist/tailscale/daemon-manager.js +112 -0
- package/dist/tailscale/installer.js +131 -0
- package/dist/tailscale/manifest.js +15 -0
- package/dist/tailscale/tailnet-cli.js +101 -0
- package/dist/tunnel/relay-orchestrator.js +43 -37
- package/dist/tunnel/self-hosted-provider.js +147 -0
- package/dist/tunnel/tunnel-controller.js +10 -0
- package/dist/update/update-command.js +1 -0
- package/dist/update/update-worker.js +2 -0
- package/install/write-relay-default.mjs +6 -0
- package/package.json +8 -6
package/dist/args.js
CHANGED
|
@@ -3,12 +3,20 @@ import { resolve } from "node:path";
|
|
|
3
3
|
export function parseArgs(argv) {
|
|
4
4
|
const values = [...argv];
|
|
5
5
|
let command = "start";
|
|
6
|
-
if (values[0] && ["start", "doctor", "version", "service", "unlock-service", "update", "update-worker", "pair", "devices", "revoke", "approvals", "approve", "deny", "lock", "unlock", "audit", "codex-desktop", "desktop"].includes(values[0])) {
|
|
6
|
+
if (values[0] && ["start", "doctor", "version", "service", "unlock-service", "update", "update-worker", "pair", "devices", "revoke", "approvals", "approve", "deny", "lock", "unlock", "audit", "codex-desktop", "desktop", "mesh"].includes(values[0])) {
|
|
7
7
|
command = values.shift();
|
|
8
8
|
}
|
|
9
9
|
let serviceAction = null;
|
|
10
10
|
let unlockServiceAction = null;
|
|
11
11
|
let desktopAction;
|
|
12
|
+
let meshAction;
|
|
13
|
+
if (command === "mesh") {
|
|
14
|
+
const action = values.shift();
|
|
15
|
+
if (!action || !["status", "onboard", "offboard", "qr", "nodes"].includes(action)) {
|
|
16
|
+
throw cliError("mesh requires status, onboard, offboard, qr, or nodes");
|
|
17
|
+
}
|
|
18
|
+
meshAction = action;
|
|
19
|
+
}
|
|
12
20
|
if (command === "desktop") {
|
|
13
21
|
const action = values.shift();
|
|
14
22
|
if (!action || !["authorize", "status", "disable"].includes(action))
|
|
@@ -75,12 +83,16 @@ export function parseArgs(argv) {
|
|
|
75
83
|
updateVersion,
|
|
76
84
|
updateStateFile,
|
|
77
85
|
...(desktopAction ? { desktopAction } : {}),
|
|
86
|
+
...(meshAction ? { meshAction } : {}),
|
|
78
87
|
};
|
|
79
88
|
for (let index = 0; index < values.length && command !== "update-worker"; index++) {
|
|
80
89
|
const arg = values[index];
|
|
81
90
|
if (command === "desktop" && !["--data-dir", "--help", "-h"].includes(arg)) {
|
|
82
91
|
throw cliError("desktop accepts only --data-dir");
|
|
83
92
|
}
|
|
93
|
+
if (command === "mesh" && !["--data-dir", "--node-name", "--no-qr", "--help", "-h"].includes(arg)) {
|
|
94
|
+
throw cliError("mesh accepts only --data-dir, --node-name and --no-qr");
|
|
95
|
+
}
|
|
84
96
|
if (command === "codex-desktop" && !["--restart", "--dry-run", "--setup", "--status", "--repair", "--data-dir", "--help", "-h"].includes(arg)) {
|
|
85
97
|
throw cliError("codex-desktop accepts only --setup, --restart, --dry-run, --status, --repair and --data-dir");
|
|
86
98
|
}
|
|
@@ -104,6 +116,12 @@ export function parseArgs(argv) {
|
|
|
104
116
|
options.desktopSetup = true;
|
|
105
117
|
else if (arg === "--url" && command === "pair")
|
|
106
118
|
options.pairingUrl = next();
|
|
119
|
+
else if (arg === "--node-name" && command === "mesh") {
|
|
120
|
+
const name = next();
|
|
121
|
+
if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(name))
|
|
122
|
+
throw cliError("node name must be 1-63 letters, digits or hyphens and cannot start or end with a hyphen");
|
|
123
|
+
options.meshNodeName = name;
|
|
124
|
+
}
|
|
107
125
|
else if (arg === "--root")
|
|
108
126
|
options.roots.push(resolve(next()));
|
|
109
127
|
else if (arg === "--port") {
|
|
@@ -114,11 +132,13 @@ export function parseArgs(argv) {
|
|
|
114
132
|
}
|
|
115
133
|
else if (arg === "--relay") {
|
|
116
134
|
const relay = next();
|
|
117
|
-
if (!["auto", "cloudflare", "pinggy", "custom"].includes(relay)) {
|
|
118
|
-
throw cliError("relay must be auto, cloudflare, pinggy, or
|
|
135
|
+
if (!["auto", "cloudflare", "pinggy", "custom", "self-hosted"].includes(relay)) {
|
|
136
|
+
throw cliError("relay must be auto, cloudflare, pinggy, custom, or self-hosted");
|
|
119
137
|
}
|
|
120
138
|
options.relay = relay;
|
|
121
139
|
}
|
|
140
|
+
else if (arg === "--relay-url")
|
|
141
|
+
options.relayUrl = next();
|
|
122
142
|
else if (arg === "--tunnel-command")
|
|
123
143
|
options.tunnelCommand = next();
|
|
124
144
|
else if (arg === "--data-dir")
|
|
@@ -148,7 +168,7 @@ export function parseArgs(argv) {
|
|
|
148
168
|
if (command === "update" && updateVersion && !/^\d+\.\d+\.\d+$/.test(updateVersion)) {
|
|
149
169
|
throw cliError("update version must be an exact stable X.Y.Z version");
|
|
150
170
|
}
|
|
151
|
-
if (options.testNoPairing && (command !== "start" || !options.localOnly || options.tunnelCommand || options.relay !== "auto"))
|
|
171
|
+
if (options.testNoPairing && (command !== "start" || !options.localOnly || options.tunnelCommand || options.relayUrl || options.relay !== "auto"))
|
|
152
172
|
throw cliError("--test-no-pairing requires start --local-only and cannot use a tunnel or background service");
|
|
153
173
|
if (!options.roots.length)
|
|
154
174
|
options.roots = [process.cwd()];
|
package/dist/cli.js
CHANGED
|
@@ -26,6 +26,8 @@ import { createCliErrorLog } from "./error-log.js";
|
|
|
26
26
|
import { runCodexDesktopCommand } from "./codex-desktop-command.js";
|
|
27
27
|
import { setupCodexDesktop } from "./codex-desktop-setup.js";
|
|
28
28
|
import { runDesktopCommand } from "./desktop-authorization.js";
|
|
29
|
+
import { runMeshCommand } from "./mesh/mesh-command.js";
|
|
30
|
+
import { attachMeshControl, createMeshRuntime } from "./mesh/mesh-runtime.js";
|
|
29
31
|
import { withCliProgress } from "../bin/cli-progress.mjs";
|
|
30
32
|
const VERSION = AGENTROAM_VERSION;
|
|
31
33
|
export async function main(argv) {
|
|
@@ -36,6 +38,7 @@ export async function main(argv) {
|
|
|
36
38
|
if (argv.includes("--help") || argv.includes("-h")) {
|
|
37
39
|
console.log(`AgentRoam
|
|
38
40
|
agentroam [start] [--local-only] [--test-no-pairing] [--data-dir PATH]
|
|
41
|
+
agentroam start --relay self-hosted --relay-url https://connect.example.com
|
|
39
42
|
agentroam pair 生成一次性设备配对码
|
|
40
43
|
agentroam pair --url <服务器地址> 生成 App 扫码直连授权(终端显示)
|
|
41
44
|
agentroam approvals 查看待批准请求和核对短语
|
|
@@ -48,6 +51,12 @@ export async function main(argv) {
|
|
|
48
51
|
agentroam revoke <设备ID> 移除一台设备
|
|
49
52
|
agentroam revoke --all 全部退出并取消待用配对码
|
|
50
53
|
agentroam service install|start|stop|restart|status|url|logs|uninstall
|
|
54
|
+
首次启动时通过 AGENTROAM_MESH_ACTIVATION_CODE 提供一次性组网激活码
|
|
55
|
+
agentroam mesh status 查看组网入网状态
|
|
56
|
+
agentroam mesh onboard 加入自建 Headscale 控制面(安装后自动执行)
|
|
57
|
+
agentroam mesh qr 生成手机加入组网的一次性二维码(15 分钟)
|
|
58
|
+
agentroam mesh nodes 查看控制面节点
|
|
59
|
+
agentroam mesh offboard 退出组网并清除本机入网状态
|
|
51
60
|
agentroam desktop authorize 本机弹窗授权远程桌面,无需浏览器;可重复执行
|
|
52
61
|
agentroam desktop status 重新检查远程桌面权限和共享状态
|
|
53
62
|
agentroam desktop disable 关闭远程桌面共享,保留系统权限
|
|
@@ -130,6 +139,17 @@ async function executeCommand(options, argv) {
|
|
|
130
139
|
await runDesktopCommand(options);
|
|
131
140
|
return;
|
|
132
141
|
}
|
|
142
|
+
if (options.command === "mesh") {
|
|
143
|
+
if (!argv.includes("--data-dir"))
|
|
144
|
+
options.dataDir = await installedDataDir(options.dataDir);
|
|
145
|
+
await runMeshCommand({
|
|
146
|
+
action: options.meshAction,
|
|
147
|
+
dataDir: options.dataDir,
|
|
148
|
+
nodeName: options.meshNodeName,
|
|
149
|
+
qr: options.qr,
|
|
150
|
+
});
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
133
153
|
if (options.command === "codex-desktop") {
|
|
134
154
|
if (!argv.includes("--data-dir"))
|
|
135
155
|
options.dataDir = await installedDataDir(options.dataDir);
|
|
@@ -165,6 +185,9 @@ async function executeCommand(options, argv) {
|
|
|
165
185
|
const controller = new AbortController();
|
|
166
186
|
let runtime = null;
|
|
167
187
|
let tunnel = null;
|
|
188
|
+
let mesh;
|
|
189
|
+
let meshOnboarding;
|
|
190
|
+
let detachMesh;
|
|
168
191
|
let detachTunnel;
|
|
169
192
|
let closing = false;
|
|
170
193
|
let releaseStartup;
|
|
@@ -180,6 +203,8 @@ async function executeCommand(options, argv) {
|
|
|
180
203
|
controller.abort();
|
|
181
204
|
closePromise = withCliProgress("Stopping local service and connections", async () => {
|
|
182
205
|
detachTunnel?.();
|
|
206
|
+
detachMesh?.();
|
|
207
|
+
await mesh?.close();
|
|
183
208
|
await tunnel?.close().catch(() => { });
|
|
184
209
|
await runtime?.close().catch(() => { });
|
|
185
210
|
});
|
|
@@ -202,6 +227,13 @@ async function executeCommand(options, argv) {
|
|
|
202
227
|
}
|
|
203
228
|
void runtime.exited.then(() => controller.abort());
|
|
204
229
|
await serviceReporter?.localReady(runtime.localUrl);
|
|
230
|
+
if (!options.testNoPairing) {
|
|
231
|
+
mesh = createMeshRuntime({ dataDir: options.dataDir, localUrl: runtime.localUrl, target });
|
|
232
|
+
detachMesh = attachMeshControl(runtime.process, mesh);
|
|
233
|
+
meshOnboarding = mesh.run("onboard", undefined, true)
|
|
234
|
+
.catch(error => { if (!closing)
|
|
235
|
+
console.error(`⚠ 组网自动入网未完成:${error.message}`); });
|
|
236
|
+
}
|
|
205
237
|
const relayRuntime = runtime;
|
|
206
238
|
tunnel = new TunnelController({
|
|
207
239
|
relay: {
|
|
@@ -244,8 +276,12 @@ async function executeCommand(options, argv) {
|
|
|
244
276
|
else {
|
|
245
277
|
console.log(`\nOpen: ${accessUrl}`);
|
|
246
278
|
printLocalDesktopUrl(runtime.localUrl);
|
|
247
|
-
if (!options.testNoPairing)
|
|
248
|
-
await
|
|
279
|
+
if (!options.testNoPairing) {
|
|
280
|
+
await meshOnboarding;
|
|
281
|
+
if (controller.signal.aborted)
|
|
282
|
+
return;
|
|
283
|
+
await printPairingCode(options.dataDir, console.log, { signal: controller.signal, fallbackUrl: accessUrl, qr: options.qr });
|
|
284
|
+
}
|
|
249
285
|
console.log("Ctrl+C stops the tunnel and local server.");
|
|
250
286
|
}
|
|
251
287
|
await Promise.race([
|
|
@@ -329,6 +365,8 @@ function reportDoctorFailure(error, prefix = "") {
|
|
|
329
365
|
process.exitCode = 1;
|
|
330
366
|
}
|
|
331
367
|
function providerDisplayName(provider) {
|
|
368
|
+
if (provider === "self-hosted")
|
|
369
|
+
return "自建 HTTPS";
|
|
332
370
|
if (provider === "cloudflare")
|
|
333
371
|
return "Cloudflare";
|
|
334
372
|
if (provider === "pinggy")
|
package/dist/codex-sharing.js
CHANGED
|
@@ -135,14 +135,16 @@ export async function inspectCodexSharing(context = {}) {
|
|
|
135
135
|
if (!result.daemonReachable)
|
|
136
136
|
return result;
|
|
137
137
|
const socket = await realpath(paths.socketPath);
|
|
138
|
-
|
|
138
|
+
// ChatGPT can connect through a bundled helper instead of its main process.
|
|
139
|
+
const desktopPids = new Set([desktop.pid, ...processes.filter(p => p.parent === desktop.pid && p.command.startsWith(`${desktop.appPath}/Contents/`)).map(p => p.pid)]);
|
|
140
|
+
const pids = [...desktopPids, ...processes.filter(p => /\bapp-server\b/.test(p.command) && /\bcodex\b/.test(p.command)).map(p => p.pid)];
|
|
139
141
|
const sockets = await execute("/usr/sbin/lsof", ["-nP", "-a", "-p", [...new Set(pids)].join(","), "-U"], commandOptions);
|
|
140
142
|
const rows = String(sockets.stdout).split("\n").flatMap(line => {
|
|
141
143
|
const match = /^\S+\s+(\d+)\s+\S+\s+\S+\s+unix\s+(0x[\da-f]+)\s+\S+\s+(.*)$/i.exec(line);
|
|
142
144
|
return match ? [{ pid: Number(match[1]), device: match[2], name: match[3].trim() }] : [];
|
|
143
145
|
});
|
|
144
|
-
const devices = new Set(rows.filter(row => row.pid
|
|
145
|
-
if (rows.some(row => row.pid
|
|
146
|
+
const devices = new Set(rows.filter(row => !desktopPids.has(row.pid) && row.name === socket).map(row => row.device));
|
|
147
|
+
if (rows.some(row => desktopPids.has(row.pid) && row.name.startsWith("->") && devices.has(row.name.slice(2)))) {
|
|
146
148
|
return { ...result, state: "shared", message: "Codex 已连接共享后台。" };
|
|
147
149
|
}
|
|
148
150
|
return { ...result, message: "共享后台可用,但尚未确认 Codex 连接。请在任务结束时退出,再用 头像菜单或 agentroam codex-desktop 启动。" };
|
package/dist/device-pairing.js
CHANGED
|
@@ -31,21 +31,21 @@ export function pairingQrPayload(accessUrl, grant) {
|
|
|
31
31
|
return `${url.origin}/pair#pair=${grant}`;
|
|
32
32
|
}
|
|
33
33
|
export async function printPairingCode(dataDir, log = console.log, options = {}) {
|
|
34
|
+
const interactiveQr = (options.qr ?? true) && (options.interactive ?? process.stdout.isTTY);
|
|
35
|
+
if (interactiveQr && options.accessUrl === undefined) {
|
|
36
|
+
const relay = await localServiceRequest(dataDir, "/api/desktop/tunnel", { signal: options.signal }).catch(() => null);
|
|
37
|
+
if (relay?.phase === "ready" && relay.provider === "self-hosted" && relay.accessUrl) {
|
|
38
|
+
await printPairingQr(dataDir, relay.accessUrl, log);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
34
42
|
const result = await withCliProgress("Generating device pairing code", () => pairingAdmin(dataDir, "code"));
|
|
35
43
|
log(`Pairing code: ${result.code.slice(0, 4)} ${result.code.slice(4)}`);
|
|
36
44
|
log("Valid for 5 minutes, single use. After entering it on your phone, confirm the verification phrase on this computer.");
|
|
37
|
-
if (
|
|
38
|
-
const accessUrl =
|
|
39
|
-
if (accessUrl)
|
|
40
|
-
|
|
41
|
-
pairingQrPayload(accessUrl, "a".repeat(43));
|
|
42
|
-
const qr = await withCliProgress("Generating phone connection QR code", async () => {
|
|
43
|
-
const { grant } = await pairingAdmin(dataDir, "qr");
|
|
44
|
-
return renderQr(pairingQrPayload(accessUrl, grant));
|
|
45
|
-
});
|
|
46
|
-
log("Scan with your phone to connect (valid for 5 minutes, single use; do not share screenshots):");
|
|
47
|
-
log(qr);
|
|
48
|
-
}
|
|
45
|
+
if (interactiveQr) {
|
|
46
|
+
const accessUrl = await resolvePairingAccessUrl(dataDir, options);
|
|
47
|
+
if (accessUrl)
|
|
48
|
+
await printPairingQr(dataDir, accessUrl, log);
|
|
49
49
|
else
|
|
50
50
|
log("Generate an app authorization QR code: agentroam pair --url <phone-accessible-server-url>");
|
|
51
51
|
}
|
|
@@ -56,6 +56,29 @@ export async function printPairingCode(dataDir, log = console.log, options = {})
|
|
|
56
56
|
else
|
|
57
57
|
log("View requests: agentroam approvals; approve: agentroam approve <request-id> --phrase <phone-verification-phrase>");
|
|
58
58
|
}
|
|
59
|
+
async function printPairingQr(dataDir, accessUrl, log) {
|
|
60
|
+
pairingQrPayload(accessUrl, "a".repeat(43));
|
|
61
|
+
const qr = await withCliProgress("Generating phone connection QR code", async () => {
|
|
62
|
+
const { grant } = await pairingAdmin(dataDir, "qr");
|
|
63
|
+
return renderQr(pairingQrPayload(accessUrl, grant));
|
|
64
|
+
});
|
|
65
|
+
log("Scan with your phone to connect (valid for 5 minutes, single use; do not share screenshots):");
|
|
66
|
+
log(qr);
|
|
67
|
+
}
|
|
68
|
+
export async function resolvePairingAccessUrl(dataDir, options = {}) {
|
|
69
|
+
if (options.accessUrl !== undefined)
|
|
70
|
+
return options.accessUrl;
|
|
71
|
+
const readMesh = () => localServiceRequest(dataDir, "/api/mesh/status", { signal: options.signal }).catch(() => null);
|
|
72
|
+
const deadline = Date.now() + 20_000;
|
|
73
|
+
let mesh = await readMesh();
|
|
74
|
+
while (options.waitForMesh && mesh?.phase === "ready" && Date.now() < deadline) {
|
|
75
|
+
await delay(400, undefined, { signal: options.signal });
|
|
76
|
+
mesh = await readMesh();
|
|
77
|
+
}
|
|
78
|
+
if (mesh?.phase === "joined" && mesh.accessUrl)
|
|
79
|
+
return mesh.accessUrl;
|
|
80
|
+
return options.fallbackUrl ?? await readFile(join(dataDir, "tunnel.url"), "utf8").then(value => value.trim(), () => null);
|
|
81
|
+
}
|
|
59
82
|
/** Open the controlling terminal (`/dev/tty`) — the same source install-agentroam.sh reads from. */
|
|
60
83
|
function openControllingTerminal() {
|
|
61
84
|
if (process.platform === "win32")
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { renderQr } from "../qr.js";
|
|
2
|
+
import { localServiceRequest } from "../local-service-request.js";
|
|
3
|
+
import { meshQrPayload } from "./mesh-payload.js";
|
|
4
|
+
export { meshQrPayload };
|
|
5
|
+
export async function runMeshCommand(options) {
|
|
6
|
+
if (options.action === "status")
|
|
7
|
+
return printStatus(options);
|
|
8
|
+
if (options.action === "nodes")
|
|
9
|
+
return printNodes(options);
|
|
10
|
+
if (options.action === "qr")
|
|
11
|
+
return printJoinQr(options);
|
|
12
|
+
await localServiceRequest(options.dataDir, `/api/mesh/admin/${options.action}`, {
|
|
13
|
+
method: "POST", body: { nodeName: options.nodeName }, timeoutMs: 125_000,
|
|
14
|
+
});
|
|
15
|
+
await printStatus(options);
|
|
16
|
+
}
|
|
17
|
+
async function printStatus(options) {
|
|
18
|
+
const status = await localServiceRequest(options.dataDir, "/api/mesh/status");
|
|
19
|
+
console.log(`控制面:${status.configured ? status.controlPlaneUrl : "未配置(使用一次性激活码启动,或配置自管 Headscale 后重启服务)"}`);
|
|
20
|
+
console.log(`状态:${status.phase}${status.lastError ? `(${status.lastError})` : ""}`);
|
|
21
|
+
if (status.hostname)
|
|
22
|
+
console.log(`设备:${status.hostname}`);
|
|
23
|
+
if (status.tailnetIPv4)
|
|
24
|
+
console.log(`Tailnet IP:${status.tailnetIPv4}`);
|
|
25
|
+
if (status.phase === "joined" && status.dnsName)
|
|
26
|
+
console.log(`网关地址:http://${status.dnsName}`);
|
|
27
|
+
if (status.user)
|
|
28
|
+
console.log(`Headscale 用户:${status.user}`);
|
|
29
|
+
if (status.joinedAt)
|
|
30
|
+
console.log(`入网时间:${new Date(status.joinedAt).toLocaleString()}`);
|
|
31
|
+
}
|
|
32
|
+
async function printNodes(options) {
|
|
33
|
+
const { nodes } = await localServiceRequest(options.dataDir, "/api/mesh/admin/nodes");
|
|
34
|
+
console.log(nodes.length
|
|
35
|
+
? nodes.map((node) => `${node.id} ${node.name} ${node.user ?? "-"}`).join("\n")
|
|
36
|
+
: "控制面上暂无节点");
|
|
37
|
+
}
|
|
38
|
+
async function printJoinQr(options) {
|
|
39
|
+
const issued = await localServiceRequest(options.dataDir, "/api/mesh/admin/key", {
|
|
40
|
+
method: "POST",
|
|
41
|
+
body: { device: "phone", nodeName: options.nodeName }, timeoutMs: 60_000,
|
|
42
|
+
});
|
|
43
|
+
const payload = meshQrPayload(issued);
|
|
44
|
+
console.log("手机加入组网(一次性,15 分钟内有效;请勿截图分享):");
|
|
45
|
+
if (options.qr !== false && process.stdout.isTTY)
|
|
46
|
+
console.log(await renderQr(payload));
|
|
47
|
+
console.log(`\n控制面地址:${issued.loginServer}`);
|
|
48
|
+
console.log(`认证 key:${issued.authkey}`);
|
|
49
|
+
console.log("在 Tailscale 客户端选择自定义控制面,使用以上认证 key 注册设备。");
|
|
50
|
+
console.log(`入网后生成 AgentRoam App 授权码:agentroam pair`);
|
|
51
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { link, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { writePrivateJson } from "../service/service-files.js";
|
|
5
|
+
const DEFAULT_CONTROL_PLANE = "https://headscale.kaiwuyouwei.com";
|
|
6
|
+
const SECRET = /^[A-Za-z0-9_-]{43}$/;
|
|
7
|
+
function configPath(dataDir) {
|
|
8
|
+
return join(dataDir, "mesh", "control-plane.json");
|
|
9
|
+
}
|
|
10
|
+
export async function saveMeshEnvironment(dataDir, env) {
|
|
11
|
+
const url = env.AGENT_HEADSCALE_URL?.trim();
|
|
12
|
+
const apiKey = env.AGENT_HEADSCALE_API_KEY?.trim();
|
|
13
|
+
const code = env.AGENTROAM_MESH_ACTIVATION_CODE?.trim();
|
|
14
|
+
if (code) {
|
|
15
|
+
if (apiKey || env.AGENTROAM_MESH_CREDENTIAL)
|
|
16
|
+
throw new Error("组网激活码不能与其他组网凭据同时使用");
|
|
17
|
+
await activateMesh(dataDir, url ?? DEFAULT_CONTROL_PLANE, code);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (!url && !apiKey)
|
|
21
|
+
return;
|
|
22
|
+
if (!url || !apiKey)
|
|
23
|
+
throw new Error("请同时设置 AGENT_HEADSCALE_URL 和 AGENT_HEADSCALE_API_KEY");
|
|
24
|
+
await writePrivateJson(configPath(dataDir), { url, apiKey });
|
|
25
|
+
}
|
|
26
|
+
/** Keep the same credential after a lost activation response. The code itself is never stored. */
|
|
27
|
+
async function activateMesh(dataDir, url, code) {
|
|
28
|
+
const plane = new URL(url);
|
|
29
|
+
if (plane.protocol !== "https:" || plane.username || plane.password || plane.pathname !== "/" || plane.search || plane.hash) {
|
|
30
|
+
throw new Error("组网激活需要 HTTPS 控制面地址");
|
|
31
|
+
}
|
|
32
|
+
if (!SECRET.test(code))
|
|
33
|
+
throw new Error("无效的组网激活码");
|
|
34
|
+
const path = configPath(dataDir);
|
|
35
|
+
if (!await readMeshConfig(dataDir)) {
|
|
36
|
+
const temporary = `${path}.${randomBytes(8).toString("hex")}.pending`;
|
|
37
|
+
await writePrivateJson(temporary, { url: plane.origin, credential: randomBytes(32).toString("base64url") });
|
|
38
|
+
try {
|
|
39
|
+
await link(temporary, path);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.code !== "EEXIST")
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
await rm(temporary, { force: true });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const config = await readMeshConfig(dataDir);
|
|
50
|
+
if (config?.url !== plane.origin || !config.credential)
|
|
51
|
+
throw new Error("此数据目录已有其他组网配置");
|
|
52
|
+
if (config.activated)
|
|
53
|
+
return;
|
|
54
|
+
const response = await fetch(new URL("/agentroam-enrollment/v1/activate", plane), {
|
|
55
|
+
method: "POST",
|
|
56
|
+
headers: { authorization: `Bearer ${config.credential}`, "content-type": "application/json" },
|
|
57
|
+
body: JSON.stringify({ code }),
|
|
58
|
+
redirect: "error", signal: AbortSignal.timeout(10_000),
|
|
59
|
+
});
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
if ([400, 403].includes(response.status)) {
|
|
62
|
+
throw new Error("组网激活码已失效、无效或已被另一台设备使用");
|
|
63
|
+
}
|
|
64
|
+
throw new Error(`组网激活失败 (HTTP ${response.status})`);
|
|
65
|
+
}
|
|
66
|
+
await writePrivateJson(path, { ...config, activated: true });
|
|
67
|
+
}
|
|
68
|
+
async function readMeshConfig(dataDir) {
|
|
69
|
+
const raw = await readFile(configPath(dataDir), "utf8").catch(error => {
|
|
70
|
+
if (error.code === "ENOENT")
|
|
71
|
+
return null;
|
|
72
|
+
throw error;
|
|
73
|
+
});
|
|
74
|
+
if (raw === null)
|
|
75
|
+
return null;
|
|
76
|
+
try {
|
|
77
|
+
const config = JSON.parse(raw);
|
|
78
|
+
if (typeof config?.url === "string" && (typeof config.apiKey === "string" || (typeof config.credential === "string" && SECRET.test(config.credential))))
|
|
79
|
+
return config;
|
|
80
|
+
}
|
|
81
|
+
catch { /* Report a malformed private config without its contents. */ }
|
|
82
|
+
throw new Error("无法读取组网控制面配置");
|
|
83
|
+
}
|
|
84
|
+
export async function loadMeshEnvironment(dataDir, env) {
|
|
85
|
+
if (env.AGENTROAM_MESH_ACTIVATION_CODE?.trim())
|
|
86
|
+
await saveMeshEnvironment(dataDir, env);
|
|
87
|
+
else if (env.AGENT_HEADSCALE_URL !== undefined || env.AGENT_HEADSCALE_API_KEY !== undefined || env.AGENTROAM_MESH_CREDENTIAL !== undefined)
|
|
88
|
+
return {};
|
|
89
|
+
const config = await readMeshConfig(dataDir);
|
|
90
|
+
if (config?.apiKey)
|
|
91
|
+
return { AGENT_HEADSCALE_URL: config.url, AGENT_HEADSCALE_API_KEY: config.apiKey };
|
|
92
|
+
if (config?.activated && config.credential)
|
|
93
|
+
return { AGENT_HEADSCALE_URL: config.url, AGENTROAM_MESH_CREDENTIAL: config.credential };
|
|
94
|
+
return {};
|
|
95
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
/**
|
|
3
|
+
* 纯函数层(无子进程、无二维码依赖),便于在 CLI 之外复用与单测:
|
|
4
|
+
* 机器标识、扫码载荷、本机服务地址发现。
|
|
5
|
+
*/
|
|
6
|
+
/** 机器标识:与 headscale user 命名一一对应(agentroam-<id>)。 */
|
|
7
|
+
export function meshMachineId(host = hostname()) {
|
|
8
|
+
return host.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32).replace(/-+$/g, "") || "local";
|
|
9
|
+
}
|
|
10
|
+
/** 手机扫码载荷:JSON,官方客户端 M2 手工输入,M3 内嵌客户端直接解析。 */
|
|
11
|
+
export function meshQrPayload(input) {
|
|
12
|
+
return JSON.stringify({
|
|
13
|
+
type: "agentroam-mesh",
|
|
14
|
+
version: 1,
|
|
15
|
+
loginServer: input.loginServer,
|
|
16
|
+
authkey: input.authkey,
|
|
17
|
+
...(input.accessUrl ? { accessUrl: input.accessUrl } : {}),
|
|
18
|
+
...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { isIPv4 } from "node:net";
|
|
2
|
+
import { localServiceRequest } from "../local-service-request.js";
|
|
3
|
+
import { TailscaleDaemon } from "../tailscale/daemon-manager.js";
|
|
4
|
+
import { ensureTailscaleBinaries } from "../tailscale/installer.js";
|
|
5
|
+
import { readTailscaleStatus, tailscaleLogout, tailscaleServe, tailscaleServeReset, tailscaleUp } from "../tailscale/tailnet-cli.js";
|
|
6
|
+
import { meshMachineId } from "./mesh-payload.js";
|
|
7
|
+
export function createMeshRuntime({ dataDir, localUrl, target, log }) {
|
|
8
|
+
const controller = new AbortController();
|
|
9
|
+
const { signal } = controller;
|
|
10
|
+
let daemon;
|
|
11
|
+
let pending = Promise.resolve();
|
|
12
|
+
const request = (action, body) => localServiceRequest(dataDir, `/api/mesh/${action}`, body === undefined
|
|
13
|
+
? { signal } : { signal, method: "POST", body, timeoutMs: 60_000 });
|
|
14
|
+
async function apply(action, requestedName, automatic = false) {
|
|
15
|
+
signal.throwIfAborted();
|
|
16
|
+
const state = await request("status");
|
|
17
|
+
if (!state.configured) {
|
|
18
|
+
if (automatic)
|
|
19
|
+
return;
|
|
20
|
+
throw new Error("请先用激活码配置组网并重启 AgentRoam");
|
|
21
|
+
}
|
|
22
|
+
if (automatic && state.phase === "offboarded")
|
|
23
|
+
return;
|
|
24
|
+
if (action === "offboard" && state.phase === "offboarded")
|
|
25
|
+
return;
|
|
26
|
+
try {
|
|
27
|
+
const binaries = await ensureTailscaleBinaries(target, dataDir);
|
|
28
|
+
signal.throwIfAborted();
|
|
29
|
+
daemon ??= new TailscaleDaemon({ dataDir, tailscaledPath: binaries.tailscaled, signal, onLog: log });
|
|
30
|
+
const cli = { tailscalePath: binaries.tailscale, socketPath: daemon.socketPath(), signal };
|
|
31
|
+
const runtime = await daemon.ensureRunning(binaries.tailscale);
|
|
32
|
+
const isRunning = runtime.status.backendState === "Running";
|
|
33
|
+
if (isRunning && runtime.status.controlPlaneUrl !== state.controlPlaneUrl) {
|
|
34
|
+
throw new Error("已加入的控制面与当前配置不同,请先恢复原配置并退出组网");
|
|
35
|
+
}
|
|
36
|
+
if (action === "offboard") {
|
|
37
|
+
try {
|
|
38
|
+
await tailscaleServeReset(cli);
|
|
39
|
+
if (isRunning)
|
|
40
|
+
await tailscaleLogout(cli);
|
|
41
|
+
await request("admin/left", {});
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
await daemon.stop();
|
|
45
|
+
}
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const name = requestedName ?? meshMachineId(runtime.status.hostname ?? undefined);
|
|
49
|
+
if (!isRunning) {
|
|
50
|
+
const issued = await request("admin/key", { device: "desktop", nodeName: name });
|
|
51
|
+
await tailscaleUp(cli, { loginServer: issued.loginServer, authKey: issued.authkey, hostname: name, stateDir: runtime.stateDir });
|
|
52
|
+
}
|
|
53
|
+
const status = await readTailscaleStatus(cli);
|
|
54
|
+
const tailnetIPv4 = status.tailscaleIPs.find(ip => {
|
|
55
|
+
if (!isIPv4(ip))
|
|
56
|
+
return false;
|
|
57
|
+
const [network, subnet] = ip.split(".").map(Number);
|
|
58
|
+
return network === 100 && subnet >= 64 && subnet <= 127;
|
|
59
|
+
});
|
|
60
|
+
if (status.backendState !== "Running" || !tailnetIPv4)
|
|
61
|
+
throw new Error("入网未完成,未获得组网 IPv4 地址");
|
|
62
|
+
if (!status.dnsName)
|
|
63
|
+
throw new Error("Headscale 未提供 MagicDNS 地址,请检查控制面配置");
|
|
64
|
+
await tailscaleServe(cli, localUrl);
|
|
65
|
+
await request("admin/report", { hostname: status.hostname ? meshMachineId(status.hostname) : name, tailnetIPv4, dnsName: status.dnsName });
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (!signal.aborted) {
|
|
69
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
70
|
+
await request("admin/error", { message }).catch(() => { });
|
|
71
|
+
}
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
run(action, name, automatic = false) {
|
|
77
|
+
const operation = pending.then(() => apply(action, name, automatic));
|
|
78
|
+
pending = operation.catch(() => { });
|
|
79
|
+
return operation;
|
|
80
|
+
},
|
|
81
|
+
async close() {
|
|
82
|
+
controller.abort();
|
|
83
|
+
await daemon?.stop();
|
|
84
|
+
await pending;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export function attachMeshControl(child, runtime) {
|
|
89
|
+
const receive = (message) => {
|
|
90
|
+
if (message?.type !== "agentroam:mesh-run" || typeof message.id !== "string" ||
|
|
91
|
+
(message.action !== "onboard" && message.action !== "offboard"))
|
|
92
|
+
return;
|
|
93
|
+
const reply = (error) => {
|
|
94
|
+
if (child.connected)
|
|
95
|
+
child.send({ type: "agentroam:mesh-result", id: message.id, error }, () => { });
|
|
96
|
+
};
|
|
97
|
+
void runtime.run(message.action, message.name).then(() => reply(), error => reply(error instanceof Error ? error.message : String(error)));
|
|
98
|
+
};
|
|
99
|
+
child.on("message", receive);
|
|
100
|
+
return () => child.off("message", receive);
|
|
101
|
+
}
|
|
@@ -15,11 +15,13 @@ export const PLATFORM_PACKAGES = {
|
|
|
15
15
|
"darwin-arm64": {
|
|
16
16
|
runtime: "agentroam-runtime-darwin-arm64",
|
|
17
17
|
cloudflared: "agentroam-cloudflared-darwin-arm64",
|
|
18
|
+
tailscale: "agentroam-tailscale-darwin-arm64",
|
|
18
19
|
tui: "agentroam-tui-darwin-arm64",
|
|
19
20
|
},
|
|
20
21
|
"windows-amd64": {
|
|
21
22
|
runtime: "agentroam-runtime-win32-x64",
|
|
22
23
|
cloudflared: "agentroam-cloudflared-win32-x64",
|
|
24
|
+
tailscale: "agentroam-tailscale-win32-x64",
|
|
23
25
|
tui: "@caoqu/agentroam-tui-win32-x64",
|
|
24
26
|
},
|
|
25
27
|
};
|
package/dist/runtime-manager.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { loadMeshEnvironment } from "./mesh/mesh-config.js";
|
|
1
2
|
import { mkdir } from "node:fs/promises";
|
|
2
3
|
import { delimiter, resolve } from "node:path";
|
|
3
4
|
import { fileURLToPath } from "node:url";
|
|
@@ -29,7 +30,8 @@ export class RuntimeManager {
|
|
|
29
30
|
const port = await findAvailablePort(options.port);
|
|
30
31
|
const dataDir = resolve(options.dataDir);
|
|
31
32
|
await Promise.all(["data", "bin", "cache", "logs"].map((name) => mkdir(resolve(dataDir, name), { recursive: true })));
|
|
32
|
-
const
|
|
33
|
+
const { AGENTROAM_MESH_ACTIVATION_CODE: _, ...runtimeEnvironment } = process.env;
|
|
34
|
+
const childEnvironment = await withCliProgress("正在检查 Agent 组件;缺少 Codex 时自动安装最新版,最多等待 180 秒", () => prepareAgentRuntimeEnvironment(runtimeEnvironment, { dataDir, target }, this.codexResolver, this.report, this.opencodeResolver));
|
|
33
35
|
if (process.platform === "darwin" && childEnvironment.AGENT_CODEX_BIN) {
|
|
34
36
|
try {
|
|
35
37
|
await withTimeout(signal => configureCodexSharing(options, { environment: childEnvironment, signal }), CODEX_SHARING_TIMEOUT_MS, "Codex 共享后台配置超时(10 秒)");
|
|
@@ -50,11 +52,18 @@ export class RuntimeManager {
|
|
|
50
52
|
const { runtimeRoot } = resolvePlatformRuntime(target);
|
|
51
53
|
await repairNativeRuntimePermissions(runtimeRoot);
|
|
52
54
|
const gateway = resolve(runtimeRoot, "ws-server.mjs");
|
|
55
|
+
const meshEnvironment = await loadMeshEnvironment(dataDir, process.env).catch(error => {
|
|
56
|
+
if (process.env.AGENTROAM_MESH_ACTIVATION_CODE?.trim())
|
|
57
|
+
throw error;
|
|
58
|
+
this.report(`组网配置未加载:${error.message}`);
|
|
59
|
+
return {};
|
|
60
|
+
});
|
|
53
61
|
const child = this.supervisor.spawn(process.execPath, [gateway, ...(options.testNoPairing ? ["--test-no-pairing"] : [])], {
|
|
54
62
|
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
|
55
63
|
cwd: runtimeRoot,
|
|
56
64
|
env: {
|
|
57
65
|
...childEnvironment,
|
|
66
|
+
...meshEnvironment,
|
|
58
67
|
NODE_ENV: "production",
|
|
59
68
|
NEXT_DIST_DIR: ".next",
|
|
60
69
|
PORT: String(port),
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"url":"https://connect.kaiwuyouwei.com"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { saveMeshEnvironment } from "../mesh/mesh-config.js";
|
|
1
2
|
import { printLocalDesktopUrl } from '../local-desktop-url.js';
|
|
2
3
|
import { delimiter, dirname, isAbsolute, resolve, win32 } from "node:path";
|
|
3
4
|
import { resolveCodexRuntime } from "../codex-runtime-manager.js";
|
|
@@ -49,6 +50,7 @@ export async function runServiceCommand(options, context) {
|
|
|
49
50
|
catch (error) {
|
|
50
51
|
log(`Codex will be checked and installed during service startup: ${error instanceof Error ? error.message : error}`);
|
|
51
52
|
}
|
|
53
|
+
const relayUrl = options.relayUrl ?? environment.AGENTROAM_HTTPS_RELAY_URL?.trim();
|
|
52
54
|
const config = {
|
|
53
55
|
version: context.version,
|
|
54
56
|
nodePath: context.nodePath,
|
|
@@ -60,6 +62,7 @@ export async function runServiceCommand(options, context) {
|
|
|
60
62
|
port: options.port,
|
|
61
63
|
relay: options.relay,
|
|
62
64
|
tunnelCommand: options.tunnelCommand,
|
|
65
|
+
...(relayUrl ? { relayUrl } : {}),
|
|
63
66
|
localOnly: options.localOnly,
|
|
64
67
|
dataDir: options.dataDir,
|
|
65
68
|
installedAt: now.toISOString(),
|
|
@@ -74,6 +77,7 @@ export async function runServiceCommand(options, context) {
|
|
|
74
77
|
log(`Codex sharing setup incomplete; repair it from the computer menu: ${error instanceof Error ? error.message : error}`);
|
|
75
78
|
}
|
|
76
79
|
}
|
|
80
|
+
await saveMeshEnvironment(options.dataDir, environment);
|
|
77
81
|
const { definition, state } = await withCliProgress("Starting service; Codex: up to 180s, Cloudflare: up to 30s, then LAN fallback", () => controller.install(config));
|
|
78
82
|
log(`✓ AgentRoam service installed: ${definition}`);
|
|
79
83
|
if (state?.status !== "ready" && state?.localUrl)
|
|
@@ -104,7 +108,10 @@ export async function runServiceCommand(options, context) {
|
|
|
104
108
|
if (options.desktopSetup && ["darwin", "win32"].includes(platform)) {
|
|
105
109
|
await withCliProgress("Configuring Codex Desktop sharing", () => (context.desktopSetup ?? setupCodexDesktop)(options, { platform, environment, service: config, log }));
|
|
106
110
|
}
|
|
107
|
-
await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, {
|
|
111
|
+
await (context.pairingPrinter ?? printPairingCode)(options.dataDir, log, {
|
|
112
|
+
fallbackUrl: state.accessUrl, waitForMesh: Boolean(environment.AGENTROAM_MESH_ACTIVATION_CODE?.trim()),
|
|
113
|
+
qr: options.qr, interactive: stdoutIsTTY,
|
|
114
|
+
});
|
|
108
115
|
return;
|
|
109
116
|
}
|
|
110
117
|
case "start": {
|
|
@@ -9,6 +9,8 @@ export function buildStartArguments(config) {
|
|
|
9
9
|
args.push("--local-only");
|
|
10
10
|
else
|
|
11
11
|
args.push("--relay", config.relay);
|
|
12
|
+
if (config.relayUrl)
|
|
13
|
+
args.push("--relay-url", config.relayUrl);
|
|
12
14
|
if (!config.localOnly && config.tunnelCommand)
|
|
13
15
|
args.push("--tunnel-command", config.tunnelCommand);
|
|
14
16
|
args.push("--data-dir", config.dataDir, "--no-qr");
|