@syengup/fridaynext-claude-code-channel 0.1.0-beta.3 → 0.1.0-beta.5
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 +16 -10
- package/host-version.mjs +19 -0
- package/install.mjs +107 -23
- package/installer-process.mjs +4 -1
- package/package.json +6 -2
- package/plugin.tgz +0 -0
- package/provider.mjs +165 -0
- package/release.json +4 -4
- package/service-owner.mjs +134 -0
package/README.md
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
|
-
# FridayNext Claude Code 插件 · Beta
|
|
1
|
+
# FridayNext Claude Code 插件 · Beta 5 候选
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
本页的一键命令对应 Beta 5 候选 `0.1.0-beta.5`(内置适配器 0.1.32)。当前公开 npm 版本为 `0.1.0-beta.4`(适配器 0.1.31,要求宿主严格为 2.1.312)。
|
|
4
|
+
|
|
5
|
+
Beta 5 发行后,在要连接的项目目录打开终端执行以下命令。
|
|
4
6
|
|
|
5
7
|
```sh
|
|
6
|
-
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.
|
|
8
|
+
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5
|
|
7
9
|
```
|
|
8
10
|
|
|
9
11
|
安装器依次安装官方标准插件、配置连接、启动网关、校验网关并显示二维码。用 Friday Next 扫码即可配对,无需另开终端运行 start 或 pair,也无需手工设置监听和LAN环境变量。关闭安装终端后服务继续运行;电脑重启后重新执行同一命令。
|
|
10
12
|
|
|
11
13
|
## 准备
|
|
12
14
|
|
|
13
|
-
-
|
|
15
|
+
- 候选支持 macOS 和 Linux(实测 Armbian/Debian 13 ARM64),需要 Node.js ≥22.13、Claude Code **2.1.312 或更高版本**,以及兼容插件0.1.32的 Friday iOS 版本。宿主低于 2.1.312 或版本无法识别时,安装器在写入前拒绝并提示“需要 Claude Code 2.1.312 或更高版本”。已验证基线为 2.1.312,更高版本未逐项回归。
|
|
14
16
|
- 先在电脑端安装、登录并配置 Claude Code。固定CLI不在PATH时设置 `FN_CLAUDE_BINARY=/绝对路径/claude`;安装器不安装或替换宿主版本,不复制模型认证。
|
|
15
17
|
- 手机和电脑先连接同一局域网。安装器自动选择实际私网IPv4;多网卡或从个人主目录启动时会询问地址或项目目录。项目范围取运行命令的目录,不自动授权整个HOME。
|
|
16
18
|
|
|
17
19
|
也可以显式选择:
|
|
18
20
|
|
|
19
21
|
```sh
|
|
20
|
-
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.
|
|
22
|
+
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5 --workspace /绝对路径/项目 --lan-host 192.168.1.10
|
|
21
23
|
```
|
|
22
24
|
|
|
23
25
|
## 服务与数据
|
|
@@ -28,16 +30,20 @@ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.3 --workspace /绝对
|
|
|
28
30
|
|
|
29
31
|
重跑同一命令复用已有活跃服务,保留身份/TLS/配对/历史,不重启或修改原监听地址。已有服务只监听环回时会明确提示无法LAN配对,先按原运维方式正常停止,再运行安装器。原来源/版本冲突时拒绝混装;旧研发市场须先正常停止并用官方命令移除旧来源,保留原私有数据。同运行摘要的beta.1安装器可升级到beta.2,其他版本按对应说明操作。
|
|
30
32
|
|
|
33
|
+
## Friday 连接器 Provider(FN-655)
|
|
34
|
+
|
|
35
|
+
发行包另带 `provider.mjs`(bin `fridaynext-claude-provider`),供 Friday 连接器以子进程调用:`node <发行目录>/provider.mjs <probe|enable|start|restart|status|pairing|agents|projects> [--json-input <文件>]`。stdout 为单个合同 JSON,永不输出后端永久 token。手工安装用户无需使用;接口细节见源码仓库中本组件的 API.md。
|
|
36
|
+
|
|
31
37
|
## 常用操作
|
|
32
38
|
|
|
33
39
|
```sh
|
|
34
|
-
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.
|
|
35
|
-
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.
|
|
36
|
-
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.
|
|
40
|
+
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5 status
|
|
41
|
+
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5 pair --qr
|
|
42
|
+
npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5 stop
|
|
37
43
|
```
|
|
38
44
|
|
|
39
45
|
stop正常关闭控制器并保留会话和数据,不把关闭连接当作取消模型。重新运行默认命令恢复。二维码为十分钟一次券,重出作废旧券,已配对手机不受影响;不要公开配对资料。自动化只安装不启动时用 `install --only --json`;原start前台方式及doctor/recover仍可用。卸载使用官方 `claude plugin uninstall fridaynext-claude-code@fridaynext-claude-beta --scope user`,先正常停止自有服务,不删除私有数据。
|
|
40
46
|
|
|
41
|
-
本包内置适配器 0.1.
|
|
47
|
+
本包内置适配器 0.1.32,依赖精确 registry Kit 0.2.0-beta.9 与 SDK 0.3.312。本版提供工作目录的持久卷身份、队列删除、语音输入及会话完全访问选项。外部运行中的原生会话仍按既有权限处理。安装只创建连接所需状态,首次模型请求由用户发起。
|
|
42
48
|
|
|
43
|
-
从较早的 beta
|
|
49
|
+
从较早的 beta 升级时,安装器(以及 Friday 连接器的“添加”)会自动完成升级:停止本安装器或连接器拉起的旧服务,用官方命令卸载旧插件并移除 `fridaynext-claude-beta` 市场登记,把原代码目录改名为 `claude-code-plugin.backup-<时间戳>` 保留,再安装新版。数据目录、工作目录及配置不变,原有身份、配对和历史继续使用。若服务由你自己的 LaunchAgent 等外部方式常驻,安装器不会停止或接管它,也不会升级,会提示先停止该服务;不升级时 Friday 仍可经该服务直接配对。其他来源或更新版本仍返回冲突,需要手工处理。
|
package/host-version.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Claude Code 宿主版本门禁(FN-663):用户决定只要求最低版本,不再精确锁定。
|
|
2
|
+
// 本文件同时随插件载荷与 npm 发行包分发(发行包内为 host-version.mjs),不得引入其他依赖。
|
|
3
|
+
export const MIN_HOST_VERSION = '2.1.312';
|
|
4
|
+
|
|
5
|
+
// 只接受“x.y.z”或“x.y.z (Claude Code)”;预发布后缀、其他产品名或无法解析的输出一律返回 null。
|
|
6
|
+
export function parseHostVersion(text) {
|
|
7
|
+
const match = typeof text === 'string' ? /^(\d+)\.(\d+)\.(\d+)(?: \(Claude Code\))?$/.exec(text.trim()) : null;
|
|
8
|
+
return match ? match.slice(1, 4).map(Number) : null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function hostVersionSupported(text, minimum = MIN_HOST_VERSION) {
|
|
12
|
+
const actual = parseHostVersion(text), floor = parseHostVersion(minimum);
|
|
13
|
+
if (!actual || !floor) return false;
|
|
14
|
+
for (let index = 0; index < 3; index++) if (actual[index] !== floor[index]) return actual[index] > floor[index];
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const hostRequirement = (minimum = MIN_HOST_VERSION, lang = 'zh') =>
|
|
19
|
+
lang === 'zh' ? `需要 Claude Code ${minimum} 或更高版本` : `Requires Claude Code ${minimum} or later`;
|
package/install.mjs
CHANGED
|
@@ -9,11 +9,15 @@ import { promisify } from 'node:util';
|
|
|
9
9
|
import { runInstaller, language } from './installer-flow.mjs';
|
|
10
10
|
import { recovery } from './installer-process.mjs';
|
|
11
11
|
import { claudeOnboarding } from './onboarding.mjs';
|
|
12
|
+
import { hostVersionSupported, hostRequirement, parseHostVersion } from './host-version.mjs';
|
|
13
|
+
import { classifyOwner, ownedByComponent, componentCall, readOwner, processAlive, externalDescription } from './service-owner.mjs';
|
|
12
14
|
|
|
13
|
-
const packageRoot = fileURLToPath(new URL('.', import.meta.url));
|
|
14
|
-
const root = path.resolve(process.env.FN_CLAUDE_INSTALL_ROOT ?? path.join(os.homedir(), '.fridaynext/claude-code-plugin'));
|
|
15
|
-
const binary = process.env.FN_CLAUDE_BINARY ?? 'claude';
|
|
16
|
-
const
|
|
15
|
+
export const packageRoot = fileURLToPath(new URL('.', import.meta.url));
|
|
16
|
+
export const root = path.resolve(process.env.FN_CLAUDE_INSTALL_ROOT ?? path.join(os.homedir(), '.fridaynext/claude-code-plugin'));
|
|
17
|
+
export const binary = process.env.FN_CLAUDE_BINARY ?? 'claude';
|
|
18
|
+
export const dataRoot = path.resolve(process.env.FN_CLAUDE_DATA_ROOT ?? path.join(os.homedir(), 'Library/Application Support/FridayNext/ClaudeCode/service'));
|
|
19
|
+
const MARKET = 'fridaynext-claude-beta';
|
|
20
|
+
export const pluginId = 'fridaynext-claude-code@fridaynext-claude-beta';
|
|
17
21
|
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
18
22
|
const read = file => JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
19
23
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
@@ -34,7 +38,7 @@ async function cli(args, json = true) {
|
|
|
34
38
|
throw Object.assign(new Error('CLAUDE_PLUGIN_COMMAND_FAILED'), { code: 'CLAUDE_PLUGIN_COMMAND_FAILED', operation: args.slice(0, 2).join(' ') });
|
|
35
39
|
}
|
|
36
40
|
}
|
|
37
|
-
async function verify(release) {
|
|
41
|
+
export async function verify(release) {
|
|
38
42
|
const plugin = path.join(root, 'plugin');
|
|
39
43
|
const manifest = read(path.join(plugin, '.claude-plugin/plugin.json'));
|
|
40
44
|
// 与适配器的来源合同核对相同字节;验证前不能加载待验证目录中的程序。
|
|
@@ -44,23 +48,86 @@ async function verify(release) {
|
|
|
44
48
|
for (const file of files) digest.update(file + '\0').update(fs.readFileSync(path.join(plugin, file))).update('\0');
|
|
45
49
|
if (manifest.version !== release.adapterVersion || manifest.name !== 'fridaynext-claude-code' || digest.digest('hex') !== release.sourceDigest) fail('INSTALLED_SOURCE_CHANGED');
|
|
46
50
|
}
|
|
47
|
-
|
|
51
|
+
// 已装代码与本发行的关系(FN-663):none 未装;current 同一载荷;older 同一 marketplace 身份的更旧适配器,可自动升级;conflict 其他。
|
|
52
|
+
const olderVersion = (installed, current) => {
|
|
53
|
+
const a = parseHostVersion(installed), b = parseHostVersion(current);
|
|
54
|
+
if (!a || !b) return false;
|
|
55
|
+
for (let index = 0; index < 3; index++) if (a[index] !== b[index]) return a[index] < b[index];
|
|
56
|
+
return false;
|
|
57
|
+
};
|
|
58
|
+
function sameMarketplace() {
|
|
59
|
+
try {
|
|
60
|
+
const market = read(path.join(root, '.claude-plugin/marketplace.json'));
|
|
61
|
+
return market.name === MARKET && market.plugins?.some(value => value?.name === 'fridaynext-claude-code' && value.source === './plugin');
|
|
62
|
+
} catch { return false; }
|
|
63
|
+
}
|
|
64
|
+
const upgradable = (old, release) => typeof old?.adapterVersion === 'string' && olderVersion(old.adapterVersion, release.adapterVersion) && sameMarketplace();
|
|
65
|
+
export function installedCode() {
|
|
66
|
+
if (!fs.lstatSync(root, { throwIfNoEntry: false })) return { state: 'none' };
|
|
67
|
+
const release = read(path.join(packageRoot, 'release.json'));
|
|
68
|
+
let old;
|
|
69
|
+
try { old = read(path.join(root, 'release.json')); } catch { return { state: 'conflict' }; }
|
|
70
|
+
if (old.payloadSHA256 === release.payloadSHA256) return { state: 'current', old };
|
|
71
|
+
return upgradable(old, release) ? { state: 'older', old } : { state: 'conflict', old };
|
|
72
|
+
}
|
|
73
|
+
// 停止本组件自己拉起的旧 worker:只走其现有的 stop 入口并等待退出,不发信号、不删除数据。
|
|
74
|
+
async function stopOwned(owner) {
|
|
75
|
+
try { await componentCall(owner, 'stop'); } catch { fail('OWNER_STOP_REJECTED'); }
|
|
76
|
+
const end = Date.now() + 100000;
|
|
77
|
+
while (Date.now() < end) {
|
|
78
|
+
const current = readOwner(dataRoot);
|
|
79
|
+
if (!current || current.token !== owner.token || !processAlive(owner.pid)) return;
|
|
80
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
81
|
+
}
|
|
82
|
+
fail('OWNER_STOP_TIMEOUT');
|
|
83
|
+
}
|
|
84
|
+
// 按发行说明的升级流程退役同一 marketplace 身份的旧版本:先核对全部前提再改动;
|
|
85
|
+
// 停本组件旧 worker → 官方命令卸载旧插件与市场登记 → 旧代码目录移到带时间戳的备份(不删除)。数据根不触碰。
|
|
86
|
+
async function retireOlder(old) {
|
|
87
|
+
const ownership = classifyOwner({ dataRoot, installRoots: [root] });
|
|
88
|
+
if (ownership.kind === 'unknown') fail('OWNER_RECORD_UNKNOWN');
|
|
89
|
+
if (ownership.kind === 'external') throw Object.assign(new Error('UPGRADE_BLOCKED_BY_EXTERNAL_SERVICE'), { code: 'UPGRADE_BLOCKED_BY_EXTERNAL_SERVICE',
|
|
90
|
+
hint: `检测到${externalDescription(ownership)}正在运行;为避免与其冲突,未升级插件也未做任何改动。请先停止该服务后重试,或继续使用它直接配对` });
|
|
91
|
+
const plugins = await cli(['plugin', 'list', '--json']), markets = await cli(['plugin', 'marketplace', 'list', '--json']);
|
|
92
|
+
if (plugins.some(value => value.id.startsWith('fridaynext-claude-code@') && value.id !== pluginId)) fail('PLUGIN_SOURCE_CONFLICT');
|
|
93
|
+
const market = markets.find(value => value.name === MARKET);
|
|
94
|
+
if (market && path.resolve(market.installLocation) !== root) fail('MARKETPLACE_SOURCE_CONFLICT');
|
|
95
|
+
if (ownedByComponent(ownership)) await stopOwned(ownership.owner);
|
|
96
|
+
if (plugins.some(value => value.id === pluginId && value.scope === 'user')) await cli(['plugin', 'uninstall', pluginId, '--scope', 'user'], false);
|
|
97
|
+
if (market) await cli(['plugin', 'marketplace', 'remove', MARKET, '--scope', 'user'], false);
|
|
98
|
+
let backup = root + '.backup-' + new Date().toISOString().replace(/[:.]/g, '-');
|
|
99
|
+
if (fs.existsSync(backup)) backup += '-' + process.pid;
|
|
100
|
+
fs.renameSync(root, backup);
|
|
101
|
+
return { upgradedFrom: old.adapterVersion, backup };
|
|
102
|
+
}
|
|
103
|
+
// onChange 只用于 Provider 判断 enable 是否真的改动了宿主或代码(FN-655);安装器流程不传,行为不变。
|
|
104
|
+
export async function install(options = {}) {
|
|
105
|
+
const changed = typeof options.onChange === 'function' ? options.onChange : () => {};
|
|
48
106
|
const release = read(path.join(packageRoot, 'release.json'));
|
|
49
|
-
const dataRoot = path.resolve(process.env.FN_CLAUDE_DATA_ROOT ?? path.join(os.homedir(), 'Library/Application Support/FridayNext/ClaudeCode/service'));
|
|
50
107
|
if (root === dataRoot || root.startsWith(dataRoot + path.sep) || dataRoot.startsWith(root + path.sep)) fail('INSTALL_ROOT_OVERLAPS_STATE');
|
|
51
|
-
|
|
108
|
+
// release.host 自 beta.5 起是最低宿主版本(FN-663):更高版本放行,更低或无法解析的版本在任何写入前拒绝。
|
|
109
|
+
if (!hostVersionSupported(await cli(['--version'], false), release.host))
|
|
110
|
+
throw Object.assign(new Error('HOST_VERSION_UNSUPPORTED'), { code: 'HOST_VERSION_UNSUPPORTED', hint: hostRequirement(release.host) });
|
|
52
111
|
if (hash(fs.readFileSync(path.join(packageRoot, 'plugin.tgz'))) !== release.payloadSHA256) fail('RELEASE_PAYLOAD_CHANGED');
|
|
53
112
|
if (fs.lstatSync(path.dirname(root), { throwIfNoEntry: false })?.isSymbolicLink()) fail('INSTALL_ROOT_UNSAFE');
|
|
113
|
+
let upgrade;
|
|
54
114
|
if (fs.lstatSync(root, { throwIfNoEntry: false })) {
|
|
55
115
|
privateRoot();
|
|
56
116
|
const old = read(path.join(root, 'release.json'));
|
|
57
117
|
if (old.payloadSHA256 !== release.payloadSHA256 || old.distributionVersion !== release.distributionVersion) {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
118
|
+
const installerOnly = old.distributionVersion === '0.1.0-beta.1' && release.distributionVersion === '0.1.0-beta.2' &&
|
|
119
|
+
['adapterVersion', 'sourceDigest', 'host', 'sdk', 'kit'].every(key => old[key] === release[key]);
|
|
120
|
+
if (installerOnly) {
|
|
121
|
+
await verify(old);
|
|
122
|
+
fs.writeFileSync(path.join(root, 'release.json'), JSON.stringify({ ...release, runtimePayloadSHA256: old.runtimePayloadSHA256 ?? old.payloadSHA256 }), { mode: 0o600 });
|
|
123
|
+
changed('release');
|
|
124
|
+
} else if (upgradable(old, release)) {
|
|
125
|
+
upgrade = await retireOlder(old);
|
|
126
|
+
changed('upgrade');
|
|
127
|
+
} else fail('INSTALL_VERSION_CONFLICT');
|
|
62
128
|
}
|
|
63
|
-
}
|
|
129
|
+
}
|
|
130
|
+
if (!fs.lstatSync(root, { throwIfNoEntry: false })) {
|
|
64
131
|
fs.mkdirSync(path.dirname(root), { recursive: true, mode: 0o700 });
|
|
65
132
|
const stage = fs.mkdtempSync(path.join(path.dirname(root), '.claude-install-'));
|
|
66
133
|
try {
|
|
@@ -69,6 +136,7 @@ async function install() {
|
|
|
69
136
|
execFileSync('tar', ['-xzf', path.join(packageRoot, 'plugin.tgz'), '-C', stage]);
|
|
70
137
|
fs.writeFileSync(path.join(stage, 'release.json'), JSON.stringify(release), { mode: 0o600 });
|
|
71
138
|
fs.renameSync(stage, root);
|
|
139
|
+
changed('code');
|
|
72
140
|
} finally { if (fs.existsSync(stage)) fs.rmSync(stage, { recursive: true, force: true }); }
|
|
73
141
|
}
|
|
74
142
|
privateRoot(); await verify(release);
|
|
@@ -76,18 +144,31 @@ async function install() {
|
|
|
76
144
|
const markets = await cli(['plugin', 'marketplace', 'list', '--json']);
|
|
77
145
|
const market = markets.find(value => value.name === 'fridaynext-claude-beta');
|
|
78
146
|
if (market && path.resolve(market.installLocation) !== root) fail('MARKETPLACE_SOURCE_CONFLICT');
|
|
79
|
-
if (!market) await cli(['plugin', 'marketplace', 'add', root, '--scope', 'user', '--json']);
|
|
147
|
+
if (!market) { await cli(['plugin', 'marketplace', 'add', root, '--scope', 'user', '--json']); changed('marketplace'); }
|
|
80
148
|
const plugins = await cli(['plugin', 'list', '--json']);
|
|
81
149
|
if (plugins.some(value => value.id.startsWith('fridaynext-claude-code@') && value.id !== pluginId)) fail('PLUGIN_SOURCE_CONFLICT');
|
|
82
150
|
const current = plugins.find(value => value.id === pluginId && value.scope === 'user');
|
|
83
151
|
if (current && current.version !== release.adapterVersion) fail('PLUGIN_VERSION_CONFLICT');
|
|
84
|
-
if (!current) await cli(['plugin', 'install', pluginId, '--scope', 'user', '--json']);
|
|
85
|
-
|
|
152
|
+
if (!current) { await cli(['plugin', 'install', pluginId, '--scope', 'user', '--json']); changed('install'); }
|
|
153
|
+
// 官方列表明确报告已启用时不重复 enable;其余情况沿原调用,官方幂等回执不算改动。
|
|
154
|
+
if (current?.enabled !== true) {
|
|
155
|
+
const enabled = await cli(['plugin', 'enable', pluginId, '--scope', 'user', '--json']);
|
|
156
|
+
if (enabled?.alreadyInGoalState !== true) changed('enable');
|
|
157
|
+
}
|
|
86
158
|
const receipt = { state: 'installed', distributionVersion: release.distributionVersion, adapterVersion: release.adapterVersion,
|
|
87
|
-
pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false };
|
|
159
|
+
pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false, ...(upgrade ? { upgradedFrom: upgrade.upgradedFrom, backup: upgrade.backup } : {}) };
|
|
88
160
|
fs.writeFileSync(path.join(root, 'installed.json'), JSON.stringify(receipt), { mode: 0o600 });
|
|
89
161
|
return receipt;
|
|
90
162
|
}
|
|
163
|
+
// Provider 委托运行时命令前的同一套已装源码核对:版本一致且源码摘要未变,验证前不执行目标目录中的程序。
|
|
164
|
+
export async function assertInstalledRelease() {
|
|
165
|
+
if (!fs.existsSync(root)) fail('PLUGIN_NOT_INSTALLED'); privateRoot();
|
|
166
|
+
const release = read(path.join(packageRoot, 'release.json')), installed = read(path.join(root, 'release.json'));
|
|
167
|
+
if (installed.payloadSHA256 !== release.payloadSHA256) fail('INSTALL_VERSION_CONFLICT');
|
|
168
|
+
await verify(release);
|
|
169
|
+
return release;
|
|
170
|
+
}
|
|
171
|
+
async function main() {
|
|
91
172
|
try {
|
|
92
173
|
const [major, minor] = process.versions.node.split('.').map(Number);
|
|
93
174
|
if (major < 22 || major === 22 && minor < 13) fail('NODE_VERSION_UNSUPPORTED');
|
|
@@ -105,17 +186,20 @@ try {
|
|
|
105
186
|
if (options.only) console.log(JSON.stringify(await install(), null, 2));
|
|
106
187
|
else {
|
|
107
188
|
const onboarding = claudeOnboarding({ root, binary, options });
|
|
108
|
-
|
|
189
|
+
// 宿主版本不足时提示最低版本;带说明的失败(如外部常驻服务阻止升级)显示该说明;其余沿共享安装器的恢复说明。
|
|
190
|
+
const claudeRecovery = (error, lang) => error.code === 'HOST_VERSION_UNSUPPORTED'
|
|
191
|
+
? [hostRequirement(read(path.join(packageRoot, 'release.json')).host, lang)] : typeof error.hint === 'string' ? [error.hint] : recovery(error, lang);
|
|
192
|
+
await runInstaller({ name: 'Claude Code', lang: language(), install, ...onboarding, recovery: claudeRecovery });
|
|
109
193
|
}
|
|
110
194
|
}
|
|
111
195
|
else if (['start', 'status', 'pair', 'stop', 'doctor', 'recover'].includes(command)) {
|
|
112
|
-
|
|
113
|
-
const release = read(path.join(packageRoot, 'release.json')), installed = read(path.join(root, 'release.json'));
|
|
114
|
-
if (installed.payloadSHA256 !== release.payloadSHA256) fail('INSTALL_VERSION_CONFLICT');
|
|
115
|
-
await verify(release);
|
|
196
|
+
await assertInstalledRelease();
|
|
116
197
|
const child = spawnSync(process.execPath, [path.join(root, 'plugin/src/cli.mjs'), command, ...args], { stdio: 'inherit', env: process.env });
|
|
117
198
|
process.exitCode = child.status ?? 1;
|
|
118
199
|
} else fail('COMMAND_UNSUPPORTED');
|
|
119
200
|
} catch (error) {
|
|
120
|
-
if (!error.presented) console.error(JSON.stringify({ code: typeof error.code === 'string' ? error.code : 'CLAUDE_INSTALL_FAILED', operation: error.operation })); process.exitCode = 1;
|
|
201
|
+
if (!error.presented) console.error(JSON.stringify({ code: typeof error.code === 'string' ? error.code : 'CLAUDE_INSTALL_FAILED', operation: error.operation, hint: error.hint })); process.exitCode = 1;
|
|
202
|
+
}
|
|
121
203
|
}
|
|
204
|
+
// 仅作为可执行入口运行时执行安装器;被 Provider 导入时只提供上面的函数。
|
|
205
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
|
package/installer-process.mjs
CHANGED
|
@@ -146,7 +146,10 @@ export function recovery(error, lang = language()) {
|
|
|
146
146
|
const zh = lang === 'zh';
|
|
147
147
|
const messages = {
|
|
148
148
|
HOST_VERSION_UNSUPPORTED: zh ? '请安装文档指定的宿主版本后重试' : 'Install the documented host version and retry',
|
|
149
|
-
|
|
149
|
+
CODEX_BINARY_NOT_FOUND: zh ? '找不到 Codex CLI。请安装 Codex 或将 FN_CODEX_BINARY 指向其可执行文件' : 'Codex CLI was not found. Install it or set FN_CODEX_BINARY to its executable',
|
|
150
|
+
CODEX_PLUGIN_COMMAND_FAILED: zh ? 'Codex 的本地插件命令未执行成功。请确认当前的官方 CLI 支持本地插件市场并重试' : 'A local Codex plugin command failed. Ensure the official CLI supports local plugin marketplaces and retry',
|
|
151
|
+
CODEX_PLUGIN_COMMAND_TIMEOUT: zh ? 'Codex 本地插件命令超时。请检查 Codex 是否能正常启动后重试' : 'A local Codex plugin command timed out. Check that Codex starts normally and retry',
|
|
152
|
+
CODEX_CLI_RESPONSE_UNKNOWN: zh ? '无法识别 Codex CLI 返回。请核对 PATH 或 FN_CODEX_BINARY 是否指向官方 Codex CLI' : 'Unrecognized Codex CLI response. Check PATH or FN_CODEX_BINARY for the official Codex CLI',
|
|
150
153
|
CLAUDE_PLUGIN_COMMAND_FAILED: zh ? '请确认 Claude Code 已安装,或设置 FN_CLAUDE_BINARY 后重试' : 'Check Claude Code installation or set FN_CLAUDE_BINARY and retry',
|
|
151
154
|
UPSTREAM_LOGIN_REQUIRED: zh ? '请先在电脑端登录宿主,再重新运行安装命令' : 'Sign in to the host on this computer, then rerun the installer',
|
|
152
155
|
WORKSPACE_REQUIRED: zh ? '请在要连接的项目目录运行,或传入 --workspace /项目绝对路径' : 'Run in your project, or pass --workspace /absolute/project/path',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syengup/fridaynext-claude-code-channel",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "通过Claude Code官方插件命令安装FridayNext,并连接已授权的SDK自有会话",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -8,10 +8,14 @@
|
|
|
8
8
|
"node": ">=22.13.0"
|
|
9
9
|
},
|
|
10
10
|
"bin": {
|
|
11
|
-
"fridaynext-claude-code-channel": "install.mjs"
|
|
11
|
+
"fridaynext-claude-code-channel": "install.mjs",
|
|
12
|
+
"fridaynext-claude-provider": "provider.mjs"
|
|
12
13
|
},
|
|
13
14
|
"files": [
|
|
14
15
|
"install.mjs",
|
|
16
|
+
"provider.mjs",
|
|
17
|
+
"host-version.mjs",
|
|
18
|
+
"service-owner.mjs",
|
|
15
19
|
"onboarding.mjs",
|
|
16
20
|
"installer-ui.mjs",
|
|
17
21
|
"installer-flow.mjs",
|
package/plugin.tgz
CHANGED
|
Binary file
|
package/provider.mjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Friday 连接器调用的 Claude Code Provider 入口(合同 fridaynext.provider/1,FN-655)。
|
|
3
|
+
// 用法:fridaynext-claude-provider <probe|enable|start|restart|status|pairing|agents|projects> [--json-input <文件>]
|
|
4
|
+
// probe/enable/agents 在本发行包内完成;运行时命令在核对已装源码后委托给已装插件的 src/provider.mjs。
|
|
5
|
+
// stdout 只输出一个 JSON 对象;日志写 stderr,且不含凭据。永不输出后端永久 token。
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { execFile } from 'node:child_process';
|
|
11
|
+
import { promisify } from 'node:util';
|
|
12
|
+
import { install, assertInstalledRelease, installedCode, root, binary, pluginId, packageRoot, dataRoot } from './install.mjs';
|
|
13
|
+
import { observeService, componentCall, pairingProjection, externalDescription, EXTERNAL_PAIRING_HINT } from './service-owner.mjs';
|
|
14
|
+
import { parseHostVersion, hostVersionSupported, hostRequirement } from './host-version.mjs';
|
|
15
|
+
|
|
16
|
+
const CONTRACT = 'fridaynext.provider/1', HOST_ID = 'claude-code';
|
|
17
|
+
const AGENTS = [{ agentId: 'claude-code', displayName: 'Claude Code' }];
|
|
18
|
+
const run = promisify(execFile);
|
|
19
|
+
class ProviderFailure extends Error {
|
|
20
|
+
constructor(code, message = code, retryable = false) { super(message); this.code = code; this.retryable = retryable; }
|
|
21
|
+
}
|
|
22
|
+
const release = () => JSON.parse(fs.readFileSync(path.join(packageRoot, 'release.json'), 'utf8'));
|
|
23
|
+
// 只有与本发行同一载荷的已装代码才委托给已装插件;旧版本或外部常驻服务由本入口只读观察(FN-663)。
|
|
24
|
+
const codeCurrent = () => installedCode().state === 'current';
|
|
25
|
+
const observe = () => observeService({ dataRoot, installRoots: [root] });
|
|
26
|
+
// release.host 自 beta.5 起表示最低宿主版本(FN-663);指引只提示最低版本,安装官方当前版本即可。
|
|
27
|
+
const installGuide = host => ({ title: `安装 Claude Code ${host} 或更高版本`, command: 'npm install -g @anthropic-ai/claude-code',
|
|
28
|
+
url: 'https://docs.claude.com/en/docs/claude-code/setup' });
|
|
29
|
+
|
|
30
|
+
// 只读宿主探测:可执行文件不存在即未安装;版本须不低于 release.host(最低版本),无法解析视为不兼容。
|
|
31
|
+
async function hostProbe() {
|
|
32
|
+
const host = release().host;
|
|
33
|
+
try {
|
|
34
|
+
const { stdout } = await run(binary, ['--version'], { timeout: 8000, maxBuffer: 8192 });
|
|
35
|
+
const version = parseHostVersion(stdout)?.join('.') ?? null;
|
|
36
|
+
return { installed: true, hostVersion: version, compatible: hostVersionSupported(stdout, host), host };
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code)) return { installed: false, hostVersion: null, compatible: false, host };
|
|
39
|
+
return { installed: true, hostVersion: null, compatible: false, host };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// 只读插件状态:官方 plugin list;未报告 enabled 字段时退回读取用户 settings.json 的 enabledPlugins。
|
|
43
|
+
async function pluginEnabled() {
|
|
44
|
+
let list;
|
|
45
|
+
try { list = JSON.parse((await run(binary, ['plugin', 'list', '--json'], { timeout: 8000, maxBuffer: 1048576 })).stdout); }
|
|
46
|
+
catch { return false; }
|
|
47
|
+
const entry = Array.isArray(list) ? list.find(value => value?.id === pluginId && value.scope === 'user') : undefined;
|
|
48
|
+
if (!entry) return false;
|
|
49
|
+
if (typeof entry.enabled === 'boolean') return entry.enabled;
|
|
50
|
+
try {
|
|
51
|
+
const config = process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), '.claude');
|
|
52
|
+
return JSON.parse(fs.readFileSync(path.join(config, 'settings.json'), 'utf8')).enabledPlugins?.[pluginId] === true;
|
|
53
|
+
} catch { return false; }
|
|
54
|
+
}
|
|
55
|
+
// 委托已装插件:先核对已装源码与本发行一致,再以固定参数启动子进程。
|
|
56
|
+
async function delegate(command, inputFile) {
|
|
57
|
+
try { await assertInstalledRelease(); }
|
|
58
|
+
catch (error) { throw new ProviderFailure('PROVIDER_INTERNAL', typeof error.code === 'string' ? error.code : 'INSTALLED_SOURCE_UNVERIFIED'); }
|
|
59
|
+
const args = [path.join(root, 'plugin/src/provider.mjs'), command, ...(inputFile ? ['--json-input', inputFile] : [])];
|
|
60
|
+
let stdout;
|
|
61
|
+
try { stdout = (await run(process.execPath, args, { timeout: 115000, maxBuffer: 1048576, env: process.env })).stdout; }
|
|
62
|
+
catch (error) { stdout = error.stdout; if (!stdout) throw new ProviderFailure('PROVIDER_INTERNAL', 'RUNTIME_PROVIDER_FAILED', true); }
|
|
63
|
+
let body;
|
|
64
|
+
try { body = JSON.parse(stdout); } catch { throw new ProviderFailure('PROVIDER_INTERNAL', 'RUNTIME_PROVIDER_OUTPUT_INVALID'); }
|
|
65
|
+
if (body?.contract !== CONTRACT || body.hostId !== HOST_ID) throw new ProviderFailure('PROVIDER_INTERNAL', 'RUNTIME_PROVIDER_CONTRACT_MISMATCH');
|
|
66
|
+
if (body.ok !== true) throw new ProviderFailure(body.error?.code ?? 'PROVIDER_INTERNAL', body.error?.message ?? 'RUNTIME_PROVIDER_FAILED', body.error?.retryable === true);
|
|
67
|
+
const { contract: _contract, hostId: _host, ok: _ok, ...result } = body;
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
const runningState = async () => {
|
|
71
|
+
if (!codeCurrent()) return (await observe()).state === 'running';
|
|
72
|
+
try { return (await delegate('status')).state === 'running'; } catch { return false; }
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const commands = {
|
|
76
|
+
async probe() {
|
|
77
|
+
const host = await hostProbe();
|
|
78
|
+
const result = { installed: host.installed, hostVersion: host.hostVersion, compatible: host.compatible,
|
|
79
|
+
pluginEnabled: false, running: false, needsHostRestartToEnable: false, upgradeAvailable: false };
|
|
80
|
+
if (!host.installed) return { ...result, installGuide: installGuide(host.host) };
|
|
81
|
+
if (!host.compatible) return result;
|
|
82
|
+
const code = installedCode(), enabled = await pluginEnabled();
|
|
83
|
+
if (code.state === 'current') return { ...result, pluginEnabled: enabled, running: await runningState() };
|
|
84
|
+
// 已装同一 marketplace 的旧版本:如实报告可升级。外部常驻服务健康时按运行中报告以便直接配对;
|
|
85
|
+
// 否则报告为未启用(needsEnable),App 点“添加”即调用 enable 完成自动升级。
|
|
86
|
+
const service = await observe(), running = service.state === 'running';
|
|
87
|
+
const externalRunning = running && service.ownership.kind === 'external';
|
|
88
|
+
return { ...result, upgradeAvailable: code.state === 'older', pluginEnabled: code.state === 'older' ? externalRunning && enabled : enabled, running };
|
|
89
|
+
},
|
|
90
|
+
async enable() {
|
|
91
|
+
const host = await hostProbe();
|
|
92
|
+
if (!host.installed) throw new ProviderFailure('HOST_NOT_INSTALLED', '未找到 Claude Code CLI');
|
|
93
|
+
if (!host.compatible) throw new ProviderFailure('HOST_INCOMPATIBLE', hostRequirement(host.host));
|
|
94
|
+
let changed = false, receipt;
|
|
95
|
+
try { receipt = await install({ onChange: () => { changed = true; } }); }
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (error.code === 'HOST_VERSION_UNSUPPORTED') throw new ProviderFailure('HOST_INCOMPATIBLE', hostRequirement(host.host));
|
|
98
|
+
// 外部常驻服务在跑:不升级、不改动,说明原因(FN-663)。
|
|
99
|
+
if (error.code === 'UPGRADE_BLOCKED_BY_EXTERNAL_SERVICE') throw new ProviderFailure('PLUGIN_NOT_ENABLED', error.hint);
|
|
100
|
+
if (['OWNER_STOP_REJECTED', 'OWNER_STOP_TIMEOUT'].includes(error.code)) throw new ProviderFailure('PROVIDER_INTERNAL', error.code, true);
|
|
101
|
+
throw new ProviderFailure('PROVIDER_INTERNAL', typeof error.code === 'string' ? error.code : 'CLAUDE_INSTALL_FAILED');
|
|
102
|
+
}
|
|
103
|
+
// 启用插件不需要重启 Claude Code;后端服务由 start 单独启动。
|
|
104
|
+
return { changed, hostRestarted: false, state: await runningState() ? 'running' : 'stopped', ...(receipt?.upgradedFrom ? { upgradedFrom: receipt.upgradedFrom } : {}) };
|
|
105
|
+
},
|
|
106
|
+
async agents() { return { agents: AGENTS, revision: createHash('sha256').update(JSON.stringify(AGENTS)).digest('hex') }; },
|
|
107
|
+
async status() {
|
|
108
|
+
const code = installedCode();
|
|
109
|
+
if (code.state === 'current' || code.state === 'conflict') {
|
|
110
|
+
const result = await delegate('status');
|
|
111
|
+
if (result.state !== 'stopped' || await pluginEnabled()) return result;
|
|
112
|
+
return { ...result, state: 'needsEnable' };
|
|
113
|
+
}
|
|
114
|
+
const service = await observe();
|
|
115
|
+
if (service.state === 'running') return { state: 'running', health: service.health };
|
|
116
|
+
if (code.state === 'older') return { state: 'needsEnable', health: { reachable: false } };
|
|
117
|
+
const host = await hostProbe();
|
|
118
|
+
return { state: !host.installed ? 'notInstalled' : !host.compatible ? 'incompatible' : 'needsEnable', health: { reachable: false } };
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
// 未装当前版本时:外部常驻服务健康则 start 如实返回运行中、pairing 经其现有铸券入口;restart 与升级都不动它(FN-663)。
|
|
122
|
+
async function withoutCurrentCode(name) {
|
|
123
|
+
const code = installedCode();
|
|
124
|
+
if (code.state === 'conflict') return delegate(name);
|
|
125
|
+
if (name !== 'projects') {
|
|
126
|
+
const service = await observe(), external = service.ownership.kind === 'external', running = service.state === 'running';
|
|
127
|
+
const describe = action => `${externalDescription(service.ownership)}${action};连接器不停止、接管或重启它`;
|
|
128
|
+
if (name === 'pairing' && running) {
|
|
129
|
+
let value;
|
|
130
|
+
try { value = await componentCall(service.ownership.owner, 'pair'); }
|
|
131
|
+
catch { throw external ? new ProviderFailure('PAIRING_UNAVAILABLE', EXTERNAL_PAIRING_HINT) : new ProviderFailure('PAIRING_UNAVAILABLE', 'PAIRING_REQUEST_FAILED', true); }
|
|
132
|
+
const projected = pairingProjection(value);
|
|
133
|
+
if (projected.invalid) throw new ProviderFailure('PAIRING_UNAVAILABLE', external && projected.invalid === 'PAIRING_RESULT_INVALID' ? EXTERNAL_PAIRING_HINT : projected.invalid);
|
|
134
|
+
return projected.result;
|
|
135
|
+
}
|
|
136
|
+
if (external && name === 'start') {
|
|
137
|
+
if (running) return { state: 'running', health: service.health };
|
|
138
|
+
throw new ProviderFailure('HOST_NOT_RUNNING', describe('未就绪'), true);
|
|
139
|
+
}
|
|
140
|
+
if (external && name === 'restart') throw new ProviderFailure('HOST_RESTART_FAILED', describe('正在运行'));
|
|
141
|
+
}
|
|
142
|
+
throw new ProviderFailure('PLUGIN_NOT_ENABLED', code.state === 'older' ? '已装旧版本插件,请先启用以升级到当前版本' : '请先启用 FridayNext Claude Code 插件');
|
|
143
|
+
}
|
|
144
|
+
for (const name of ['start', 'restart', 'pairing', 'projects']) {
|
|
145
|
+
commands[name] = async inputFile => codeCurrent() ? delegate(name, name === 'restart' ? inputFile : undefined) : withoutCurrentCode(name);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const args = process.argv.slice(2), command = args[0];
|
|
149
|
+
const write = value => process.stdout.write(JSON.stringify(value) + '\n');
|
|
150
|
+
try {
|
|
151
|
+
if (args.length !== 1 && !(args.length === 3 && args[1] === '--json-input')) throw new ProviderFailure('UNSUPPORTED_COMMAND', 'CLI_ARGUMENT_INVALID');
|
|
152
|
+
const inputFile = args[2];
|
|
153
|
+
if (inputFile !== undefined) {
|
|
154
|
+
// 输入只接受 JSON 对象;当前命令都不依赖其中字段(重启确认由连接器把关)。
|
|
155
|
+
let input; try { input = JSON.parse(fs.readFileSync(inputFile, 'utf8')); } catch { throw new ProviderFailure('UNSUPPORTED_COMMAND', 'JSON_INPUT_INVALID'); }
|
|
156
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new ProviderFailure('UNSUPPORTED_COMMAND', 'JSON_INPUT_INVALID');
|
|
157
|
+
}
|
|
158
|
+
if (!Object.hasOwn(commands, command)) throw new ProviderFailure('UNSUPPORTED_COMMAND', '不支持的命令');
|
|
159
|
+
write({ contract: CONTRACT, hostId: HOST_ID, ok: true, ...await commands[command](inputFile) });
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const known = error instanceof ProviderFailure;
|
|
162
|
+
write({ contract: CONTRACT, hostId: HOST_ID, ok: false, error: { code: known ? error.code : 'PROVIDER_INTERNAL',
|
|
163
|
+
message: known ? error.message : 'PROVIDER_INTERNAL', retryable: known && error.retryable === true } });
|
|
164
|
+
process.exitCode = 1;
|
|
165
|
+
}
|
package/release.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"distributionVersion": "0.1.0-beta.
|
|
4
|
-
"adapterVersion": "0.1.
|
|
3
|
+
"distributionVersion": "0.1.0-beta.5",
|
|
4
|
+
"adapterVersion": "0.1.32",
|
|
5
5
|
"host": "2.1.312",
|
|
6
6
|
"sdk": "0.3.312",
|
|
7
7
|
"kit": "0.2.0-beta.9",
|
|
8
|
-
"sourceDigest": "
|
|
9
|
-
"payloadSHA256": "
|
|
8
|
+
"sourceDigest": "47affa5c4c1475b2a8b83ccfa7717424d9a7e13dfbc938fc1f96c02e07cc57af",
|
|
9
|
+
"payloadSHA256": "9819683a4c1f8fc3fa49e0d7f4f0ce36314fdbbdcb020e2267d198859889acbf"
|
|
10
10
|
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// 常驻服务归属判定与只读观察(FN-663)。
|
|
2
|
+
// 随插件载荷与 npm 发行包分发(发行包内为 service-owner.mjs);只依赖 Node 内置模块,不加载已装目录中的程序。
|
|
3
|
+
// 归属只认两类“本组件拉起”的进程:连接器 worker(数据根中的标记与当前 owner token 摘要一致)
|
|
4
|
+
// 与本组件 npx 安装器的后台 worker(命令行为本组件代码根下 installer/onboarding.mjs --worker)。
|
|
5
|
+
// 其余仍存活的 owner(例如用户自己的 LaunchAgent 常驻服务)一律视为外部托管:不停止、不接管、不重启。
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import http from 'node:http';
|
|
9
|
+
import https from 'node:https';
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import { createHash, X509Certificate } from 'node:crypto';
|
|
12
|
+
|
|
13
|
+
export const CONNECTOR_MARKER = 'connector-worker.json';
|
|
14
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
15
|
+
|
|
16
|
+
export function readPrivateJSON(file) {
|
|
17
|
+
const stat = fs.lstatSync(file);
|
|
18
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 0o077)) throw Object.assign(new Error('STATE_FILE_NOT_PRIVATE'), { code: 'STATE_FILE_NOT_PRIVATE' });
|
|
19
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
20
|
+
}
|
|
21
|
+
export const processAlive = pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
|
|
22
|
+
|
|
23
|
+
// null:没有 owner 锁;{ unknown: true }:锁存在但记录不可读。
|
|
24
|
+
export function readOwner(dataRoot) {
|
|
25
|
+
const directory = path.join(dataRoot, 'controller-owner');
|
|
26
|
+
try { fs.lstatSync(directory); } catch { return null; }
|
|
27
|
+
try { return readPrivateJSON(path.join(directory, 'owner.json')); } catch { return { unknown: true }; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 只读进程信息:命令行(ps)与 macOS launchd 托管标签(launchctl list 中该 pid 所在的作业)。
|
|
31
|
+
export function defaultProcessInfo(pid) {
|
|
32
|
+
let command = null, launchdLabel = null;
|
|
33
|
+
try { command = execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null; } catch { /* 无法读取时按未知处理。 */ }
|
|
34
|
+
if (process.platform === 'darwin') {
|
|
35
|
+
try {
|
|
36
|
+
for (const row of execFileSync('launchctl', ['list'], { encoding: 'utf8', timeout: 5000, maxBuffer: 8 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] }).split('\n')) {
|
|
37
|
+
const [value, , label] = row.split('\t');
|
|
38
|
+
if (Number(value) === pid && label) { launchdLabel = label.trim(); break; }
|
|
39
|
+
}
|
|
40
|
+
} catch { /* launchctl 不可用时只依据命令行。 */ }
|
|
41
|
+
}
|
|
42
|
+
return { command, launchdLabel };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const quoteFree = value => value.replace(/["']/g, '');
|
|
46
|
+
// kind:none | unknown | stale | connector | installer | external
|
|
47
|
+
export function classifyOwner({ dataRoot, installRoots = [], owner = readOwner(dataRoot), processInfo = defaultProcessInfo }) {
|
|
48
|
+
if (!owner) return { kind: 'none' };
|
|
49
|
+
if (owner.unknown) return { kind: 'unknown', owner };
|
|
50
|
+
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 || !processAlive(owner.pid)) return { kind: 'stale', owner };
|
|
51
|
+
const info = processInfo(owner.pid) ?? {};
|
|
52
|
+
// 由 launchd 作业托管的进程,即使命令行相似也不是本组件拉起的(KeepAlive 会与停止/接管互相打架)。
|
|
53
|
+
if (info.launchdLabel) return { kind: 'external', owner, reason: 'LAUNCHD_JOB', launchdLabel: info.launchdLabel };
|
|
54
|
+
let marker = false;
|
|
55
|
+
try { marker = typeof owner.token === 'string' && readPrivateJSON(path.join(dataRoot, CONNECTOR_MARKER)).owner === digest(owner.token); } catch { marker = false; }
|
|
56
|
+
if (marker) return { kind: 'connector', owner };
|
|
57
|
+
const command = quoteFree(info.command ?? '');
|
|
58
|
+
const roots = installRoots.filter(Boolean).flatMap(root => { const value = path.resolve(root); try { return [value, fs.realpathSync(value)]; } catch { return [value]; } });
|
|
59
|
+
const worker = roots.some(root => command.includes(path.join(root, 'installer', 'onboarding.mjs') + ' --worker'));
|
|
60
|
+
if (worker) return { kind: 'installer', owner };
|
|
61
|
+
return { kind: 'external', owner, reason: command ? 'PROCESS_NOT_OWNED' : 'PROCESS_UNKNOWN' };
|
|
62
|
+
}
|
|
63
|
+
export const ownedByComponent = ownership => ownership.kind === 'connector' || ownership.kind === 'installer';
|
|
64
|
+
|
|
65
|
+
// 控制器本机 IPC(与 component-ipc.mjs 同一协议),只发往环回。
|
|
66
|
+
export function componentCall({ port, token } = {}, method, timeoutMs = 5000) {
|
|
67
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || typeof token !== 'string' || token.length < 32)
|
|
68
|
+
return Promise.reject(Object.assign(new Error('CONTROLLER_NOT_CONFIGURED'), { code: 'CONTROLLER_NOT_CONFIGURED' }));
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
const body = JSON.stringify({ method, input: {} });
|
|
71
|
+
const request = http.request({ hostname: '127.0.0.1', port, path: '/component', method: 'POST', timeout: timeoutMs,
|
|
72
|
+
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, response => {
|
|
73
|
+
let text = '';
|
|
74
|
+
response.on('data', chunk => { text += chunk; if (text.length > 65536) request.destroy(new Error('CONTROLLER_RESPONSE_TOO_LARGE')); });
|
|
75
|
+
response.on('end', () => {
|
|
76
|
+
try { const value = JSON.parse(text); response.statusCode === 200 ? resolve(value) : reject(Object.assign(new Error(value.code ?? 'CONTROLLER_REJECTED'), { code: value.code ?? 'CONTROLLER_REJECTED' })); }
|
|
77
|
+
catch (error) { reject(error); }
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
request.once('timeout', () => request.destroy(Object.assign(new Error('CONTROLLER_UNAVAILABLE'), { code: 'CONTROLLER_UNAVAILABLE' })));
|
|
81
|
+
request.once('error', reject); request.end(body);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 健康检查只发往本机环回,先固定数据根中的持久证书指纹再带凭据;凭据只在本进程内使用,绝不输出。
|
|
86
|
+
export async function serviceHealth(dataRoot, origin) {
|
|
87
|
+
try {
|
|
88
|
+
const token = readPrivateJSON(path.join(dataRoot, 'service-identity.json')).token;
|
|
89
|
+
const cert = readPrivateJSON(path.join(dataRoot, 'tls', 'identity.json')).cert;
|
|
90
|
+
const expected = new X509Certificate(cert).fingerprint256;
|
|
91
|
+
const target = new URL('/friday-next/health', origin); target.hostname = '127.0.0.1';
|
|
92
|
+
const body = await new Promise((resolve, reject) => {
|
|
93
|
+
const request = https.get(target, { ca: cert, allowPartialTrustChain: true, timeout: 5000,
|
|
94
|
+
checkServerIdentity: (_host, peer) => peer.fingerprint256 === expected ? undefined : new Error('TLS_IDENTITY_CHANGED'),
|
|
95
|
+
headers: { authorization: 'Bearer ' + token, 'x-fridaynext-event-format': 'canonical-v1' } }, response => {
|
|
96
|
+
let text = ''; response.on('data', chunk => { text += chunk; if (text.length > 1048576) request.destroy(new Error('HEALTH_TOO_LARGE')); });
|
|
97
|
+
response.on('end', () => { try { response.statusCode === 200 ? resolve(JSON.parse(text)) : reject(new Error('HEALTH_STATUS')); } catch (error) { reject(error); } });
|
|
98
|
+
});
|
|
99
|
+
request.once('timeout', () => request.destroy(new Error('HEALTH_TIMEOUT'))); request.once('error', reject);
|
|
100
|
+
});
|
|
101
|
+
return { reachable: true, backendId: body.backend?.id ?? 'claude-code', ...(typeof body.serverInstanceId === 'string' ? { serverInstanceId: body.serverInstanceId } : {}) };
|
|
102
|
+
} catch { return { reachable: false }; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 只读观察当前常驻服务:owner 锁 → 归属 → 控制器 IPC 状态 → 后端 health。
|
|
106
|
+
export async function observeService({ dataRoot, installRoots, processInfo }) {
|
|
107
|
+
const ownership = classifyOwner({ dataRoot, installRoots, processInfo });
|
|
108
|
+
if (ownership.kind === 'none' || ownership.kind === 'stale') return { state: 'stopped', ownership };
|
|
109
|
+
if (ownership.kind === 'unknown') return { state: 'unknown', ownership };
|
|
110
|
+
let value;
|
|
111
|
+
try { value = await componentCall(ownership.owner, 'status'); } catch { return { state: 'unknown', ownership }; }
|
|
112
|
+
if (value?.state !== 'connected' || typeof value.origin !== 'string') return { state: 'unknown', ownership, value };
|
|
113
|
+
const health = await serviceHealth(dataRoot, value.origin);
|
|
114
|
+
return { state: health.reachable ? 'running' : 'unknown', ownership, value, health };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 合同 pairing 字段投影:只挑出合同字段,绝不转出永久 token;无效时返回 null。
|
|
118
|
+
export function pairingProjection(value, env = process.env) {
|
|
119
|
+
const result = { backendId: value?.backendId, lanUrl: value?.lanUrl, fingerprint: value?.fingerprint,
|
|
120
|
+
pairingTicket: value?.pairingTicket, pairingTicketTtlSec: value?.pairingTicketTtlSec };
|
|
121
|
+
if (Object.values(result).some(item => item === undefined) || typeof result.pairingTicket !== 'string' || !/^fnpv1-/.test(result.pairingTicket)) return { invalid: 'PAIRING_RESULT_INVALID' };
|
|
122
|
+
if (typeof value?.publicUrl === 'string' && /^https:\/\//.test(value.publicUrl)) result.publicUrl = value.publicUrl;
|
|
123
|
+
if (typeof value?.controlPlane === 'string' && /^https:\/\//.test(value.controlPlane)) result.controlPlane = value.controlPlane;
|
|
124
|
+
let host;
|
|
125
|
+
try { host = new URL(result.lanUrl).hostname; } catch { return { invalid: 'PAIRING_RESULT_INVALID' }; }
|
|
126
|
+
// 仅监听环回的旧服务无法被手机访问;除非运维显式把局域网地址设为该环回地址。
|
|
127
|
+
if (/^(127\.|localhost$|\[?::1\]?$)/.test(host) && env.FN_CLAUDE_LAN_ADDRESS !== host) return { invalid: 'EXISTING_SERVICE_LAN_UNAVAILABLE' };
|
|
128
|
+
return { result };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const EXTERNAL_PAIRING_HINT = '常驻服务由外部托管,其版本没有可用的本机铸券入口,请升级常驻服务后重试';
|
|
132
|
+
export function externalDescription(ownership) {
|
|
133
|
+
return ownership.launchdLabel ? `外部 LaunchAgent(${ownership.launchdLabel})托管的常驻服务` : '非本组件拉起的外部常驻服务';
|
|
134
|
+
}
|