@syengup/fridaynext-codex-channel 0.1.0-beta.3 → 0.1.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -9
- package/install.mjs +46 -15
- package/installer-process.mjs +4 -1
- package/onboarding.mjs +21 -7
- package/package.json +4 -2
- package/plugin.tgz +0 -0
- package/provider.mjs +381 -0
- package/release.json +4 -4
package/README.md
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
# FridayNext Codex 插件 · Beta
|
|
1
|
+
# FridayNext Codex 插件 · Beta 5
|
|
2
2
|
|
|
3
3
|
在要连接的项目目录打开终端,执行:
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.
|
|
6
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.5
|
|
7
7
|
```
|
|
8
8
|
|
|
9
9
|
安装器依次安装官方标准插件、配置连接、启动网关、校验网关并显示二维码。用 Friday Next 扫码即可配对,无需另开终端运行 configure、activate 或 pair。关闭安装终端后专用进程继续运行,电脑重启后重新执行同一命令。
|
|
10
10
|
|
|
11
11
|
## 准备
|
|
12
12
|
|
|
13
|
-
- 当前验证 macOS、Node.js ≥22.13、Codex CLI **0.159.3
|
|
13
|
+
- 当前验证 macOS、Node.js ≥22.13、Codex CLI **0.159.3**(最早已验证版本,更新的官方 CLI 不做精确版本门禁),以及兼容适配器0.1.103的 Friday iOS 版本。
|
|
14
14
|
- 先在电脑端安装并登录 Codex。固定CLI不在PATH时设置 `FN_CODEX_BINARY=/绝对路径/codex`;安装器不替换电脑已有的 Codex 版本,不复制认证。
|
|
15
15
|
- 手机和电脑先连接同一局域网。安装器自动选择实际私网IPv4;多网卡或从个人主目录启动时,会询问地址或项目目录。项目范围取运行命令的目录,不自动授权整个HOME。
|
|
16
16
|
|
|
17
17
|
也可以显式选择:
|
|
18
18
|
|
|
19
19
|
```sh
|
|
20
|
-
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.
|
|
20
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.5 --workspace /绝对路径/项目 --lan-host 192.168.1.10
|
|
21
21
|
```
|
|
22
22
|
|
|
23
23
|
## 服务与数据
|
|
@@ -31,15 +31,43 @@ npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.3 --workspace /绝对路径/
|
|
|
31
31
|
## 常用操作
|
|
32
32
|
|
|
33
33
|
```sh
|
|
34
|
-
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.
|
|
35
|
-
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.
|
|
36
|
-
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.
|
|
34
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.5 status
|
|
35
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.5 pair
|
|
36
|
+
npx -y @syengup/fridaynext-codex-channel@0.1.0-beta.5 stop
|
|
37
37
|
```
|
|
38
38
|
|
|
39
39
|
`stop`只作用于本安装器登记的工作进程,等待原生执行空闲后关闭专用宿主;不停止外部已有宿主。重跑默认命令可恢复。单独pair保留原CLI的完整资料及0600 PNG/文本输出;二维码十分钟有效,重出作废旧券,已配对手机不受影响。不要公开配对资料。
|
|
40
40
|
|
|
41
41
|
自动化只安装不启动时用 `install --only --json`;原configure/roots/permissions/sessions入口继续保留。卸载使用官方 `codex plugin remove fridaynext-codex@fridaynext-local` 和 `codex plugin marketplace remove fridaynext-local`,先正常停止自有服务,不删除私有数据。
|
|
42
42
|
|
|
43
|
-
本包内置适配器 0.1.
|
|
43
|
+
本包内置适配器 0.1.103,依赖精确 registry Kit 0.2.0-beta.9,运行载荷与 beta.4 逐字节相同。beta.4 在 beta.3 的工作目录持久卷身份、队列删除及语音输入基础上,新增连接器 Provider 入口,并按本机实际 CLI 能力安装插件;beta.5 只更新安装器与 Provider,使 App 添加时可自动升级旧运行代码。专用宿主经标准插件见证后才可使用。安装只创建连接所需状态,首次模型请求由用户发起。
|
|
44
44
|
|
|
45
|
-
从较早的 beta
|
|
45
|
+
从较早的 beta 升级时,安装器会校验原代码来源。beta.4 升级到 beta.5 复用同一运行载荷,原地升级安装器并继续使用已有服务。不同运行版本共用同一代码目录时,npx 安装器返回 `INSTALL_VERSION_CONFLICT`;beta.3(适配器 0.1.102)升级到 beta.5(0.1.103)属于这种情况。
|
|
46
|
+
|
|
47
|
+
- 在 Friday App 中添加 Codex 时,连接器调用 Provider 的 `enable` 自动完成升级(FN-663):先经本组件登记的 worker 正常停止旧专用宿主并等待执行空闲,再用官方命令移除旧插件登记和 marketplace,把旧代码目录移到同级 `plugin.backup-<UTC时间>`(不删除),最后安装新代码并重新登记。数据目录、`integration.json`、安装器登记、serverInstanceId、token、TLS 及已授权目录保持不变。旧代码来源被改动、已装版本更新、登记指向其他来源或旧服务不由本组件 worker 管理时,返回结构化错误且不做改动。
|
|
48
|
+
- 只用 npx 时,请先使用原版的 stop 停止该安装器管理的服务,通过上面的官方命令移除其插件登记和 marketplace,移走原代码目录作为备份,再执行新版安装。保留原数据目录、工作目录及配置以继续使用原有身份和历史。
|
|
49
|
+
|
|
50
|
+
## 安装器行为 · FN-519
|
|
51
|
+
|
|
52
|
+
beta.4 起安装器使用 PATH 上的官方 Codex,允许显式指定 `FN_CODEX_BINARY`。安装以官方 CLI 的本地插件命令、实际加载来源及原生宿主见证为准。安装命令仅在当前调用关闭远程插件市场查询。可执行文件缺失、CLI 输出异常、本地插件命令失败或超时会给出对应提示。复用相同运行载荷时,可原地升级安装器并继续使用已有服务。
|
|
53
|
+
|
|
54
|
+
完整发行(FN-663)只接受固定的 0.1.103 运行源摘要;源码变化后必须换新发行号。`--plan` 只查阅计划,`--output` 必须是全新目录:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
node packages/codex-channel/scripts/build-release.mjs --output /全新候选目录
|
|
58
|
+
npm pack /全新候选目录
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
运行源不变、只升级安装器时(beta.5 即按此生成),将已发布 beta.4 的包解出到独立目录,使用原 `plugin.tgz` 生成新安装器候选。脚本对照本仓的适配器源码摘要、Kit 版本及原压缩包 SHA,新版本须晚于已发行版本,新输出目录必须为空缺。
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
node packages/codex-channel/scripts/build-release.mjs \
|
|
65
|
+
--installer-from /原发行包/package --version 0.1.0-beta.5 \
|
|
66
|
+
--output /全新候选目录
|
|
67
|
+
npm pack /全新候选目录
|
|
68
|
+
npx -y --package /本地候选.tgz -- fridaynext-codex-channel
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## 连接器 Provider · FN-654
|
|
72
|
+
|
|
73
|
+
beta.4 起同包提供 `provider.mjs`(bin `fridaynext-codex-provider`),供 Friday 连接器检测、启用、启动和铸券;不交互、不授权目录、不输出永久凭据。接管旧 npx 安装时复用原数据目录与配置;beta.5 起已装本组件更旧运行代码时,`probe` 报告 `upgradeAvailable:true` 与 `installedAdapterVersion`,`enable` 按上文流程自动升级。命令与限制见 [API](../API.md#connector-provider-合同-v1--fn-654)。
|
package/install.mjs
CHANGED
|
@@ -12,35 +12,64 @@ import { codexOnboarding } from './onboarding.mjs';
|
|
|
12
12
|
const pkg = fileURLToPath(new URL('.', import.meta.url));
|
|
13
13
|
const root = path.resolve(process.env.FN_CODEX_INSTALL_ROOT ?? path.join(os.homedir(), '.fridaynext/codex/plugin'));
|
|
14
14
|
const binary = process.env.FN_CODEX_BINARY ?? 'codex', pluginId = 'fridaynext-codex@fridaynext-local';
|
|
15
|
+
// 供 FN-654 Provider 复用同一安装根、宿主可执行文件与官方插件命令;不改变安装器自身行为。
|
|
16
|
+
export { pkg as packageRoot, root as installRoot, binary as codexBinary, pluginId };
|
|
15
17
|
const read = file => JSON.parse(fs.readFileSync(file));
|
|
16
18
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
19
|
+
const execute = promisify(execFile);
|
|
17
20
|
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
18
21
|
function privateRoot() {
|
|
19
22
|
const st = fs.lstatSync(root); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || st.mode & 0o077) fail('INSTALL_ROOT_UNSAFE');
|
|
20
23
|
}
|
|
21
|
-
function verify(release) {
|
|
24
|
+
export function verify(release) {
|
|
22
25
|
privateRoot();
|
|
23
26
|
const plugin = path.join(root, 'plugins/fridaynext-codex'), h = createHash('sha256');
|
|
24
27
|
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
28
|
h.update(file + '\0').update(fs.readFileSync(path.join(plugin, file))).update('\0');
|
|
26
29
|
if (read(path.join(plugin, 'plugin.json')).version !== release.adapterVersion || h.digest('hex') !== release.sourceDigest) fail('INSTALLED_SOURCE_CHANGED');
|
|
27
30
|
}
|
|
28
|
-
async function cli(args, json = true) {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
+
export async function cli(args, json = true) {
|
|
32
|
+
// 只给本次官方插件命令关闭远程市场,保留 Codex 用户配置以及所有本地来源冲突检查。
|
|
33
|
+
const command = args[0] === 'plugin' ? [...args, '--disable', 'remote_plugin'] : args;
|
|
34
|
+
let stdout;
|
|
35
|
+
try {
|
|
36
|
+
({ stdout } = await execute(binary, command, { encoding: 'utf8', timeout: 30_000, maxBuffer: 1_048_576 }));
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (error.code === 'ENOENT') fail('CODEX_BINARY_NOT_FOUND');
|
|
39
|
+
if (error.killed && error.signal === 'SIGTERM') fail('CODEX_PLUGIN_COMMAND_TIMEOUT');
|
|
40
|
+
fail('CODEX_PLUGIN_COMMAND_FAILED');
|
|
41
|
+
}
|
|
42
|
+
if (!json) return stdout.trim();
|
|
43
|
+
try { return JSON.parse(stdout); }
|
|
44
|
+
catch { fail('CODEX_CLI_RESPONSE_UNKNOWN'); }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function installerUpgrade(old, release) {
|
|
48
|
+
if (['adapterVersion', 'sourceDigest', 'kit'].some(key => old[key] !== release[key])) return false;
|
|
49
|
+
if (old.distributionVersion === '0.1.0-beta.1' && release.distributionVersion === '0.1.0-beta.2') {
|
|
50
|
+
return old.host === release.host;
|
|
51
|
+
}
|
|
52
|
+
// 后续安装器单独升级只接受同一个运行压缩包,已有 owner 不需要换代码或重启。
|
|
53
|
+
const from = /^0\.1\.0-beta\.(\d+)$/.exec(old.distributionVersion);
|
|
54
|
+
const to = /^0\.1\.0-beta\.(\d+)$/.exec(release.distributionVersion);
|
|
55
|
+
return !!from && !!to && Number(to[1]) > Number(from[1]) && old.payloadSHA256 === release.payloadSHA256;
|
|
31
56
|
}
|
|
32
|
-
|
|
57
|
+
|
|
58
|
+
async function install() { return (await installRelease()).receipt; }
|
|
59
|
+
// changed 只供 Provider 判断幂等;安装器回执与原输出保持不变。
|
|
60
|
+
export async function installRelease() {
|
|
61
|
+
let changed = false;
|
|
33
62
|
const release = read(path.join(pkg, 'release.json'));
|
|
34
63
|
const dataRoot = path.join(os.homedir(), '.fridaynext/codex/data');
|
|
35
64
|
if (root === dataRoot || root.startsWith(dataRoot + path.sep) || dataRoot.startsWith(root + path.sep)) fail('INSTALL_ROOT_OVERLAPS_STATE');
|
|
36
|
-
|
|
65
|
+
const version = /^codex-cli (\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(await cli(['--version'], false));
|
|
66
|
+
if (!version) fail('CODEX_CLI_RESPONSE_UNKNOWN');
|
|
37
67
|
if (hash(fs.readFileSync(path.join(pkg, 'plugin.tgz'))) !== release.payloadSHA256) fail('RELEASE_PAYLOAD_CHANGED');
|
|
38
68
|
if (fs.lstatSync(root, { throwIfNoEntry: false })) {
|
|
39
69
|
privateRoot(); const old = read(path.join(root, 'release.json'));
|
|
40
70
|
if (old.payloadSHA256 !== release.payloadSHA256 || old.distributionVersion !== release.distributionVersion) {
|
|
41
|
-
if (old
|
|
42
|
-
|
|
43
|
-
verify(old);
|
|
71
|
+
if (!installerUpgrade(old, release)) fail('INSTALL_VERSION_CONFLICT');
|
|
72
|
+
verify(old); changed = true;
|
|
44
73
|
fs.writeFileSync(path.join(root, 'release.json'), JSON.stringify({ ...release, runtimePayloadSHA256: old.runtimePayloadSHA256 ?? old.payloadSHA256 }), { mode: 0o600 });
|
|
45
74
|
}
|
|
46
75
|
} else {
|
|
@@ -50,7 +79,7 @@ async function install() {
|
|
|
50
79
|
const names = execFileSync('tar', ['-tzf', path.join(pkg, 'plugin.tgz')], { encoding: 'utf8', maxBuffer: 8388608 }).split('\n');
|
|
51
80
|
if (names.some(name => path.isAbsolute(name) || name.split('/').includes('..'))) fail('RELEASE_PATH_UNSAFE');
|
|
52
81
|
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);
|
|
82
|
+
fs.writeFileSync(path.join(stage, 'release.json'), JSON.stringify(release), { mode: 0o600 }); fs.renameSync(stage, root); changed = true;
|
|
54
83
|
} finally { fs.rmSync(stage, { recursive: true, force: true }); }
|
|
55
84
|
}
|
|
56
85
|
verify(release);
|
|
@@ -58,17 +87,19 @@ async function install() {
|
|
|
58
87
|
if (!Array.isArray(markets)) fail('MARKETPLACE_RESPONSE_UNKNOWN');
|
|
59
88
|
const market = markets.find(value => value.name === 'fridaynext-local');
|
|
60
89
|
if (market && fs.realpathSync(market.root) !== fs.realpathSync(root)) fail('MARKETPLACE_SOURCE_CONFLICT');
|
|
61
|
-
if (!market) await cli(['plugin', 'marketplace', 'add', root, '--json']);
|
|
90
|
+
if (!market) { await cli(['plugin', 'marketplace', 'add', root, '--json']); changed = true; }
|
|
62
91
|
const installed = (await cli(['plugin', 'list', '--json'])).installed;
|
|
63
92
|
if (!Array.isArray(installed)) fail('PLUGIN_RESPONSE_UNKNOWN');
|
|
64
93
|
if (installed.some(value => value.name === 'fridaynext-codex' && value.pluginId !== pluginId)) fail('PLUGIN_SOURCE_CONFLICT');
|
|
65
94
|
const current = installed.find(value => value.pluginId === pluginId);
|
|
66
95
|
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;
|
|
96
|
+
if (!current) { await cli(['plugin', 'add', pluginId, '--json']); changed = true; }
|
|
97
|
+
const receipt = { state: 'installed', distributionVersion: release.distributionVersion, adapterVersion: release.adapterVersion, cliVersion: version[1], pluginId, codeRoot: root, sourceDigest: release.sourceDigest, serviceStarted: false };
|
|
98
|
+
fs.writeFileSync(path.join(root, 'installed.json'), JSON.stringify(receipt), { mode: 0o600 }); return { receipt, changed };
|
|
70
99
|
}
|
|
71
|
-
|
|
100
|
+
// 仅作为 bin 入口直接运行时执行安装器主流程;被 Provider 导入时只提供上述函数。
|
|
101
|
+
const entry = (() => { try { return fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; } })();
|
|
102
|
+
if (entry) try {
|
|
72
103
|
const [major, minor] = process.versions.node.split('.').map(Number); if (major < 22 || major === 22 && minor < 13) fail('NODE_VERSION_UNSUPPORTED');
|
|
73
104
|
const input = process.argv.slice(2), command = input[0]?.startsWith('--') && input[0] !== '--help' ? 'install' : input.shift() ?? 'install', args = input;
|
|
74
105
|
if (['help', '--help'].includes(command)) console.log('用法:fridaynext-codex-channel [install [--only --json] [--workspace <目录>] [--lan-host <IPv4>]|configure|status|pair|stop|roots|permissions|sessions];默认完成官方插件安装、配置、专用宿主启动、校验并显示配对二维码。');
|
package/installer-process.mjs
CHANGED
|
@@ -146,7 +146,10 @@ export function recovery(error, lang = language()) {
|
|
|
146
146
|
const zh = lang === 'zh';
|
|
147
147
|
const messages = {
|
|
148
148
|
HOST_VERSION_UNSUPPORTED: zh ? '请安装文档指定的宿主版本后重试' : 'Install the documented host version and retry',
|
|
149
|
-
|
|
149
|
+
CODEX_BINARY_NOT_FOUND: zh ? '找不到 Codex CLI。请安装 Codex 或将 FN_CODEX_BINARY 指向其可执行文件' : 'Codex CLI was not found. Install it or set FN_CODEX_BINARY to its executable',
|
|
150
|
+
CODEX_PLUGIN_COMMAND_FAILED: zh ? 'Codex 的本地插件命令未执行成功。请确认当前的官方 CLI 支持本地插件市场并重试' : 'A local Codex plugin command failed. Ensure the official CLI supports local plugin marketplaces and retry',
|
|
151
|
+
CODEX_PLUGIN_COMMAND_TIMEOUT: zh ? 'Codex 本地插件命令超时。请检查 Codex 是否能正常启动后重试' : 'A local Codex plugin command timed out. Check that Codex starts normally and retry',
|
|
152
|
+
CODEX_CLI_RESPONSE_UNKNOWN: zh ? '无法识别 Codex CLI 返回。请核对 PATH 或 FN_CODEX_BINARY 是否指向官方 Codex CLI' : 'Unrecognized Codex CLI response. Check PATH or FN_CODEX_BINARY for the official Codex CLI',
|
|
150
153
|
CLAUDE_PLUGIN_COMMAND_FAILED: zh ? '请确认 Claude Code 已安装,或设置 FN_CLAUDE_BINARY 后重试' : 'Check Claude Code installation or set FN_CLAUDE_BINARY and retry',
|
|
151
154
|
UPSTREAM_LOGIN_REQUIRED: zh ? '请先在电脑端登录宿主,再重新运行安装命令' : 'Sign in to the host on this computer, then rerun the installer',
|
|
152
155
|
WORKSPACE_REQUIRED: zh ? '请在要连接的项目目录运行,或传入 --workspace /项目绝对路径' : 'Run in your project, or pass --workspace /absolute/project/path',
|
package/onboarding.mjs
CHANGED
|
@@ -6,6 +6,11 @@ import { spawn } from 'node:child_process';
|
|
|
6
6
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
7
7
|
import { failure, privateDirectory, readPrivate, savePrivate, until, workspace, lanAddress, launch, jsonCommand, managedEndpoint, stopManaged, verifyHealth, runtimeModule } from './installer-process.mjs';
|
|
8
8
|
|
|
9
|
+
function ownerGone(file) {
|
|
10
|
+
try { process.kill(readPrivate(file).pid, 0); return false; }
|
|
11
|
+
catch (error) { return error.code === 'ESRCH'; }
|
|
12
|
+
}
|
|
13
|
+
|
|
9
14
|
export function codexOnboarding({ root, binary, options = {} }) {
|
|
10
15
|
const plugin = path.join(root, 'plugins/fridaynext-codex');
|
|
11
16
|
const load = name => import(pathToFileURL(path.join(plugin, 'src', name + '.mjs')));
|
|
@@ -31,10 +36,13 @@ export function codexOnboarding({ root, binary, options = {} }) {
|
|
|
31
36
|
if (code === data || code.startsWith(data + path.sep) || data.startsWith(code + path.sep)) throw failure('INSTALL_ROOT_OVERLAPS_STATE');
|
|
32
37
|
}
|
|
33
38
|
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
|
-
|
|
39
|
+
try { if ((await jsonCommand(cli, ['status'])).codex?.host?.state === 'verified') { reused = true; return { changed: false, reused }; } } catch {}
|
|
40
|
+
// 连接器模式(重启电脑或崩溃后)仅在原 owner 进程确认已不存在时继续,由插件自身的 owner 恢复流程接管锁;其余情况保持拒绝。
|
|
41
|
+
if (!options.connector || !ownerGone(path.join(config.dataRoot, 'service-owner/owner.json'))) throw failure('EXISTING_SERVICE_UNREACHABLE');
|
|
36
42
|
}
|
|
37
|
-
|
|
43
|
+
// 连接器模式(FN-654)不交互询问工作目录:沿用已登记目录,否则使用插件私有专用目录,不授权 HOME。
|
|
44
|
+
const cwd = options.connector ? previous?.cwd ?? fs.realpathSync(privateDirectory(path.join(paths.root, 'connector-workspace')))
|
|
45
|
+
: await workspace(options.workspace, previous?.cwd, ask);
|
|
38
46
|
if (!config) {
|
|
39
47
|
const lanHost = await lanAddress(options['lan-host'], undefined, ask);
|
|
40
48
|
let nativeSocket = path.join(paths.root, 'native.sock');
|
|
@@ -51,8 +59,10 @@ export function codexOnboarding({ root, binary, options = {} }) {
|
|
|
51
59
|
ownsNative: previous?.ownsNative === true && previous.nativeSocket === config.nativeSocket };
|
|
52
60
|
if (!setup.ownsNative && !fs.existsSync(config.nativeSocket)) throw failure('NATIVE_ENDPOINT_UNAVAILABLE');
|
|
53
61
|
}
|
|
54
|
-
|
|
62
|
+
const changed = JSON.stringify(previous) !== JSON.stringify(setup);
|
|
63
|
+
if (changed) savePrivate(setupFile, setup);
|
|
55
64
|
if (fs.existsSync(setupFile + '.failure.json')) { readPrivate(setupFile + '.failure.json'); fs.rmSync(setupFile + '.failure.json'); }
|
|
65
|
+
return { changed };
|
|
56
66
|
},
|
|
57
67
|
async start() {
|
|
58
68
|
if (reused) return;
|
|
@@ -69,10 +79,14 @@ export function codexOnboarding({ root, binary, options = {} }) {
|
|
|
69
79
|
try { const status = await jsonCommand(cli, ['status']); return status.codex?.host?.state === 'verified' && status.endpoint?.serverInstanceId; }
|
|
70
80
|
catch { return false; }
|
|
71
81
|
});
|
|
72
|
-
const live = await jsonCommand(cli, ['status'])
|
|
73
|
-
|
|
82
|
+
const live = await jsonCommand(cli, ['status']);
|
|
83
|
+
// 连接器模式只核对当前服务指纹,不为启动额外铸券(重出会作废旧券)。
|
|
84
|
+
const fingerprint = options.connector ? live.endpoint.fingerprint : (await jsonCommand(cli, ['pair'])).fingerprint;
|
|
85
|
+
await verifyHealth(live.endpoint.origin, fingerprint, readPrivate(path.join(config.dataRoot, 'component-identity.json')).token,
|
|
74
86
|
JSON.parse(fs.readFileSync(path.join(root, 'release.json'))).adapterVersion, readPrivate(path.join(config.dataRoot, 'tls/identity.json')).cert);
|
|
75
|
-
|
|
87
|
+
// 连接器模式初始授权 roots 为空,由用户在 App 选择项目后经后端授权。
|
|
88
|
+
if (!reused && !options.connector) await jsonCommand(cli, ['roots', 'add', '--path', setup.cwd]);
|
|
89
|
+
return live;
|
|
76
90
|
},
|
|
77
91
|
async pair() {
|
|
78
92
|
const value = await jsonCommand(cli, ['pair']);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syengup/fridaynext-codex-channel",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"description": "通过Codex官方标准插件命令安装FridayNext并连接显式授权的本机宿主",
|
|
@@ -8,11 +8,13 @@
|
|
|
8
8
|
"node": ">=22.13.0"
|
|
9
9
|
},
|
|
10
10
|
"bin": {
|
|
11
|
-
"fridaynext-codex-channel": "install.mjs"
|
|
11
|
+
"fridaynext-codex-channel": "install.mjs",
|
|
12
|
+
"fridaynext-codex-provider": "provider.mjs"
|
|
12
13
|
},
|
|
13
14
|
"files": [
|
|
14
15
|
"install.mjs",
|
|
15
16
|
"onboarding.mjs",
|
|
17
|
+
"provider.mjs",
|
|
16
18
|
"installer-ui.mjs",
|
|
17
19
|
"installer-flow.mjs",
|
|
18
20
|
"installer-process.mjs",
|
package/plugin.tgz
CHANGED
|
Binary file
|
package/provider.mjs
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// FN-654:Codex 的 Connector Provider 合同 v1 入口。连接器以固定参数调用:
|
|
3
|
+
// provider.mjs <probe|enable|start|restart|status|pairing|agents|projects> [--json-input <file>]
|
|
4
|
+
// stdout 只输出一个 JSON 对象;绝不输出后端永久 token。只启动/停止本组件自己创建的专用 app-server,
|
|
5
|
+
// 不重启、接管或停止用户已有的常驻宿主,不修改 Codex core,也不另起模型循环。
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import net from 'node:net';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { installRelease, verify, cli, installRoot as root, codexBinary as binary, packageRoot as pkg, pluginId } from './install.mjs';
|
|
14
|
+
import { codexOnboarding } from './onboarding.mjs';
|
|
15
|
+
import { stopManaged, verifyHealth, readPrivate, until } from './installer-process.mjs';
|
|
16
|
+
|
|
17
|
+
const CONTRACT = 'fridaynext.provider/1', HOST_ID = 'codex', BACKEND_ID = 'codex';
|
|
18
|
+
// 已验证的最早官方 CLI;更新的版本不做精确门禁,另以本地插件命令是否可用判断兼容。
|
|
19
|
+
const MIN_HOST_VERSION = '0.159.3';
|
|
20
|
+
const COMMANDS = new Set(['probe', 'enable', 'start', 'restart', 'status', 'pairing', 'agents', 'projects']);
|
|
21
|
+
const INSTALL_GUIDE = { title: '安装 Codex CLI', command: 'npm install -g @openai/codex', url: 'https://developers.openai.com/codex/cli' };
|
|
22
|
+
const AGENTS = [{ agentId: 'codex', displayName: 'Codex' }];
|
|
23
|
+
const plugin = path.join(root, 'plugins/fridaynext-codex');
|
|
24
|
+
const load = name => import(pathToFileURL(path.join(plugin, 'src', name + '.mjs')));
|
|
25
|
+
const read = file => JSON.parse(fs.readFileSync(file));
|
|
26
|
+
const realpath = value => { try { return fs.realpathSync(value); } catch { return undefined; } };
|
|
27
|
+
|
|
28
|
+
class ProviderFailure extends Error {
|
|
29
|
+
constructor(code, message, retryable = false) { super(message); this.code = code; this.retryable = retryable; }
|
|
30
|
+
}
|
|
31
|
+
// 内部错误码统一映射到合同错误码;message 只含内部错误码,不含路径以外的凭据或券。
|
|
32
|
+
const MAPPED = {
|
|
33
|
+
CODEX_BINARY_NOT_FOUND: ['HOST_NOT_INSTALLED', false],
|
|
34
|
+
CODEX_CLI_RESPONSE_UNKNOWN: ['HOST_INCOMPATIBLE', false],
|
|
35
|
+
CODEX_PLUGIN_COMMAND_FAILED: ['HOST_INCOMPATIBLE', false],
|
|
36
|
+
CODEX_PLUGIN_COMMAND_TIMEOUT: ['PROVIDER_INTERNAL', true],
|
|
37
|
+
EXISTING_SERVICE_UNREACHABLE: ['HOST_NOT_RUNNING', true],
|
|
38
|
+
NATIVE_ENDPOINT_UNAVAILABLE: ['HOST_NOT_RUNNING', true],
|
|
39
|
+
SERVICE_NOT_READY: ['PROVIDER_INTERNAL', true],
|
|
40
|
+
SERVICE_START_FAILED: ['PROVIDER_INTERNAL', true],
|
|
41
|
+
LAN_ADDRESS_REQUIRED: ['PROVIDER_INTERNAL', true],
|
|
42
|
+
};
|
|
43
|
+
function contractError(error) {
|
|
44
|
+
if (error instanceof ProviderFailure) return error;
|
|
45
|
+
const internal = typeof error?.code === 'string' && /^[A-Z0-9_]+$/.test(error.code) ? error.code : 'CODEX_PROVIDER_FAILED';
|
|
46
|
+
const [code, retryable] = MAPPED[internal] ?? ['PROVIDER_INTERNAL', false];
|
|
47
|
+
return new ProviderFailure(code, 'Codex Provider 执行失败:' + internal, retryable);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function versionAtLeast(value, minimum) {
|
|
51
|
+
const parse = text => { const [core, pre] = text.split('+')[0].split('-'); return { parts: core.split('.').map(Number), pre: pre !== undefined }; };
|
|
52
|
+
const a = parse(value), b = parse(minimum);
|
|
53
|
+
for (let i = 0; i < 3; i++) if (a.parts[i] !== b.parts[i]) return a.parts[i] > b.parts[i];
|
|
54
|
+
return !a.pre || b.pre;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// FN-663:已装运行代码是否为本组件更旧的发行。只读文件,不调用宿主;无法确认时抛出结构化内部错误码。
|
|
58
|
+
const semver = value => typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value) ? value.split('.').map(Number) : undefined;
|
|
59
|
+
const internal = code => Object.assign(new Error(code), { code });
|
|
60
|
+
function legacyRelease() {
|
|
61
|
+
if (!fs.lstatSync(root, { throwIfNoEntry: false })) return undefined;
|
|
62
|
+
const release = read(path.join(pkg, 'release.json'));
|
|
63
|
+
let old;
|
|
64
|
+
try { old = read(path.join(root, 'release.json')); } catch { throw internal('INSTALLED_RELEASE_UNKNOWN'); }
|
|
65
|
+
if (old.payloadSHA256 === release.payloadSHA256) return undefined;
|
|
66
|
+
const from = semver(old.adapterVersion), to = semver(release.adapterVersion);
|
|
67
|
+
if (!from || !to) throw internal('INSTALLED_RELEASE_UNKNOWN');
|
|
68
|
+
const order = from.findIndex((part, i) => part !== to[i]);
|
|
69
|
+
// 同一适配器版本的不同载荷交给安装器既有规则(仅安装器升级或 INSTALL_VERSION_CONFLICT)。
|
|
70
|
+
if (order < 0) return undefined;
|
|
71
|
+
if (from[order] > to[order]) throw internal('INSTALLED_VERSION_NEWER');
|
|
72
|
+
verify(old); // 旧代码须仍是本组件原样发行(私有根、来源摘要一致)。
|
|
73
|
+
return old;
|
|
74
|
+
}
|
|
75
|
+
// 官方登记须为空缺或指向本安装根;返回现有登记,冲突时抛出。
|
|
76
|
+
async function legacyRegistration(installed) {
|
|
77
|
+
installed ??= (await cli(['plugin', 'list', '--json'])).installed;
|
|
78
|
+
const markets = (await cli(['plugin', 'marketplace', 'list', '--json'])).marketplaces;
|
|
79
|
+
if (!Array.isArray(installed) || !Array.isArray(markets)) throw internal('MARKETPLACE_RESPONSE_UNKNOWN');
|
|
80
|
+
const market = markets.find(value => value?.name === 'fridaynext-local');
|
|
81
|
+
if (market && realpath(market.root) !== realpath(root)) throw internal('MARKETPLACE_SOURCE_CONFLICT');
|
|
82
|
+
if (installed.some(value => value?.name === 'fridaynext-codex' && value.pluginId !== pluginId)) throw internal('PLUGIN_SOURCE_CONFLICT');
|
|
83
|
+
const current = installed.find(value => value?.pluginId === pluginId);
|
|
84
|
+
if (current && realpath(current.source?.path) !== realpath(plugin)) throw internal('PLUGIN_SOURCE_CONFLICT');
|
|
85
|
+
return { market: !!market, plugin: !!current };
|
|
86
|
+
}
|
|
87
|
+
// 旧代码的连接配置在独立子进程中用旧代码自身读取,避免本进程缓存旧模块后再加载同路径的新代码。
|
|
88
|
+
function legacyConfiguration() {
|
|
89
|
+
const script = `import(${JSON.stringify(pathToFileURL(path.join(plugin, 'src/private-state.mjs')).href)}).then(({ readConfiguration }) => {
|
|
90
|
+
try { const c = readConfiguration(); console.log(JSON.stringify({ dataRoot: c.dataRoot, nativeSocket: c.nativeSocket })); }
|
|
91
|
+
catch (error) { if (error.code === 'CODEX_PLUGIN_NOT_CONFIGURED') console.log('null'); else process.exit(3); } });`;
|
|
92
|
+
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', env: process.env, timeout: 30000 });
|
|
93
|
+
if (result.status !== 0) throw internal('INSTALLED_CONFIG_UNKNOWN');
|
|
94
|
+
try { return JSON.parse(result.stdout); } catch { throw internal('INSTALLED_CONFIG_UNKNOWN'); }
|
|
95
|
+
}
|
|
96
|
+
const pidAlive = pid => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
|
|
97
|
+
const ownerAlive = config => { try { return pidAlive(readPrivate(path.join(config.dataRoot, 'service-owner', 'owner.json')).pid); } catch { return false; } };
|
|
98
|
+
const stamp = () => new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
|
|
99
|
+
|
|
100
|
+
// 按 distribution/README 的升级流程:停本组件旧 worker → 移除官方登记 → 旧代码移到备份 → 安装新代码并重新登记。
|
|
101
|
+
// 数据根、连接配置与安装器登记一律不动;任何前置核对失败都在改动之前返回。
|
|
102
|
+
async function upgradeLegacy(old) {
|
|
103
|
+
const registration = await legacyRegistration();
|
|
104
|
+
const config = legacyConfiguration();
|
|
105
|
+
if (config) {
|
|
106
|
+
const record = path.join(config.dataRoot, 'installer-worker.json');
|
|
107
|
+
if (!fs.existsSync(record) && ownerAlive(config)) throw internal('EXISTING_SERVICE_NOT_OWNED');
|
|
108
|
+
await stopOwnWorker(config, 'PROVIDER_INTERNAL');
|
|
109
|
+
try { await until(() => !ownerAlive(config), 30000); }
|
|
110
|
+
catch { throw new ProviderFailure('PROVIDER_INTERNAL', 'Codex Provider 执行失败:OLD_SERVICE_STILL_RUNNING', true); }
|
|
111
|
+
}
|
|
112
|
+
if (registration.plugin) await cli(['plugin', 'remove', pluginId], false);
|
|
113
|
+
if (registration.market) await cli(['plugin', 'marketplace', 'remove', 'fridaynext-local'], false);
|
|
114
|
+
const left = await legacyRegistration();
|
|
115
|
+
if (left.plugin || left.market) throw internal('LEGACY_REGISTRATION_REMAINS');
|
|
116
|
+
const backup = path.join(path.dirname(root), path.basename(root) + '.backup-' + stamp());
|
|
117
|
+
if (fs.existsSync(backup)) throw new ProviderFailure('PROVIDER_INTERNAL', 'Codex Provider 执行失败:BACKUP_EXISTS', true);
|
|
118
|
+
fs.renameSync(root, backup);
|
|
119
|
+
try { await installRelease(); }
|
|
120
|
+
catch (error) {
|
|
121
|
+
// 回滚:删除本次新解出的代码,恢复旧代码目录与原官方登记;原错误照常返回。
|
|
122
|
+
try {
|
|
123
|
+
if (fs.existsSync(root)) fs.rmSync(root, { recursive: true, force: true });
|
|
124
|
+
fs.renameSync(backup, root);
|
|
125
|
+
const now = await legacyRegistration();
|
|
126
|
+
if (registration.market && !now.market) await cli(['plugin', 'marketplace', 'add', root, '--json']);
|
|
127
|
+
if (registration.plugin && !now.plugin) await cli(['plugin', 'add', pluginId, '--json']);
|
|
128
|
+
} catch { /* 回滚尽力而为,备份目录保留供人工恢复。 */ }
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
return { upgradedFrom: old.adapterVersion, backupRoot: backup };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function hostVersion() {
|
|
135
|
+
let output;
|
|
136
|
+
try { output = await cli(['--version'], false); }
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (error.code === 'CODEX_BINARY_NOT_FOUND') return { installed: false, hostVersion: null, compatible: false };
|
|
139
|
+
if (error.code === 'CODEX_PLUGIN_COMMAND_FAILED') return { installed: true, hostVersion: null, compatible: false };
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
const match = /^codex-cli (\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(output);
|
|
143
|
+
if (!match) return { installed: true, hostVersion: null, compatible: false };
|
|
144
|
+
return { installed: true, hostVersion: match[1], compatible: versionAtLeast(match[1], MIN_HOST_VERSION) };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function configurationFile() {
|
|
148
|
+
const { runtimePaths } = await load('runtime-paths');
|
|
149
|
+
return path.resolve(process.env.FN_CODEX_CONFIG ?? runtimePaths().configFile);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// 读取当前宿主、插件与专用服务的状态;只读,不改动宿主或插件。
|
|
153
|
+
async function snapshot() {
|
|
154
|
+
const version = await hostVersion();
|
|
155
|
+
const state = { ...version, pluginEnabled: false, running: false };
|
|
156
|
+
if (!version.installed || !version.compatible) return state;
|
|
157
|
+
let installed;
|
|
158
|
+
try { installed = (await cli(['plugin', 'list', '--json'])).installed; }
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (['CODEX_PLUGIN_COMMAND_FAILED', 'CODEX_CLI_RESPONSE_UNKNOWN'].includes(error.code)) return { ...state, compatible: false };
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
if (!Array.isArray(installed)) return { ...state, compatible: false };
|
|
164
|
+
// FN-663:本安装根是本组件更旧的运行代码时如实上报可升级;仍按未启用处理,连接器据此视为可添加,enable 负责升级。
|
|
165
|
+
try {
|
|
166
|
+
const old = legacyRelease();
|
|
167
|
+
if (old) {
|
|
168
|
+
await legacyRegistration(installed);
|
|
169
|
+
return { ...state, upgradeAvailable: true, installedAdapterVersion: old.adapterVersion };
|
|
170
|
+
}
|
|
171
|
+
} catch { return state; }
|
|
172
|
+
const current = installed.find(value => value?.pluginId === pluginId);
|
|
173
|
+
if (current?.enabled !== true || !realpath(plugin) || realpath(current.source?.path) !== realpath(plugin)) return state;
|
|
174
|
+
// 已安装代码须与本发行运行载荷一致并通过来源摘要核验后,才加载其中模块。
|
|
175
|
+
try {
|
|
176
|
+
const release = read(path.join(pkg, 'release.json'));
|
|
177
|
+
if (read(path.join(root, 'release.json')).payloadSHA256 !== release.payloadSHA256) return state;
|
|
178
|
+
verify(release);
|
|
179
|
+
} catch { return state; }
|
|
180
|
+
const { readConfiguration } = await load('private-state');
|
|
181
|
+
let config;
|
|
182
|
+
try { config = readConfiguration(); }
|
|
183
|
+
catch (error) { if (error.code === 'CODEX_PLUGIN_NOT_CONFIGURED') return state; throw error; }
|
|
184
|
+
Object.assign(state, { pluginEnabled: true, config });
|
|
185
|
+
const ownerFile = path.join(config.dataRoot, 'service-owner', 'owner.json');
|
|
186
|
+
if (!fs.existsSync(ownerFile)) return state;
|
|
187
|
+
try {
|
|
188
|
+
const { ownerRequest } = await load('ownership');
|
|
189
|
+
const owner = readPrivate(ownerFile), live = await ownerRequest(owner, 'status');
|
|
190
|
+
if (live?.codex?.host?.state === 'verified' && typeof live.endpoint?.serverInstanceId === 'string') Object.assign(state, { running: true, owner, live });
|
|
191
|
+
} catch { /* 不可达即视为未运行,不推断。 */ }
|
|
192
|
+
return state;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const stateOf = s => !s.installed ? 'notInstalled' : !s.compatible ? 'incompatible' : !s.pluginEnabled ? 'needsEnable' : s.running ? 'running' : 'stopped';
|
|
196
|
+
function requireEnabled(s) {
|
|
197
|
+
if (!s.installed) throw new ProviderFailure('HOST_NOT_INSTALLED', '未检测到 Codex CLI');
|
|
198
|
+
if (!s.compatible) throw new ProviderFailure('HOST_INCOMPATIBLE', 'Codex CLI 版本或本地插件命令不兼容');
|
|
199
|
+
if (!s.pluginEnabled) throw new ProviderFailure('PLUGIN_NOT_ENABLED', 'FridayNext Codex 插件尚未启用');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function health(s) {
|
|
203
|
+
if (!s.running) return { reachable: false };
|
|
204
|
+
try {
|
|
205
|
+
await verifyHealth(s.live.endpoint.origin, s.live.endpoint.fingerprint, readPrivate(path.join(s.config.dataRoot, 'component-identity.json')).token,
|
|
206
|
+
read(path.join(root, 'release.json')).adapterVersion, readPrivate(path.join(s.config.dataRoot, 'tls/identity.json')).cert);
|
|
207
|
+
return { reachable: true, backendId: BACKEND_ID, serverInstanceId: s.live.endpoint.serverInstanceId };
|
|
208
|
+
} catch { return { reachable: false, serverInstanceId: s.live.endpoint.serverInstanceId }; }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const PRIVATE_IPV4 = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/;
|
|
212
|
+
// 连接器模式不交互:显式输入或环境变量优先,否则与连接器同规则选择 en0/en1 等私网地址。
|
|
213
|
+
function lanHost(input) {
|
|
214
|
+
const explicit = input?.lanHost ?? process.env.FN_CODEX_LAN_HOST;
|
|
215
|
+
if (explicit) return explicit;
|
|
216
|
+
const rank = name => name === 'en0' ? 0 : name === 'en1' ? 1 : name.startsWith('en') ? 2 : 3;
|
|
217
|
+
const rows = Object.entries(os.networkInterfaces())
|
|
218
|
+
.filter(([name]) => !/^(utun|tun|tap|tailscale|wg|docker|veth|br-|lo)/i.test(name))
|
|
219
|
+
.flatMap(([name, list]) => (list ?? []).filter(item => item.family === 'IPv4' && !item.internal && PRIVATE_IPV4.test(item.address)).map(item => ({ name, address: item.address })));
|
|
220
|
+
rows.sort((a, b) => rank(a.name) - rank(b.name));
|
|
221
|
+
return rows[0]?.address;
|
|
222
|
+
}
|
|
223
|
+
const onboarding = input => codexOnboarding({ root, binary, options: { connector: true, 'lan-host': lanHost(input) } });
|
|
224
|
+
|
|
225
|
+
function socketRefused(file) {
|
|
226
|
+
return new Promise(resolve => {
|
|
227
|
+
const socket = net.createConnection({ path: file });
|
|
228
|
+
socket.once('connect', () => { socket.destroy(); resolve(false); });
|
|
229
|
+
socket.once('error', error => resolve(error.code === 'ECONNREFUSED'));
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 停止本安装器登记的专用 worker(复用 stopManaged),不删除任何数据;只清理确认失效的控制记录与自有残留 socket。
|
|
234
|
+
async function stopOwnWorker(config, failureCode) {
|
|
235
|
+
const record = path.join(config.dataRoot, 'installer-worker.json');
|
|
236
|
+
if (!fs.existsSync(record)) return false;
|
|
237
|
+
try { await stopManaged(record); }
|
|
238
|
+
catch (error) {
|
|
239
|
+
if (error.code !== 'ECONNREFUSED') throw new ProviderFailure(failureCode, '无法停止专用 Codex 进程', true);
|
|
240
|
+
fs.rmSync(record, { force: true });
|
|
241
|
+
}
|
|
242
|
+
try { await until(() => !fs.existsSync(record), 45000); }
|
|
243
|
+
catch { throw new ProviderFailure(failureCode, '专用 Codex 进程仍有执行未结束,稍后重试', true); }
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
async function clearOwnStaleSocket(config) {
|
|
247
|
+
let setup;
|
|
248
|
+
try { setup = readPrivate((await configurationFile()) + '.installer.json'); } catch { return; }
|
|
249
|
+
if (setup.ownsNative !== true || setup.nativeSocket !== config.nativeSocket || !fs.existsSync(config.nativeSocket)) return;
|
|
250
|
+
if (await socketRefused(config.nativeSocket)) fs.rmSync(config.nativeSocket, { force: true });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function start(input) {
|
|
254
|
+
const s = await snapshot();
|
|
255
|
+
requireEnabled(s);
|
|
256
|
+
if (s.running) return { state: 'running' };
|
|
257
|
+
await stopOwnWorker(s.config, 'PROVIDER_INTERNAL');
|
|
258
|
+
await clearOwnStaleSocket(s.config);
|
|
259
|
+
const flow = onboarding(input);
|
|
260
|
+
await flow.configure();
|
|
261
|
+
await flow.start();
|
|
262
|
+
try { await flow.verify(); }
|
|
263
|
+
catch (error) { await flow.cleanup().catch(() => {}); throw error; }
|
|
264
|
+
return { state: 'running' };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function projects() {
|
|
268
|
+
const s = await snapshot();
|
|
269
|
+
// 只读查询不为此拉起宿主;专用宿主未运行时如实返回空列表。
|
|
270
|
+
if (!s.running) return { projects: [] };
|
|
271
|
+
const { connectNative } = await load('native-client');
|
|
272
|
+
const peer = await connectNative(s.config.nativeSocket, { experimentalApi: true });
|
|
273
|
+
const rows = [];
|
|
274
|
+
try {
|
|
275
|
+
let cursor;
|
|
276
|
+
for (let page = 0; page < 5; page++) {
|
|
277
|
+
const result = await peer.rpc('project/list', { limit: 100, sortKey: 'position', sortDirection: 'asc', ...(cursor ? { cursor } : {}) });
|
|
278
|
+
if (!Array.isArray(result?.data)) throw new ProviderFailure('PROVIDER_INTERNAL', 'Codex 原生项目列表无法确认', true);
|
|
279
|
+
rows.push(...result.data);
|
|
280
|
+
if (!result.nextCursor || result.nextCursor === cursor) break;
|
|
281
|
+
cursor = result.nextCursor;
|
|
282
|
+
}
|
|
283
|
+
} finally { peer.close(); }
|
|
284
|
+
const time = value => Number.isFinite(value) ? new Date(value < 1e12 ? value * 1000 : value).toISOString() : undefined;
|
|
285
|
+
const list = rows.flatMap(project => {
|
|
286
|
+
const first = Array.isArray(project?.roots) ? project.roots.find(item => typeof item?.path === 'string' && path.isAbsolute(item.path)) : undefined;
|
|
287
|
+
if (!first || typeof project.name !== 'string' || !project.name) return [];
|
|
288
|
+
const lastUsedAt = time(project.updatedAt);
|
|
289
|
+
return [{ path: first.path, displayName: project.name, ...(lastUsedAt ? { lastUsedAt } : {}) }];
|
|
290
|
+
});
|
|
291
|
+
// 最近使用在前;无时间的项目保持原生顺序排在后面。
|
|
292
|
+
list.sort((a, b) => (b.lastUsedAt ?? '').localeCompare(a.lastUsedAt ?? ''));
|
|
293
|
+
return { projects: list.slice(0, 50) };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const handlers = {
|
|
297
|
+
async probe() {
|
|
298
|
+
const s = await snapshot();
|
|
299
|
+
return { installed: s.installed, hostVersion: s.hostVersion, compatible: s.compatible, pluginEnabled: s.pluginEnabled, running: s.running,
|
|
300
|
+
needsHostRestartToEnable: false, state: stateOf(s), upgradeAvailable: s.upgradeAvailable === true,
|
|
301
|
+
...(s.upgradeAvailable ? { installedAdapterVersion: s.installedAdapterVersion } : {}),
|
|
302
|
+
...(s.installed ? {} : { installGuide: INSTALL_GUIDE }) };
|
|
303
|
+
},
|
|
304
|
+
async enable(input) {
|
|
305
|
+
const before = await hostVersion();
|
|
306
|
+
requireEnabled({ ...before, pluginEnabled: true });
|
|
307
|
+
// FN-663:本组件更旧的运行代码先按升级流程替换;数据根与连接配置保持,随后沿既有配置判断。
|
|
308
|
+
const old = legacyRelease();
|
|
309
|
+
const upgrade = old ? await upgradeLegacy(old) : undefined;
|
|
310
|
+
const { changed: installed } = upgrade ? { changed: true } : await installRelease();
|
|
311
|
+
const { readConfiguration } = await load('private-state');
|
|
312
|
+
let configured = false;
|
|
313
|
+
try { readConfiguration(); }
|
|
314
|
+
catch (error) {
|
|
315
|
+
if (error.code !== 'CODEX_PLUGIN_NOT_CONFIGURED') throw error;
|
|
316
|
+
// 首次启用:写入连接配置与自有端点登记;既有配置(旧安装器装过)原样保留。
|
|
317
|
+
await onboarding(input).configure();
|
|
318
|
+
configured = true;
|
|
319
|
+
}
|
|
320
|
+
return { changed: installed || configured, hostRestarted: false, state: stateOf(await snapshot()), ...(upgrade ?? {}) };
|
|
321
|
+
},
|
|
322
|
+
start,
|
|
323
|
+
async restart(input) {
|
|
324
|
+
const s = await snapshot();
|
|
325
|
+
requireEnabled(s);
|
|
326
|
+
const stopped = await stopOwnWorker(s.config, 'HOST_RESTART_FAILED');
|
|
327
|
+
// 运行中的服务若不是本组件登记的专用进程(例如用户自己的会话),不接管也不停止。
|
|
328
|
+
if (!stopped && s.running) throw new ProviderFailure('HOST_RESTART_FAILED', '当前 Codex 服务不由 FridayNext 专用进程管理,未做改动');
|
|
329
|
+
return start(input);
|
|
330
|
+
},
|
|
331
|
+
async status() {
|
|
332
|
+
const s = await snapshot();
|
|
333
|
+
const h = await health(s);
|
|
334
|
+
return { state: s.running && !h.reachable ? 'unknown' : stateOf(s), health: h };
|
|
335
|
+
},
|
|
336
|
+
async pairing() {
|
|
337
|
+
const s = await snapshot();
|
|
338
|
+
requireEnabled(s);
|
|
339
|
+
if (!s.running) throw new ProviderFailure('HOST_NOT_RUNNING', 'Codex 专用服务未运行', true);
|
|
340
|
+
let value;
|
|
341
|
+
const { ownerRequest } = await load('ownership');
|
|
342
|
+
try { value = await ownerRequest(s.owner, 'pair'); }
|
|
343
|
+
catch { throw new ProviderFailure('PAIRING_UNAVAILABLE', '无法铸造配对券', true); }
|
|
344
|
+
const text = key => typeof value?.[key] === 'string' && value[key].length > 0;
|
|
345
|
+
if (!['backendId', 'lanUrl', 'fingerprint', 'pairingTicket'].every(text) || /^https?:\/\/(127\.|localhost|\[::1\])/.test(value.lanUrl))
|
|
346
|
+
throw new ProviderFailure('PAIRING_UNAVAILABLE', '本后端没有可用的局域网配对坐标', true);
|
|
347
|
+
// 白名单输出:一次性券与坐标,永久 token 等其他字段一律不输出。
|
|
348
|
+
return { backendId: value.backendId, lanUrl: value.lanUrl, fingerprint: value.fingerprint, pairingTicket: value.pairingTicket,
|
|
349
|
+
pairingTicketTtlSec: Number.isSafeInteger(value.pairingTicketTtlSec) ? value.pairingTicketTtlSec : 600,
|
|
350
|
+
// 合同 v1 可选:已开启公网访问时透传 FridayTunnel 地址与控制面(FN-661)。
|
|
351
|
+
...(typeof value?.publicUrl === 'string' && /^https:\/\//.test(value.publicUrl) ? { publicUrl: value.publicUrl } : {}),
|
|
352
|
+
...(typeof value?.controlPlane === 'string' && /^https:\/\//.test(value.controlPlane) ? { controlPlane: value.controlPlane } : {}) };
|
|
353
|
+
},
|
|
354
|
+
async agents() {
|
|
355
|
+
return { agents: AGENTS, revision: createHash('sha256').update(JSON.stringify(AGENTS)).digest('hex').slice(0, 16) };
|
|
356
|
+
},
|
|
357
|
+
projects,
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
function respond(body, code) {
|
|
361
|
+
process.stdout.write(JSON.stringify({ contract: CONTRACT, hostId: HOST_ID, ...body }) + '\n', () => process.exit(code));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const args = process.argv.slice(2);
|
|
365
|
+
const command = args[0];
|
|
366
|
+
try {
|
|
367
|
+
if (!COMMANDS.has(command)) throw new ProviderFailure('UNSUPPORTED_COMMAND', '不支持的命令');
|
|
368
|
+
let input;
|
|
369
|
+
const rest = args.slice(1);
|
|
370
|
+
if (rest.length) {
|
|
371
|
+
if (rest.length !== 2 || rest[0] !== '--json-input') throw new ProviderFailure('PROVIDER_INTERNAL', '参数无效');
|
|
372
|
+
input = JSON.parse(fs.readFileSync(rest[1], 'utf8'));
|
|
373
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new ProviderFailure('PROVIDER_INTERNAL', '输入无效');
|
|
374
|
+
}
|
|
375
|
+
const [major, minor] = process.versions.node.split('.').map(Number);
|
|
376
|
+
if (major < 22 || major === 22 && minor < 13) throw new ProviderFailure('PROVIDER_INTERNAL', 'Node.js 版本过低');
|
|
377
|
+
respond({ ok: true, ...await handlers[command](input) }, 0);
|
|
378
|
+
} catch (error) {
|
|
379
|
+
const failure = contractError(error);
|
|
380
|
+
respond({ ok: false, error: { code: failure.code, message: failure.message, retryable: failure.retryable } }, 1);
|
|
381
|
+
}
|
package/release.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"distributionVersion": "0.1.0-beta.
|
|
4
|
-
"adapterVersion": "0.1.
|
|
3
|
+
"distributionVersion": "0.1.0-beta.5",
|
|
4
|
+
"adapterVersion": "0.1.103",
|
|
5
5
|
"host": "0.159.3",
|
|
6
6
|
"kit": "0.2.0-beta.9",
|
|
7
|
-
"sourceDigest": "
|
|
8
|
-
"payloadSHA256": "
|
|
7
|
+
"sourceDigest": "a509f5c3dac6382e3f9ebf6d84e25dba712c4460842c0d09e50a0aa6fad44bea",
|
|
8
|
+
"payloadSHA256": "e9d65e869f35337c36a2bced2de436bb0bf1f107a00ea707d7bc4502991a0cda"
|
|
9
9
|
}
|