localmcp-cli 0.0.0-stage → 0.0.11
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/LICENSE +21 -0
- package/README.md +104 -2
- package/bin/cli.js +27 -0
- package/package.json +28 -4
- package/src/agents/hub.js +663 -0
- package/src/agents/providers.js +840 -0
- package/src/agents/store.js +524 -0
- package/src/cli/options.js +177 -0
- package/src/cli/runtime.js +126 -0
- package/src/cli/service.js +29 -0
- package/src/cli/tunnel.js +242 -0
- package/src/core/audit.js +105 -0
- package/src/core/auth.js +326 -0
- package/src/core/bounded-log.js +39 -0
- package/src/core/config.js +319 -0
- package/src/core/context-discovery.js +245 -0
- package/src/core/mesh.js +103 -0
- package/src/core/protocol.js +112 -0
- package/src/core/updater-client.js +165 -0
- package/src/server.js +260 -0
- package/src/tools/agents.js +149 -0
- package/src/tools/apply-patch.js +454 -0
- package/src/tools/diagnostics.js +158 -0
- package/src/tools/filesystem.js +1122 -0
- package/src/tools/gui-windows.js +268 -0
- package/src/tools/registry.js +119 -0
- package/src/tools/system.js +591 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import net from "node:net";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
10
|
+
import { TUNNEL_PROVIDERS, startTunnel } from "./tunnel.js";
|
|
11
|
+
|
|
12
|
+
export const home = path.join(os.homedir(), ".local-mcp");
|
|
13
|
+
export const entry = fileURLToPath(new URL("../../bin/cli.js", import.meta.url));
|
|
14
|
+
const file = name => path.join(home, name);
|
|
15
|
+
function read(name) {
|
|
16
|
+
try { return JSON.parse(fs.readFileSync(file(name), "utf8")); }
|
|
17
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
18
|
+
}
|
|
19
|
+
function save(name, data) {
|
|
20
|
+
const temp = file(randomUUID() + ".tmp");
|
|
21
|
+
fs.writeFileSync(temp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
|
22
|
+
try { fs.renameSync(temp, file(name)); }
|
|
23
|
+
finally { fs.rmSync(temp, { force: true }); }
|
|
24
|
+
}
|
|
25
|
+
export function configFor(opts, t) {
|
|
26
|
+
const prior = opts.resume ? read("cli.json") : {};
|
|
27
|
+
if (!prior) throw Error(t("No saved configuration", "尚无已保存的配置"));
|
|
28
|
+
return { mode: "read", root: process.cwd(), daemon: true, port: 8787, tunnel: "local", ...prior, ...opts.overrides };
|
|
29
|
+
}
|
|
30
|
+
async function state() {
|
|
31
|
+
const record = read("cli.pid.json");
|
|
32
|
+
if (!record) return;
|
|
33
|
+
const url = "http://127.0.0.1:" + record.port;
|
|
34
|
+
try {
|
|
35
|
+
const res = await fetch(url + "/__local_admin/state", { headers: { "x-secret-key": record.key },
|
|
36
|
+
redirect: "error", signal: AbortSignal.timeout(1500) });
|
|
37
|
+
if (res.ok && (await res.json()).pid === record.pid) return { pid: record.pid, url: record.url || (url + "/mcp") };
|
|
38
|
+
} catch {}
|
|
39
|
+
}
|
|
40
|
+
export async function manage(command, t) {
|
|
41
|
+
const instance = await state();
|
|
42
|
+
if (!instance) {
|
|
43
|
+
if (command === "url") throw Error(t("No running instance", "没有运行中的实例"));
|
|
44
|
+
console.log(t("Stopped", "已停止"));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (command === "stop") {
|
|
48
|
+
process.kill(instance.pid);
|
|
49
|
+
for (let i = 0; i < 50 && await state(); i++) await delay(100);
|
|
50
|
+
if (await state()) throw Error(t("Stop timed out", "停止超时"));
|
|
51
|
+
console.log(t("Stopped", "已停止"));
|
|
52
|
+
} else console.log(command === "url" ? instance.url : t("Running", "运行中") + " PID " + instance.pid + " " + instance.url);
|
|
53
|
+
}
|
|
54
|
+
export async function start(config, lang, t) {
|
|
55
|
+
if (!["read", "write", "full"].includes(config.mode) || !TUNNEL_PROVIDERS.includes(config.tunnel) ||
|
|
56
|
+
!Number.isInteger(config.port) || config.port < 1 || config.port > 65535 ||
|
|
57
|
+
!path.isAbsolute(config.root) || config.root.includes(path.delimiter) || !fs.statSync(config.root).isDirectory())
|
|
58
|
+
throw Error(t("Invalid configuration", "配置无效"));
|
|
59
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
60
|
+
if (await state()) throw Error(t("Already running", "已有实例运行中"));
|
|
61
|
+
if (config.daemon && !process.send) {
|
|
62
|
+
const child = spawn(process.execPath, [entry, "--lang", lang], { cwd: process.cwd(), detached: true, windowsHide: true,
|
|
63
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"] });
|
|
64
|
+
const waitMs = config.tunnel === "local" ? 30000 : 60000;
|
|
65
|
+
await new Promise((resolve, reject) => {
|
|
66
|
+
const timer = setTimeout(() => { child.kill(); reject(Error(t("Startup timed out", "启动超时"))); }, waitMs);
|
|
67
|
+
child.once("error", error => { clearTimeout(timer); reject(error); });
|
|
68
|
+
child.once("exit", () => { clearTimeout(timer); reject(Error(t("Startup failed, see ", "启动失败,查看 ") + file("cli.log"))); });
|
|
69
|
+
child.once("message", msg => { clearTimeout(timer); console.log(msg.url); child.disconnect(); child.unref(); resolve(); });
|
|
70
|
+
child.send(config);
|
|
71
|
+
});
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const socket = process.platform === "win32"
|
|
75
|
+
? "\\\\.\\pipe\\localmcp-start-" + createHash("sha256").update(home).digest("hex")
|
|
76
|
+
: file("cli-start.sock");
|
|
77
|
+
const lock = net.createServer(connection => connection.end());
|
|
78
|
+
await new Promise((resolve, reject) => {
|
|
79
|
+
lock.once("error", reject);
|
|
80
|
+
lock.listen(socket, resolve);
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
if (await state()) throw Error(t("Already running", "已有实例运行中"));
|
|
84
|
+
await runServer(config);
|
|
85
|
+
} finally { lock.close(); }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function runServer(config) {
|
|
89
|
+
const isLocal = config.tunnel === "local";
|
|
90
|
+
const key = config.secretKey || randomUUID();
|
|
91
|
+
const full = config.mode === "full" ? "1" : "0";
|
|
92
|
+
Object.assign(process.env, { PORT: String(config.port), CONNECTION_MODE: isLocal ? "local" : "tunnel", MCP_PATH: "/mcp",
|
|
93
|
+
PUBLIC_MCP_URL: "", DOTENV_CONFIG_PATH: file("unused-" + key), SECRET_KEY: key, LOCAL_CONTROL_ROOTS: config.root,
|
|
94
|
+
ALLOW_WRITES: config.mode === "read" ? "0" : "1", ALLOW_SHELL: full, ALLOW_UNSAFE_SHELL: full,
|
|
95
|
+
ALLOW_AGENTS: full, ALLOW_APPLESCRIPT: "0", ALLOW_GUI: "0", ALLOW_SCREENSHOT: "0", ALLOW_OPEN: "0" });
|
|
96
|
+
process.env.LOCALMCP_RUNTIME_DIR = home;
|
|
97
|
+
process.chdir(config.root);
|
|
98
|
+
const { httpServer } = await import("../server.js");
|
|
99
|
+
if (!httpServer.listening) await new Promise((resolve, reject) => {
|
|
100
|
+
httpServer.once("error", reject);
|
|
101
|
+
httpServer.once("listening", resolve);
|
|
102
|
+
});
|
|
103
|
+
let tunnelHandle = null;
|
|
104
|
+
let url = "http://127.0.0.1:" + config.port + "/mcp";
|
|
105
|
+
let activeProvider = "local";
|
|
106
|
+
try {
|
|
107
|
+
if (!isLocal) {
|
|
108
|
+
tunnelHandle = await startTunnel(config, config.port, home);
|
|
109
|
+
activeProvider = tunnelHandle.provider;
|
|
110
|
+
url = `${tunnelHandle.origin}/mcp?secret-key=${encodeURIComponent(key)}`;
|
|
111
|
+
const cleanup = () => { try { tunnelHandle?.stop(); } catch {} };
|
|
112
|
+
process.once("SIGTERM", () => { cleanup(); process.exit(0); });
|
|
113
|
+
process.once("SIGINT", () => { cleanup(); process.exit(0); });
|
|
114
|
+
process.once("exit", cleanup);
|
|
115
|
+
}
|
|
116
|
+
const savedCfg = isLocal ? config : { ...config, secretKey: key };
|
|
117
|
+
save("cli.json", savedCfg);
|
|
118
|
+
save("cli.pid.json", { pid: process.pid, port: config.port, key, url, provider: activeProvider });
|
|
119
|
+
} catch (error) {
|
|
120
|
+
try { tunnelHandle?.stop(); } catch {}
|
|
121
|
+
httpServer.close();
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
if (process.send) process.send({ url, provider: activeProvider });
|
|
125
|
+
else console.log(url);
|
|
126
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { entry, home } from "./runtime.js";
|
|
6
|
+
|
|
7
|
+
export function service(command, t) {
|
|
8
|
+
if (process.platform !== "linux") throw Error(t("Linux systemd required", "需要 Linux systemd"));
|
|
9
|
+
const ctl = (...args) => execFileSync("systemctl", ["--user", ...args], { stdio: "inherit" });
|
|
10
|
+
ctl("show", "--property=Version");
|
|
11
|
+
const unit = "localmcp-cli.service";
|
|
12
|
+
const dir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "systemd", "user");
|
|
13
|
+
const target = path.join(dir, unit);
|
|
14
|
+
const marker = "# Managed by localmcp-cli\n";
|
|
15
|
+
if (fs.existsSync(target) && !fs.readFileSync(target, "utf8").startsWith(marker)) throw Error(target);
|
|
16
|
+
if (command === "service uninstall") {
|
|
17
|
+
if (!fs.existsSync(target)) return;
|
|
18
|
+
ctl("disable", "--now", unit);
|
|
19
|
+
fs.unlinkSync(target);
|
|
20
|
+
} else {
|
|
21
|
+
if (!fs.existsSync(path.join(home, "cli.json"))) throw Error(t("Start LocalMCP once first", "请先启动一次 LocalMCP"));
|
|
22
|
+
const quote = value => '"' + value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%").replaceAll("$", "$$") + '"';
|
|
23
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
24
|
+
fs.writeFileSync(target, marker + "[Unit]\nDescription=LocalMCP CLI\n[Service]\nExecStart=" +
|
|
25
|
+
quote(process.execPath) + " " + quote(entry) + " --resume --foreground\nRestart=on-failure\n[Install]\nWantedBy=default.target\n");
|
|
26
|
+
}
|
|
27
|
+
ctl("daemon-reload");
|
|
28
|
+
if (command === "service install") ctl("enable", unit);
|
|
29
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
export const TUNNEL_PROVIDERS = [
|
|
6
|
+
"auto",
|
|
7
|
+
"local",
|
|
8
|
+
"tunnl_gg",
|
|
9
|
+
"localhost_run",
|
|
10
|
+
"cloudflare_quick",
|
|
11
|
+
"cloudflare_auth",
|
|
12
|
+
"frp_custom",
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
function commandExists(cmd) {
|
|
16
|
+
try {
|
|
17
|
+
const res = spawnSync(cmd, ["-V"], { stdio: "ignore", timeout: 3000, windowsHide: true });
|
|
18
|
+
if (!res.error) return true;
|
|
19
|
+
} catch {}
|
|
20
|
+
try {
|
|
21
|
+
const res = spawnSync(cmd, ["--version"], { stdio: "ignore", timeout: 3000, windowsHide: true });
|
|
22
|
+
if (!res.error) return true;
|
|
23
|
+
} catch {}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function hasSshBinary() {
|
|
28
|
+
if (process.platform === "win32" && fs.existsSync("C:\\Windows\\System32\\OpenSSH\\ssh.exe")) return true;
|
|
29
|
+
if (process.platform !== "win32" && fs.existsSync("/usr/bin/ssh")) return true;
|
|
30
|
+
return commandExists(process.platform === "win32" ? "ssh.exe" : "ssh");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function resolveSshBinary() {
|
|
34
|
+
if (process.platform === "win32" && fs.existsSync("C:\\Windows\\System32\\OpenSSH\\ssh.exe")) {
|
|
35
|
+
return "C:\\Windows\\System32\\OpenSSH\\ssh.exe";
|
|
36
|
+
}
|
|
37
|
+
if (process.platform !== "win32" && fs.existsSync("/usr/bin/ssh")) return "/usr/bin/ssh";
|
|
38
|
+
return process.platform === "win32" ? "ssh.exe" : "ssh";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function resolveAutoOrder(config = {}, sshAvailable = hasSshBinary()) {
|
|
42
|
+
const order = [];
|
|
43
|
+
if (config.cfToken && config.cfHostname) order.push("cloudflare_auth");
|
|
44
|
+
if (config.frpServer && config.frpDomain) order.push("frp_custom");
|
|
45
|
+
if (sshAvailable) order.push("tunnl_gg", "localhost_run");
|
|
46
|
+
order.push("cloudflare_quick");
|
|
47
|
+
return order;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function resolveFrpcBinary(homeDir) {
|
|
51
|
+
const ext = process.platform === "win32" ? ".exe" : "";
|
|
52
|
+
const candidates = [
|
|
53
|
+
path.join(homeDir, "bin", `frpc${ext}`),
|
|
54
|
+
"/usr/local/bin/frpc",
|
|
55
|
+
"/usr/bin/frpc",
|
|
56
|
+
];
|
|
57
|
+
for (const c of candidates) {
|
|
58
|
+
if (fs.existsSync(c)) return c;
|
|
59
|
+
}
|
|
60
|
+
return `frpc${ext}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function ensureCloudflared(homeDir) {
|
|
64
|
+
const ext = process.platform === "win32" ? ".exe" : "";
|
|
65
|
+
const localBin = path.join(homeDir, "bin", `cloudflared${ext}`);
|
|
66
|
+
const candidates = [
|
|
67
|
+
localBin,
|
|
68
|
+
"/opt/homebrew/bin/cloudflared",
|
|
69
|
+
"/usr/local/bin/cloudflared",
|
|
70
|
+
"/usr/bin/cloudflared",
|
|
71
|
+
];
|
|
72
|
+
for (const c of candidates) {
|
|
73
|
+
if (fs.existsSync(c)) return c;
|
|
74
|
+
}
|
|
75
|
+
if (commandExists(`cloudflared${ext}`)) return `cloudflared${ext}`;
|
|
76
|
+
|
|
77
|
+
const arch = process.arch === "arm64" ? "arm64" : process.arch === "x64" ? "amd64" : null;
|
|
78
|
+
if (!arch) throw new Error(`Unsupported architecture for cloudflared: ${process.arch}`);
|
|
79
|
+
let asset = "";
|
|
80
|
+
if (process.platform === "linux") asset = `cloudflared-linux-${arch}`;
|
|
81
|
+
else if (process.platform === "win32") asset = `cloudflared-windows-${arch}.exe`;
|
|
82
|
+
else throw new Error("cloudflared not found; please install cloudflared first");
|
|
83
|
+
|
|
84
|
+
const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/${asset}`;
|
|
85
|
+
const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(45000) });
|
|
86
|
+
if (!res.ok) throw new Error(`Failed to download cloudflared (${res.status})`);
|
|
87
|
+
fs.mkdirSync(path.dirname(localBin), { recursive: true, mode: 0o700 });
|
|
88
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
89
|
+
const tmp = `${localBin}.tmp`;
|
|
90
|
+
fs.writeFileSync(tmp, buf, { mode: 0o755 });
|
|
91
|
+
fs.renameSync(tmp, localBin);
|
|
92
|
+
if (process.platform !== "win32") fs.chmodSync(localBin, 0o755);
|
|
93
|
+
return localBin;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function waitForUrl(child, regex, timeoutMs, providerName) {
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
let settled = false;
|
|
99
|
+
let lastLine = "";
|
|
100
|
+
const timer = setTimeout(() => {
|
|
101
|
+
if (settled) return;
|
|
102
|
+
settled = true;
|
|
103
|
+
try { child.kill(); } catch {}
|
|
104
|
+
reject(new Error(`${providerName} timed out${lastLine ? `: ${lastLine}` : ""}`));
|
|
105
|
+
}, timeoutMs);
|
|
106
|
+
|
|
107
|
+
const onChunk = (buf) => {
|
|
108
|
+
const text = buf.toString("utf8");
|
|
109
|
+
for (const line of text.split(/\r?\n/)) {
|
|
110
|
+
const trimmed = line.trim();
|
|
111
|
+
if (trimmed) lastLine = trimmed.slice(0, 160);
|
|
112
|
+
const match = trimmed.match(regex);
|
|
113
|
+
if (match && !settled) {
|
|
114
|
+
settled = true;
|
|
115
|
+
clearTimeout(timer);
|
|
116
|
+
resolve(match[0].replace(/\/+$/, ""));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
child.stdout?.on("data", onChunk);
|
|
122
|
+
child.stderr?.on("data", onChunk);
|
|
123
|
+
child.once("error", (err) => {
|
|
124
|
+
if (settled) return;
|
|
125
|
+
settled = true;
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
reject(err);
|
|
128
|
+
});
|
|
129
|
+
child.once("exit", (code) => {
|
|
130
|
+
if (settled) return;
|
|
131
|
+
settled = true;
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
reject(new Error(`${providerName} exited (${code ?? "signal"})${lastLine ? `: ${lastLine}` : ""}`));
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function startSingleProvider(provider, config, port, homeDir) {
|
|
139
|
+
if (provider === "tunnl_gg") {
|
|
140
|
+
const child = spawn(
|
|
141
|
+
resolveSshBinary(),
|
|
142
|
+
[
|
|
143
|
+
"-o", "StrictHostKeyChecking=no",
|
|
144
|
+
"-o", "UserKnownHostsFile=/dev/null",
|
|
145
|
+
"-o", "ExitOnForwardFailure=yes",
|
|
146
|
+
"-o", "ServerAliveInterval=30",
|
|
147
|
+
"-R", `80:127.0.0.1:${port}`,
|
|
148
|
+
"proxy.tunnl.gg",
|
|
149
|
+
],
|
|
150
|
+
{ stdio: ["ignore", "pipe", "pipe"], windowsHide: true },
|
|
151
|
+
);
|
|
152
|
+
const origin = await waitForUrl(child, /https:\/\/[a-z0-9.-]+\.tunnl\.gg/i, 20000, "tunnl_gg");
|
|
153
|
+
return { origin, provider, stop: () => { try { child.kill(); } catch {} } };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (provider === "localhost_run") {
|
|
157
|
+
const child = spawn(
|
|
158
|
+
resolveSshBinary(),
|
|
159
|
+
[
|
|
160
|
+
"-o", "StrictHostKeyChecking=no",
|
|
161
|
+
"-o", "UserKnownHostsFile=/dev/null",
|
|
162
|
+
"-o", "ExitOnForwardFailure=yes",
|
|
163
|
+
"-o", "ServerAliveInterval=30",
|
|
164
|
+
"-R", `80:127.0.0.1:${port}`,
|
|
165
|
+
"nokey@localhost.run",
|
|
166
|
+
],
|
|
167
|
+
{ stdio: ["ignore", "pipe", "pipe"], windowsHide: true },
|
|
168
|
+
);
|
|
169
|
+
const origin = await waitForUrl(child, /https:\/\/[a-z0-9.-]+\.(?:lhr\.life|localhost\.run)/i, 20000, "localhost_run");
|
|
170
|
+
return { origin, provider, stop: () => { try { child.kill(); } catch {} } };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (provider === "cloudflare_quick") {
|
|
174
|
+
const bin = await ensureCloudflared(homeDir);
|
|
175
|
+
const child = spawn(
|
|
176
|
+
bin,
|
|
177
|
+
["tunnel", "--url", `http://127.0.0.1:${port}`, "--no-autoupdate"],
|
|
178
|
+
{ stdio: ["ignore", "pipe", "pipe"], windowsHide: true },
|
|
179
|
+
);
|
|
180
|
+
const origin = await waitForUrl(child, /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i, 30000, "cloudflare_quick");
|
|
181
|
+
return { origin, provider, stop: () => { try { child.kill(); } catch {} } };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (provider === "cloudflare_auth") {
|
|
185
|
+
if (!config.cfToken || !config.cfHostname) {
|
|
186
|
+
throw new Error("cloudflare_auth requires --cf-token and --cf-hostname");
|
|
187
|
+
}
|
|
188
|
+
const bin = await ensureCloudflared(homeDir);
|
|
189
|
+
const child = spawn(
|
|
190
|
+
bin,
|
|
191
|
+
["tunnel", "run", "--no-autoupdate", "--token", config.cfToken],
|
|
192
|
+
{ stdio: ["ignore", "pipe", "pipe"], windowsHide: true },
|
|
193
|
+
);
|
|
194
|
+
await waitForUrl(child, /Registered tunnel connection/i, 25000, "cloudflare_auth");
|
|
195
|
+
const host = String(config.cfHostname).replace(/^https?:\/\//i, "").replace(/\/+$/, "");
|
|
196
|
+
return { origin: `https://${host}`, provider, stop: () => { try { child.kill(); } catch {} } };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (provider === "frp_custom") {
|
|
200
|
+
if (!config.frpServer || !config.frpDomain) {
|
|
201
|
+
throw new Error("frp_custom requires --frp-server and --frp-domain");
|
|
202
|
+
}
|
|
203
|
+
const bin = resolveFrpcBinary(homeDir);
|
|
204
|
+
const cfgFile = path.join(homeDir, "cli-frpc.toml");
|
|
205
|
+
const serverPort = Number(config.frpPort) || 7000;
|
|
206
|
+
const domain = String(config.frpDomain).replace(/^https?:\/\//i, "").replace(/\/+$/, "");
|
|
207
|
+
const toml = [
|
|
208
|
+
`serverAddr = ${JSON.stringify(String(config.frpServer))}`,
|
|
209
|
+
`serverPort = ${serverPort}`,
|
|
210
|
+
config.frpToken ? `auth.method = "token"\nauth.token = ${JSON.stringify(String(config.frpToken))}` : "",
|
|
211
|
+
"[[proxies]]",
|
|
212
|
+
'name = "localmcp-cli"',
|
|
213
|
+
'type = "http"',
|
|
214
|
+
'localIP = "127.0.0.1"',
|
|
215
|
+
`localPort = ${port}`,
|
|
216
|
+
`customDomains = [${JSON.stringify(domain)}]`,
|
|
217
|
+
].filter(Boolean).join("\n") + "\n";
|
|
218
|
+
fs.writeFileSync(cfgFile, toml, { mode: 0o600 });
|
|
219
|
+
const child = spawn(bin, ["-c", cfgFile], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
220
|
+
await waitForUrl(child, /start proxy success/i, 20000, "frp_custom");
|
|
221
|
+
return { origin: `https://${domain}`, provider, stop: () => { try { child.kill(); } catch {} } };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
throw new Error(`Unsupported tunnel provider: ${provider}`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export async function startTunnel(config, port, homeDir) {
|
|
228
|
+
const provider = config.tunnel || "auto";
|
|
229
|
+
if (provider !== "auto") {
|
|
230
|
+
return startSingleProvider(provider, config, port, homeDir);
|
|
231
|
+
}
|
|
232
|
+
const order = resolveAutoOrder(config);
|
|
233
|
+
let lastError;
|
|
234
|
+
for (const candidate of order) {
|
|
235
|
+
try {
|
|
236
|
+
return await startSingleProvider(candidate, config, port, homeDir);
|
|
237
|
+
} catch (err) {
|
|
238
|
+
lastError = err;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
throw lastError || new Error("All tunnel providers failed");
|
|
242
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { appendLog, boundExistingLog } from "./bounded-log.js";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
function auditFields({ time, tool, ok, authKind, durationMs }) {
|
|
6
|
+
return { time, tool, ok, authKind, durationMs };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function formatLegacyBridgeLine(entry) {
|
|
10
|
+
const authLabel =
|
|
11
|
+
entry.authKind === "secret-key"
|
|
12
|
+
? "密钥鉴权"
|
|
13
|
+
: entry.authKind === "oauth"
|
|
14
|
+
? "OAuth"
|
|
15
|
+
: entry.authKind || "";
|
|
16
|
+
const parts = [];
|
|
17
|
+
if (entry.ok === false) parts.push("调用失败");
|
|
18
|
+
if (typeof entry.durationMs === "number") parts.push(`${entry.durationMs}ms`);
|
|
19
|
+
if (authLabel) parts.push(authLabel);
|
|
20
|
+
return JSON.stringify({
|
|
21
|
+
...entry,
|
|
22
|
+
status: entry.ok === false ? "error" : "ok",
|
|
23
|
+
target: parts.join(" · "),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createAuditLogger({ auditDir, maxMemoryEvents = 200 }) {
|
|
28
|
+
const actionsFile = path.join(auditDir, "actions.jsonl");
|
|
29
|
+
const legacyEventsFile = path.join(auditDir, "events.jsonl");
|
|
30
|
+
const memoryEvents = [];
|
|
31
|
+
const sseClients = new Set();
|
|
32
|
+
|
|
33
|
+
mkdirSync(auditDir, { recursive: true });
|
|
34
|
+
for (const file of [actionsFile, legacyEventsFile]) boundExistingLog(file);
|
|
35
|
+
if (existsSync(actionsFile) || existsSync(actionsFile + ".1")) {
|
|
36
|
+
try {
|
|
37
|
+
const lines = [actionsFile + ".1", actionsFile].filter(file => existsSync(file))
|
|
38
|
+
.flatMap(file => readFileSync(file, "utf8").trim().split(/\r?\n/).filter(Boolean));
|
|
39
|
+
const parsedTail = [];
|
|
40
|
+
for (const line of lines.slice(-Math.max(maxMemoryEvents, 300))) {
|
|
41
|
+
try {
|
|
42
|
+
parsedTail.push(auditFields(JSON.parse(line)));
|
|
43
|
+
} catch {
|
|
44
|
+
// Ignore corrupted lines
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
memoryEvents.push(...parsedTail.slice(-maxMemoryEvents));
|
|
48
|
+
// Bridge for <= v0.0.8 in-memory RuntimeManager during zero-drop in-place hot-updates
|
|
49
|
+
if (!existsSync(legacyEventsFile) && parsedTail.length > 0) {
|
|
50
|
+
for (const entry of parsedTail) appendLog(legacyEventsFile, formatLegacyBridgeLine(entry) + "\n", { wholeRecord: true });
|
|
51
|
+
}
|
|
52
|
+
} catch {
|
|
53
|
+
// Non-fatal startup read error
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function pushToMemory(record) {
|
|
58
|
+
memoryEvents.push(record);
|
|
59
|
+
if (memoryEvents.length > maxMemoryEvents) {
|
|
60
|
+
memoryEvents.splice(0, memoryEvents.length - maxMemoryEvents);
|
|
61
|
+
}
|
|
62
|
+
const payload = `data: ${JSON.stringify(record)}\n\n`;
|
|
63
|
+
for (const res of sseClients) {
|
|
64
|
+
try {
|
|
65
|
+
res.write(payload);
|
|
66
|
+
} catch {
|
|
67
|
+
sseClients.delete(res);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function record(entry) {
|
|
73
|
+
const safeEntry = auditFields({
|
|
74
|
+
time: new Date().toISOString(),
|
|
75
|
+
...entry,
|
|
76
|
+
});
|
|
77
|
+
try {
|
|
78
|
+
mkdirSync(auditDir, { recursive: true });
|
|
79
|
+
appendLog(actionsFile, `${JSON.stringify(safeEntry)}\n`, { wholeRecord: true });
|
|
80
|
+
appendLog(legacyEventsFile, `${formatLegacyBridgeLine(safeEntry)}\n`, { wholeRecord: true });
|
|
81
|
+
} catch {
|
|
82
|
+
// Keep tool calls resilient if disk logging fails transiently
|
|
83
|
+
}
|
|
84
|
+
pushToMemory(safeEntry);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function addSseClient(res) {
|
|
88
|
+
sseClients.add(res);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function removeSseClient(res) {
|
|
92
|
+
sseClients.delete(res);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function recent(limit = 100) {
|
|
96
|
+
return memoryEvents.slice(-Math.max(1, limit));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
record,
|
|
101
|
+
addSseClient,
|
|
102
|
+
removeSseClient,
|
|
103
|
+
recent,
|
|
104
|
+
};
|
|
105
|
+
}
|