@syengup/fridaynext-codex-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 +42 -2
- package/install.mjs +95 -0
- package/installer-flow.mjs +60 -0
- package/installer-process.mjs +160 -0
- package/installer-ui.mjs +162 -0
- package/onboarding.mjs +165 -0
- package/package.json +26 -4
- package/plugin.tgz +0 -0
- package/release.json +9 -0
package/README.md
CHANGED
|
@@ -1,3 +1,43 @@
|
|
|
1
|
-
#
|
|
1
|
+
# FridayNext Codex 插件 · Beta 2
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
在要连接的项目目录打开终端,执行:
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.2
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
安装器依次安装官方标准插件、配置连接、启动网关、校验网关并显示二维码。用 Friday Next 扫码即可配对,无需另开终端运行 configure、activate 或 pair。关闭安装终端后专用进程继续运行,电脑重启后重新执行同一命令。
|
|
10
|
+
|
|
11
|
+
## 准备
|
|
12
|
+
|
|
13
|
+
- 当前验证 macOS、Node.js ≥22.13、Codex CLI **0.159.3**,以及兼容适配器0.1.64的 Friday iOS 版本。
|
|
14
|
+
- 先在电脑端安装并登录 Codex。固定CLI不在PATH时设置 `FN_CODEX_BINARY=/绝对路径/codex`;安装器不替换电脑已有的 Codex 版本,不复制认证。
|
|
15
|
+
- 手机和电脑先连接同一局域网。安装器自动选择实际私网IPv4;多网卡或从个人主目录启动时,会询问地址或项目目录。项目范围取运行命令的目录,不自动授权整个HOME。
|
|
16
|
+
|
|
17
|
+
也可以显式选择:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.2 --workspace /绝对路径/项目 --lan-host 192.168.1.10
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## 服务与数据
|
|
24
|
+
|
|
25
|
+
首次安装由安装器创建专用官方 app-server,通过标准插件加载、真实原生会话和随机挑战见证后启动唯一Kit服务。安装只创建空的安装会话,不发送模型消息;服务可用不代表模型额度或首答已验证。插件运行时仍只连接明确配置的已运行Unix socket。
|
|
26
|
+
|
|
27
|
+
代码默认在 `~/.fridaynext/codex/plugin/`,配置在 `~/.fridaynext/codex/integration.json`,身份/TLS/配对/历史在独立 `data/`;`FN_CODEX_INSTALL_ROOT`只更改代码位置。`FN_CODEX_CONFIG`可显式指定配置,原生MCP进程也必须收到该环境;安装器创建的专用宿主继承该变量。原生CODEX_HOME、账号和项目保持电脑端。
|
|
28
|
+
|
|
29
|
+
已有活跃服务时复用原服务,不重启、改地址或扩大项目范围;原配置或旧来源冲突时明确停止,不自动接管。已有手工配置但端点未运行时,先恢复该宿主后重试。同运行摘要的beta.1安装器可升级到beta.2并保留运行代码/数据;其他运行版本按各版本说明升级,不覆盖活跃owner。
|
|
30
|
+
|
|
31
|
+
## 常用操作
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.2 status
|
|
35
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.2 pair
|
|
36
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.2 stop
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`stop`只作用于本安装器登记的工作进程,等待原生执行空闲后关闭专用宿主;不停止外部已有宿主。重跑默认命令可恢复。单独pair保留原CLI的完整资料及0600 PNG/文本输出;二维码十分钟有效,重出作废旧券,已配对手机不受影响。不要公开配对资料。
|
|
40
|
+
|
|
41
|
+
自动化只安装不启动时用 `install --only --json`;原configure/roots/permissions/sessions入口继续保留。卸载使用官方 `codex plugin remove fridaynext-codex@fridaynext-local` 和 `codex plugin marketplace remove fridaynext-local`,先正常停止自有服务,不删除私有数据。
|
|
42
|
+
|
|
43
|
+
本包内置已验收适配器0.1.64及精确registry Kit0.2.0-beta.3。支持范围沿原生会话/历史、流式与工具、设置/审批/提问、停止/排队、授权目录/新工作树、图片/普通文件及子任务。会话迁移、归档/恢复、完整目录漂移、原生配置/技能管理和语音未纳入本版;其他操作系统和宿主版本未认证。公网须原服务明确配置、权益及production App Attest成立,安装不自动开通或购买。
|
package/install.mjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
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 { codexOnboarding } from './onboarding.mjs';
|
|
12
|
+
const pkg = fileURLToPath(new URL('.', import.meta.url));
|
|
13
|
+
const root = path.resolve(process.env.FN_CODEX_INSTALL_ROOT ?? path.join(os.homedir(), '.fridaynext/codex/plugin'));
|
|
14
|
+
const binary = process.env.FN_CODEX_BINARY ?? 'codex', pluginId = 'fridaynext-codex@fridaynext-local';
|
|
15
|
+
const read = file => JSON.parse(fs.readFileSync(file));
|
|
16
|
+
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
17
|
+
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
18
|
+
function privateRoot() {
|
|
19
|
+
const st = fs.lstatSync(root); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || st.mode & 0o077) fail('INSTALL_ROOT_UNSAFE');
|
|
20
|
+
}
|
|
21
|
+
function verify(release) {
|
|
22
|
+
privateRoot();
|
|
23
|
+
const plugin = path.join(root, 'plugins/fridaynext-codex'), h = createHash('sha256');
|
|
24
|
+
for (const file of ['plugin.json', 'mcp.json', ...fs.readdirSync(path.join(plugin, 'src')).filter(f => f.endsWith('.mjs')).map(f => 'src/' + f)].sort())
|
|
25
|
+
h.update(file + '\0').update(fs.readFileSync(path.join(plugin, file))).update('\0');
|
|
26
|
+
if (read(path.join(plugin, 'plugin.json')).version !== release.adapterVersion || h.digest('hex') !== release.sourceDigest) fail('INSTALLED_SOURCE_CHANGED');
|
|
27
|
+
}
|
|
28
|
+
async function cli(args, json = true) {
|
|
29
|
+
try { const value = (await promisify(execFile)(binary, args, { encoding: 'utf8', timeout: 120000, maxBuffer: 1048576, stdio: ['ignore', 'pipe', 'pipe'] })).stdout; return json ? JSON.parse(value) : value.trim(); }
|
|
30
|
+
catch { fail('CODEX_PLUGIN_COMMAND_FAILED'); }
|
|
31
|
+
}
|
|
32
|
+
async function install() {
|
|
33
|
+
const release = read(path.join(pkg, 'release.json'));
|
|
34
|
+
const dataRoot = path.join(os.homedir(), '.fridaynext/codex/data');
|
|
35
|
+
if (root === dataRoot || root.startsWith(dataRoot + path.sep) || dataRoot.startsWith(root + path.sep)) fail('INSTALL_ROOT_OVERLAPS_STATE');
|
|
36
|
+
if (await cli(['--version'], false) !== 'codex-cli ' + release.host) fail('HOST_VERSION_UNSUPPORTED');
|
|
37
|
+
if (hash(fs.readFileSync(path.join(pkg, 'plugin.tgz'))) !== release.payloadSHA256) fail('RELEASE_PAYLOAD_CHANGED');
|
|
38
|
+
if (fs.lstatSync(root, { throwIfNoEntry: false })) {
|
|
39
|
+
privateRoot(); const old = read(path.join(root, 'release.json'));
|
|
40
|
+
if (old.payloadSHA256 !== release.payloadSHA256 || old.distributionVersion !== release.distributionVersion) {
|
|
41
|
+
if (old.distributionVersion !== '0.1.0-beta.1' || release.distributionVersion !== '0.1.0-beta.2' ||
|
|
42
|
+
['adapterVersion', 'sourceDigest', 'host', 'kit'].some(key => old[key] !== release[key])) fail('INSTALL_VERSION_CONFLICT');
|
|
43
|
+
verify(old);
|
|
44
|
+
fs.writeFileSync(path.join(root, 'release.json'), JSON.stringify({ ...release, runtimePayloadSHA256: old.runtimePayloadSHA256 ?? old.payloadSHA256 }), { mode: 0o600 });
|
|
45
|
+
}
|
|
46
|
+
} else {
|
|
47
|
+
fs.mkdirSync(path.dirname(root), { recursive: true, mode: 0o700 });
|
|
48
|
+
const stage = fs.mkdtempSync(path.join(path.dirname(root), '.codex-install-'));
|
|
49
|
+
try {
|
|
50
|
+
const names = execFileSync('tar', ['-tzf', path.join(pkg, 'plugin.tgz')], { encoding: 'utf8', maxBuffer: 8388608 }).split('\n');
|
|
51
|
+
if (names.some(name => path.isAbsolute(name) || name.split('/').includes('..'))) fail('RELEASE_PATH_UNSAFE');
|
|
52
|
+
execFileSync('tar', ['-xzf', path.join(pkg, 'plugin.tgz'), '-C', stage]);
|
|
53
|
+
fs.writeFileSync(path.join(stage, 'release.json'), JSON.stringify(release), { mode: 0o600 }); fs.renameSync(stage, root);
|
|
54
|
+
} finally { fs.rmSync(stage, { recursive: true, force: true }); }
|
|
55
|
+
}
|
|
56
|
+
verify(release);
|
|
57
|
+
const markets = (await cli(['plugin', 'marketplace', 'list', '--json'])).marketplaces;
|
|
58
|
+
if (!Array.isArray(markets)) fail('MARKETPLACE_RESPONSE_UNKNOWN');
|
|
59
|
+
const market = markets.find(value => value.name === 'fridaynext-local');
|
|
60
|
+
if (market && fs.realpathSync(market.root) !== fs.realpathSync(root)) fail('MARKETPLACE_SOURCE_CONFLICT');
|
|
61
|
+
if (!market) await cli(['plugin', 'marketplace', 'add', root, '--json']);
|
|
62
|
+
const installed = (await cli(['plugin', 'list', '--json'])).installed;
|
|
63
|
+
if (!Array.isArray(installed)) fail('PLUGIN_RESPONSE_UNKNOWN');
|
|
64
|
+
if (installed.some(value => value.name === 'fridaynext-codex' && value.pluginId !== pluginId)) fail('PLUGIN_SOURCE_CONFLICT');
|
|
65
|
+
const current = installed.find(value => value.pluginId === pluginId);
|
|
66
|
+
if (current && (current.enabled !== true || fs.realpathSync(current.source.path) !== fs.realpathSync(path.join(root, 'plugins/fridaynext-codex')))) fail('PLUGIN_SOURCE_CONFLICT');
|
|
67
|
+
if (!current) await cli(['plugin', 'add', pluginId, '--json']);
|
|
68
|
+
const receipt = { state: 'installed', distributionVersion: release.distributionVersion, adapterVersion: release.adapterVersion, pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false };
|
|
69
|
+
fs.writeFileSync(path.join(root, 'installed.json'), JSON.stringify(receipt), { mode: 0o600 }); return receipt;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const [major, minor] = process.versions.node.split('.').map(Number); if (major < 22 || major === 22 && minor < 13) fail('NODE_VERSION_UNSUPPORTED');
|
|
73
|
+
const input = process.argv.slice(2), command = input[0]?.startsWith('--') && input[0] !== '--help' ? 'install' : input.shift() ?? 'install', args = input;
|
|
74
|
+
if (['help', '--help'].includes(command)) console.log('用法:fridaynext-codex-channel [install [--only --json] [--workspace <目录>] [--lan-host <IPv4>]|configure|status|pair|stop|roots|permissions|sessions];默认完成官方插件安装、配置、专用宿主启动、校验并显示配对二维码。');
|
|
75
|
+
else if (command === 'install') {
|
|
76
|
+
const options = {};
|
|
77
|
+
for (let i = 0; i < args.length; i++) {
|
|
78
|
+
const key = args[i];
|
|
79
|
+
if (['--only', '--json'].includes(key)) options[key.slice(2)] = true;
|
|
80
|
+
else if (['--workspace', '--lan-host'].includes(key) && args[i + 1] && !args[i + 1].startsWith('--')) options[key.slice(2)] = args[++i];
|
|
81
|
+
else fail('CLI_ARGUMENT_INVALID');
|
|
82
|
+
}
|
|
83
|
+
if (options.json && !options.only) fail('JSON_REQUIRES_INSTALL_ONLY');
|
|
84
|
+
if (options.only) console.log(JSON.stringify(await install(), null, 2));
|
|
85
|
+
else {
|
|
86
|
+
const onboarding = codexOnboarding({ root, binary, options });
|
|
87
|
+
await runInstaller({ name: 'Codex', lang: language(), install, ...onboarding, recovery });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
else if (['configure', 'status', 'pair', 'stop', 'roots', 'permissions', 'sessions'].includes(command)) {
|
|
91
|
+
const release = read(path.join(pkg, 'release.json')); if (read(path.join(root, 'release.json')).payloadSHA256 !== release.payloadSHA256) fail('INSTALL_VERSION_CONFLICT'); verify(release);
|
|
92
|
+
if (command === 'stop') console.log(JSON.stringify(await codexOnboarding({ root, binary }).stop()));
|
|
93
|
+
else { const child = spawnSync(process.execPath, [path.join(root, 'plugins/fridaynext-codex/src/cli.mjs'), command, ...args], { stdio: 'inherit', env: process.env }); process.exitCode = child.status ?? 1; }
|
|
94
|
+
} else fail('COMMAND_UNSUPPORTED');
|
|
95
|
+
} catch (error) { if (!error.presented) console.error(JSON.stringify({ code: typeof error.code === 'string' ? error.code : 'CODEX_INSTALL_FAILED' })); process.exitCode = 1; }
|
|
@@ -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
|
+
}
|
package/installer-ui.mjs
ADDED
|
@@ -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,165 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
7
|
+
import { failure, privateDirectory, readPrivate, savePrivate, until, workspace, lanAddress, launch, jsonCommand, managedEndpoint, stopManaged, verifyHealth, runtimeModule } from './installer-process.mjs';
|
|
8
|
+
|
|
9
|
+
export function codexOnboarding({ root, binary, options = {} }) {
|
|
10
|
+
const plugin = path.join(root, 'plugins/fridaynext-codex');
|
|
11
|
+
const load = name => import(pathToFileURL(path.join(plugin, 'src', name + '.mjs')));
|
|
12
|
+
const cli = path.join(plugin, 'src/cli.mjs');
|
|
13
|
+
let config, setup, setupFile, worker, reused = false;
|
|
14
|
+
return {
|
|
15
|
+
async stop() {
|
|
16
|
+
const { readConfiguration } = await load('private-state');
|
|
17
|
+
const config = readConfiguration();
|
|
18
|
+
return stopManaged(path.join(config.dataRoot, 'installer-worker.json'));
|
|
19
|
+
},
|
|
20
|
+
async configure({ ask } = {}) {
|
|
21
|
+
const { readConfiguration } = await load('private-state');
|
|
22
|
+
const { runtimePaths } = await load('runtime-paths');
|
|
23
|
+
const paths = runtimePaths();
|
|
24
|
+
const file = path.resolve(process.env.FN_CODEX_CONFIG ?? paths.configFile);
|
|
25
|
+
setupFile = file + '.installer.json';
|
|
26
|
+
const previous = fs.existsSync(setupFile) ? readPrivate(setupFile) : undefined;
|
|
27
|
+
try { config = readConfiguration(); }
|
|
28
|
+
catch (error) { if (error.code !== 'CODEX_PLUGIN_NOT_CONFIGURED') throw error; }
|
|
29
|
+
if (config) {
|
|
30
|
+
const code = fs.realpathSync(root), data = fs.realpathSync(config.dataRoot);
|
|
31
|
+
if (code === data || code.startsWith(data + path.sep) || data.startsWith(code + path.sep)) throw failure('INSTALL_ROOT_OVERLAPS_STATE');
|
|
32
|
+
}
|
|
33
|
+
if (config && fs.existsSync(path.join(config.dataRoot, 'service-owner/owner.json'))) {
|
|
34
|
+
try { if ((await jsonCommand(cli, ['status'])).codex?.host?.state === 'verified') { reused = true; return; } } catch {}
|
|
35
|
+
throw failure('EXISTING_SERVICE_UNREACHABLE');
|
|
36
|
+
}
|
|
37
|
+
const cwd = await workspace(options.workspace, previous?.cwd, ask);
|
|
38
|
+
if (!config) {
|
|
39
|
+
const lanHost = await lanAddress(options['lan-host'], undefined, ask);
|
|
40
|
+
let nativeSocket = path.join(paths.root, 'native.sock');
|
|
41
|
+
if (Buffer.byteLength(nativeSocket) > 96) {
|
|
42
|
+
const tag = createHash('sha256').update(file).digest('hex').slice(0, 16);
|
|
43
|
+
nativeSocket = path.join(privateDirectory(path.join(os.tmpdir(), 'friday-codex-' + process.getuid() + '-' + tag)), 'native.sock');
|
|
44
|
+
}
|
|
45
|
+
await jsonCommand(cli, ['configure', '--native-socket', nativeSocket, '--data-root', paths.dataRoot, '--lan-host', lanHost]);
|
|
46
|
+
config = readConfiguration();
|
|
47
|
+
setup = { version: 1, cwd, nativeSocket, ownsNative: true };
|
|
48
|
+
} else {
|
|
49
|
+
// 只有本安装器已经登记的端点才能重新拉起;原配置端点不可达时不接管。
|
|
50
|
+
setup = { version: 1, cwd, nativeSocket: config.nativeSocket,
|
|
51
|
+
ownsNative: previous?.ownsNative === true && previous.nativeSocket === config.nativeSocket };
|
|
52
|
+
if (!setup.ownsNative && !fs.existsSync(config.nativeSocket)) throw failure('NATIVE_ENDPOINT_UNAVAILABLE');
|
|
53
|
+
}
|
|
54
|
+
savePrivate(setupFile, setup);
|
|
55
|
+
if (fs.existsSync(setupFile + '.failure.json')) { readPrivate(setupFile + '.failure.json'); fs.rmSync(setupFile + '.failure.json'); }
|
|
56
|
+
},
|
|
57
|
+
async start() {
|
|
58
|
+
if (reused) return;
|
|
59
|
+
const directory = privateDirectory(path.join(root, 'installer'));
|
|
60
|
+
for (const name of ['onboarding.mjs', 'installer-process.mjs', 'installer-flow.mjs', 'installer-ui.mjs'])
|
|
61
|
+
fs.copyFileSync(new URL(name, import.meta.url), path.join(directory, name));
|
|
62
|
+
worker = launch(path.join(directory, 'onboarding.mjs'), ['--worker', root, setupFile], { cwd: setup.cwd,
|
|
63
|
+
env: { ...process.env, FN_CODEX_BINARY: binary } });
|
|
64
|
+
},
|
|
65
|
+
async verify() {
|
|
66
|
+
await until(async () => {
|
|
67
|
+
if (setupFile && fs.existsSync(setupFile + '.failure.json')) throw failure(readPrivate(setupFile + '.failure.json').code);
|
|
68
|
+
worker?.assertRunning();
|
|
69
|
+
try { const status = await jsonCommand(cli, ['status']); return status.codex?.host?.state === 'verified' && status.endpoint?.serverInstanceId; }
|
|
70
|
+
catch { return false; }
|
|
71
|
+
});
|
|
72
|
+
const live = await jsonCommand(cli, ['status']), pairing = await jsonCommand(cli, ['pair']);
|
|
73
|
+
await verifyHealth(live.endpoint.origin, pairing.fingerprint, readPrivate(path.join(config.dataRoot, 'component-identity.json')).token,
|
|
74
|
+
JSON.parse(fs.readFileSync(path.join(root, 'release.json'))).adapterVersion, readPrivate(path.join(config.dataRoot, 'tls/identity.json')).cert);
|
|
75
|
+
if (!reused) await jsonCommand(cli, ['roots', 'add', '--path', setup.cwd]);
|
|
76
|
+
},
|
|
77
|
+
async pair() {
|
|
78
|
+
const value = await jsonCommand(cli, ['pair']);
|
|
79
|
+
if (!value.lanUrl || /https?:\/\/(127\.|localhost|\[::1\])/.test(value.lanUrl)) throw failure('EXISTING_SERVICE_LAN_UNAVAILABLE');
|
|
80
|
+
const { encodePairingCode } = await runtimeModule(plugin, '@syengup/fridaynext-channel-kit');
|
|
81
|
+
return { code: encodePairingCode(value, { format: 'json' }) };
|
|
82
|
+
},
|
|
83
|
+
async render(code) {
|
|
84
|
+
const { default: QRCode } = await runtimeModule(plugin, 'qrcode');
|
|
85
|
+
return QRCode.toString(code, { type: process.stdout.isTTY ? 'terminal' : 'utf8', small: true, margin: 4 });
|
|
86
|
+
},
|
|
87
|
+
async cleanup() { await worker?.stop(); },
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (process.argv[2] === '--worker' && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
92
|
+
const root = process.argv[3], setup = readPrivate(process.argv[4]);
|
|
93
|
+
const plugin = path.join(root, 'plugins/fridaynext-codex');
|
|
94
|
+
let native, peer, threadId, server, closing, release, startup = true, stopRequested = false;
|
|
95
|
+
const requestStop = () => { stopRequested = true; if (!startup) void stop(); };
|
|
96
|
+
const stop = () => closing ??= (async () => {
|
|
97
|
+
try {
|
|
98
|
+
if (threadId && server) await peer?.rpc('mcpServer/tool/call', { threadId, server, tool: 'fridaynext_deactivate', arguments: {} });
|
|
99
|
+
if (threadId) await peer?.rpc('thread/unsubscribe', { threadId });
|
|
100
|
+
} catch {}
|
|
101
|
+
peer?.close();
|
|
102
|
+
// 只停止本工作进程实际创建的专用宿主,绝不停止原有端点的宿主。
|
|
103
|
+
if (native && native.exitCode === null && native.signalCode === null) {
|
|
104
|
+
native.kill('SIGTERM');
|
|
105
|
+
await until(() => native.exitCode !== null || native.signalCode !== null, 15000).catch(() => { process.exitCode = 1; });
|
|
106
|
+
}
|
|
107
|
+
await release?.();
|
|
108
|
+
})();
|
|
109
|
+
process.once('SIGTERM', requestStop); process.once('SIGINT', requestStop);
|
|
110
|
+
try {
|
|
111
|
+
const { readConfiguration } = await import(pathToFileURL(path.join(plugin, 'src/private-state.mjs')));
|
|
112
|
+
const configuration = readConfiguration();
|
|
113
|
+
release = await managedEndpoint(path.join(configuration.dataRoot, 'installer-worker.json'), async () => {
|
|
114
|
+
// 关闭入口等待专用宿主中已加载的原生执行空闲,不用stop伪装取消。
|
|
115
|
+
await until(async () => {
|
|
116
|
+
let cursor;
|
|
117
|
+
do {
|
|
118
|
+
const page = await peer.rpc('thread/loaded/list', cursor ? { cursor } : {});
|
|
119
|
+
for (const id of page.data) {
|
|
120
|
+
const { thread } = await peer.rpc('thread/read', { threadId: id, includeTurns: false });
|
|
121
|
+
if (!['idle', 'notLoaded'].includes(thread.status?.type)) return false;
|
|
122
|
+
}
|
|
123
|
+
cursor = page.nextCursor;
|
|
124
|
+
} while (cursor);
|
|
125
|
+
return true;
|
|
126
|
+
}).then(stop).catch(() => {});
|
|
127
|
+
});
|
|
128
|
+
const { connectNative } = await import(pathToFileURL(path.join(plugin, 'src/native-client.mjs')));
|
|
129
|
+
if (setup.ownsNative) {
|
|
130
|
+
if (fs.existsSync(setup.nativeSocket)) throw failure('NATIVE_SOCKET_ALREADY_EXISTS');
|
|
131
|
+
privateDirectory(path.dirname(setup.nativeSocket));
|
|
132
|
+
native = spawn(process.env.FN_CODEX_BINARY ?? 'codex', ['app-server', '--listen', 'unix://' + setup.nativeSocket],
|
|
133
|
+
{ cwd: setup.cwd, env: process.env, stdio: 'ignore' });
|
|
134
|
+
native.once('error', () => { void stop(); });
|
|
135
|
+
await until(() => {
|
|
136
|
+
if (native.exitCode !== null || native.signalCode !== null) throw failure('NATIVE_START_FAILED');
|
|
137
|
+
return fs.existsSync(setup.nativeSocket);
|
|
138
|
+
}, 15000);
|
|
139
|
+
}
|
|
140
|
+
peer = await connectNative(setup.nativeSocket, { experimentalApi: true });
|
|
141
|
+
// 创建空的安装会话用于官方MCP调用;不创建turn或向模型发送提示。
|
|
142
|
+
const thread = await peer.rpc('thread/start', { cwd: setup.cwd, approvalPolicy: 'on-request', sandbox: 'read-only' });
|
|
143
|
+
threadId = thread.thread.id;
|
|
144
|
+
server = await until(async () => {
|
|
145
|
+
let cursor;
|
|
146
|
+
do {
|
|
147
|
+
const result = await peer.rpc('mcpServerStatus/list', { threadId, ...(cursor ? { cursor } : {}) });
|
|
148
|
+
const found = result.data.find(row => Object.values(row.tools ?? {}).some(tool => tool.name === 'fridaynext_activate'));
|
|
149
|
+
if (found) return found.name;
|
|
150
|
+
cursor = result.nextCursor;
|
|
151
|
+
} while (cursor);
|
|
152
|
+
});
|
|
153
|
+
const activation = await peer.rpc('mcpServer/tool/call', { threadId, server, tool: 'fridaynext_activate', arguments: { server } });
|
|
154
|
+
const result = JSON.parse(activation.content.find(item => item.type === 'text').text);
|
|
155
|
+
if (result.state !== 'active') throw failure(result.code ?? 'HOST_PROOF_REQUIRED');
|
|
156
|
+
peer.onClose(() => { void stop(); });
|
|
157
|
+
native?.once('exit', () => { void stop(); });
|
|
158
|
+
startup = false;
|
|
159
|
+
if (stopRequested) await stop();
|
|
160
|
+
} catch (error) {
|
|
161
|
+
startup = false;
|
|
162
|
+
savePrivate(process.argv[4] + '.failure.json', { code: typeof error.code === 'string' ? error.code : 'CODEX_START_FAILED' });
|
|
163
|
+
process.exitCode = 1; await stop();
|
|
164
|
+
}
|
|
165
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syengup/fridaynext-codex-channel",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-beta.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"description": "通过Codex官方标准插件命令安装FridayNext并连接显式授权的本机宿主",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.13.0"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"fridaynext-codex-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,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 1,
|
|
3
|
+
"distributionVersion": "0.1.0-beta.2",
|
|
4
|
+
"adapterVersion": "0.1.64",
|
|
5
|
+
"host": "0.159.3",
|
|
6
|
+
"kit": "0.2.0-beta.3",
|
|
7
|
+
"sourceDigest": "884048827cd127a433a36f0c0ed2c1fdf4f3a5b1fb8c76d071f6109749bb410c",
|
|
8
|
+
"payloadSHA256": "0b246d7eaa57f79aff8357b4306f59857a6be1adfdbd3d92271a09077e675d20"
|
|
9
|
+
}
|