@syengup/fridaynext-claude-code-channel 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/README.md CHANGED
@@ -1,47 +1,43 @@
1
- # FridayNext Claude Code 插件 · Beta 1
1
+ # FridayNext Claude Code 插件 · Beta 3
2
2
 
3
- 发行包 `@syengup/fridaynext-claude-code-channel@0.1.0-beta.1` 内置已验证的官方标准插件 `0.1.11`。Claude Code 通过公开 TypeScript SDK 执行,Friday Kit 提供配对、持久队列、恢复和网络服务。
4
-
5
- ## 环境
6
-
7
- - 当前验证 macOS、Node.js ≥22.13、Claude Code **2.1.312**,以及包含 Claude Code 模块且兼容插件0.1.11的 Friday iOS 候选。
8
- - 请先在电脑端完成 Claude Code 登录和模型配置。安装器不安装、更新或降级 Claude Code,不复制模型认证。
9
- - 内置精确 registry SDK0.3.312、Kit0.2.0-beta.3及运行依赖。无需访问 Friday 私有源码仓库。
10
-
11
- ## 安装与配对
3
+ 在要连接的项目目录打开终端,执行:
12
4
 
13
5
  ```sh
14
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.1
6
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.3
15
7
  ```
16
8
 
17
- 默认命令只通过官方插件命令注册并启用用户级插件。代码安装到 `~/.fridaynext/claude-code-plugin`,不启动模型或服务。若固定CLI不在PATH,可先设置 `FN_CLAUDE_BINARY=/绝对路径/claude-2.1.312`。已有其他市场的研发版时会拒绝混装;先正常停止原控制器,按官方命令移除旧来源,再安装,保留原私有数据目录。
9
+ 安装器依次安装官方标准插件、配置连接、启动网关、校验网关并显示二维码。用 Friday Next 扫码即可配对,无需另开终端运行 start 或 pair,也无需手工设置监听和LAN环境变量。关闭安装终端后服务继续运行;电脑重启后重新执行同一命令。
18
10
 
19
- 在授权项目目录运行:
11
+ ## 准备
20
12
 
21
- ```sh
22
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.1 start
23
- ```
13
+ - 当前验证 macOS、Node.js ≥22.13、Claude Code **2.1.312**,以及兼容插件0.1.29的 Friday iOS 版本。
14
+ - 先在电脑端安装、登录并配置 Claude Code。固定CLI不在PATH时设置 `FN_CLAUDE_BINARY=/绝对路径/claude`;安装器不安装或替换宿主版本,不复制模型认证。
15
+ - 手机和电脑先连接同一局域网。安装器自动选择实际私网IPv4;多网卡或从个人主目录启动时会询问地址或项目目录。项目范围取运行命令的目录,不自动授权整个HOME。
24
16
 
25
- 保持这个终端运行,另开终端生成一次性配对二维码:
17
+ 也可以显式选择:
26
18
 
27
19
  ```sh
28
- npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.1 pair --qr
20
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.3 --workspace /绝对路径/项目 --lan-host 192.168.1.10
29
21
  ```
30
22
 
31
- 默认仅监听本机。需要手机局域网连接时,在启动前设置 `FN_CLAUDE_LISTEN_HOST=0.0.0.0` 和 `FN_CLAUDE_LAN_ADDRESS=电脑实际私网IPv4`;默认端口9849,可用 `FN_CLAUDE_PORT` 指定。工作目录取启动终端当前项目;更多目录通过 `FN_CLAUDE_WORKSPACE_ROOTS` 的JSON路径数组明确授权。FridayTunnel需要在服务私有根配置既有公网管理,权益、App Attest和宿主授权分别成立。
23
+ ## 服务与数据
32
24
 
33
- `doctor`检查固定CLI/认证状态,模型可用性另行判断;`status`读取当前服务;`stop`正常等待已有工作结束,保留会话。Ctrl+C同样正常关闭,不把断开连接当作取消模型。
25
+ 官方插件实际加载及原生MCP/SessionStart见证齐备后,安装器才启用SDK自有会话控制器和唯一Kit服务。安装本身不发送模型消息,连接成功不等于模型额度或首答已验证。默认局域网监听 `0.0.0.0:9849`;`FN_CLAUDE_PORT`可选其他端口。
34
26
 
35
- ## 数据、重装与回退
27
+ 代码默认在 `~/.fridaynext/claude-code-plugin`;身份/TLS/配对/账本及安装连接参数在 `~/Library/Application Support/FridayNext/ClaudeCode/service`,可用 `FN_CLAUDE_DATA_ROOT`指定独立0700私有根。`FN_CLAUDE_INSTALL_ROOT`只更改代码位置,不能与数据根重叠。原生认证留在CLAUDE_CONFIG_DIR对应电脑配置,安装连接参数不保存认证或完整环境。
36
28
 
37
- 插件缓存和稳定安装根只放代码。身份/TLS/配对/账本默认位于 `~/Library/Application Support/FridayNext/ClaudeCode/service`;可用 `FN_CLAUDE_DATA_ROOT`指定独立0700私有根。`FN_CLAUDE_INSTALL_ROOT`只更改代码位置,不能指向数据目录。`CLAUDE_CONFIG_DIR`沿原Claude配置,模型认证留在电脑;手机使用Kit配对凭据。
29
+ 重跑同一命令复用已有活跃服务,保留身份/TLS/配对/历史,不重启或修改原监听地址。已有服务只监听环回时会明确提示无法LAN配对,先按原运维方式正常停止,再运行安装器。原来源/版本冲突时拒绝混装;旧研发市场须先正常停止并用官方命令移除旧来源,保留原私有数据。同运行摘要的beta.1安装器可升级到beta.2,其他版本按对应说明操作。
38
30
 
39
- 相同固定版本重复运行安装命令保留服务数据。未来版本或代码摘要不符会保守拒绝覆盖,先正常停止服务,再依对应版本说明升级/回退;不要删除身份/TLS/账本或手工抢owner锁。未知执行保留原请求查询,不换号重跑。官方卸载本版可用 `claude plugin uninstall fridaynext-claude-code@fridaynext-claude-beta --scope user`,它不等于撤销手机或清理服务数据。
31
+ ## 常用操作
40
32
 
41
- ## 当前支持与限制
33
+ ```sh
34
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.3 status
35
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.3 pair --qr
36
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.3 stop
37
+ ```
42
38
 
43
- 支持SDK自有会话的首答/续聊/历史、真实流式与工具过程、停止/排队、会话设置、审批/多题提问、授权目录/新工作树、图片/普通文件输入输出、子任务及原有Friday辅助功能。图片为PNG/JPEG;输入最多4件、单件2MiB、合计4MiB。音视频、会话迁移、工作树归档/恢复、原生技能/配置管理未纳入本版。
39
+ stop正常关闭控制器并保留会话和数据,不把关闭连接当作取消模型。重新运行默认命令恢复。二维码为十分钟一次券,重出作废旧券,已配对手机不受影响;不要公开配对资料。自动化只安装不启动时用 `install --only --json`;原start前台方式及doctor/recover仍可用。卸载使用官方 `claude plugin uninstall fridaynext-claude-code@fridaynext-claude-beta --scope user`,先正常停止自有服务,不删除私有数据。
44
40
 
45
- **外部已经活动的原生会话尚无满足要求的公开同实例附着接缝。** 本版只控制本集成创建并持有的执行;同UUID resume不是接管原进程。电脑/手机原生控制赢家、部分宿主默认模型/权限持久写入仍有公开接口限制。Beta发行不表示这些条件或完整首发已完成。
41
+ 本包内置适配器 0.1.29,依赖精确 registry Kit 0.2.0-beta.9。本版提供工作目录的持久卷身份、队列删除、语音输入及会话完全访问选项。外部运行中的原生会话仍按既有权限处理。安装只创建连接所需状态,首次模型请求由用户发起。
46
42
 
47
- 请只在愿意授权的工作目录使用,并保留配对资料的私密性。重新出码会使旧券失效,不撤销已配对手机;日志和反馈中不要粘贴认证、内容密钥或配对码。
43
+ 从较早的 beta 升级时,安装器会校验原代码来源。不同运行版本共用同一代码目录会返回 `INSTALL_VERSION_CONFLICT`。请先使用原版的 stop 停止该安装器管理的服务,执行上面的卸载命令,再用 `claude plugin marketplace remove fridaynext-claude-beta --scope user` 移除旧市场登记。将原插件代码目录移作备份,再执行新版安装。保留原数据目录、工作目录及配置以继续使用原有身份和历史。
package/install.mjs CHANGED
@@ -4,7 +4,11 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createHash } from 'node:crypto';
7
- import { execFileSync, spawnSync } from 'node:child_process';
7
+ import { execFile, execFileSync, spawnSync } from 'node:child_process';
8
+ import { promisify } from 'node:util';
9
+ import { runInstaller, language } from './installer-flow.mjs';
10
+ import { recovery } from './installer-process.mjs';
11
+ import { claudeOnboarding } from './onboarding.mjs';
8
12
 
9
13
  const packageRoot = fileURLToPath(new URL('.', import.meta.url));
10
14
  const root = path.resolve(process.env.FN_CLAUDE_INSTALL_ROOT ?? path.join(os.homedir(), '.fridaynext/claude-code-plugin'));
@@ -17,9 +21,9 @@ const privateRoot = () => {
17
21
  const st = fs.lstatSync(root);
18
22
  if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077)) fail('INSTALL_ROOT_UNSAFE');
19
23
  };
20
- function cli(args, json = true) {
24
+ async function cli(args, json = true) {
21
25
  try {
22
- const text = execFileSync(binary, args, { encoding: 'utf8', timeout: 120000, maxBuffer: 1048576, stdio: ['ignore', 'pipe', 'pipe'] });
26
+ const text = (await promisify(execFile)(binary, args, { encoding: 'utf8', timeout: 120000, maxBuffer: 1048576, stdio: ['ignore', 'pipe', 'pipe'] })).stdout;
23
27
  return json ? JSON.parse(text) : text.trim();
24
28
  } catch (error) {
25
29
  try {
@@ -44,13 +48,18 @@ async function install() {
44
48
  const release = read(path.join(packageRoot, 'release.json'));
45
49
  const dataRoot = path.resolve(process.env.FN_CLAUDE_DATA_ROOT ?? path.join(os.homedir(), 'Library/Application Support/FridayNext/ClaudeCode/service'));
46
50
  if (root === dataRoot || root.startsWith(dataRoot + path.sep) || dataRoot.startsWith(root + path.sep)) fail('INSTALL_ROOT_OVERLAPS_STATE');
47
- if (cli(['--version'], false) !== release.host + ' (Claude Code)') fail('HOST_VERSION_UNSUPPORTED');
51
+ if (await cli(['--version'], false) !== release.host + ' (Claude Code)') fail('HOST_VERSION_UNSUPPORTED');
48
52
  if (hash(fs.readFileSync(path.join(packageRoot, 'plugin.tgz'))) !== release.payloadSHA256) fail('RELEASE_PAYLOAD_CHANGED');
49
53
  if (fs.lstatSync(path.dirname(root), { throwIfNoEntry: false })?.isSymbolicLink()) fail('INSTALL_ROOT_UNSAFE');
50
54
  if (fs.lstatSync(root, { throwIfNoEntry: false })) {
51
55
  privateRoot();
52
56
  const old = read(path.join(root, 'release.json'));
53
- if (old.payloadSHA256 !== release.payloadSHA256 || old.distributionVersion !== release.distributionVersion) fail('INSTALL_VERSION_CONFLICT');
57
+ if (old.payloadSHA256 !== release.payloadSHA256 || old.distributionVersion !== release.distributionVersion) {
58
+ if (old.distributionVersion !== '0.1.0-beta.1' || release.distributionVersion !== '0.1.0-beta.2' ||
59
+ ['adapterVersion', 'sourceDigest', 'host', 'sdk', 'kit'].some(key => old[key] !== release[key])) fail('INSTALL_VERSION_CONFLICT');
60
+ await verify(old);
61
+ fs.writeFileSync(path.join(root, 'release.json'), JSON.stringify({ ...release, runtimePayloadSHA256: old.runtimePayloadSHA256 ?? old.payloadSHA256 }), { mode: 0o600 });
62
+ }
54
63
  } else {
55
64
  fs.mkdirSync(path.dirname(root), { recursive: true, mode: 0o700 });
56
65
  const stage = fs.mkdtempSync(path.join(path.dirname(root), '.claude-install-'));
@@ -63,28 +72,42 @@ async function install() {
63
72
  } finally { if (fs.existsSync(stage)) fs.rmSync(stage, { recursive: true, force: true }); }
64
73
  }
65
74
  privateRoot(); await verify(release);
66
- cli(['plugin', 'validate', path.join(root, 'plugin')], false);
67
- const markets = cli(['plugin', 'marketplace', 'list', '--json']);
75
+ await cli(['plugin', 'validate', path.join(root, 'plugin')], false);
76
+ const markets = await cli(['plugin', 'marketplace', 'list', '--json']);
68
77
  const market = markets.find(value => value.name === 'fridaynext-claude-beta');
69
78
  if (market && path.resolve(market.installLocation) !== root) fail('MARKETPLACE_SOURCE_CONFLICT');
70
- if (!market) cli(['plugin', 'marketplace', 'add', root, '--scope', 'user', '--json']);
71
- const plugins = cli(['plugin', 'list', '--json']);
79
+ if (!market) await cli(['plugin', 'marketplace', 'add', root, '--scope', 'user', '--json']);
80
+ const plugins = await cli(['plugin', 'list', '--json']);
72
81
  if (plugins.some(value => value.id.startsWith('fridaynext-claude-code@') && value.id !== pluginId)) fail('PLUGIN_SOURCE_CONFLICT');
73
82
  const current = plugins.find(value => value.id === pluginId && value.scope === 'user');
74
83
  if (current && current.version !== release.adapterVersion) fail('PLUGIN_VERSION_CONFLICT');
75
- if (!current) cli(['plugin', 'install', pluginId, '--scope', 'user', '--json']);
76
- cli(['plugin', 'enable', pluginId, '--scope', 'user', '--json']);
84
+ if (!current) await cli(['plugin', 'install', pluginId, '--scope', 'user', '--json']);
85
+ await cli(['plugin', 'enable', pluginId, '--scope', 'user', '--json']);
77
86
  const receipt = { state: 'installed', distributionVersion: release.distributionVersion, adapterVersion: release.adapterVersion,
78
87
  pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false };
79
88
  fs.writeFileSync(path.join(root, 'installed.json'), JSON.stringify(receipt), { mode: 0o600 });
80
- console.log(JSON.stringify(receipt, null, 2));
89
+ return receipt;
81
90
  }
82
91
  try {
83
92
  const [major, minor] = process.versions.node.split('.').map(Number);
84
93
  if (major < 22 || major === 22 && minor < 13) fail('NODE_VERSION_UNSUPPORTED');
85
- const [command = 'install', ...args] = process.argv.slice(2);
86
- if (command === 'help' || command === '--help') console.log('用法:fridaynext-claude-code-channel [install|start|status|pair --qr|stop|doctor|recover]\n默认只安装并启用官方标准插件;start在当前项目以前台方式运行,另开终端pair --qr。');
87
- else if (command === 'install') await install();
94
+ const input = process.argv.slice(2), command = input[0]?.startsWith('--') && input[0] !== '--help' ? 'install' : input.shift() ?? 'install', args = input;
95
+ if (command === 'help' || command === '--help') console.log('用法:fridaynext-claude-code-channel [install [--only --json] [--workspace <目录>] [--lan-host <IPv4>]|start|status|pair --qr|stop|doctor|recover]\n默认完成官方插件安装、配置、后台启动、校验并显示配对二维码。');
96
+ else if (command === 'install') {
97
+ const options = {};
98
+ for (let i = 0; i < args.length; i++) {
99
+ const key = args[i];
100
+ if (['--only', '--json'].includes(key)) options[key.slice(2)] = true;
101
+ else if (['--workspace', '--lan-host'].includes(key) && args[i + 1] && !args[i + 1].startsWith('--')) options[key.slice(2)] = args[++i];
102
+ else fail('CLI_ARGUMENT_INVALID');
103
+ }
104
+ if (options.json && !options.only) fail('JSON_REQUIRES_INSTALL_ONLY');
105
+ if (options.only) console.log(JSON.stringify(await install(), null, 2));
106
+ else {
107
+ const onboarding = claudeOnboarding({ root, binary, options });
108
+ await runInstaller({ name: 'Claude Code', lang: language(), install, ...onboarding, recovery });
109
+ }
110
+ }
88
111
  else if (['start', 'status', 'pair', 'stop', 'doctor', 'recover'].includes(command)) {
89
112
  if (!fs.existsSync(root)) fail('PLUGIN_NOT_INSTALLED'); privateRoot();
90
113
  const release = read(path.join(packageRoot, 'release.json')), installed = read(path.join(root, 'release.json'));
@@ -94,5 +117,5 @@ try {
94
117
  process.exitCode = child.status ?? 1;
95
118
  } else fail('COMMAND_UNSUPPORTED');
96
119
  } catch (error) {
97
- console.error(JSON.stringify({ code: typeof error.code === 'string' ? error.code : 'CLAUDE_INSTALL_FAILED', operation: error.operation })); process.exitCode = 1;
120
+ if (!error.presented) console.error(JSON.stringify({ code: typeof error.code === 'string' ? error.code : 'CLAUDE_INSTALL_FAILED', operation: error.operation })); process.exitCode = 1;
98
121
  }
@@ -0,0 +1,60 @@
1
+ import os from 'node:os';
2
+ import { createInstallerUI } from './installer-ui.mjs';
3
+
4
+ // 只编排安装呈现;宿主启动、来源验证与配对仍由各组件提供。
5
+ export function language(env = process.env) {
6
+ const forced = env.FRIDAY_INSTALL_LANG;
7
+ if (forced) return /^zh/i.test(forced) ? 'zh' : 'en';
8
+ const locale = env.LC_ALL || env.LC_MESSAGES || env.LANG;
9
+ if (locale && !/^(C|POSIX)(\.|$)/i.test(locale)) return /^(zh|yue)([_-]|$)/i.test(locale) ? 'zh' : 'en';
10
+ return /^(zh|yue)/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? 'zh' : 'en';
11
+ }
12
+ export function lanAddresses(interfaces = os.networkInterfaces()) {
13
+ return [...new Set(Object.entries(interfaces).flatMap(([name, entries]) =>
14
+ /^(utun|tun|tap|tailscale|wg|docker|veth|br-|lo)/i.test(name) ? [] : (entries ?? []).filter(item =>
15
+ item.family === 'IPv4' && !item.internal && /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(item.address)
16
+ ).map(item => item.address)))];
17
+ }
18
+ export function copy(lang = language()) {
19
+ return lang === 'zh' ? {
20
+ labels: ['安装插件', '配置连接', '启动网关', '校验网关', '准备配对'],
21
+ scan: '扫描下方二维码完成配对', fallback: '二维码无法显示,请在 Friday Next 中粘贴配对码',
22
+ code: '配对码', failed: '安装未完成',
23
+ } : {
24
+ labels: ['Install plugin', 'Configure connection', 'Start gateway', 'Verify gateway', 'Prepare pairing'],
25
+ scan: 'Scan the code below to pair', fallback: 'QR unavailable — paste the pairing code in Friday Next',
26
+ code: 'Pairing code', failed: 'Installation incomplete',
27
+ };
28
+ }
29
+ export async function runInstaller(options) {
30
+ const ui = createInstallerUI({ stream: options.stream, tty: options.tty });
31
+ const t = copy(options.lang); let step, cancelled = false;
32
+ const cancel = () => { cancelled = true; void options.cleanup?.().catch(() => {}); };
33
+ process.once('SIGINT', cancel); process.once('SIGTERM', cancel);
34
+ ui.header(options.name);
35
+ try {
36
+ for (const [index, operation] of [options.install, options.configure, options.start, options.verify].entries()) {
37
+ step = ui.step(t.labels[index]);
38
+ const detail = await operation({ ask: async question => {
39
+ step.pause();
40
+ try { return await question(); } finally { step.resume(); }
41
+ } });
42
+ if (cancelled) throw Object.assign(Error(), { code: 'INSTALL_CANCELLED' });
43
+ step.ok(typeof detail === 'string' ? detail : undefined); step = undefined;
44
+ }
45
+ step = ui.step(t.labels[4]);
46
+ const pairing = await options.pair();
47
+ if (typeof pairing?.code !== 'string' || !pairing.code) throw Object.assign(Error(), { code: 'PAIRING_UNAVAILABLE' });
48
+ let qr;
49
+ try { qr = await options.render(pairing.code); } catch { /* 一次券文本仍是正式可用的配对入口。 */ }
50
+ step.ok(); step = undefined;
51
+ ui.result({ qr, hint: qr ? t.scan : t.fallback, hintMuted: !qr, fields: qr ? [] : [{ label: t.code, value: pairing.code }] });
52
+ return { state: 'ready' };
53
+ } catch (error) {
54
+ step?.fail();
55
+ await options.cleanup?.().catch(() => {});
56
+ ui.fatal([t.failed, ...(options.recovery?.(error, options.lang) ?? [error.code ?? 'INSTALL_FAILED'])]);
57
+ error.presented = true;
58
+ throw error;
59
+ } finally { ui.cleanup(); process.off('SIGINT', cancel); process.off('SIGTERM', cancel); }
60
+ }
@@ -0,0 +1,160 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { spawn, execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { createRequire } from 'node:module';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { setTimeout as delay } from 'node:timers/promises';
9
+ import { createInterface } from 'node:readline/promises';
10
+ import http from 'node:http';
11
+ import https from 'node:https';
12
+ import { isIP } from 'node:net';
13
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
14
+ import { lanAddresses, language } from './installer-flow.mjs';
15
+
16
+ export const failure = code => Object.assign(new Error(code), { code });
17
+ export const execute = promisify(execFile);
18
+ export const runtimeModule = (root, name) => import(pathToFileURL(createRequire(path.join(root, 'package.json')).resolve(name)));
19
+ export function privateDirectory(root) {
20
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
21
+ const st = fs.lstatSync(root);
22
+ if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077)) throw failure('SETUP_ROOT_UNSAFE');
23
+ return root;
24
+ }
25
+ export function readPrivate(file) {
26
+ const st = fs.lstatSync(file);
27
+ if (!st.isFile() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077)) throw failure('SETUP_FILE_UNSAFE');
28
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
29
+ }
30
+ export function savePrivate(file, value) {
31
+ privateDirectory(path.dirname(file));
32
+ const temporary = file + '.' + process.pid + '.tmp';
33
+ const fd = fs.openSync(temporary, 'wx', 0o600);
34
+ try { fs.writeFileSync(fd, JSON.stringify(value)); fs.fsyncSync(fd); }
35
+ finally { fs.closeSync(fd); }
36
+ try { fs.renameSync(temporary, file); } finally { fs.rmSync(temporary, { force: true }); }
37
+ }
38
+ export async function until(check, timeoutMs = 60000) {
39
+ const end = Date.now() + timeoutMs;
40
+ while (Date.now() < end) { const value = await check(); if (value) return value; await delay(150); }
41
+ throw failure('SERVICE_NOT_READY');
42
+ }
43
+ export async function workspace(explicit, saved, ask = question => question()) {
44
+ if (saved) return saved;
45
+ let selected = explicit ?? process.cwd();
46
+ if (!explicit && [os.homedir(), path.parse(selected).root].includes(path.resolve(selected))) {
47
+ if (!process.stdin.isTTY) throw failure('WORKSPACE_REQUIRED');
48
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
49
+ try { selected = await ask(() => prompt.question(language() === 'zh' ? ' 项目目录:' : ' Project directory: ')); }
50
+ finally { prompt.close(); }
51
+ }
52
+ if (!selected || !path.isAbsolute(path.resolve(selected))) throw failure('WORKSPACE_REQUIRED');
53
+ const real = fs.realpathSync(selected);
54
+ if (!fs.statSync(real).isDirectory() || real === fs.realpathSync(os.homedir()) || real === path.parse(real).root) throw failure('WORKSPACE_REQUIRED');
55
+ return real;
56
+ }
57
+ export async function lanAddress(explicit, saved, ask = question => question()) {
58
+ const valid = value => isIP(value) === 4 && /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(value);
59
+ if (explicit || saved) {
60
+ const value = explicit || saved;
61
+ if (!valid(value)) throw failure('LAN_ADDRESS_REQUIRED');
62
+ return value;
63
+ }
64
+ const candidates = lanAddresses();
65
+ if (candidates.length === 1) return candidates[0];
66
+ if (!process.stdin.isTTY) throw failure(candidates.length ? 'LAN_ADDRESS_AMBIGUOUS' : 'LAN_ADDRESS_REQUIRED');
67
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
68
+ try {
69
+ const answer = await ask(() => prompt.question(language() === 'zh' ? ` 电脑局域网 IPv4${candidates.length ? ' (' + candidates.join(', ') + ')' : ''}:` : ` Computer LAN IPv4${candidates.length ? ' (' + candidates.join(', ') + ')' : ''}: `));
70
+ if (!valid(answer)) throw failure('LAN_ADDRESS_REQUIRED');
71
+ return answer;
72
+ } finally { prompt.close(); }
73
+ }
74
+ // 安装器只向自己的工作进程发出退出信号,不按磁盘旧PID停止其他进程。
75
+ export function launch(file, args, { cwd, env = process.env } = {}) {
76
+ const child = spawn(process.execPath, [file, ...args], { cwd, env, detached: true, stdio: 'ignore' });
77
+ let error, stopping; child.once('error', value => { error = value; });
78
+ child.unref();
79
+ return {
80
+ child,
81
+ assertRunning() { if (error || child.exitCode !== null || child.signalCode !== null) throw failure('SERVICE_START_FAILED'); },
82
+ stop() {
83
+ return stopping ??= (async () => {
84
+ if (child.exitCode !== null || child.signalCode !== null || !child.pid) return;
85
+ child.kill('SIGTERM');
86
+ await until(() => child.exitCode !== null || child.signalCode !== null, 60000);
87
+ })();
88
+ },
89
+ };
90
+ }
91
+ export async function jsonCommand(file, args, env = process.env) {
92
+ const result = await execute(process.execPath, [file, ...args], { env, timeout: 20000, maxBuffer: 1048576 });
93
+ return JSON.parse(result.stdout);
94
+ }
95
+ export function verifyHealth(origin, fingerprint, token, version, certificate) {
96
+ const target = new URL('/friday-next/health', origin); target.hostname = '127.0.0.1';
97
+ return new Promise((resolve, reject) => {
98
+ const request = https.get(target, { ca: certificate, allowPartialTrustChain: true, timeout: 10000,
99
+ checkServerIdentity: (_hostname, peer) => peer.fingerprint256?.replaceAll(':', '').toLowerCase() === fingerprint
100
+ ? undefined : failure('SERVICE_TLS_IDENTITY_CHANGED'),
101
+ headers: { authorization: 'Bearer ' + token, 'x-fridaynext-event-format': 'canonical-v1' } }, response => {
102
+ // 在握手完成及发送HTTP凭据之前核对同一证书,响应阶段再核一次。
103
+ const observed = response.socket.getPeerCertificate().fingerprint256?.replaceAll(':', '').toLowerCase();
104
+ if (observed !== fingerprint) { response.resume(); reject(failure('SERVICE_TLS_IDENTITY_CHANGED')); return; }
105
+ let text = ''; response.on('data', chunk => { text += chunk; if (text.length > 1048576) request.destroy(failure('HEALTH_RESPONSE_TOO_LARGE')); });
106
+ response.on('end', () => {
107
+ try {
108
+ const value = JSON.parse(text);
109
+ if (response.statusCode !== 200 || value.backend?.adapter?.version !== version) throw failure('SERVICE_HEALTH_MISMATCH');
110
+ resolve();
111
+ } catch { reject(failure('SERVICE_HEALTH_MISMATCH')); }
112
+ });
113
+ });
114
+ request.once('timeout', () => request.destroy(failure('SERVICE_HEALTH_TIMEOUT'))); request.once('error', reject);
115
+ });
116
+ }
117
+ export async function managedEndpoint(file, close) {
118
+ const token = randomBytes(32).toString('hex');
119
+ if (fs.existsSync(file)) throw failure('MANAGED_SERVICE_RECORD_EXISTS');
120
+ const server = http.createServer((req, res) => {
121
+ const expected = Buffer.from('Bearer ' + token), actual = Buffer.from(req.headers.authorization ?? '');
122
+ if (actual.length !== expected.length || !timingSafeEqual(expected, actual)) { res.writeHead(401); res.end(); return; }
123
+ if (req.method !== 'POST' || req.url !== '/stop') { res.writeHead(404); res.end(); return; }
124
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"state":"stopping"}');
125
+ setImmediate(() => { void close(); });
126
+ });
127
+ server.requestTimeout = 5000; server.headersTimeout = 3000;
128
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
129
+ savePrivate(file, { version: 1, port: server.address().port, token });
130
+ return async () => {
131
+ if (fs.existsSync(file) && readPrivate(file).token === token) fs.rmSync(file);
132
+ await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); });
133
+ };
134
+ }
135
+ export async function stopManaged(file) {
136
+ const record = readPrivate(file);
137
+ return new Promise((resolve, reject) => {
138
+ const req = http.request({ hostname: '127.0.0.1', port: record.port, path: '/stop', method: 'POST', timeout: 10000,
139
+ headers: { authorization: 'Bearer ' + record.token } }, res => {
140
+ res.resume(); res.on('end', () => res.statusCode === 200 ? resolve({ state: 'stopping' }) : reject(failure('MANAGED_STOP_FAILED')));
141
+ });
142
+ req.once('timeout', () => req.destroy(failure('MANAGED_STOP_FAILED'))); req.once('error', reject); req.end();
143
+ });
144
+ }
145
+ export function recovery(error, lang = language()) {
146
+ const zh = lang === 'zh';
147
+ const messages = {
148
+ HOST_VERSION_UNSUPPORTED: zh ? '请安装文档指定的宿主版本后重试' : 'Install the documented host version and retry',
149
+ CODEX_PLUGIN_COMMAND_FAILED: zh ? '请确认 Codex 已安装,或设置 FN_CODEX_BINARY 后重试' : 'Check Codex installation or set FN_CODEX_BINARY and retry',
150
+ CLAUDE_PLUGIN_COMMAND_FAILED: zh ? '请确认 Claude Code 已安装,或设置 FN_CLAUDE_BINARY 后重试' : 'Check Claude Code installation or set FN_CLAUDE_BINARY and retry',
151
+ UPSTREAM_LOGIN_REQUIRED: zh ? '请先在电脑端登录宿主,再重新运行安装命令' : 'Sign in to the host on this computer, then rerun the installer',
152
+ WORKSPACE_REQUIRED: zh ? '请在要连接的项目目录运行,或传入 --workspace /项目绝对路径' : 'Run in your project, or pass --workspace /absolute/project/path',
153
+ LAN_ADDRESS_REQUIRED: zh ? '请连接局域网后重试,或传入 --lan-host 电脑局域网IPv4' : 'Connect to your LAN and retry, or pass --lan-host LAN_IPv4',
154
+ LAN_ADDRESS_AMBIGUOUS: zh ? '检测到多张网卡,请传入 --lan-host 电脑局域网IPv4' : 'Multiple adapters found; pass --lan-host LAN_IPv4',
155
+ INSTALL_VERSION_CONFLICT: zh ? '已安装其他版本;请先正常停止原服务,再按升级说明操作' : 'Another version is installed; stop it normally and follow the upgrade guide',
156
+ NATIVE_ENDPOINT_UNAVAILABLE: zh ? '原生端点不可用;请恢复已有宿主后重试,原配置保持' : 'Native endpoint unavailable; restore the configured host and retry',
157
+ EXISTING_SERVICE_UNREACHABLE: zh ? '已有服务记录但暂不可达;请先恢复或正常停止原服务后重试' : 'Existing service is unreachable; restore or stop it normally before retrying',
158
+ };
159
+ return [messages[error.code] ?? (zh ? '请解决以下错误后重试:' : 'Resolve this error and retry: ') + (error.code ?? 'INSTALL_FAILED')];
160
+ }
@@ -0,0 +1,162 @@
1
+
2
+
3
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
4
+ const SPINNER_INTERVAL_MS = 80;
5
+
6
+
7
+ function displayWidth(s) {
8
+ let w = 0;
9
+ for (const ch of String(s)) {
10
+ const c = ch.codePointAt(0);
11
+ w +=
12
+ (c >= 0x1100 && c <= 0x115f) ||
13
+ (c >= 0x2e80 && c <= 0xa4cf) ||
14
+ (c >= 0xac00 && c <= 0xd7a3) ||
15
+ (c >= 0xf900 && c <= 0xfaff) ||
16
+ (c >= 0xfe30 && c <= 0xfe6f) ||
17
+ (c >= 0xff00 && c <= 0xff60) ||
18
+ (c >= 0xffe0 && c <= 0xffe6)
19
+ ? 2
20
+ : 1;
21
+ }
22
+ return w;
23
+ }
24
+
25
+ const ANSI = {
26
+ reset: "\x1b[0m",
27
+ dim: "\x1b[2m",
28
+ bold: "\x1b[1m",
29
+ green: "\x1b[32m",
30
+ greenBright: "\x1b[92m",
31
+ red: "\x1b[31m",
32
+ yellow: "\x1b[33m",
33
+ };
34
+
35
+
36
+ export function createInstallerUI(opts = {}) {
37
+ const stream = opts.stream ?? process.stdout;
38
+ const isTTY = opts.tty ?? Boolean(stream.isTTY);
39
+ const color = opts.color ?? isTTY;
40
+
41
+ const paint = (code, s) => (color ? code + s + ANSI.reset : s);
42
+ const dim = (s) => paint(ANSI.dim, s);
43
+ const write = (s) => stream.write(s);
44
+
45
+ let timer = null;
46
+ let frame = 0;
47
+
48
+ let running = null;
49
+
50
+ const stepLine = (mark, label, detail) => ` ${mark} ${label}${detail ? " " + dim(detail) : ""}`;
51
+
52
+ function redraw() {
53
+ if (!running) return;
54
+ const mark = paint(ANSI.yellow, SPINNER_FRAMES[frame % SPINNER_FRAMES.length]);
55
+ write("\r\x1b[2K" + stepLine(mark, running.label, running.detail));
56
+ }
57
+
58
+ function stopSpinner() {
59
+ if (timer) {
60
+ clearInterval(timer);
61
+ timer = null;
62
+ }
63
+ if (isTTY) write("\r\x1b[2K");
64
+ }
65
+
66
+ return {
67
+
68
+ header(subtitle) {
69
+ write("\n " + paint(ANSI.bold, "Friday Next"));
70
+ if (subtitle) write(dim(" " + subtitle));
71
+ write("\n\n");
72
+ },
73
+
74
+
75
+ step(label) {
76
+ running = { label, detail: "" };
77
+ if (isTTY) {
78
+ frame = 0;
79
+ redraw();
80
+ timer = setInterval(() => {
81
+ frame += 1;
82
+ redraw();
83
+ }, SPINNER_INTERVAL_MS);
84
+ }
85
+ const resolve = (mark, detail) => {
86
+ const finished = running;
87
+ stopSpinner();
88
+ running = null;
89
+ if (!finished) return;
90
+ write(stepLine(mark, finished.label, detail ?? finished.detail) + "\n");
91
+ };
92
+ return {
93
+ pause() { stopSpinner(); },
94
+ resume() {
95
+ if (!isTTY || !running) return;
96
+ redraw();
97
+ timer = setInterval(() => { frame += 1; redraw(); }, SPINNER_INTERVAL_MS);
98
+ },
99
+ detail(text) {
100
+ if (running) running.detail = text;
101
+ if (isTTY) redraw();
102
+ },
103
+ ok(detail) {
104
+ resolve(paint(ANSI.green, "✔"), detail);
105
+ },
106
+ fail(detail) {
107
+ resolve(paint(ANSI.red, "✘"), detail);
108
+ },
109
+ };
110
+ },
111
+
112
+
113
+ note(text) {
114
+ write(stepLine(paint(ANSI.yellow, "!"), dim(text), "") + "\n");
115
+ },
116
+
117
+
118
+ result({ qr, hint, hintMuted = false, fields = [] }) {
119
+ if (hint) {
120
+ write(
121
+ hintMuted
122
+ ? "\n " + dim(hint) + "\n"
123
+ : "\n " +
124
+ paint(ANSI.greenBright, "▎") +
125
+ paint(ANSI.bold + ANSI.greenBright, " " + hint) +
126
+ "\n",
127
+ );
128
+ }
129
+ if (qr) {
130
+ const body = qr
131
+ .replace(/\n$/, "")
132
+ .split("\n")
133
+ .map((l) => " " + l)
134
+ .join("\n");
135
+ write("\n" + body + "\n");
136
+ }
137
+ write("\n");
138
+ const shown = fields.filter((f) => f?.value);
139
+ const width = Math.max(0, ...shown.map((f) => displayWidth(f.label)));
140
+ for (const { label, value } of shown) {
141
+ const pad = " ".repeat(width - displayWidth(label));
142
+ write(` ${dim(label)}${pad} ${value}\n`);
143
+ }
144
+ write("\n");
145
+ },
146
+
147
+
148
+ fatal(lines) {
149
+ write("\n");
150
+ for (const [i, line] of lines.entries()) {
151
+ write(i === 0 ? ` ${paint(ANSI.red, "✘")} ${line}\n` : ` ${dim("→ " + line)}\n`);
152
+ }
153
+ write("\n");
154
+ },
155
+
156
+
157
+ cleanup() {
158
+ stopSpinner();
159
+ running = null;
160
+ },
161
+ };
162
+ }
package/onboarding.mjs ADDED
@@ -0,0 +1,77 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { pathToFileURL, fileURLToPath } from 'node:url';
5
+ import { failure, privateDirectory, readPrivate, savePrivate, until, workspace, lanAddress, launch, jsonCommand, verifyHealth, runtimeModule } from './installer-process.mjs';
6
+
7
+ export function claudeOnboarding({ root, binary, options = {} }) {
8
+ const cli = path.join(root, 'plugin/src/cli.mjs');
9
+ const data = path.resolve(process.env.FN_CLAUDE_DATA_ROOT ?? path.join(os.homedir(), 'Library/Application Support/FridayNext/ClaudeCode/service'));
10
+ const setup = path.join(data, 'installer-setup.json');
11
+ let configured, worker, reused = false;
12
+ const env = () => ({ ...process.env, FN_CLAUDE_BINARY: binary, FN_CLAUDE_DATA_ROOT: data });
13
+ const status = () => jsonCommand(cli, ['status'], env());
14
+ return {
15
+ async configure({ ask } = {}) {
16
+ if (fs.existsSync(path.join(data, 'controller-owner/owner.json'))) {
17
+ try { if ((await status()).state === 'connected') { reused = true; return; } } catch {}
18
+ throw failure('EXISTING_SERVICE_UNREACHABLE');
19
+ }
20
+ const previous = fs.existsSync(setup) ? readPrivate(setup) : undefined;
21
+ configured = { version: 1, cwd: await workspace(options.workspace, previous?.cwd, ask),
22
+ lanHost: await lanAddress(options['lan-host'] ?? process.env.FN_CLAUDE_LAN_ADDRESS, previous?.lanHost, ask),
23
+ port: Number(process.env.FN_CLAUDE_PORT ?? previous?.port ?? 9849) };
24
+ if (!Number.isInteger(configured.port) || configured.port < 1 || configured.port > 65535) throw failure('LISTEN_PORT_INVALID');
25
+ const doctor = await jsonCommand(cli, ['doctor'], env());
26
+ if (doctor.authenticationState === 'not-authenticated' && !process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) throw failure('UPSTREAM_LOGIN_REQUIRED');
27
+ // 只保存连接参数;认证与完整环境变量不落入安装配置。
28
+ privateDirectory(data); savePrivate(setup, configured);
29
+ if (fs.existsSync(setup + '.failure.json')) { readPrivate(setup + '.failure.json'); fs.rmSync(setup + '.failure.json'); }
30
+ },
31
+ async start() {
32
+ if (reused) return;
33
+ const directory = privateDirectory(path.join(root, 'installer'));
34
+ for (const name of ['onboarding.mjs', 'installer-process.mjs', 'installer-flow.mjs', 'installer-ui.mjs'])
35
+ fs.copyFileSync(new URL(name, import.meta.url), path.join(directory, name));
36
+ worker = launch(path.join(directory, 'onboarding.mjs'), ['--worker', root, setup], { cwd: configured.cwd, env: env() });
37
+ },
38
+ async verify() {
39
+ await until(async () => {
40
+ if (!reused && fs.existsSync(setup + '.failure.json')) throw failure(readPrivate(setup + '.failure.json').code);
41
+ worker?.assertRunning();
42
+ try { return (await status()).state === 'connected'; } catch { return false; }
43
+ });
44
+ const live = await status(), pairing = await jsonCommand(cli, ['pair'], env());
45
+ await verifyHealth(live.origin, pairing.fingerprint, readPrivate(path.join(data, 'service-identity.json')).token,
46
+ JSON.parse(fs.readFileSync(path.join(root, 'release.json'))).adapterVersion, readPrivate(path.join(data, 'tls/identity.json')).cert);
47
+ },
48
+ async pair() {
49
+ const result = await jsonCommand(cli, ['pair'], env());
50
+ if (!result.lanUrl || /https?:\/\/(127\.|localhost|\[::1\])/.test(result.lanUrl)) throw failure('EXISTING_SERVICE_LAN_UNAVAILABLE');
51
+ return { code: result.code };
52
+ },
53
+ async render(code) {
54
+ const { default: QRCode } = await runtimeModule(path.join(root, 'plugin'), 'qrcode');
55
+ return QRCode.toString(code, { type: process.stdout.isTTY ? 'terminal' : 'utf8', small: true, margin: 4, errorCorrectionLevel: 'L' });
56
+ },
57
+ async cleanup() { await worker?.stop(); },
58
+ };
59
+ }
60
+
61
+ if (process.argv[2] === '--worker' && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
62
+ const root = process.argv[3], setup = readPrivate(process.argv[4]);
63
+ let controller, stopping = false;
64
+ const stop = () => { stopping = true; void controller?.close().catch(() => { process.exitCode = 1; }); };
65
+ process.once('SIGTERM', stop); process.once('SIGINT', stop);
66
+ try {
67
+ const { startController } = await import(pathToFileURL(path.join(root, 'plugin/src/controller.mjs')));
68
+ controller = await startController({ root: process.env.FN_CLAUDE_DATA_ROOT,
69
+ nativeConfigRoot: process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), '.claude'),
70
+ binary: process.env.FN_CLAUDE_BINARY ?? 'claude', cwd: setup.cwd, port: setup.port,
71
+ listenHost: '0.0.0.0', lanAddress: setup.lanHost });
72
+ if (stopping) await controller.close();
73
+ } catch (error) {
74
+ savePrivate(process.argv[4] + '.failure.json', { code: typeof error.code === 'string' ? error.code : 'CLAUDE_START_FAILED' });
75
+ process.exitCode = 1;
76
+ }
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syengup/fridaynext-claude-code-channel",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.3",
4
4
  "type": "module",
5
5
  "description": "通过Claude Code官方插件命令安装FridayNext,并连接已授权的SDK自有会话",
6
6
  "license": "UNLICENSED",
@@ -12,6 +12,10 @@
12
12
  },
13
13
  "files": [
14
14
  "install.mjs",
15
+ "onboarding.mjs",
16
+ "installer-ui.mjs",
17
+ "installer-flow.mjs",
18
+ "installer-process.mjs",
15
19
  "release.json",
16
20
  "plugin.tgz",
17
21
  "README.md"
package/plugin.tgz CHANGED
Binary file
package/release.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "version": 1,
3
- "distributionVersion": "0.1.0-beta.1",
4
- "adapterVersion": "0.1.11",
3
+ "distributionVersion": "0.1.0-beta.3",
4
+ "adapterVersion": "0.1.29",
5
5
  "host": "2.1.312",
6
6
  "sdk": "0.3.312",
7
- "kit": "0.2.0-beta.3",
8
- "sourceDigest": "44b4ee99b054c147ef73a5706f23a46f47a306935305f1acd1b4bbbc7dc80862",
9
- "payloadSHA256": "dc7baf735d6f84894e4cebc81ddf28a9bf355ca9c3538a907a9e660132c90bd4"
7
+ "kit": "0.2.0-beta.9",
8
+ "sourceDigest": "3ef924e9cbf41e8be87fa860e131581af049cac80d49fd62f83f54c58539a005",
9
+ "payloadSHA256": "646e252beb5fabbf1fa10bdd3951358ce30f64a840a11439de43db9c1b16ca0d"
10
10
  }