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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # FridayNext Claude Code 插件 · Beta 2
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在要连接的项目目录打开终端,执行:
4
+
5
+ ```sh
6
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.2
7
+ ```
8
+
9
+ 安装器依次安装官方标准插件、配置连接、启动网关、校验网关并显示二维码。用 Friday Next 扫码即可配对,无需另开终端运行 start 或 pair,也无需手工设置监听和LAN环境变量。关闭安装终端后服务继续运行;电脑重启后重新执行同一命令。
10
+
11
+ ## 准备
12
+
13
+ - 当前验证 macOS、Node.js ≥22.13、Claude Code **2.1.312**,以及兼容插件0.1.11的 Friday iOS 版本。
14
+ - 先在电脑端安装、登录并配置 Claude Code。固定CLI不在PATH时设置 `FN_CLAUDE_BINARY=/绝对路径/claude`;安装器不安装或替换宿主版本,不复制模型认证。
15
+ - 手机和电脑先连接同一局域网。安装器自动选择实际私网IPv4;多网卡或从个人主目录启动时会询问地址或项目目录。项目范围取运行命令的目录,不自动授权整个HOME。
16
+
17
+ 也可以显式选择:
18
+
19
+ ```sh
20
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.2 --workspace /绝对路径/项目 --lan-host 192.168.1.10
21
+ ```
22
+
23
+ ## 服务与数据
24
+
25
+ 官方插件实际加载及原生MCP/SessionStart见证齐备后,安装器才启用SDK自有会话控制器和唯一Kit服务。安装本身不发送模型消息,连接成功不等于模型额度或首答已验证。默认局域网监听 `0.0.0.0:9849`;`FN_CLAUDE_PORT`可选其他端口。
26
+
27
+ 代码默认在 `~/.fridaynext/claude-code-plugin`;身份/TLS/配对/账本及安装连接参数在 `~/Library/Application Support/FridayNext/ClaudeCode/service`,可用 `FN_CLAUDE_DATA_ROOT`指定独立0700私有根。`FN_CLAUDE_INSTALL_ROOT`只更改代码位置,不能与数据根重叠。原生认证留在CLAUDE_CONFIG_DIR对应电脑配置,安装连接参数不保存认证或完整环境。
28
+
29
+ 重跑同一命令复用已有活跃服务,保留身份/TLS/配对/历史,不重启或修改原监听地址。已有服务只监听环回时会明确提示无法LAN配对,先按原运维方式正常停止,再运行安装器。原来源/版本冲突时拒绝混装;旧研发市场须先正常停止并用官方命令移除旧来源,保留原私有数据。同运行摘要的beta.1安装器可升级到beta.2,其他版本按对应说明操作。
30
+
31
+ ## 常用操作
32
+
33
+ ```sh
34
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.2 status
35
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.2 pair --qr
36
+ npx -y @syengup/fridaynext-claude-code-channel@0.1.0-beta.2 stop
37
+ ```
38
+
39
+ stop正常关闭控制器并保留会话和数据,不把关闭连接当作取消模型。重新运行默认命令恢复。二维码为十分钟一次券,重出作废旧券,已配对手机不受影响;不要公开配对资料。自动化只安装不启动时用 `install --only --json`;原start前台方式及doctor/recover仍可用。卸载使用官方 `claude plugin uninstall fridaynext-claude-code@fridaynext-claude-beta --scope user`,先正常停止自有服务,不删除私有数据。
40
+
41
+ 本包内置原已验收插件0.1.11、SDK0.3.312和精确registry Kit0.2.0-beta.3,无需访问私有源码仓库。支持SDK自有会话、历史、流式/工具、停止/排队、设置/审批/提问、授权目录/新工作树、图片/普通文件及子任务。外部已经活动的原生会话仍无满足要求的公开同实例附着接缝,本版只控制本集成创建并持有的执行;原生赢家、部分默认writer限制保持。音视频、会话迁移、归档/恢复和原生技能/配置管理未纳入本版。FridayTunnel须另行配置,权益、App Attest和宿主授权分别成立,安装不自动开通或购买。
package/install.mjs ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { createHash } from 'node:crypto';
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';
12
+
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 pluginId = 'fridaynext-claude-code@fridaynext-claude-beta';
17
+ const fail = code => { throw Object.assign(new Error(code), { code }); };
18
+ const read = file => JSON.parse(fs.readFileSync(file, 'utf8'));
19
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex');
20
+ const privateRoot = () => {
21
+ const st = fs.lstatSync(root);
22
+ if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077)) fail('INSTALL_ROOT_UNSAFE');
23
+ };
24
+ async function cli(args, json = true) {
25
+ try {
26
+ const text = (await promisify(execFile)(binary, args, { encoding: 'utf8', timeout: 120000, maxBuffer: 1048576, stdio: ['ignore', 'pipe', 'pipe'] })).stdout;
27
+ return json ? JSON.parse(text) : text.trim();
28
+ } catch (error) {
29
+ try {
30
+ const receipt = JSON.parse(error.stdout);
31
+ if (args[0] === 'plugin' && args[1] === 'enable' && receipt.command === 'enable' && receipt.plugin === pluginId
32
+ && receipt.scope === 'user' && receipt.failureCode === 'already_in_goal_state' && receipt.alreadyInGoalState === true) return receipt;
33
+ } catch { /* 未取得官方明确幂等回执时,仍保留失败。 */ }
34
+ throw Object.assign(new Error('CLAUDE_PLUGIN_COMMAND_FAILED'), { code: 'CLAUDE_PLUGIN_COMMAND_FAILED', operation: args.slice(0, 2).join(' ') });
35
+ }
36
+ }
37
+ async function verify(release) {
38
+ const plugin = path.join(root, 'plugin');
39
+ const manifest = read(path.join(plugin, '.claude-plugin/plugin.json'));
40
+ // 与适配器的来源合同核对相同字节;验证前不能加载待验证目录中的程序。
41
+ const files = ['.claude-plugin/plugin.json', '.mcp.json', 'hooks/hooks.json',
42
+ ...fs.readdirSync(path.join(plugin, 'src')).filter(name => name.endsWith('.mjs')).map(name => 'src/' + name)].sort();
43
+ const digest = createHash('sha256');
44
+ for (const file of files) digest.update(file + '\0').update(fs.readFileSync(path.join(plugin, file))).update('\0');
45
+ if (manifest.version !== release.adapterVersion || manifest.name !== 'fridaynext-claude-code' || digest.digest('hex') !== release.sourceDigest) fail('INSTALLED_SOURCE_CHANGED');
46
+ }
47
+ async function install() {
48
+ 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
+ if (root === dataRoot || root.startsWith(dataRoot + path.sep) || dataRoot.startsWith(root + path.sep)) fail('INSTALL_ROOT_OVERLAPS_STATE');
51
+ if (await cli(['--version'], false) !== release.host + ' (Claude Code)') fail('HOST_VERSION_UNSUPPORTED');
52
+ if (hash(fs.readFileSync(path.join(packageRoot, 'plugin.tgz'))) !== release.payloadSHA256) fail('RELEASE_PAYLOAD_CHANGED');
53
+ if (fs.lstatSync(path.dirname(root), { throwIfNoEntry: false })?.isSymbolicLink()) fail('INSTALL_ROOT_UNSAFE');
54
+ if (fs.lstatSync(root, { throwIfNoEntry: false })) {
55
+ privateRoot();
56
+ const old = read(path.join(root, 'release.json'));
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
+ }
63
+ } else {
64
+ fs.mkdirSync(path.dirname(root), { recursive: true, mode: 0o700 });
65
+ const stage = fs.mkdtempSync(path.join(path.dirname(root), '.claude-install-'));
66
+ try {
67
+ const names = execFileSync('tar', ['-tzf', path.join(packageRoot, 'plugin.tgz')], { encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 }).split('\n').filter(Boolean);
68
+ if (names.some(name => path.isAbsolute(name) || name.split('/').includes('..'))) fail('RELEASE_PATH_UNSAFE');
69
+ execFileSync('tar', ['-xzf', path.join(packageRoot, 'plugin.tgz'), '-C', stage]);
70
+ fs.writeFileSync(path.join(stage, 'release.json'), JSON.stringify(release), { mode: 0o600 });
71
+ fs.renameSync(stage, root);
72
+ } finally { if (fs.existsSync(stage)) fs.rmSync(stage, { recursive: true, force: true }); }
73
+ }
74
+ privateRoot(); await verify(release);
75
+ await cli(['plugin', 'validate', path.join(root, 'plugin')], false);
76
+ const markets = await cli(['plugin', 'marketplace', 'list', '--json']);
77
+ const market = markets.find(value => value.name === 'fridaynext-claude-beta');
78
+ if (market && path.resolve(market.installLocation) !== root) fail('MARKETPLACE_SOURCE_CONFLICT');
79
+ if (!market) await cli(['plugin', 'marketplace', 'add', root, '--scope', 'user', '--json']);
80
+ const plugins = await cli(['plugin', 'list', '--json']);
81
+ if (plugins.some(value => value.id.startsWith('fridaynext-claude-code@') && value.id !== pluginId)) fail('PLUGIN_SOURCE_CONFLICT');
82
+ const current = plugins.find(value => value.id === pluginId && value.scope === 'user');
83
+ if (current && current.version !== release.adapterVersion) fail('PLUGIN_VERSION_CONFLICT');
84
+ if (!current) await cli(['plugin', 'install', pluginId, '--scope', 'user', '--json']);
85
+ await cli(['plugin', 'enable', pluginId, '--scope', 'user', '--json']);
86
+ const receipt = { state: 'installed', distributionVersion: release.distributionVersion, adapterVersion: release.adapterVersion,
87
+ pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false };
88
+ fs.writeFileSync(path.join(root, 'installed.json'), JSON.stringify(receipt), { mode: 0o600 });
89
+ return receipt;
90
+ }
91
+ try {
92
+ const [major, minor] = process.versions.node.split('.').map(Number);
93
+ if (major < 22 || major === 22 && minor < 13) fail('NODE_VERSION_UNSUPPORTED');
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
+ }
111
+ else if (['start', 'status', 'pair', 'stop', 'doctor', 'recover'].includes(command)) {
112
+ if (!fs.existsSync(root)) fail('PLUGIN_NOT_INSTALLED'); privateRoot();
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);
116
+ const child = spawnSync(process.execPath, [path.join(root, 'plugin/src/cli.mjs'), command, ...args], { stdio: 'inherit', env: process.env });
117
+ process.exitCode = child.status ?? 1;
118
+ } else fail('COMMAND_UNSUPPORTED');
119
+ } 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;
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,79 @@
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
+ const { code: _code, ...payload } = result;
52
+ const { encodePairingCode } = await runtimeModule(path.join(root, 'plugin'), '@syengup/fridaynext-channel-kit');
53
+ return { code: encodePairingCode(payload, { format: 'json' }) };
54
+ },
55
+ async render(code) {
56
+ const { default: QRCode } = await runtimeModule(path.join(root, 'plugin'), 'qrcode');
57
+ return QRCode.toString(code, { type: process.stdout.isTTY ? 'terminal' : 'utf8', small: true, margin: 4 });
58
+ },
59
+ async cleanup() { await worker?.stop(); },
60
+ };
61
+ }
62
+
63
+ if (process.argv[2] === '--worker' && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
64
+ const root = process.argv[3], setup = readPrivate(process.argv[4]);
65
+ let controller, stopping = false;
66
+ const stop = () => { stopping = true; void controller?.close().catch(() => { process.exitCode = 1; }); };
67
+ process.once('SIGTERM', stop); process.once('SIGINT', stop);
68
+ try {
69
+ const { startController } = await import(pathToFileURL(path.join(root, 'plugin/src/controller.mjs')));
70
+ controller = await startController({ root: process.env.FN_CLAUDE_DATA_ROOT,
71
+ nativeConfigRoot: process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), '.claude'),
72
+ binary: process.env.FN_CLAUDE_BINARY ?? 'claude', cwd: setup.cwd, port: setup.port,
73
+ listenHost: '0.0.0.0', lanAddress: setup.lanHost });
74
+ if (stopping) await controller.close();
75
+ } catch (error) {
76
+ savePrivate(process.argv[4] + '.failure.json', { code: typeof error.code === 'string' ? error.code : 'CLAUDE_START_FAILED' });
77
+ process.exitCode = 1;
78
+ }
79
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@syengup/fridaynext-claude-code-channel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.2",
4
+ "type": "module",
5
+ "description": "通过Claude Code官方插件命令安装FridayNext,并连接已授权的SDK自有会话",
6
+ "license": "UNLICENSED",
7
+ "engines": {
8
+ "node": ">=22.13.0"
9
+ },
10
+ "bin": {
11
+ "fridaynext-claude-code-channel": "install.mjs"
12
+ },
13
+ "files": [
14
+ "install.mjs",
15
+ "onboarding.mjs",
16
+ "installer-ui.mjs",
17
+ "installer-flow.mjs",
18
+ "installer-process.mjs",
19
+ "release.json",
20
+ "plugin.tgz",
21
+ "README.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "tag": "beta",
26
+ "registry": "https://registry.npmjs.org/"
27
+ }
28
+ }
package/plugin.tgz ADDED
Binary file
package/release.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 1,
3
+ "distributionVersion": "0.1.0-beta.2",
4
+ "adapterVersion": "0.1.11",
5
+ "host": "2.1.312",
6
+ "sdk": "0.3.312",
7
+ "kit": "0.2.0-beta.3",
8
+ "sourceDigest": "44b4ee99b054c147ef73a5706f23a46f47a306935305f1acd1b4bbbc7dc80862",
9
+ "payloadSHA256": "aafd2ffa4d2e016cf7d9899106f7c53eec31544d84a43018382e0d89a75283f7"
10
+ }