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.
- package/README.md +61 -15
- package/bin/agentroam.mjs +10 -1
- package/bin/cli-progress.d.mts +9 -0
- package/bin/cli-progress.mjs +65 -0
- package/bin/desktop-download.mjs +69 -0
- package/bin/node-preflight.mjs +171 -0
- package/bin/node-runtime-policy.json +4 -0
- package/bin/runtime-policy.d.mts +5 -0
- package/bin/runtime-policy.mjs +37 -0
- package/dist/abort.js +25 -0
- package/dist/args.js +136 -5
- package/dist/cli.js +295 -44
- package/dist/cloudflared/bundled-asset.js +3 -2
- package/dist/cloudflared/manifest.js +2 -2
- package/dist/codex-desktop-command.js +70 -0
- package/dist/codex-desktop-force-stop.js +46 -0
- package/dist/codex-desktop-idle-guard.js +15 -0
- package/dist/codex-desktop-preflight.js +63 -0
- package/dist/codex-desktop-probe.js +152 -0
- package/dist/codex-desktop-setup.js +154 -0
- package/dist/codex-desktop-status.js +85 -0
- package/dist/codex-desktop-windows.js +122 -0
- package/dist/codex-runtime-manager.js +368 -0
- package/dist/codex-sharing.js +155 -0
- package/dist/codex-windows-backend-host.js +59 -0
- package/dist/codex-windows-backend.js +120 -0
- package/dist/desktop-authorization-prompt.js +84 -0
- package/dist/desktop-authorization.js +161 -0
- package/dist/device-pairing.js +228 -0
- package/dist/error-log.js +113 -0
- package/dist/instance-takeover.js +143 -0
- package/dist/local-desktop-url.js +8 -0
- package/dist/local-service-request.js +69 -0
- 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/native-runtime.js +68 -0
- package/dist/network.js +46 -3
- package/dist/node-runtime-manager.js +251 -0
- package/dist/opencode-runtime-manager.js +260 -0
- package/dist/platform-packages.js +18 -5
- package/dist/platform.js +6 -4
- package/dist/power/sleep-inhibitor.js +161 -0
- package/dist/runtime-manager.js +139 -19
- package/dist/self-hosted-relay.json +1 -0
- package/dist/service/launcher-cleanup.js +79 -0
- package/dist/service/macos-launch-agent.js +288 -0
- package/dist/service/runtime-state.js +43 -0
- package/dist/service/service-command.js +226 -0
- package/dist/service/service-controller.js +29 -0
- package/dist/service/service-files.js +78 -0
- package/dist/service/windows-service-host.js +59 -0
- package/dist/service/windows-task-service.js +289 -0
- package/dist/startup-lock.js +81 -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/todo-mcp-command.js +27 -0
- package/dist/tunnel/cloudflare-provider.js +4 -1
- package/dist/tunnel/public-readiness.js +76 -50
- package/dist/tunnel/relay-orchestrator.js +53 -19
- package/dist/tunnel/self-hosted-provider.js +147 -0
- package/dist/tunnel/tunnel-controller.js +232 -0
- package/dist/unlock-service.js +105 -0
- package/dist/update/update-channel.js +38 -0
- package/dist/update/update-command.js +97 -0
- package/dist/update/update-install.js +34 -0
- package/dist/update/update-state.js +43 -0
- package/dist/update/update-worker.js +82 -0
- package/install/README.md +55 -0
- package/install/codex-shared-watchdog.sh +16 -0
- package/install/install-agentroam.ps1 +358 -0
- package/install/install-agentroam.sh +457 -0
- package/install/install-manifest.json +15 -0
- package/install/start-codex-desktop-shared.sh +152 -0
- package/install/write-relay-default.mjs +6 -0
- package/package.json +15 -10
- package/dist/args.test.js +0 -27
- package/dist/cloudflared/bundled-asset.test.js +0 -76
- package/dist/cloudflared/installer.test.js +0 -95
- package/dist/native-runtime.test.js +0 -19
- package/dist/network.test.js +0 -20
- package/dist/pairing.js +0 -2
- package/dist/platform-packages.test.js +0 -75
- package/dist/platform.test.js +0 -3
- package/dist/port.test.js +0 -3
- package/dist/process-supervisor.test.js +0 -42
- package/dist/tunnel/cloudflare-provider.test.js +0 -33
- package/dist/tunnel/pinggy-provider.test.js +0 -40
- package/dist/tunnel/proxy-settings.test.js +0 -111
- package/dist/tunnel/public-readiness.test.js +0 -104
- package/dist/tunnel/relay-orchestrator.test.js +0 -72
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
// Self-contained daily error log for the CLI process. The CLI cannot depend
|
|
4
|
+
// on @agent/core (it ships as a thin launcher), so this mirrors the exact
|
|
5
|
+
// NDJSON entry format of core's DailyFileLogger
|
|
6
|
+
// (`{ts, level, source, message, error?, data?}`) into `<dataDir>/logs/`.
|
|
7
|
+
// It records uncaughtException / unhandledRejection so launcher failures are
|
|
8
|
+
// strictly persisted, matching the server/desktop log series.
|
|
9
|
+
const LEVELS = new Set(["debug", "info", "warn", "error", "fatal"]);
|
|
10
|
+
function localDateString(date) {
|
|
11
|
+
const y = date.getFullYear();
|
|
12
|
+
const m = String(date.getMonth() + 1).padStart(2, "0");
|
|
13
|
+
const d = String(date.getDate()).padStart(2, "0");
|
|
14
|
+
return `${y}-${m}-${d}`;
|
|
15
|
+
}
|
|
16
|
+
function serializeError(err) {
|
|
17
|
+
if (err === undefined || err === null)
|
|
18
|
+
return undefined;
|
|
19
|
+
if (err instanceof Error) {
|
|
20
|
+
const out = { name: err.name, message: err.message };
|
|
21
|
+
if (err.stack)
|
|
22
|
+
out.stack = err.stack;
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
if (typeof err === "object") {
|
|
26
|
+
const anyErr = err;
|
|
27
|
+
const out = {
|
|
28
|
+
name: typeof anyErr.name === "string" ? anyErr.name : "NonError",
|
|
29
|
+
message: typeof anyErr.message === "string" ? anyErr.message : String(err),
|
|
30
|
+
};
|
|
31
|
+
if (typeof anyErr.stack === "string")
|
|
32
|
+
out.stack = anyErr.stack;
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
return { name: "NonError", message: String(err) };
|
|
36
|
+
}
|
|
37
|
+
function safeStringify(value) {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.stringify(value) ?? "null";
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return '"[unserializable]"';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function createCliErrorLog(logsDir) {
|
|
46
|
+
let reportedWriteFailure = false;
|
|
47
|
+
const write = (line) => {
|
|
48
|
+
try {
|
|
49
|
+
if (!existsSync(logsDir))
|
|
50
|
+
mkdirSync(logsDir, { recursive: true });
|
|
51
|
+
appendFileSync(join(logsDir, `${localDateString(new Date())}.log`), line, "utf8");
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
if (!reportedWriteFailure) {
|
|
55
|
+
reportedWriteFailure = true;
|
|
56
|
+
try {
|
|
57
|
+
process.stderr.write(`[agentroam] failed to write error log to ${logsDir}; further failures are silent\n`);
|
|
58
|
+
}
|
|
59
|
+
catch { /* stderr gone */ }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const cleanupOldFiles = () => {
|
|
64
|
+
// 30-day retention, aligned with the core logger default. Best effort.
|
|
65
|
+
try {
|
|
66
|
+
if (!existsSync(logsDir))
|
|
67
|
+
return;
|
|
68
|
+
const cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;
|
|
69
|
+
for (const name of readdirSync(logsDir)) {
|
|
70
|
+
if (!/^\d{4}-\d{2}-\d{2}\.log$/.test(name))
|
|
71
|
+
continue;
|
|
72
|
+
const full = join(logsDir, name);
|
|
73
|
+
try {
|
|
74
|
+
if (statSync(full).mtimeMs < cutoff)
|
|
75
|
+
unlinkSync(full);
|
|
76
|
+
}
|
|
77
|
+
catch { /* concurrent removal */ }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch { /* best effort */ }
|
|
81
|
+
};
|
|
82
|
+
const log = (level, message, error, data) => {
|
|
83
|
+
if (!LEVELS.has(level))
|
|
84
|
+
level = "error";
|
|
85
|
+
const entry = {
|
|
86
|
+
ts: new Date().toISOString(),
|
|
87
|
+
level,
|
|
88
|
+
source: "cli",
|
|
89
|
+
message: typeof message === "string" ? message.slice(0, 4000) : String(message),
|
|
90
|
+
};
|
|
91
|
+
const serialized = serializeError(error);
|
|
92
|
+
if (serialized)
|
|
93
|
+
entry.error = serialized;
|
|
94
|
+
if (data !== undefined)
|
|
95
|
+
entry.data = data;
|
|
96
|
+
write(`${safeStringify(entry)}\n`);
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
log,
|
|
100
|
+
installGlobalErrorHandlers: (options = {}) => {
|
|
101
|
+
const exitOnUncaughtException = options.exitOnUncaughtException ?? true;
|
|
102
|
+
process.on("uncaughtException", (err) => {
|
|
103
|
+
log("fatal", "uncaughtException", err);
|
|
104
|
+
if (exitOnUncaughtException)
|
|
105
|
+
process.exit(1);
|
|
106
|
+
});
|
|
107
|
+
process.on("unhandledRejection", (reason) => {
|
|
108
|
+
log("error", "unhandledRejection", reason);
|
|
109
|
+
});
|
|
110
|
+
cleanupOldFiles();
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { readdir, readFile, mkdir, realpath, rename } from "node:fs/promises";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { runCommand } from "./service/service-controller.js";
|
|
7
|
+
import { MacLaunchAgent } from "./service/macos-launch-agent.js";
|
|
8
|
+
import { WindowsTaskService } from "./service/windows-task-service.js";
|
|
9
|
+
function alive(pid) {
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, 0);
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return error.code !== "ESRCH";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function processList() {
|
|
19
|
+
if (process.platform === "win32") {
|
|
20
|
+
const result = await runCommand("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress"]);
|
|
21
|
+
if (result.code !== 0)
|
|
22
|
+
throw new Error("无法核验旧 CLI 进程");
|
|
23
|
+
return JSON.parse(result.stdout).map((p) => ({ pid: p.ProcessId, ppid: p.ParentProcessId, command: p.CommandLine ?? "" }));
|
|
24
|
+
}
|
|
25
|
+
const result = await runCommand("ps", ["-axo", "pid=,ppid=,command="]);
|
|
26
|
+
if (result.code !== 0)
|
|
27
|
+
throw new Error("无法核验旧 CLI 进程");
|
|
28
|
+
return result.stdout.split("\n").flatMap(line => {
|
|
29
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
|
|
30
|
+
return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] }] : [];
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
async function stopCli(pid) {
|
|
34
|
+
const service = process.platform === "win32" ? new WindowsTaskService() : new MacLaunchAgent();
|
|
35
|
+
const status = await service.status();
|
|
36
|
+
if (status.running && status.state?.pid === pid) {
|
|
37
|
+
await service.stop();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (process.platform === "win32") {
|
|
41
|
+
const result = await runCommand("taskkill", ["/PID", String(pid), "/T", "/F"]);
|
|
42
|
+
if (result.code !== 0)
|
|
43
|
+
throw new Error("旧 CLI 进程树停止失败");
|
|
44
|
+
}
|
|
45
|
+
else
|
|
46
|
+
process.kill(pid, "SIGTERM");
|
|
47
|
+
}
|
|
48
|
+
async function isPackagedRuntime(command) {
|
|
49
|
+
const match = /(?:^|\s)(?:"([^"]+[\\/]ws-server\.mjs)"|(\S+[\\/]ws-server\.mjs))(?=\s|$)/.exec(command);
|
|
50
|
+
const gateway = match?.[1] ?? match?.[2];
|
|
51
|
+
if (!gateway)
|
|
52
|
+
return false;
|
|
53
|
+
try {
|
|
54
|
+
const path = await realpath(gateway);
|
|
55
|
+
if (!/[\\/]node_modules[\\/]agentroam-runtime-(?:darwin-arm64|win32-x64)[\\/]runtime[\\/]ws-server\.mjs$/.test(path))
|
|
56
|
+
return false;
|
|
57
|
+
const manifest = JSON.parse(await readFile(join(dirname(dirname(path)), "package.json"), "utf8"));
|
|
58
|
+
return ["agentroam-runtime-darwin-arm64", "agentroam-runtime-win32-x64"].includes(manifest.name);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Authenticate the local server, then verify its CLI parent before sending any signal. */
|
|
65
|
+
export async function stopPreviousInstances(dataDir, log, dependencies = {}) {
|
|
66
|
+
const canonical = await realpath(dataDir);
|
|
67
|
+
const registry = dependencies.registry ?? process.env.AGENTROAM_DISCOVERY_DIR ?? join(homedir(), ".agentroam/services");
|
|
68
|
+
const names = await readdir(registry).catch((error) => { if (error.code === "ENOENT")
|
|
69
|
+
return []; throw error; });
|
|
70
|
+
for (const name of names.filter(name => name.endsWith(".json"))) {
|
|
71
|
+
let d;
|
|
72
|
+
let source;
|
|
73
|
+
const recordPath = join(registry, name);
|
|
74
|
+
try {
|
|
75
|
+
source = await readFile(recordPath, "utf8");
|
|
76
|
+
d = JSON.parse(source);
|
|
77
|
+
if (d.protocol !== 1 || !Number.isSafeInteger(d.pid) || d.pid <= 1 || typeof d.instanceId !== "string" || !/^[a-f0-9]{64}$/.test(d.token))
|
|
78
|
+
continue;
|
|
79
|
+
const actual = await realpath(d.dataDir);
|
|
80
|
+
if (actual !== canonical && actual !== join(canonical, "data"))
|
|
81
|
+
continue;
|
|
82
|
+
const url = new URL(d.url);
|
|
83
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || url.pathname !== "/" || url.username || url.password || url.search || url.hash)
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
let identity;
|
|
90
|
+
try {
|
|
91
|
+
const response = await (dependencies.request ?? fetch)(new URL("/api/desktop/identity", d.url), { headers: { "x-agentroam-desktop-token": d.token }, redirect: "error", signal: AbortSignal.timeout(1500) });
|
|
92
|
+
if (!response.ok)
|
|
93
|
+
throw new Error("实例认证失败");
|
|
94
|
+
identity = await response.json();
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
if ((dependencies.alive ?? alive)(d.pid)) {
|
|
98
|
+
const processes = dependencies.processes ?? processList;
|
|
99
|
+
const owner = (await processes()).find(p => p.pid === d.pid);
|
|
100
|
+
// An unavailable gateway may still own live sessions. Only quarantine
|
|
101
|
+
// when the PID demonstrably belongs to a different kind of process.
|
|
102
|
+
if (!owner?.command.trim() || /[\\/]ws-server\.mjs(?:["\s]|$)|[\\/]agentroam[\\/]bin[\\/]agentroam\.mjs(?:["\s]|$)/.test(owner.command)) {
|
|
103
|
+
throw new Error("同一数据目录的旧实例无法核验,请先停止旧实例再重试");
|
|
104
|
+
}
|
|
105
|
+
const current = (await processes()).find(p => p.pid === d.pid);
|
|
106
|
+
if (!current || current.ppid !== owner.ppid || current.command !== owner.command) {
|
|
107
|
+
throw new Error("旧实例身份已变化,请重试");
|
|
108
|
+
}
|
|
109
|
+
if (await readFile(recordPath, "utf8") !== source)
|
|
110
|
+
throw new Error("旧实例记录已变化,请重试");
|
|
111
|
+
const backupDir = join(registry, "stale");
|
|
112
|
+
await mkdir(backupDir, { recursive: true, mode: 0o700 });
|
|
113
|
+
await rename(recordPath, join(backupDir, `${randomUUID()}-${name}`));
|
|
114
|
+
log("检测到旧服务记录的 PID 已被其他进程复用,已备份失效记录,继续启动。");
|
|
115
|
+
}
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (identity.protocol !== 1 || identity.instanceId !== d.instanceId || identity.dataDir !== d.dataDir)
|
|
119
|
+
throw new Error("旧实例身份不匹配,已取消启动");
|
|
120
|
+
const processes = await (dependencies.processes ?? processList)();
|
|
121
|
+
const server = processes.find(p => p.pid === d.pid);
|
|
122
|
+
const parent = processes.find(p => p.pid === server?.ppid);
|
|
123
|
+
const orphan = server && (server.ppid === 1 || !parent) && await isPackagedRuntime(server.command);
|
|
124
|
+
if (!server || server.pid === process.pid || (!orphan && (!parent || parent.pid === process.pid || !/[\\/]ws-server\.mjs(?:["\s]|$)/.test(server.command) || !/[\\/]agentroam[\\/]bin[\\/]agentroam\.mjs(?:["\s]|$)/.test(parent.command)))) {
|
|
125
|
+
throw new Error("同一数据目录已有服务,但无法确认它是可接管的 CLI 实例,请先停止该服务");
|
|
126
|
+
}
|
|
127
|
+
// Re-read the process relationship immediately before stopping, to reject stale PID records.
|
|
128
|
+
const current = await (dependencies.processes ?? processList)();
|
|
129
|
+
if (!current.some(p => p.pid === server.pid && p.ppid === server.ppid && p.command === server.command) || (!orphan && !current.some(p => p.pid === parent.pid && p.command === parent.command)))
|
|
130
|
+
throw new Error("旧实例身份已变化,请重试");
|
|
131
|
+
const targetPid = orphan ? server.pid : parent.pid;
|
|
132
|
+
log(orphan ? "检测到旧 CLI 遗留的服务进程,正在停止…" : "检测到同一数据目录的旧 CLI,正在停止…");
|
|
133
|
+
await (dependencies.stop ?? stopCli)(targetPid);
|
|
134
|
+
const deadline = Date.now() + (dependencies.timeoutMs ?? 15_000);
|
|
135
|
+
while ((dependencies.alive ?? alive)(targetPid) || (dependencies.alive ?? alive)(server.pid)) {
|
|
136
|
+
if (Date.now() >= deadline)
|
|
137
|
+
throw new Error("旧 CLI 尚未退出,已取消新实例启动,请稍后重试");
|
|
138
|
+
await delay(100);
|
|
139
|
+
}
|
|
140
|
+
log("✓ 旧 CLI 已停止,继续启动新实例");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
export { lockInstanceStartup } from "./startup-lock.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function printLocalDesktopUrl(localUrl, log = console.log, platform = process.platform) {
|
|
2
|
+
log(`Local-only desktop authorization (open on this computer, not your phone): ${localUrl.replace(/\/$/, '')}/web`);
|
|
3
|
+
log('Authorize again: agentroam desktop authorize. Browser fallback: open the local URL on this computer, pair, then click Remote Authorization (shield icon).');
|
|
4
|
+
if (platform === 'win32')
|
|
5
|
+
log('Click Enable Sharing. Keep Windows signed in and unlocked; UAC secure desktop and administrator windows are not supported.');
|
|
6
|
+
else
|
|
7
|
+
log('Grant Screen Recording and Accessibility permissions when prompted, then click Enable Sharing.');
|
|
8
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
export class LocalServiceHttpError extends Error {
|
|
5
|
+
status;
|
|
6
|
+
detail;
|
|
7
|
+
constructor(status, detail) {
|
|
8
|
+
super(detail ? `本机服务请求失败 (HTTP ${status}): ${detail}` : `本机服务请求失败 (HTTP ${status})`);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.detail = detail;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Resolve an identity-checked loopback service; never send its token to a tunnel. */
|
|
14
|
+
export async function localServiceRequest(dataDir, path, options = {}) {
|
|
15
|
+
if (!path.startsWith("/api/"))
|
|
16
|
+
throw new Error("无效的本机服务路径");
|
|
17
|
+
const request = options.request ?? fetch;
|
|
18
|
+
options.signal?.throwIfAborted();
|
|
19
|
+
const requestSignal = (timeoutMs) => options.signal
|
|
20
|
+
? AbortSignal.any([options.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
|
|
21
|
+
const directory = options.registry ?? process.env.AGENTROAM_DISCOVERY_DIR ?? join(homedir(), ".agentroam", "services");
|
|
22
|
+
const names = await readdir(directory).catch((error) => { if (error.code === "ENOENT")
|
|
23
|
+
return []; throw error; });
|
|
24
|
+
const candidates = [];
|
|
25
|
+
for (const name of names.filter((name) => name.endsWith(".json"))) {
|
|
26
|
+
try {
|
|
27
|
+
const d = JSON.parse(await readFile(join(directory, name), "utf8"));
|
|
28
|
+
const url = new URL(d.url);
|
|
29
|
+
if (d.protocol !== 1 || typeof d.instanceId !== "string" || !Number.isSafeInteger(d.pid) || d.pid <= 0 || ![resolve(dataDir), resolve(dataDir, "data")].includes(d.dataDir) || !/^[a-f0-9]{64}$/.test(d.token))
|
|
30
|
+
continue;
|
|
31
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port || url.pathname !== "/" || url.username || url.password || url.search || url.hash)
|
|
32
|
+
continue;
|
|
33
|
+
options.signal?.throwIfAborted();
|
|
34
|
+
const response = await request(new URL("/api/desktop/identity", url), { headers: { "x-agentroam-desktop-token": d.token }, redirect: "error", signal: requestSignal(1500) });
|
|
35
|
+
if (!response.ok)
|
|
36
|
+
continue;
|
|
37
|
+
const identity = await response.json();
|
|
38
|
+
if (identity.protocol === 1 && identity.instanceId === d.instanceId && identity.dataDir === d.dataDir)
|
|
39
|
+
candidates.push(d);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
options.signal?.throwIfAborted(); /* Stale descriptors are expected after a process crash. */
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
options.signal?.throwIfAborted();
|
|
46
|
+
if (candidates.length !== 1)
|
|
47
|
+
throw new Error(candidates.length ? "多个服务使用此数据目录,请先停止多余实例" : "未找到运行中的 AgentRoam 服务,请先启动服务或指定 --data-dir");
|
|
48
|
+
const d = candidates[0];
|
|
49
|
+
const url = new URL(path, d.url);
|
|
50
|
+
if (url.origin !== new URL(d.url).origin)
|
|
51
|
+
throw new Error("无效的本机服务路径");
|
|
52
|
+
const response = await request(url, {
|
|
53
|
+
method: options.method ?? "GET",
|
|
54
|
+
headers: { "x-agentroam-desktop-token": d.token, "content-type": "application/json", origin: new URL(d.url).origin },
|
|
55
|
+
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
|
56
|
+
redirect: "error", signal: requestSignal(options.timeoutMs ?? 5000),
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
let detail;
|
|
60
|
+
try {
|
|
61
|
+
const body = await response.json();
|
|
62
|
+
if (typeof body.error === "string" && body.error.trim())
|
|
63
|
+
detail = body.error.trim().slice(0, 500);
|
|
64
|
+
}
|
|
65
|
+
catch { /* Preserve the status when the service did not return JSON. */ }
|
|
66
|
+
throw new LocalServiceHttpError(response.status, detail);
|
|
67
|
+
}
|
|
68
|
+
return response.json();
|
|
69
|
+
}
|
|
@@ -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
|
+
}
|