@syengup/fridaynext 0.0.0-stage → 0.1.0-beta.2

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/API.md ADDED
@@ -0,0 +1,26 @@
1
+ # Friday 连接器 API
2
+
3
+ 本组件实现 [连接器合同 v1](../../docs/architecture/connector-contract.md) 中连接器一侧的部分:
4
+
5
+ - 连接器 HTTP API v1:`/friday-next/connector/v1/*`
6
+ - Provider 合同 v1 的调用方
7
+ - 连接器二维码(FNQR2 tag 12)
8
+
9
+ ## 模块入口(供测试与守护进程使用)
10
+
11
+ | 入口 | 说明 |
12
+ |---|---|
13
+ | `startConnector({home, host, port, lanHost?, manifest?, env?, computerName?, now?})` | 启动 HTTPS 服务。返回 `{url, port, address, fingerprint, computerId, mintPairing(), inventory(), close()}` |
14
+ | `providerRegistry({manifest, env})` | Provider 调用器,以固定参数启动子进程 |
15
+ | `collectInventory({registry, stateFile, computer})` | 汇总各宿主,单个出错只影响自己;内容变化时 revision 加 1 |
16
+ | `mintConnectorPairing({vouchers, lanUrl, fingerprint, now})` | 生成电脑级一次性券和连接器二维码 |
17
+ | `plistFor` / `installService` / `stopService` / `uninstallService` | 管理 LaunchAgent。可注入 `exec`,测试时不会真正执行 bootstrap |
18
+
19
+ ## 实现约定
20
+
21
+ - **限流**:claim 只统计无效券,10 分钟内失败 10 次后返回 429。过期券返回 410,不计入失败次数。
22
+ - **超时**:读命令默认 30 秒,enable 300 秒,start/restart 180 秒;可在 `providers.json` 的 `timeouts` 中覆盖。超时按 `PROVIDER_TIMEOUT` 返回,表示结果未知。
23
+ - **Provider 安装**:`installProviders({home, template, node, npmInstall})` 按 `provider-packages.json` 以精确版本安装各适配组件并生成 `providers.json`;单个失败只跳过该宿主并返回 `failed`。
24
+ - **合同修订 1**:pairing 的 `fingerprint` 可为 null,只透传 https 的 `publicUrl`/`controlPlane`;enable/start 传入 `lanHost`;restart 回传 `hostRestarted`。
25
+ - **pairing 校验**:Provider 返回的 pairing 结果必须含 `backendId`、`lanUrl`、`fingerprint`、`pairingTicket`,而且不得含 `token`,否则返回 `PAIRING_UNAVAILABLE`。
26
+ - **重启确认**:enable 遇到 `needsHostRestartToEnable`、以及 restart,都要求 `confirmHostRestart:true`,缺少时返回 409,Provider 不会被调用。
package/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # Friday 连接器(@syengup/fridaynext)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在 Mac 上只装一次、扫一次码,就能在 Friday App 中发现并添加这台电脑上所有受支持的 Agent:OpenClaw、Hermes、Codex、Claude Code。
4
+
5
+ ```bash
6
+ npx -y @syengup/fridaynext
7
+ ```
8
+
9
+ 安装会做三件事:
10
+
11
+ 1. 把连接器复制到 `~/.fridaynext/connector/app`。
12
+ 2. 写入 LaunchAgent `ai.fridaynext.connector`,设为开机自启并保活。
13
+ 3. 在终端打印一个二维码,10 分钟内有效,只能使用一次。
14
+
15
+ | 命令 | 作用 |
16
+ |---|---|
17
+ | `npx -y @syengup/fridaynext pair` | 重新出码 |
18
+ | `… status` | 查看运行状态 |
19
+ | `… stop` | 停止,下次登录会自动启动 |
20
+ | `… uninstall` | 卸载,保留数据 |
21
+ | `… uninstall --purge` | 卸载并删除数据 |
22
+
23
+ 数据目录为 `~/.fridaynext/connector/`,可用 `FN_CONNECTOR_HOME` 改到别处。其中:
24
+
25
+ - `data/computer.json`:电脑身份
26
+ - `data/devices.json`:电脑令牌,只保存哈希
27
+ - `data/tls/`:TLS 身份
28
+ - `providers.json`:Provider 清单
29
+ - `logs/daemon.log`:运行日志
30
+
31
+ 合同见 [连接器合同 v1](../../docs/architecture/connector-contract.md),接口说明见 [API.md](API.md)。第一期只支持 macOS,连接器接口只在局域网内可用。
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@syengup/fridaynext",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.2",
4
+ "description": "Friday 连接器:一次安装、一次配对,发现并添加这台 Mac 上的全部 Agent",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.13.0"
9
+ },
10
+ "os": ["darwin"],
11
+ "bin": {
12
+ "fridaynext": "src/cli.mjs"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public",
16
+ "tag": "latest",
17
+ "registry": "https://registry.npmjs.org/"
18
+ },
19
+ "files": ["src", "provider-packages.json", "README.md", "API.md"],
20
+ "scripts": {
21
+ "test": "node --test tests/*.test.mjs"
22
+ },
23
+ "dependencies": {
24
+ "@syengup/fridaynext-channel-kit": "0.2.0-beta.11",
25
+ "qrcode": "1.5.4"
26
+ }
27
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "contract": "fridaynext.provider/1",
3
+ "note": "各适配组件含 Provider 入口的候选版本,发布前须与 registry 实际版本一致(发包需单独授权)。",
4
+ "packages": [
5
+ { "hostId": "openclaw", "package": "@syengup/friday-channel-next", "version": "2026.10.6-beta.7", "entry": "provider.js" },
6
+ { "hostId": "hermes", "package": "@syengup/fridaynext-hermes-channel", "version": "0.1.0-beta.8", "entry": "provider.js" },
7
+ { "hostId": "codex", "package": "@syengup/fridaynext-codex-channel", "version": "0.1.0-beta.4", "entry": "provider.mjs" },
8
+ { "hostId": "claude-code", "package": "@syengup/fridaynext-claude-code-channel", "version": "0.1.0-beta.4", "entry": "provider.mjs" }
9
+ ]
10
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ // Friday 连接器命令行:默认安装/升级并出码;pair 重新出码;status / stop / uninstall。
3
+ import { execFileSync } from "node:child_process";
4
+ import fs from "node:fs";
5
+ import https from "node:https";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import QRCode from "qrcode";
9
+ import { createTlsIdentity } from "@syengup/fridaynext-channel-kit";
10
+ import { connectorHome, layout } from "./paths.mjs";
11
+ import { readJSON, ensurePrivateDir, writePrivateJSON } from "./private-file.mjs";
12
+ import { loadComputer } from "./identity.mjs";
13
+ import { installService, stopService, uninstallService } from "./launchd.mjs";
14
+ import { voucherStore, mintConnectorPairing } from "./pairing.mjs";
15
+ import { installProviders } from "./provider-install.mjs";
16
+ import { installApp, appSpec } from "./install-app.mjs";
17
+ import { CONNECTOR_VERSION } from "./server.mjs";
18
+
19
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
20
+ const home = connectorHome();
21
+ const paths = layout(home);
22
+ const [command = "install", ...rest] = process.argv.slice(2);
23
+ const say = text => process.stdout.write(text + "\n");
24
+
25
+ function ensureProviders() {
26
+ const template = readJSON(path.join(packageRoot, "provider-packages.json"));
27
+ const { providers, failed } = installProviders({ home, template, node: process.execPath });
28
+ say(`已接入 ${providers.length} 个 Agent 服务的 Provider。`);
29
+ for (const item of failed) say(` ${item.hostId}:Provider 未能安装(${item.reason}),该 Agent 暂不可发现,可稍后重新运行本命令。`);
30
+ }
31
+
32
+ function health(listen) {
33
+ return new Promise(resolve => {
34
+ const req = https.get(`https://127.0.0.1:${listen.port}/friday-next/connector/v1/health`, { rejectUnauthorized: false, timeout: 1500 }, res => { res.resume(); resolve(res.statusCode === 200); });
35
+ req.on("error", () => resolve(false));
36
+ req.on("timeout", () => { req.destroy(); resolve(false); });
37
+ });
38
+ }
39
+
40
+ async function waitReady(timeoutMs = 20_000) {
41
+ const deadline = Date.now() + timeoutMs;
42
+ while (Date.now() < deadline) {
43
+ const listen = readJSON(paths.listen);
44
+ if (listen && await health(listen)) return listen;
45
+ await new Promise(r => setTimeout(r, 500));
46
+ }
47
+ throw new Error(`连接器未在 ${timeoutMs / 1000} 秒内就绪,日志:${path.join(paths.logs, "daemon.log")}`);
48
+ }
49
+
50
+ async function printPairing() {
51
+ const listen = await waitReady();
52
+ const { computerId, computerName } = loadComputer(paths.computer);
53
+ const tls = createTlsIdentity({ dataDir: paths.tls, binding: `fridaynext-connector:${computerId}`, commonName: "fridaynext-connector" });
54
+ const { code, ttlSec } = mintConnectorPairing({ vouchers: voucherStore(paths.pairing), lanUrl: listen.lanUrl, fingerprint: tls.snapshot().fingerprint });
55
+ say(await QRCode.toString(code, { type: "terminal", small: true }));
56
+ say(`用 Friday App 扫描上方二维码,添加「${computerName}」上的全部 Agent(${Math.floor(ttlSec / 60)} 分钟内有效,只能使用一次)。`);
57
+ if (rest.includes("--print-code")) say(code);
58
+ }
59
+
60
+ async function main() {
61
+ if (process.platform !== "darwin" && command !== "help") throw new Error("Friday 连接器第一期仅支持 macOS");
62
+ if (command === "install") {
63
+ ensurePrivateDir(home);
64
+ // 连同依赖装进稳定目录(npx 把依赖平铺在包目录外),launchd 不依赖 npx 缓存。
65
+ const daemon = installApp({ home, spec: appSpec({ version: CONNECTOR_VERSION }) });
66
+ ensureProviders();
67
+ installService({ home, node: process.execPath, daemon });
68
+ say(`Friday 连接器 ${CONNECTOR_VERSION} 已安装并设为开机自启。`);
69
+ await printPairing();
70
+ } else if (command === "pair") {
71
+ await printPairing();
72
+ } else if (command === "status") {
73
+ const listen = readJSON(paths.listen);
74
+ const ok = listen ? await health(listen) : false;
75
+ say(JSON.stringify({ version: CONNECTOR_VERSION, home, running: ok, lanUrl: listen?.lanUrl ?? null }, null, 2));
76
+ } else if (command === "stop") {
77
+ stopService();
78
+ say("连接器已停止(下次登录会自动启动;彻底移除请用 uninstall)。");
79
+ } else if (command === "uninstall") {
80
+ uninstallService({ home, purge: rest.includes("--purge") });
81
+ say(rest.includes("--purge") ? "连接器已卸载,数据已删除。" : `连接器已卸载,数据保留在 ${home}(加 --purge 可删除)。`);
82
+ } else {
83
+ say("用法:fridaynext [install|pair|status|stop|uninstall [--purge]]");
84
+ if (command !== "help") process.exitCode = 2;
85
+ }
86
+ }
87
+ main().catch(error => { process.stderr.write(`错误:${error.message}\n`); process.exitCode = 1; });
package/src/daemon.mjs ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ // launchd 常驻入口:监听局域网 HTTPS,供 App 配对与查询;后端监督由各 Provider 卡接入。
3
+ import { connectorHome, layout } from "./paths.mjs";
4
+ import { readJSON } from "./private-file.mjs";
5
+ import { lanAddress } from "./lan.mjs";
6
+ import { startConnector } from "./server.mjs";
7
+
8
+ const DEFAULT_PORT = 9850;
9
+ const home = connectorHome();
10
+ const paths = layout(home);
11
+ const settings = readJSON(paths.home + "/settings.json", {});
12
+ const lan = settings.lanHost ?? lanAddress();
13
+ const port = Number.isSafeInteger(settings.port) ? settings.port : DEFAULT_PORT;
14
+
15
+ const connector = await startConnector({ home, host: settings.listenHost ?? "0.0.0.0", port, lanHost: lan ?? "127.0.0.1" });
16
+ console.log(`[fridaynext-connector] 已启动 ${connector.url}`);
17
+ // 开机或崩溃恢复后,自动拉起经连接器启用过、插件已启用但未运行的宿主后端。
18
+ const stopSupervisor = connector.startSupervisor({ log: report => console.log(`[fridaynext-connector] 监督 ${JSON.stringify(report)}`) });
19
+ const stop = () => { stopSupervisor(); return connector.close().then(() => process.exit(0)); };
20
+ process.on("SIGTERM", stop);
21
+ process.on("SIGINT", stop);
@@ -0,0 +1,32 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { readJSON, writePrivateJSON } from "./private-file.mjs";
3
+
4
+ const hash = token => createHash("sha256").update(token, "utf8").digest("hex");
5
+
6
+ /** 按配对设备签发的电脑令牌;只存哈希,可单独撤销。 */
7
+ export function deviceStore(file) {
8
+ const load = () => readJSON(file, { version: 1, devices: [] });
9
+ return {
10
+ issue(deviceName) {
11
+ const token = "fnct1-" + randomBytes(32).toString("base64url");
12
+ const state = load();
13
+ const device = { deviceId: randomUUID(), deviceName: typeof deviceName === "string" ? deviceName.slice(0, 64) : null, tokenHash: hash(token), createdAt: new Date().toISOString() };
14
+ state.devices.push(device);
15
+ writePrivateJSON(file, state);
16
+ return { token, deviceId: device.deviceId };
17
+ },
18
+ verify(token) {
19
+ if (typeof token !== "string" || !token.startsWith("fnct1-")) return null;
20
+ const digest = Buffer.from(hash(token), "hex");
21
+ return load().devices.find(device => {
22
+ const known = Buffer.from(device.tokenHash, "hex");
23
+ return known.length === digest.length && timingSafeEqual(known, digest);
24
+ }) ?? null;
25
+ },
26
+ revoke(deviceId) {
27
+ const state = load();
28
+ state.devices = state.devices.filter(device => device.deviceId !== deviceId);
29
+ writePrivateJSON(file, state);
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,29 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import os from "node:os";
4
+ import { readJSON, writePrivateJSON } from "./private-file.mjs";
5
+
6
+ export function systemComputerName() {
7
+ try {
8
+ const name = execFileSync("scutil", ["--get", "ComputerName"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
9
+ if (name) return name;
10
+ } catch { /* 非 macOS 或不可用 */ }
11
+ return os.hostname().replace(/\.local$/, "");
12
+ }
13
+
14
+ /** 电脑身份:首次生成 UUID 并记录名称,之后保持不变;改名只通过 rename。 */
15
+ export function loadComputer(file, computerName = systemComputerName) {
16
+ const saved = readJSON(file);
17
+ if (saved?.version === 1 && typeof saved.computerId === "string" && typeof saved.computerName === "string") return saved;
18
+ const created = { version: 1, computerId: randomUUID(), computerName: computerName() || "Mac", createdAt: new Date().toISOString() };
19
+ writePrivateJSON(file, created);
20
+ return created;
21
+ }
22
+ export function renameComputer(file, value) {
23
+ const name = typeof value === "string" ? value.trim() : "";
24
+ if (!name || name.length > 64) return null;
25
+ const saved = readJSON(file);
26
+ const next = { ...saved, computerName: name };
27
+ writePrivateJSON(file, next);
28
+ return next;
29
+ }
@@ -0,0 +1,31 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /** 安装来源:默认本包精确版本;FN_CONNECTOR_PACKAGE_SPEC 可指向本地 tgz,用于发行前验证。 */
6
+ export function appSpec({ version, env = process.env }) {
7
+ return env.FN_CONNECTOR_PACKAGE_SPEC || `@syengup/fridaynext@${version}`;
8
+ }
9
+
10
+ const defaultExec = (cmd, args) => execFileSync(cmd, args, { stdio: ["ignore", "ignore", "inherit"] });
11
+
12
+ /**
13
+ * 把连接器连同依赖装进 ~/.fridaynext/connector/app(npx 把依赖平铺在包目录外,不能只复制包目录)。
14
+ * 先装到暂存目录并确认入口存在,再原子替换;失败时原 app 保持不动。返回 daemon 绝对路径。
15
+ */
16
+ export function installApp({ home, spec, exec = defaultExec }) {
17
+ const app = path.join(home, "app"), staging = `${app}.next`;
18
+ fs.rmSync(staging, { recursive: true, force: true });
19
+ fs.mkdirSync(staging, { recursive: true, mode: 0o700 });
20
+ try {
21
+ exec("npm", ["install", "--prefix", staging, "--no-audit", "--no-fund", "--omit=dev", "--no-package-lock", spec]);
22
+ const entry = path.join(staging, "node_modules", "@syengup", "fridaynext", "src", "daemon.mjs");
23
+ if (!fs.existsSync(entry)) throw new Error("连接器入口缺失,安装未完成");
24
+ } catch (error) {
25
+ fs.rmSync(staging, { recursive: true, force: true });
26
+ throw error;
27
+ }
28
+ fs.rmSync(app, { recursive: true, force: true });
29
+ fs.renameSync(staging, app);
30
+ return path.join(app, "node_modules", "@syengup", "fridaynext", "src", "daemon.mjs");
31
+ }
@@ -0,0 +1,39 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readJSON, writePrivateJSON } from "./private-file.mjs";
3
+
4
+ /** 由 probe 推导宿主状态。 */
5
+ export function hostState(probe) {
6
+ if (!probe.installed) return "notInstalled";
7
+ if (!probe.compatible) return "incompatible";
8
+ if (!probe.pluginEnabled) return "needsEnable";
9
+ return probe.running ? "running" : "stopped";
10
+ }
11
+ const cleanAgents = list => Array.isArray(list) ? list.filter(a => typeof a?.agentId === "string").map(a => ({ agentId: a.agentId, displayName: typeof a.displayName === "string" ? a.displayName : a.agentId })) : [];
12
+ const cleanProjects = list => Array.isArray(list) ? list.filter(p => typeof p?.path === "string").map(p => ({ path: p.path, displayName: typeof p.displayName === "string" ? p.displayName : p.path.split("/").pop(), ...(typeof p.lastUsedAt === "string" ? { lastUsedAt: p.lastUsedAt } : {}) })) : [];
13
+
14
+ /** 汇总所有宿主;单个 Provider 出错只影响自己的条目。revision 只在内容摘要变化时 +1 并持久化。 */
15
+ export async function collectInventory({ registry, stateFile, computer }) {
16
+ const hosts = await Promise.all(registry.hostIds().map(async hostId => {
17
+ try {
18
+ const probe = await registry.run(hostId, "probe");
19
+ const state = hostState(probe);
20
+ const entry = { hostId, state, hostVersion: typeof probe.hostVersion === "string" ? probe.hostVersion : null, needsHostRestartToEnable: probe.needsHostRestartToEnable === true, agents: [] };
21
+ if (probe.installGuide && typeof probe.installGuide.title === "string") entry.installGuide = probe.installGuide;
22
+ if (state !== "notInstalled" && state !== "incompatible") {
23
+ const [agents, projects] = await Promise.allSettled([registry.run(hostId, "agents"), registry.run(hostId, "projects")]);
24
+ if (agents.status === "fulfilled") entry.agents = cleanAgents(agents.value.agents);
25
+ else entry.error = agents.reason?.toJSON?.() ?? { code: "PROVIDER_INTERNAL", message: "读取 Agent 失败", retryable: true };
26
+ if (projects.status === "fulfilled") entry.projects = cleanProjects(projects.value.projects);
27
+ }
28
+ return entry;
29
+ } catch (error) {
30
+ return { hostId, state: "unknown", hostVersion: null, needsHostRestartToEnable: false, agents: [], error: error?.toJSON?.() ?? { code: "PROVIDER_INTERNAL", message: "Provider 执行失败", retryable: true } };
31
+ }
32
+ }));
33
+ hosts.sort((a, b) => a.hostId.localeCompare(b.hostId));
34
+ const digest = createHash("sha256").update(JSON.stringify({ computerName: computer.computerName, hosts })).digest("hex");
35
+ const saved = readJSON(stateFile, { revision: 0, digest: null });
36
+ let revision = saved.revision;
37
+ if (saved.digest !== digest) { revision += 1; writePrivateJSON(stateFile, { revision, digest }); }
38
+ return { computerId: computer.computerId, computerName: computer.computerName, revision, hosts };
39
+ }
package/src/lan.mjs ADDED
@@ -0,0 +1,16 @@
1
+ import os from "node:os";
2
+
3
+ /** 选择局域网 IPv4:优先 en0/en1,其次任意非内部私网地址。 */
4
+ export function lanAddress(interfaces = os.networkInterfaces()) {
5
+ const candidates = [];
6
+ for (const [name, list] of Object.entries(interfaces)) {
7
+ for (const item of list ?? []) {
8
+ if (item.family !== "IPv4" || item.internal) continue;
9
+ if (!/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(item.address)) continue;
10
+ candidates.push({ name, address: item.address });
11
+ }
12
+ }
13
+ candidates.sort((a, b) => rank(a.name) - rank(b.name));
14
+ return candidates[0]?.address ?? null;
15
+ }
16
+ const rank = name => name === "en0" ? 0 : name === "en1" ? 1 : name.startsWith("en") ? 2 : 3;
@@ -0,0 +1,79 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ export const LAUNCHD_LABEL = "ai.fridaynext.connector";
7
+ const escape = value => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
8
+
9
+ const DEFAULT_PATH = "/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin";
10
+
11
+ /** launchd 只给最小 PATH;写入安装时的 PATH 并前置 node 所在目录,Provider 才能找到宿主命令。 */
12
+ export function launchPath({ node, path: current }) {
13
+ // npx 缓存与 node_modules/.bin 是临时目录,不写入常驻服务。
14
+ const parts = [path.dirname(node), ...(current || DEFAULT_PATH).split(":")].filter(p => p && !p.includes("/_npx/") && !p.includes("/node_modules/.bin"));
15
+ return [...new Set(parts)].join(":");
16
+ }
17
+
18
+ export function plistFor({ node, daemon, home, path: currentPath }) {
19
+ for (const value of [node, daemon, home]) if (!path.isAbsolute(value)) throw new Error("LaunchAgent 需要绝对路径");
20
+ const logs = path.join(home, "logs", "daemon.log");
21
+ return `<?xml version="1.0" encoding="UTF-8"?>
22
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
23
+ <plist version="1.0">
24
+ <dict>
25
+ <key>Label</key>
26
+ <string>${LAUNCHD_LABEL}</string>
27
+ <key>ProgramArguments</key>
28
+ <array>
29
+ <string>${escape(node)}</string>
30
+ <string>${escape(daemon)}</string>
31
+ </array>
32
+ <key>EnvironmentVariables</key>
33
+ <dict>
34
+ <key>FN_CONNECTOR_HOME</key>
35
+ <string>${escape(home)}</string>
36
+ <key>PATH</key>
37
+ <string>${escape(launchPath({ node, path: currentPath }))}</string>
38
+ </dict>
39
+ <key>RunAtLoad</key>
40
+ <true/>
41
+ <key>KeepAlive</key>
42
+ <true/>
43
+ <key>ProcessType</key>
44
+ <string>Background</string>
45
+ <key>StandardOutPath</key>
46
+ <string>${escape(logs)}</string>
47
+ <key>StandardErrorPath</key>
48
+ <string>${escape(logs)}</string>
49
+ </dict>
50
+ </plist>
51
+ `;
52
+ }
53
+
54
+ const defaultExec = (cmd, args) => execFileSync(cmd, args, { stdio: "ignore" });
55
+ const plistPath = dir => path.join(dir, `${LAUNCHD_LABEL}.plist`);
56
+ const tolerant = (exec, cmd, args) => { try { exec(cmd, args); } catch { /* 旧实例不存在时 bootout 失败属正常 */ } };
57
+
58
+ /** 写入 LaunchAgent 并加载;先卸下旧实例保证升级后运行新代码。 */
59
+ export function installService({ home, node, daemon, launchAgentsDir = path.join(os.homedir(), "Library", "LaunchAgents"), uid = process.getuid(), exec = defaultExec, envPath = process.env.PATH }) {
60
+ fs.mkdirSync(launchAgentsDir, { recursive: true });
61
+ fs.mkdirSync(path.join(home, "logs"), { recursive: true, mode: 0o700 });
62
+ const file = plistPath(launchAgentsDir);
63
+ fs.writeFileSync(file, plistFor({ node, daemon, home, path: envPath }), { mode: 0o644 });
64
+ fs.chmodSync(file, 0o644);
65
+ tolerant(exec, "launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]);
66
+ exec("launchctl", ["bootstrap", `gui/${uid}`, file]);
67
+ return file;
68
+ }
69
+
70
+ export function stopService({ uid = process.getuid(), exec = defaultExec } = {}) {
71
+ tolerant(exec, "launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]);
72
+ }
73
+
74
+ /** 卸下并删除 LaunchAgent;默认保留数据,purge 时删除整个连接器目录。 */
75
+ export function uninstallService({ home, launchAgentsDir = path.join(os.homedir(), "Library", "LaunchAgents"), uid = process.getuid(), exec = defaultExec, purge = false }) {
76
+ tolerant(exec, "launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]);
77
+ fs.rmSync(plistPath(launchAgentsDir), { force: true });
78
+ if (purge) fs.rmSync(home, { recursive: true, force: true });
79
+ }
@@ -0,0 +1,23 @@
1
+ import { encodePairingCode, PAIRING_CODE_KIND_CONNECTOR } from "@syengup/fridaynext-channel-kit";
2
+ import { createPairingVoucherStore } from "@syengup/fridaynext-channel-kit/public-access/pairing-voucher";
3
+
4
+ export function voucherStore(dir) {
5
+ return createPairingVoucherStore({ dataDir: dir });
6
+ }
7
+
8
+ /** 铸一张电脑级一次性券并编码为连接器二维码(FNQR2 tag 12),不含任何永久凭据。 */
9
+ export function mintConnectorPairing({ vouchers, lanUrl, fingerprint, now = Date.now() }) {
10
+ const ticket = vouchers.mintPairingVoucher(now);
11
+ const payload = { v: 2, lanUrl, fingerprint, pairingTicket: ticket.voucher, kind: PAIRING_CODE_KIND_CONNECTOR };
12
+ return { code: encodePairingCode(payload, { format: "fnqr2" }), payload, ttlSec: ticket.ttlSec };
13
+ }
14
+
15
+ /** 失败兑换滑动窗口限流(只统计无效券,避免陌生人用垃圾请求锁死合法配对)。 */
16
+ export function claimLimiter({ windowMs = 10 * 60_000, maxFailures = 10 } = {}) {
17
+ let failures = [];
18
+ const prune = now => { failures = failures.filter(t => now - t < windowMs); };
19
+ return {
20
+ limited(now) { prune(now); return failures.length >= maxFailures; },
21
+ fail(now) { failures.push(now); prune(now); return failures.length >= maxFailures; },
22
+ };
23
+ }
package/src/paths.mjs ADDED
@@ -0,0 +1,23 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ /** 连接器根目录:默认 ~/.fridaynext/connector,可由 FN_CONNECTOR_HOME 覆盖。 */
5
+ export function connectorHome(env = process.env) {
6
+ return path.resolve(env.FN_CONNECTOR_HOME || path.join(os.homedir(), ".fridaynext", "connector"));
7
+ }
8
+ export function layout(home) {
9
+ return {
10
+ home,
11
+ app: path.join(home, "app"),
12
+ data: path.join(home, "data"),
13
+ tls: path.join(home, "data", "tls"),
14
+ pairing: path.join(home, "data", "pairing"),
15
+ logs: path.join(home, "logs"),
16
+ providers: path.join(home, "providers.json"),
17
+ computer: path.join(home, "data", "computer.json"),
18
+ devices: path.join(home, "data", "devices.json"),
19
+ inventory: path.join(home, "data", "inventory-state.json"),
20
+ listen: path.join(home, "data", "listen.json"),
21
+ supervised: path.join(home, "data", "supervised.json"),
22
+ };
23
+ }
@@ -0,0 +1,18 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ /** 私有目录 0700、私有文件 0600,原子替换写入。 */
5
+ export function ensurePrivateDir(dir) {
6
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
7
+ fs.chmodSync(dir, 0o700);
8
+ return dir;
9
+ }
10
+ export function writePrivateJSON(file, value) {
11
+ ensurePrivateDir(path.dirname(file));
12
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
13
+ fs.writeFileSync(temp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
14
+ fs.renameSync(temp, file);
15
+ }
16
+ export function readJSON(file, fallback = null) {
17
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return fallback; }
18
+ }
@@ -0,0 +1,34 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { layout } from "./paths.mjs";
5
+ import { writePrivateJSON } from "./private-file.mjs";
6
+
7
+ const EXACT = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
8
+ const defaultInstall = (dir, spec) => execFileSync("npm", ["install", "--prefix", dir, "--no-audit", "--no-fund", "--omit=dev", "--ignore-scripts", spec], { stdio: "ignore" });
9
+
10
+ /**
11
+ * 按模板以精确 registry 版本安装各适配组件(Provider 由适配组件自持宿主知识),生成连接器 Provider 清单。
12
+ * 单个安装失败只跳过该宿主并如实返回,不影响其他宿主。
13
+ */
14
+ export function installProviders({ home, template, node = process.execPath, npmInstall = defaultInstall }) {
15
+ if (template?.contract !== "fridaynext.provider/1" || !Array.isArray(template.packages)) throw new Error("Provider 模板无效");
16
+ const providers = [], failed = [];
17
+ for (const entry of template.packages) {
18
+ if (!EXACT.test(entry.version) || !/^[\w@./-]+$/.test(entry.package) || !/^[\w./-]+$/.test(entry.entry) || entry.entry.includes("..")) {
19
+ failed.push({ hostId: entry.hostId, reason: "PROVIDER_TEMPLATE_INVALID" }); continue;
20
+ }
21
+ const dir = path.join(home, "providers", entry.hostId);
22
+ try {
23
+ fs.mkdirSync(dir, { recursive: true });
24
+ npmInstall(dir, `${entry.package}@${entry.version}`);
25
+ const file = path.join(dir, "node_modules", entry.package, entry.entry);
26
+ if (!fs.existsSync(file)) throw new Error("入口缺失");
27
+ providers.push({ hostId: entry.hostId, command: [node, file] });
28
+ } catch {
29
+ failed.push({ hostId: entry.hostId, reason: "PROVIDER_INSTALL_FAILED" });
30
+ }
31
+ }
32
+ writePrivateJSON(layout(home).providers, { contract: "fridaynext.provider/1", providers });
33
+ return { providers, failed };
34
+ }
@@ -0,0 +1,77 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ export const PROVIDER_CONTRACT = "fridaynext.provider/1";
7
+ export const HOST_IDS = ["openclaw", "hermes", "codex", "claude-code"];
8
+ const COMMANDS = new Set(["probe", "enable", "start", "restart", "status", "pairing", "agents", "projects"]);
9
+ // 实测 Hermes 冷启动 probe 接近 15 秒、OpenClaw 启用含安装与重启可超过 2 分钟,留足余量;超时仍按结果未知处理。
10
+ export const DEFAULT_TIMEOUTS = { probe: 30_000, agents: 30_000, status: 30_000, pairing: 30_000, projects: 30_000, enable: 300_000, start: 180_000, restart: 180_000 };
11
+
12
+ export class ProviderError extends Error {
13
+ constructor(code, message, retryable = false) { super(message); this.code = code; this.retryable = retryable; }
14
+ toJSON() { return { code: this.code, message: this.message, retryable: this.retryable }; }
15
+ }
16
+
17
+ /**
18
+ * Provider 合同 v1 调用器:只以固定参数启动清单中的可执行入口,stdout 必须是单个 JSON 对象。
19
+ * 合同版本未知、输出非法、超时都转成结构化错误,绝不当作成功。
20
+ */
21
+ export function providerRegistry({ manifest, env = {} }) {
22
+ if (manifest?.contract !== PROVIDER_CONTRACT || !Array.isArray(manifest.providers)) throw new Error("Provider 清单无效");
23
+ const entries = new Map();
24
+ for (const entry of manifest.providers) {
25
+ if (typeof entry?.hostId !== "string" || !Array.isArray(entry.command) || !entry.command.length) throw new Error("Provider 清单项无效");
26
+ entries.set(entry.hostId, entry);
27
+ }
28
+ const timeouts = { ...DEFAULT_TIMEOUTS, ...(manifest.timeouts ?? {}) };
29
+
30
+ async function run(hostId, command, input) {
31
+ const entry = entries.get(hostId);
32
+ if (!entry) throw new ProviderError("HOST_UNKNOWN", "未知宿主");
33
+ if (!COMMANDS.has(command)) throw new ProviderError("UNSUPPORTED_COMMAND", "不支持的命令");
34
+ let inputFile = null;
35
+ const args = [...entry.command.slice(1), command];
36
+ if (input !== undefined) {
37
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fn-connector-input-"));
38
+ inputFile = path.join(dir, "input.json");
39
+ fs.writeFileSync(inputFile, JSON.stringify(input), { mode: 0o600 });
40
+ args.push("--json-input", inputFile);
41
+ }
42
+ try {
43
+ const { stdout, code } = await spawnJSON(entry.command[0], args, { ...process.env, ...env }, timeouts[command]);
44
+ let body;
45
+ try { body = JSON.parse(stdout); } catch { throw new ProviderError("PROVIDER_OUTPUT_INVALID", "Provider 输出不是 JSON"); }
46
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new ProviderError("PROVIDER_OUTPUT_INVALID", "Provider 输出不是对象");
47
+ if (body.contract !== PROVIDER_CONTRACT) throw new ProviderError("PROVIDER_CONTRACT_UNSUPPORTED", "Provider 合同版本不受支持");
48
+ if (code !== 0 || body.ok === false) {
49
+ const error = body.error ?? {};
50
+ throw new ProviderError(typeof error.code === "string" ? error.code : "PROVIDER_INTERNAL", typeof error.message === "string" ? error.message : "Provider 执行失败", error.retryable === true);
51
+ }
52
+ const { contract, hostId: _host, ok, ...result } = body;
53
+ return result;
54
+ } finally {
55
+ if (inputFile) fs.rmSync(path.dirname(inputFile), { recursive: true, force: true });
56
+ }
57
+ }
58
+ return { hostIds: () => [...entries.keys()], has: hostId => entries.has(hostId), run };
59
+ }
60
+
61
+ function spawnJSON(file, args, env, timeoutMs) {
62
+ return new Promise((resolve, reject) => {
63
+ const child = spawn(file, args, { env, stdio: ["ignore", "pipe", "pipe"] });
64
+ let stdout = "";
65
+ let settled = false;
66
+ const timer = setTimeout(() => {
67
+ if (settled) return;
68
+ settled = true;
69
+ child.kill("SIGKILL");
70
+ reject(new ProviderError("PROVIDER_TIMEOUT", "Provider 超时,结果未知", true));
71
+ }, timeoutMs);
72
+ child.stdout.on("data", chunk => { stdout += chunk; if (stdout.length > 1_000_000) child.kill("SIGKILL"); });
73
+ child.stderr.resume();
74
+ child.on("error", () => { if (!settled) { settled = true; clearTimeout(timer); reject(new ProviderError("PROVIDER_UNAVAILABLE", "Provider 无法启动", true)); } });
75
+ child.on("close", code => { if (!settled) { settled = true; clearTimeout(timer); resolve({ stdout: stdout.trim(), code }); } });
76
+ });
77
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,147 @@
1
+ import https from "node:https";
2
+ import fs from "node:fs";
3
+ import { createTlsIdentity } from "@syengup/fridaynext-channel-kit";
4
+ import { layout } from "./paths.mjs";
5
+ import { ensurePrivateDir, readJSON, writePrivateJSON } from "./private-file.mjs";
6
+ import { loadComputer, renameComputer, systemComputerName } from "./identity.mjs";
7
+ import { deviceStore } from "./devices.mjs";
8
+ import { providerRegistry, ProviderError } from "./providers.mjs";
9
+ import { collectInventory } from "./inventory.mjs";
10
+ import { voucherStore, mintConnectorPairing, claimLimiter } from "./pairing.mjs";
11
+ import { supervisedStore, startSupervisor } from "./supervisor.mjs";
12
+
13
+ export const CONNECTOR_VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
14
+ const PREFIX = "/friday-next/connector/v1/";
15
+ const RESTART_COMMANDS = new Set(["restart"]);
16
+
17
+ function send(res, status, body) {
18
+ if (body === undefined) { res.writeHead(status, { "cache-control": "no-store" }); res.end(); return; }
19
+ const raw = JSON.stringify(body);
20
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "content-length": Buffer.byteLength(raw) });
21
+ res.end(raw);
22
+ }
23
+ const fail = (res, status, code, message) => send(res, status, { error: { code, message } });
24
+
25
+ function readBody(req, limit = 16_384) {
26
+ return new Promise(resolve => {
27
+ let raw = "";
28
+ req.on("data", chunk => { raw += chunk; if (raw.length > limit) { req.destroy(); resolve(null); } });
29
+ req.on("end", () => { if (!raw) return resolve({}); try { const v = JSON.parse(raw); resolve(v && typeof v === "object" && !Array.isArray(v) ? v : null); } catch { resolve(null); } });
30
+ req.on("error", () => resolve(null));
31
+ });
32
+ }
33
+
34
+ /**
35
+ * 启动连接器 HTTPS 服务(连接器 HTTP API v1)。只监听给定地址;TLS 使用 Kit 身份设施;
36
+ * 电脑令牌只授权本 API,连接器不接触后端永久凭据。
37
+ */
38
+ export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost, manifest, env = {}, computerName = systemComputerName, now = () => Date.now() }) {
39
+ const paths = layout(home);
40
+ ensurePrivateDir(home);
41
+ ensurePrivateDir(paths.data);
42
+ const computer = () => loadComputer(paths.computer, computerName);
43
+ const { computerId } = computer();
44
+ const tls = createTlsIdentity({ dataDir: paths.tls, binding: `fridaynext-connector:${computerId}`, commonName: "fridaynext-connector" });
45
+ const devices = deviceStore(paths.devices);
46
+ const vouchers = voucherStore(paths.pairing);
47
+ const limiter = claimLimiter();
48
+ const registry = providerRegistry({ manifest: manifest ?? readJSON(paths.providers) ?? { contract: "fridaynext.provider/1", providers: [] }, env });
49
+ const supervised = supervisedStore(paths.supervised);
50
+ const advertisedHost = lanHost ?? (host === "0.0.0.0" ? "127.0.0.1" : host);
51
+ let inventoryChain = Promise.resolve();
52
+ const inventory = () => (inventoryChain = inventoryChain.then(() => collectInventory({ registry, stateFile: paths.inventory, computer: computer() })));
53
+
54
+ async function hostAction(res, hostId, command, body) {
55
+ if (!registry.has(hostId)) return fail(res, 404, "HOST_UNKNOWN", "未知宿主");
56
+ try {
57
+ if (command === "enable" || RESTART_COMMANDS.has(command)) {
58
+ const confirmed = body.confirmHostRestart === true;
59
+ if (!confirmed) {
60
+ const needsConfirm = RESTART_COMMANDS.has(command) || (await registry.run(hostId, "probe")).needsHostRestartToEnable === true;
61
+ if (needsConfirm) return fail(res, 409, "HOST_RESTART_CONFIRMATION_REQUIRED", "需要先确认重启宿主");
62
+ }
63
+ const result = await registry.run(hostId, command, command === "enable" ? { confirmHostRestart: confirmed, lanHost: advertisedHost } : { confirmHostRestart: confirmed });
64
+ supervised.add(hostId);
65
+ return send(res, 200, command === "enable"
66
+ ? { state: result.state, hostRestarted: result.hostRestarted === true, changed: result.changed === true }
67
+ : { state: result.state, hostRestarted: result.hostRestarted === true });
68
+ }
69
+ if (command === "pairing") {
70
+ const result = await registry.run(hostId, "pairing");
71
+ const required = ["backendId", "lanUrl", "pairingTicket"];
72
+ const fingerprintOk = result.fingerprint == null || (typeof result.fingerprint === "string" && result.fingerprint.length > 0);
73
+ if ("token" in result || required.some(key => typeof result[key] !== "string" || !result[key]) || !fingerprintOk || !/^https?:\/\//.test(result.lanUrl)) {
74
+ throw new ProviderError("PAIRING_UNAVAILABLE", "后端配对坐标无效");
75
+ }
76
+ const https = key => typeof result[key] === "string" && /^https:\/\//.test(result[key]) ? { [key]: result[key] } : {};
77
+ // 合同 v1:局域网为明文 HTTP 时 fingerprint 可为空(此时指向公网证书或缺省);公网坐标仅接受 https。
78
+ return send(res, 200, { backendId: result.backendId, lanUrl: result.lanUrl, fingerprint: result.fingerprint ?? null, pairingTicket: result.pairingTicket,
79
+ pairingTicketTtlSec: Number.isSafeInteger(result.pairingTicketTtlSec) ? result.pairingTicketTtlSec : 600, ...https("publicUrl"), ...https("controlPlane") });
80
+ }
81
+ const result = await registry.run(hostId, command, command === "start" ? { lanHost: advertisedHost } : undefined);
82
+ if (command === "start") supervised.add(hostId);
83
+ return send(res, 200, { state: result.state });
84
+ } catch (error) {
85
+ const known = error instanceof ProviderError ? error : new ProviderError("PROVIDER_INTERNAL", "Provider 执行失败", true);
86
+ return send(res, 502, { error: known.toJSON() });
87
+ }
88
+ }
89
+
90
+ async function handle(req, res) {
91
+ const url = new URL(req.url, "https://connector.invalid");
92
+ const route = url.pathname;
93
+ if (route === "/friday-next/pair/claim") return fail(res, 426, "CONNECTOR_REQUIRES_APP_UPGRADE", "请升级 Friday App 后扫描此码");
94
+ if (!route.startsWith(PREFIX)) return fail(res, 404, "NOT_FOUND", "未找到");
95
+ const tail = route.slice(PREFIX.length);
96
+ const method = req.method;
97
+ if (tail === "health" && method === "GET") return send(res, 200, { ok: true, contract: "fridaynext.connector/1" });
98
+ if (tail === "claim") {
99
+ if (method !== "POST") return fail(res, 405, "METHOD_NOT_ALLOWED", "方法不允许");
100
+ const body = await readBody(req);
101
+ const at = now();
102
+ const voucher = typeof body?.voucher === "string" ? body.voucher.trim() : "";
103
+ const outcome = vouchers.claimPairingVoucher(voucher, at);
104
+ if (outcome === "ok") {
105
+ const { token } = devices.issue(body.deviceName);
106
+ const { computerName: name } = computer();
107
+ return send(res, 200, { token, computerId, computerName: name, connectorVersion: CONNECTOR_VERSION });
108
+ }
109
+ if (outcome === "expired") return fail(res, 410, "VOUCHER_EXPIRED", "配对码已过期");
110
+ return limiter.fail(at) ? fail(res, 429, "TOO_MANY_ATTEMPTS", "尝试过多,请稍后再试") : fail(res, 403, "VOUCHER_INVALID", "配对码无效或已使用");
111
+ }
112
+ const auth = req.headers.authorization ?? "";
113
+ const device = devices.verify(auth.startsWith("Bearer ") ? auth.slice(7).trim() : "");
114
+ if (!device) return fail(res, 401, "UNAUTHORIZED", "未授权");
115
+ if (tail === "inventory" && method === "GET") return send(res, 200, await inventory());
116
+ if (tail === "computer" && method === "PATCH") {
117
+ const body = await readBody(req);
118
+ const next = renameComputer(paths.computer, body?.computerName);
119
+ return next ? send(res, 200, { computerName: next.computerName }) : fail(res, 400, "INVALID_NAME", "名称无效");
120
+ }
121
+ if (tail === "devices/self" && method === "DELETE") { devices.revoke(device.deviceId); return send(res, 204); }
122
+ const match = /^hosts\/([a-z0-9-]+)\/(enable|start|restart|pairing)$/.exec(tail);
123
+ if (match && method === "POST") {
124
+ const body = await readBody(req);
125
+ if (body === null) return fail(res, 400, "INVALID_BODY", "请求体无效");
126
+ return hostAction(res, match[1], match[2], body);
127
+ }
128
+ return fail(res, 404, "NOT_FOUND", "未找到");
129
+ }
130
+
131
+ const server = https.createServer({ ...tls.snapshot().tlsOptions(), minVersion: "TLSv1.2" }, (req, res) => {
132
+ handle(req, res).catch(() => { if (!res.headersSent) fail(res, 500, "INTERNAL", "内部错误"); else res.destroy(); });
133
+ });
134
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(port, host, resolve); });
135
+ const bound = server.address();
136
+ const url = `https://${advertisedHost}:${bound.port}`;
137
+ const fingerprint = tls.snapshot().fingerprint;
138
+ writePrivateJSON(paths.listen, { version: 1, host, port: bound.port, lanUrl: url, pid: process.pid });
139
+ return {
140
+ url, port: bound.port, address: bound.address, fingerprint, computerId,
141
+ mintPairing: () => mintConnectorPairing({ vouchers, lanUrl: url, fingerprint, now: now() }),
142
+ /** 守护进程调用:开机与周期监督受监督宿主的后端。 */
143
+ startSupervisor: options => startSupervisor({ registry, store: supervised, ...options }),
144
+ inventory,
145
+ close: () => new Promise(resolve => { server.closeAllConnections?.(); server.close(() => resolve()); }),
146
+ };
147
+ }
@@ -0,0 +1,48 @@
1
+ import { readJSON, writePrivateJSON } from "./private-file.mjs";
2
+ import { ProviderError } from "./providers.mjs";
3
+
4
+ /** 受监督宿主:用户经连接器成功启用/启动过的宿主。 */
5
+ export function supervisedStore(file) {
6
+ const load = () => new Set(readJSON(file, { version: 1, hosts: [] }).hosts);
7
+ return {
8
+ list: () => [...load()],
9
+ add(hostId) { const set = load(); if (!set.has(hostId)) { set.add(hostId); writePrivateJSON(file, { version: 1, hosts: [...set] }); } },
10
+ };
11
+ }
12
+
13
+ /**
14
+ * 一轮监督:受监督宿主“已安装、兼容、插件已启用但未运行”时调用 Provider start。
15
+ * 运行中、未启用(用户未授权)或探测失败的不动;失败如实返回,下轮继续。
16
+ */
17
+ export async function superviseOnce({ registry, store }) {
18
+ const started = [], failed = [];
19
+ for (const hostId of store.list()) {
20
+ if (!registry.has(hostId)) continue;
21
+ try {
22
+ const probe = await registry.run(hostId, "probe");
23
+ if (!probe.installed || !probe.compatible || !probe.pluginEnabled || probe.running) continue;
24
+ await registry.run(hostId, "start", {});
25
+ started.push(hostId);
26
+ } catch (error) {
27
+ failed.push({ hostId, code: error instanceof ProviderError ? error.code : "PROVIDER_INTERNAL" });
28
+ }
29
+ }
30
+ return { started, failed };
31
+ }
32
+
33
+ /** 守护进程内的周期监督:启动后立即一轮,之后按间隔;同一时刻只跑一轮。 */
34
+ export function startSupervisor({ registry, store, intervalMs = 60_000, log = () => {} }) {
35
+ let running = false;
36
+ const tick = async () => {
37
+ if (running) return;
38
+ running = true;
39
+ try {
40
+ const report = await superviseOnce({ registry, store });
41
+ if (report.started.length || report.failed.length) log(report);
42
+ } finally { running = false; }
43
+ };
44
+ tick();
45
+ const timer = setInterval(tick, intervalMs);
46
+ timer.unref?.();
47
+ return () => clearInterval(timer);
48
+ }