@syengup/fridaynext-claude-code-channel 0.1.0-beta.4 → 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 CHANGED
@@ -1,25 +1,25 @@
1
- # FridayNext Claude Code 插件 · Beta 4 候选
1
+ # FridayNext Claude Code 插件 · Beta 5 候选
2
2
 
3
- 本页的一键命令对应 Beta 4 候选 `0.1.0-beta.4`(内置适配器 0.1.31)。当前公开 npm 版本为 `0.1.0-beta.3`,其验证平台为 macOS。
3
+ 本页的一键命令对应 Beta 5 候选 `0.1.0-beta.5`(内置适配器 0.1.32)。当前公开 npm 版本为 `0.1.0-beta.4`(适配器 0.1.31,要求宿主严格为 2.1.312)。
4
4
 
5
- Beta 4 发行后,在要连接的项目目录打开终端执行以下命令。
5
+ Beta 5 发行后,在要连接的项目目录打开终端执行以下命令。
6
6
 
7
7
  ```sh
8
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.4
8
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5
9
9
  ```
10
10
 
11
11
  安装器依次安装官方标准插件、配置连接、启动网关、校验网关并显示二维码。用 Friday Next 扫码即可配对,无需另开终端运行 start 或 pair,也无需手工设置监听和LAN环境变量。关闭安装终端后服务继续运行;电脑重启后重新执行同一命令。
12
12
 
13
13
  ## 准备
14
14
 
15
- - 候选支持 macOS 和 Linux(实测 Armbian/Debian 13 ARM64),需要 Node.js ≥22.13、Claude Code **2.1.312**,以及兼容插件0.1.31的 Friday iOS 版本。
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,更高版本未逐项回归。
16
16
  - 先在电脑端安装、登录并配置 Claude Code。固定CLI不在PATH时设置 `FN_CLAUDE_BINARY=/绝对路径/claude`;安装器不安装或替换宿主版本,不复制模型认证。
17
17
  - 手机和电脑先连接同一局域网。安装器自动选择实际私网IPv4;多网卡或从个人主目录启动时会询问地址或项目目录。项目范围取运行命令的目录,不自动授权整个HOME。
18
18
 
19
19
  也可以显式选择:
20
20
 
21
21
  ```sh
22
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.4 --workspace /绝对路径/项目 --lan-host 192.168.1.10
22
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.5 --workspace /绝对路径/项目 --lan-host 192.168.1.10
23
23
  ```
24
24
 
25
25
  ## 服务与数据
@@ -30,20 +30,20 @@ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.4 --workspace /绝对
30
30
 
31
31
  重跑同一命令复用已有活跃服务,保留身份/TLS/配对/历史,不重启或修改原监听地址。已有服务只监听环回时会明确提示无法LAN配对,先按原运维方式正常停止,再运行安装器。原来源/版本冲突时拒绝混装;旧研发市场须先正常停止并用官方命令移除旧来源,保留原私有数据。同运行摘要的beta.1安装器可升级到beta.2,其他版本按对应说明操作。
32
32
 
33
- ## Friday 连接器 Provider(FN-655,随 Beta 4 候选)
33
+ ## Friday 连接器 Provider(FN-655)
34
34
 
35
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
36
 
37
37
  ## 常用操作
38
38
 
39
39
  ```sh
40
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.4 status
41
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.4 pair --qr
42
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.4 stop
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
43
43
  ```
44
44
 
45
45
  stop正常关闭控制器并保留会话和数据,不把关闭连接当作取消模型。重新运行默认命令恢复。二维码为十分钟一次券,重出作废旧券,已配对手机不受影响;不要公开配对资料。自动化只安装不启动时用 `install --only --json`;原start前台方式及doctor/recover仍可用。卸载使用官方 `claude plugin uninstall fridaynext-claude-code@fridaynext-claude-beta --scope user`,先正常停止自有服务,不删除私有数据。
46
46
 
47
- 本包内置适配器 0.1.31,依赖精确 registry Kit 0.2.0-beta.9 与 SDK 0.3.312。本版提供工作目录的持久卷身份、队列删除、语音输入及会话完全访问选项。外部运行中的原生会话仍按既有权限处理。安装只创建连接所需状态,首次模型请求由用户发起。
47
+ 本包内置适配器 0.1.32,依赖精确 registry Kit 0.2.0-beta.9 与 SDK 0.3.312。本版提供工作目录的持久卷身份、队列删除、语音输入及会话完全访问选项。外部运行中的原生会话仍按既有权限处理。安装只创建连接所需状态,首次模型请求由用户发起。
48
48
 
49
- 从较早的 beta 升级时,安装器会校验原代码来源。不同运行版本共用同一代码目录会返回 `INSTALL_VERSION_CONFLICT`。请先使用原版的 stop 停止该安装器管理的服务,执行上面的卸载命令,再用 `claude plugin marketplace remove fridaynext-claude-beta --scope user` 移除旧市场登记。将原插件代码目录移作备份,再执行新版安装。保留原数据目录、工作目录及配置以继续使用原有身份和历史。
49
+ 从较早的 beta 升级时,安装器(以及 Friday 连接器的“添加”)会自动完成升级:停止本安装器或连接器拉起的旧服务,用官方命令卸载旧插件并移除 `fridaynext-claude-beta` 市场登记,把原代码目录改名为 `claude-code-plugin.backup-<时间戳>` 保留,再安装新版。数据目录、工作目录及配置不变,原有身份、配对和历史继续使用。若服务由你自己的 LaunchAgent 等外部方式常驻,安装器不会停止或接管它,也不会升级,会提示先停止该服务;不升级时 Friday 仍可经该服务直接配对。其他来源或更新版本仍返回冲突,需要手工处理。
@@ -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,10 +9,14 @@ 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
15
  export const packageRoot = fileURLToPath(new URL('.', import.meta.url));
14
16
  export const root = path.resolve(process.env.FN_CLAUDE_INSTALL_ROOT ?? path.join(os.homedir(), '.fridaynext/claude-code-plugin'));
15
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';
16
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'));
@@ -44,26 +48,86 @@ export 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
  }
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
+ }
47
103
  // onChange 只用于 Provider 判断 enable 是否真的改动了宿主或代码(FN-655);安装器流程不传,行为不变。
48
104
  export async function install(options = {}) {
49
105
  const changed = typeof options.onChange === 'function' ? options.onChange : () => {};
50
106
  const release = read(path.join(packageRoot, 'release.json'));
51
- const dataRoot = path.resolve(process.env.FN_CLAUDE_DATA_ROOT ?? path.join(os.homedir(), 'Library/Application Support/FridayNext/ClaudeCode/service'));
52
107
  if (root === dataRoot || root.startsWith(dataRoot + path.sep) || dataRoot.startsWith(root + path.sep)) fail('INSTALL_ROOT_OVERLAPS_STATE');
53
- if (await cli(['--version'], false) !== release.host + ' (Claude Code)') fail('HOST_VERSION_UNSUPPORTED');
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) });
54
111
  if (hash(fs.readFileSync(path.join(packageRoot, 'plugin.tgz'))) !== release.payloadSHA256) fail('RELEASE_PAYLOAD_CHANGED');
55
112
  if (fs.lstatSync(path.dirname(root), { throwIfNoEntry: false })?.isSymbolicLink()) fail('INSTALL_ROOT_UNSAFE');
113
+ let upgrade;
56
114
  if (fs.lstatSync(root, { throwIfNoEntry: false })) {
57
115
  privateRoot();
58
116
  const old = read(path.join(root, 'release.json'));
59
117
  if (old.payloadSHA256 !== release.payloadSHA256 || old.distributionVersion !== release.distributionVersion) {
60
- if (old.distributionVersion !== '0.1.0-beta.1' || release.distributionVersion !== '0.1.0-beta.2' ||
61
- ['adapterVersion', 'sourceDigest', 'host', 'sdk', 'kit'].some(key => old[key] !== release[key])) fail('INSTALL_VERSION_CONFLICT');
62
- await verify(old);
63
- fs.writeFileSync(path.join(root, 'release.json'), JSON.stringify({ ...release, runtimePayloadSHA256: old.runtimePayloadSHA256 ?? old.payloadSHA256 }), { mode: 0o600 });
64
- changed('release');
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');
65
128
  }
66
- } else {
129
+ }
130
+ if (!fs.lstatSync(root, { throwIfNoEntry: false })) {
67
131
  fs.mkdirSync(path.dirname(root), { recursive: true, mode: 0o700 });
68
132
  const stage = fs.mkdtempSync(path.join(path.dirname(root), '.claude-install-'));
69
133
  try {
@@ -92,7 +156,7 @@ export async function install(options = {}) {
92
156
  if (enabled?.alreadyInGoalState !== true) changed('enable');
93
157
  }
94
158
  const receipt = { state: 'installed', distributionVersion: release.distributionVersion, adapterVersion: release.adapterVersion,
95
- pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false };
159
+ pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false, ...(upgrade ? { upgradedFrom: upgrade.upgradedFrom, backup: upgrade.backup } : {}) };
96
160
  fs.writeFileSync(path.join(root, 'installed.json'), JSON.stringify(receipt), { mode: 0o600 });
97
161
  return receipt;
98
162
  }
@@ -122,7 +186,10 @@ try {
122
186
  if (options.only) console.log(JSON.stringify(await install(), null, 2));
123
187
  else {
124
188
  const onboarding = claudeOnboarding({ root, binary, options });
125
- await runInstaller({ name: 'Claude Code', lang: language(), install, ...onboarding, recovery });
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 });
126
193
  }
127
194
  }
128
195
  else if (['start', 'status', 'pair', 'stop', 'doctor', 'recover'].includes(command)) {
@@ -131,7 +198,7 @@ try {
131
198
  process.exitCode = child.status ?? 1;
132
199
  } else fail('COMMAND_UNSUPPORTED');
133
200
  } catch (error) {
134
- 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;
135
202
  }
136
203
  }
137
204
  // 仅作为可执行入口运行时执行安装器;被 Provider 导入时只提供上面的函数。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syengup/fridaynext-claude-code-channel",
3
- "version": "0.1.0-beta.4",
3
+ "version": "0.1.0-beta.5",
4
4
  "type": "module",
5
5
  "description": "通过Claude Code官方插件命令安装FridayNext,并连接已授权的SDK自有会话",
6
6
  "license": "UNLICENSED",
@@ -14,6 +14,8 @@
14
14
  "files": [
15
15
  "install.mjs",
16
16
  "provider.mjs",
17
+ "host-version.mjs",
18
+ "service-owner.mjs",
17
19
  "onboarding.mjs",
18
20
  "installer-ui.mjs",
19
21
  "installer-flow.mjs",
package/plugin.tgz CHANGED
Binary file
package/provider.mjs CHANGED
@@ -9,7 +9,9 @@ import path from 'node:path';
9
9
  import { createHash } from 'node:crypto';
10
10
  import { execFile } from 'node:child_process';
11
11
  import { promisify } from 'node:util';
12
- import { install, assertInstalledRelease, root, binary, pluginId, packageRoot } from './install.mjs';
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';
13
15
 
14
16
  const CONTRACT = 'fridaynext.provider/1', HOST_ID = 'claude-code';
15
17
  const AGENTS = [{ agentId: 'claude-code', displayName: 'Claude Code' }];
@@ -18,17 +20,20 @@ class ProviderFailure extends Error {
18
20
  constructor(code, message = code, retryable = false) { super(message); this.code = code; this.retryable = retryable; }
19
21
  }
20
22
  const release = () => JSON.parse(fs.readFileSync(path.join(packageRoot, 'release.json'), 'utf8'));
21
- const codeInstalled = () => fs.existsSync(path.join(root, 'release.json'));
22
- const installGuide = host => ({ title: `安装 Claude Code ${host}`, command: `npm install -g @anthropic-ai/claude-code@${host}`,
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',
23
28
  url: 'https://docs.claude.com/en/docs/claude-code/setup' });
24
29
 
25
- // 只读宿主探测:可执行文件不存在即未安装;版本须与固定 HOST_VERSION 严格一致。
30
+ // 只读宿主探测:可执行文件不存在即未安装;版本须不低于 release.host(最低版本),无法解析视为不兼容。
26
31
  async function hostProbe() {
27
32
  const host = release().host;
28
33
  try {
29
34
  const { stdout } = await run(binary, ['--version'], { timeout: 8000, maxBuffer: 8192 });
30
- const version = /^(\S+) \(Claude Code\)$/.exec(stdout.trim())?.[1] ?? null;
31
- return { installed: true, hostVersion: version, compatible: version === host, host };
35
+ const version = parseHostVersion(stdout)?.join('.') ?? null;
36
+ return { installed: true, hostVersion: version, compatible: hostVersionSupported(stdout, host), host };
32
37
  } catch (error) {
33
38
  if (['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code)) return { installed: false, hostVersion: null, compatible: false, host };
34
39
  return { installed: true, hostVersion: null, compatible: false, host };
@@ -63,7 +68,7 @@ async function delegate(command, inputFile) {
63
68
  return result;
64
69
  }
65
70
  const runningState = async () => {
66
- if (!codeInstalled()) return false;
71
+ if (!codeCurrent()) return (await observe()).state === 'running';
67
72
  try { return (await delegate('status')).state === 'running'; } catch { return false; }
68
73
  };
69
74
 
@@ -71,40 +76,73 @@ const commands = {
71
76
  async probe() {
72
77
  const host = await hostProbe();
73
78
  const result = { installed: host.installed, hostVersion: host.hostVersion, compatible: host.compatible,
74
- pluginEnabled: false, running: false, needsHostRestartToEnable: false };
79
+ pluginEnabled: false, running: false, needsHostRestartToEnable: false, upgradeAvailable: false };
75
80
  if (!host.installed) return { ...result, installGuide: installGuide(host.host) };
76
81
  if (!host.compatible) return result;
77
- return { ...result, pluginEnabled: await pluginEnabled(), running: await runningState() };
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 };
78
89
  },
79
90
  async enable() {
80
91
  const host = await hostProbe();
81
92
  if (!host.installed) throw new ProviderFailure('HOST_NOT_INSTALLED', '未找到 Claude Code CLI');
82
- if (!host.compatible) throw new ProviderFailure('HOST_INCOMPATIBLE', `需要 Claude Code ${host.host}`);
83
- let changed = false;
84
- try { await install({ onChange: () => { changed = true; } }); }
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; } }); }
85
96
  catch (error) {
86
- if (error.code === 'HOST_VERSION_UNSUPPORTED') throw new ProviderFailure('HOST_INCOMPATIBLE', error.code);
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);
87
101
  throw new ProviderFailure('PROVIDER_INTERNAL', typeof error.code === 'string' ? error.code : 'CLAUDE_INSTALL_FAILED');
88
102
  }
89
103
  // 启用插件不需要重启 Claude Code;后端服务由 start 单独启动。
90
- return { changed, hostRestarted: false, state: await runningState() ? 'running' : 'stopped' };
104
+ return { changed, hostRestarted: false, state: await runningState() ? 'running' : 'stopped', ...(receipt?.upgradedFrom ? { upgradedFrom: receipt.upgradedFrom } : {}) };
91
105
  },
92
106
  async agents() { return { agents: AGENTS, revision: createHash('sha256').update(JSON.stringify(AGENTS)).digest('hex') }; },
93
107
  async status() {
94
- if (codeInstalled()) {
108
+ const code = installedCode();
109
+ if (code.state === 'current' || code.state === 'conflict') {
95
110
  const result = await delegate('status');
96
111
  if (result.state !== 'stopped' || await pluginEnabled()) return result;
97
112
  return { ...result, state: 'needsEnable' };
98
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 } };
99
117
  const host = await hostProbe();
100
118
  return { state: !host.installed ? 'notInstalled' : !host.compatible ? 'incompatible' : 'needsEnable', health: { reachable: false } };
101
119
  },
102
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
+ }
103
144
  for (const name of ['start', 'restart', 'pairing', 'projects']) {
104
- commands[name] = async inputFile => {
105
- if (!codeInstalled()) throw new ProviderFailure('PLUGIN_NOT_ENABLED', '请先启用 FridayNext Claude Code 插件');
106
- return delegate(name, name === 'restart' ? inputFile : undefined);
107
- };
145
+ commands[name] = async inputFile => codeCurrent() ? delegate(name, name === 'restart' ? inputFile : undefined) : withoutCurrentCode(name);
108
146
  }
109
147
 
110
148
  const args = process.argv.slice(2), command = args[0];
package/release.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "version": 1,
3
- "distributionVersion": "0.1.0-beta.4",
4
- "adapterVersion": "0.1.31",
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": "5d60ae71b414791413cb6b68dcfbaa5093793b225dfffa27d1b9a4f1b5210b93",
9
- "payloadSHA256": "1321f2f720bacd854583e6382575230f98f1c9ae633bdffd6b31e72cc62221fa"
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
+ }