@syengup/fridaynext 0.1.0-beta.1 → 0.1.0-beta.3
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/package.json +2 -2
- package/src/daemon.mjs +5 -2
- package/src/launchd.mjs +14 -3
- package/src/paths.mjs +1 -0
- package/src/server.mjs +23 -2
- package/src/supervisor.mjs +48 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syengup/fridaynext",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.3",
|
|
4
4
|
"description": "Friday 连接器:一次安装、一次配对,发现并添加这台 Mac 上的全部 Agent",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
"publishConfig": {
|
|
15
15
|
"access": "public",
|
|
16
|
-
"tag": "
|
|
16
|
+
"tag": "latest",
|
|
17
17
|
"registry": "https://registry.npmjs.org/"
|
|
18
18
|
},
|
|
19
19
|
"files": ["src", "provider-packages.json", "README.md", "API.md"],
|
package/src/daemon.mjs
CHANGED
|
@@ -12,8 +12,11 @@ const settings = readJSON(paths.home + "/settings.json", {});
|
|
|
12
12
|
const lan = settings.lanHost ?? lanAddress();
|
|
13
13
|
const port = Number.isSafeInteger(settings.port) ? settings.port : DEFAULT_PORT;
|
|
14
14
|
|
|
15
|
-
const connector = await startConnector({ home, host: settings.listenHost ?? "0.0.0.0", port, lanHost: lan ?? "127.0.0.1" });
|
|
15
|
+
const connector = await startConnector({ home, host: settings.listenHost ?? "0.0.0.0", port, lanHost: lan ?? "127.0.0.1", inventoryMaxAgeMs: 15_000 });
|
|
16
|
+
connector.warmInventory().catch(() => {});
|
|
16
17
|
console.log(`[fridaynext-connector] 已启动 ${connector.url}`);
|
|
17
|
-
|
|
18
|
+
// 开机或崩溃恢复后,自动拉起经连接器启用过、插件已启用但未运行的宿主后端。
|
|
19
|
+
const stopSupervisor = connector.startSupervisor({ log: report => console.log(`[fridaynext-connector] 监督 ${JSON.stringify(report)}`) });
|
|
20
|
+
const stop = () => { stopSupervisor(); return connector.close().then(() => process.exit(0)); };
|
|
18
21
|
process.on("SIGTERM", stop);
|
|
19
22
|
process.on("SIGINT", stop);
|
package/src/launchd.mjs
CHANGED
|
@@ -6,7 +6,16 @@ import path from "node:path";
|
|
|
6
6
|
export const LAUNCHD_LABEL = "ai.fridaynext.connector";
|
|
7
7
|
const escape = value => String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
8
8
|
|
|
9
|
-
|
|
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 }) {
|
|
10
19
|
for (const value of [node, daemon, home]) if (!path.isAbsolute(value)) throw new Error("LaunchAgent 需要绝对路径");
|
|
11
20
|
const logs = path.join(home, "logs", "daemon.log");
|
|
12
21
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
@@ -24,6 +33,8 @@ export function plistFor({ node, daemon, home }) {
|
|
|
24
33
|
<dict>
|
|
25
34
|
<key>FN_CONNECTOR_HOME</key>
|
|
26
35
|
<string>${escape(home)}</string>
|
|
36
|
+
<key>PATH</key>
|
|
37
|
+
<string>${escape(launchPath({ node, path: currentPath }))}</string>
|
|
27
38
|
</dict>
|
|
28
39
|
<key>RunAtLoad</key>
|
|
29
40
|
<true/>
|
|
@@ -45,11 +56,11 @@ const plistPath = dir => path.join(dir, `${LAUNCHD_LABEL}.plist`);
|
|
|
45
56
|
const tolerant = (exec, cmd, args) => { try { exec(cmd, args); } catch { /* 旧实例不存在时 bootout 失败属正常 */ } };
|
|
46
57
|
|
|
47
58
|
/** 写入 LaunchAgent 并加载;先卸下旧实例保证升级后运行新代码。 */
|
|
48
|
-
export function installService({ home, node, daemon, launchAgentsDir = path.join(os.homedir(), "Library", "LaunchAgents"), uid = process.getuid(), exec = defaultExec }) {
|
|
59
|
+
export function installService({ home, node, daemon, launchAgentsDir = path.join(os.homedir(), "Library", "LaunchAgents"), uid = process.getuid(), exec = defaultExec, envPath = process.env.PATH }) {
|
|
49
60
|
fs.mkdirSync(launchAgentsDir, { recursive: true });
|
|
50
61
|
fs.mkdirSync(path.join(home, "logs"), { recursive: true, mode: 0o700 });
|
|
51
62
|
const file = plistPath(launchAgentsDir);
|
|
52
|
-
fs.writeFileSync(file, plistFor({ node, daemon, home }), { mode: 0o644 });
|
|
63
|
+
fs.writeFileSync(file, plistFor({ node, daemon, home, path: envPath }), { mode: 0o644 });
|
|
53
64
|
fs.chmodSync(file, 0o644);
|
|
54
65
|
tolerant(exec, "launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]);
|
|
55
66
|
exec("launchctl", ["bootstrap", `gui/${uid}`, file]);
|
package/src/paths.mjs
CHANGED
|
@@ -18,5 +18,6 @@ export function layout(home) {
|
|
|
18
18
|
devices: path.join(home, "data", "devices.json"),
|
|
19
19
|
inventory: path.join(home, "data", "inventory-state.json"),
|
|
20
20
|
listen: path.join(home, "data", "listen.json"),
|
|
21
|
+
supervised: path.join(home, "data", "supervised.json"),
|
|
21
22
|
};
|
|
22
23
|
}
|
package/src/server.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { deviceStore } from "./devices.mjs";
|
|
|
8
8
|
import { providerRegistry, ProviderError } from "./providers.mjs";
|
|
9
9
|
import { collectInventory } from "./inventory.mjs";
|
|
10
10
|
import { voucherStore, mintConnectorPairing, claimLimiter } from "./pairing.mjs";
|
|
11
|
+
import { supervisedStore, startSupervisor } from "./supervisor.mjs";
|
|
11
12
|
|
|
12
13
|
export const CONNECTOR_VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
13
14
|
const PREFIX = "/friday-next/connector/v1/";
|
|
@@ -34,7 +35,7 @@ function readBody(req, limit = 16_384) {
|
|
|
34
35
|
* 启动连接器 HTTPS 服务(连接器 HTTP API v1)。只监听给定地址;TLS 使用 Kit 身份设施;
|
|
35
36
|
* 电脑令牌只授权本 API,连接器不接触后端永久凭据。
|
|
36
37
|
*/
|
|
37
|
-
export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost, manifest, env = {}, computerName = systemComputerName, now = () => Date.now() }) {
|
|
38
|
+
export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost, manifest, env = {}, computerName = systemComputerName, now = () => Date.now(), inventoryMaxAgeMs = 0 }) {
|
|
38
39
|
const paths = layout(home);
|
|
39
40
|
ensurePrivateDir(home);
|
|
40
41
|
ensurePrivateDir(paths.data);
|
|
@@ -45,9 +46,21 @@ export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost
|
|
|
45
46
|
const vouchers = voucherStore(paths.pairing);
|
|
46
47
|
const limiter = claimLimiter();
|
|
47
48
|
const registry = providerRegistry({ manifest: manifest ?? readJSON(paths.providers) ?? { contract: "fridaynext.provider/1", providers: [] }, env });
|
|
49
|
+
const supervised = supervisedStore(paths.supervised);
|
|
48
50
|
const advertisedHost = lanHost ?? (host === "0.0.0.0" ? "127.0.0.1" : host);
|
|
51
|
+
// 汇总需逐个探测宿主,真机上可能超过 20 秒:保留最近一次结果,过期则后台刷新;宿主操作或改名后失效。
|
|
49
52
|
let inventoryChain = Promise.resolve();
|
|
50
|
-
|
|
53
|
+
let cached = null, cachedAt = 0, refreshing = null;
|
|
54
|
+
const collect = () => (inventoryChain = inventoryChain.then(() => collectInventory({ registry, stateFile: paths.inventory, computer: computer() })));
|
|
55
|
+
const refresh = () => refreshing ??= collect().then(value => { cached = value; cachedAt = Date.now(); return value; }).finally(() => { refreshing = null; });
|
|
56
|
+
const inventory = async () => {
|
|
57
|
+
if (inventoryMaxAgeMs > 0 && cached) {
|
|
58
|
+
if (Date.now() - cachedAt > inventoryMaxAgeMs) refresh().catch(() => {});
|
|
59
|
+
return cached;
|
|
60
|
+
}
|
|
61
|
+
return refresh();
|
|
62
|
+
};
|
|
63
|
+
const invalidate = () => { cached = null; cachedAt = 0; };
|
|
51
64
|
|
|
52
65
|
async function hostAction(res, hostId, command, body) {
|
|
53
66
|
if (!registry.has(hostId)) return fail(res, 404, "HOST_UNKNOWN", "未知宿主");
|
|
@@ -59,6 +72,8 @@ export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost
|
|
|
59
72
|
if (needsConfirm) return fail(res, 409, "HOST_RESTART_CONFIRMATION_REQUIRED", "需要先确认重启宿主");
|
|
60
73
|
}
|
|
61
74
|
const result = await registry.run(hostId, command, command === "enable" ? { confirmHostRestart: confirmed, lanHost: advertisedHost } : { confirmHostRestart: confirmed });
|
|
75
|
+
supervised.add(hostId);
|
|
76
|
+
invalidate();
|
|
62
77
|
return send(res, 200, command === "enable"
|
|
63
78
|
? { state: result.state, hostRestarted: result.hostRestarted === true, changed: result.changed === true }
|
|
64
79
|
: { state: result.state, hostRestarted: result.hostRestarted === true });
|
|
@@ -76,6 +91,7 @@ export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost
|
|
|
76
91
|
pairingTicketTtlSec: Number.isSafeInteger(result.pairingTicketTtlSec) ? result.pairingTicketTtlSec : 600, ...https("publicUrl"), ...https("controlPlane") });
|
|
77
92
|
}
|
|
78
93
|
const result = await registry.run(hostId, command, command === "start" ? { lanHost: advertisedHost } : undefined);
|
|
94
|
+
if (command === "start") { supervised.add(hostId); invalidate(); }
|
|
79
95
|
return send(res, 200, { state: result.state });
|
|
80
96
|
} catch (error) {
|
|
81
97
|
const known = error instanceof ProviderError ? error : new ProviderError("PROVIDER_INTERNAL", "Provider 执行失败", true);
|
|
@@ -112,6 +128,7 @@ export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost
|
|
|
112
128
|
if (tail === "computer" && method === "PATCH") {
|
|
113
129
|
const body = await readBody(req);
|
|
114
130
|
const next = renameComputer(paths.computer, body?.computerName);
|
|
131
|
+
if (next) invalidate();
|
|
115
132
|
return next ? send(res, 200, { computerName: next.computerName }) : fail(res, 400, "INVALID_NAME", "名称无效");
|
|
116
133
|
}
|
|
117
134
|
if (tail === "devices/self" && method === "DELETE") { devices.revoke(device.deviceId); return send(res, 204); }
|
|
@@ -135,7 +152,11 @@ export async function startConnector({ home, host = "0.0.0.0", port = 0, lanHost
|
|
|
135
152
|
return {
|
|
136
153
|
url, port: bound.port, address: bound.address, fingerprint, computerId,
|
|
137
154
|
mintPairing: () => mintConnectorPairing({ vouchers, lanUrl: url, fingerprint, now: now() }),
|
|
155
|
+
/** 守护进程调用:开机与周期监督受监督宿主的后端。 */
|
|
156
|
+
startSupervisor: options => startSupervisor({ registry, store: supervised, ...options }),
|
|
138
157
|
inventory,
|
|
158
|
+
/** 守护进程启动时预热,首次扫码不必等待完整探测。 */
|
|
159
|
+
warmInventory: () => refresh(),
|
|
139
160
|
close: () => new Promise(resolve => { server.closeAllConnections?.(); server.close(() => resolve()); }),
|
|
140
161
|
};
|
|
141
162
|
}
|
|
@@ -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
|
+
}
|