@ailuntz/codex-desktop-router 0.6.1
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/LICENSE +202 -0
- package/README.md +50 -0
- package/bin/codex-desktop-router.mjs +61 -0
- package/package.json +29 -0
- package/src/chat.mjs +158 -0
- package/src/config.mjs +99 -0
- package/src/install.mjs +100 -0
- package/src/model-menu.mjs +170 -0
- package/src/picker-client.js +51 -0
- package/src/picker.html +8 -0
- package/src/picker.mjs +155 -0
- package/src/profiles.mjs +127 -0
- package/src/protocol.mjs +47 -0
- package/src/provider-switch.mjs +207 -0
- package/src/proxy.mjs +164 -0
- package/src/rpc.mjs +55 -0
- package/src/update.mjs +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ailuntz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
The text-only Responses gateway in src/chat.mjs also carries the following notice:
|
|
24
|
+
|
|
25
|
+
Copyright 2026 ailuntz
|
|
26
|
+
|
|
27
|
+
Apache License
|
|
28
|
+
Version 2.0, January 2004
|
|
29
|
+
http://www.apache.org/licenses/
|
|
30
|
+
|
|
31
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
32
|
+
|
|
33
|
+
1. Definitions.
|
|
34
|
+
|
|
35
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
36
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
37
|
+
|
|
38
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
39
|
+
the copyright owner that is granting the License.
|
|
40
|
+
|
|
41
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
42
|
+
other entities that control, are controlled by, or are under common
|
|
43
|
+
control with that entity. For the purposes of this definition,
|
|
44
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
45
|
+
direction or management of such entity, whether by contract or
|
|
46
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
47
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
48
|
+
|
|
49
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
50
|
+
exercising permissions granted by this License.
|
|
51
|
+
|
|
52
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
53
|
+
including but not limited to software source code, documentation
|
|
54
|
+
source, and configuration files.
|
|
55
|
+
|
|
56
|
+
"Object" form shall mean any form resulting from mechanical
|
|
57
|
+
transformation or translation of a Source form, including but
|
|
58
|
+
not limited to compiled object code, generated documentation,
|
|
59
|
+
and conversions to other media types.
|
|
60
|
+
|
|
61
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
62
|
+
Object form, made available under the License, as indicated by a
|
|
63
|
+
copyright notice that is included in or attached to the work
|
|
64
|
+
(an example is provided in the Appendix below).
|
|
65
|
+
|
|
66
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
67
|
+
form, that is based on (or derived from) the Work and for which the
|
|
68
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
69
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
70
|
+
of this License, Derivative Works shall not include works that remain
|
|
71
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
72
|
+
the Work and Derivative Works thereof.
|
|
73
|
+
|
|
74
|
+
"Contribution" shall mean any work of authorship, including
|
|
75
|
+
the original version of the Work and any modifications or additions
|
|
76
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
77
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
78
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
79
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
80
|
+
means any form of electronic, verbal, or written communication sent
|
|
81
|
+
to the Licensor or its representatives, including but not limited to
|
|
82
|
+
communication on electronic mailing lists, source code control systems,
|
|
83
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
84
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
85
|
+
excluding communication that is conspicuously marked or otherwise
|
|
86
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
87
|
+
|
|
88
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
89
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
90
|
+
subsequently incorporated within the Work.
|
|
91
|
+
|
|
92
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
93
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
94
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
95
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
96
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
97
|
+
Work and such Derivative Works in Source or Object form.
|
|
98
|
+
|
|
99
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
100
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
101
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
102
|
+
(except as stated in this section) patent license to make, have made,
|
|
103
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
104
|
+
where such license applies only to those patent claims licensable
|
|
105
|
+
by such Contributor that are necessarily infringed by their
|
|
106
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
107
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
108
|
+
institute patent litigation against any entity (including a
|
|
109
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
110
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
111
|
+
or contributory patent infringement, then any patent licenses
|
|
112
|
+
granted to You under this License for that Work shall terminate
|
|
113
|
+
as of the date such litigation is filed.
|
|
114
|
+
|
|
115
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
116
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
117
|
+
modifications, and in Source or Object form, provided that You
|
|
118
|
+
meet the following conditions:
|
|
119
|
+
|
|
120
|
+
(a) You must give any other recipients of the Work or
|
|
121
|
+
Derivative Works a copy of this License; and
|
|
122
|
+
|
|
123
|
+
(b) You must cause any modified files to carry prominent notices
|
|
124
|
+
stating that You changed the files; and
|
|
125
|
+
|
|
126
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
127
|
+
that You distribute, all copyright, patent, trademark, and
|
|
128
|
+
attribution notices from the Source form of the Work,
|
|
129
|
+
excluding those notices that do not pertain to any part of
|
|
130
|
+
the Derivative Works; and
|
|
131
|
+
|
|
132
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
133
|
+
distribution, then any Derivative Works that You distribute must
|
|
134
|
+
include a readable copy of the attribution notices contained
|
|
135
|
+
within such NOTICE file, excluding those notices that do not
|
|
136
|
+
pertain to any part of the Derivative Works, in at least one
|
|
137
|
+
of the following places: within a NOTICE text file distributed
|
|
138
|
+
as part of the Derivative Works; within the Source form or
|
|
139
|
+
documentation, if provided along with the Derivative Works; or,
|
|
140
|
+
within a display generated by the Derivative Works, if and
|
|
141
|
+
wherever such third-party notices normally appear. The contents
|
|
142
|
+
of the NOTICE file are for informational purposes only and
|
|
143
|
+
do not modify the License. You may add Your own attribution
|
|
144
|
+
notices within Derivative Works that You distribute, alongside
|
|
145
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
146
|
+
that such additional attribution notices cannot be construed
|
|
147
|
+
as modifying the License.
|
|
148
|
+
|
|
149
|
+
You may add Your own copyright statement to Your modifications and
|
|
150
|
+
may provide additional or different license terms and conditions
|
|
151
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
152
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
153
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
154
|
+
the conditions stated in this License.
|
|
155
|
+
|
|
156
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
157
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
158
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
159
|
+
this License, without any additional terms or conditions.
|
|
160
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
161
|
+
the terms of any separate license agreement you may have executed
|
|
162
|
+
with Licensor regarding such Contributions.
|
|
163
|
+
|
|
164
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
165
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
166
|
+
except as required for reasonable and customary use in describing the
|
|
167
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
168
|
+
|
|
169
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
170
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
171
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
172
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
173
|
+
implied, including, without limitation, any warranties or conditions
|
|
174
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
175
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
176
|
+
appropriateness of using or redistributing the Work and assume any
|
|
177
|
+
risks associated with Your exercise of permissions under this License.
|
|
178
|
+
|
|
179
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
180
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
181
|
+
unless required by applicable law (such as deliberate and grossly
|
|
182
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
183
|
+
liable to You for damages, including any direct, indirect, special,
|
|
184
|
+
incidental, or consequential damages of any character arising as a
|
|
185
|
+
result of this License or out of the use or inability to use the
|
|
186
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
187
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
188
|
+
other commercial damages or losses), even if such Contributor
|
|
189
|
+
has been advised of the possibility of such damages.
|
|
190
|
+
|
|
191
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
192
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
193
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
194
|
+
or other liability obligations and/or rights consistent with this
|
|
195
|
+
License. However, in accepting such obligations, You may act only
|
|
196
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
197
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
198
|
+
defend, and hold each Contributor harmless for any liability
|
|
199
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
200
|
+
of your accepting any such warranty or additional liability.
|
|
201
|
+
|
|
202
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# codex-desktop-router
|
|
2
|
+
|
|
3
|
+
在 ChatGPT / Codex Desktop 的原生模型菜单中使用已有 profiles。
|
|
4
|
+
|
|
5
|
+
自动读取 `~/.codex/*.config.toml`。有 `model_catalog_json` 就使用该目录,否则继承原生模型列表,无需维护模型名单。支持 API key 的 Responses 连接还会追加 `-Chat`,用于不带工具和工作区上下文的纯文字聊天。
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
macOS,Node.js ≥22.16。
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install -g @ailuntz/codex-desktop-router
|
|
13
|
+
codex-desktop-router install
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
完全退出并重开 Desktop,再运行:
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
codex-desktop-router on
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## 命令
|
|
23
|
+
|
|
24
|
+
| 命令 | 用途 |
|
|
25
|
+
| --- | --- |
|
|
26
|
+
| `install` | 安装或升级本机接入 |
|
|
27
|
+
| `on` | 开启模型选项,打开模型选择页 |
|
|
28
|
+
| `off` | 关闭追加选项和选择页接管 |
|
|
29
|
+
| `doctor` | 检查配置、运行状态和新版 |
|
|
30
|
+
| `uninstall` | 移除 Desktop 接入,保留用户配置 |
|
|
31
|
+
|
|
32
|
+
额度提示挡住菜单时,运行 `on`,在选择页切换模型后回 Desktop 发送。选择持续到交回菜单、执行 `off` 或退出 Desktop。
|
|
33
|
+
|
|
34
|
+
## 更新
|
|
35
|
+
|
|
36
|
+
每天自动检查一次,新版会在终端和模型选择页提示。升级:
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npm install -g @ailuntz/codex-desktop-router@latest
|
|
40
|
+
codex-desktop-router install
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
升级或修改 profiles、连接、密钥后,重启 Desktop。设置 `CODEX_DESKTOP_ROUTER_NO_UPDATE_CHECK=1` 可关闭检查。
|
|
44
|
+
|
|
45
|
+
## 使用说明
|
|
46
|
+
|
|
47
|
+
- 跨连接切换需要任务已保存且空闲;临时任务、尚无历史或含子代理的任务请新建。
|
|
48
|
+
- Chat 仅支持纯文字历史,不支持附件、中途追加和上下文压缩。
|
|
49
|
+
- 模型选择保留当前任务权限,不应用 profile 中的权限覆盖。
|
|
50
|
+
- 密钥使用提供商声明的环境变量,也可放在 `~/.codex/.env`。支持 `CODEX_HOME`。
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { VERSION, readConfig, configPath, codexHome, atomicJSON, discoverProfiles, resolveRealCodex, childEnvironment } from '../src/config.mjs';
|
|
6
|
+
import { checkForUpdates } from '../src/update.mjs';
|
|
7
|
+
import { runProxy } from '../src/proxy.mjs';
|
|
8
|
+
import { openPicker } from '../src/picker.mjs';
|
|
9
|
+
import { install, uninstall, installation, environmentStatus } from '../src/install.mjs';
|
|
10
|
+
|
|
11
|
+
const self = fileURLToPath(import.meta.url), args = process.argv.slice(2);
|
|
12
|
+
const commands = ['install', 'on', 'off', 'doctor', 'uninstall'];
|
|
13
|
+
const output = value => console.log(typeof value === 'string' ? value : JSON.stringify(value, null, 2));
|
|
14
|
+
const help = `codex-desktop-router
|
|
15
|
+
|
|
16
|
+
install 安装或升级本机接入
|
|
17
|
+
on 开启 profile 模型选项,并打开模型选择页
|
|
18
|
+
off 隐藏额外选项,停止选择页接管
|
|
19
|
+
doctor 检查 profiles、连接和是否需要重启
|
|
20
|
+
uninstall 移除本机接入
|
|
21
|
+
|
|
22
|
+
自动读取 CODEX_HOME 下的 *.config.toml,无需重复配置。
|
|
23
|
+
有 model_catalog_json 时使用生效目录,否则继承客户端模型目录。
|
|
24
|
+
权限仍由当前任务管理。其他 Codex 参数原样透传。`;
|
|
25
|
+
|
|
26
|
+
async function main() {
|
|
27
|
+
const command = args[0];
|
|
28
|
+
if (!command || ['--help', '-h'].includes(command)) return output(help);
|
|
29
|
+
if (commands.includes(command) && args.length !== 1) throw new Error(`${command} 不接受额外参数。`);
|
|
30
|
+
if (['configure', 'picker'].includes(command)) throw new Error('此入口已移除。配置直接在客户端管理,开启和选择模型统一使用 on。');
|
|
31
|
+
if (command === 'install') {
|
|
32
|
+
resolveRealCodex(self);
|
|
33
|
+
const state = readConfig();
|
|
34
|
+
const result = install(); atomicJSON(configPath(), state);
|
|
35
|
+
return output(`已安装 ${VERSION}:${result.wrapper}\n请完全退出并重开 Desktop,然后运行 codex-desktop-router on。`);
|
|
36
|
+
}
|
|
37
|
+
if (command === 'on' || command === 'off') {
|
|
38
|
+
if (command === 'on') discoverProfiles();
|
|
39
|
+
atomicJSON(configPath(), { version: 1, enabled: command === 'on' });
|
|
40
|
+
return output(command === 'off' ? '已关闭额外选项和选择页接管。已有任务保留当前提供商。' : openPicker(codexHome()) ? '已开启,并打开模型选择页。' : '已开启。请完全退出并重开 Desktop;需要选择页时再次运行 on。');
|
|
41
|
+
}
|
|
42
|
+
if (command === 'uninstall') return output(uninstall() ? '已移除本机接入。重启 Desktop 后生效。' : '未发现安装记录。');
|
|
43
|
+
if (command === 'doctor') {
|
|
44
|
+
const active = [], profiles = discoverProfiles(), env = childEnvironment(profiles);
|
|
45
|
+
try {
|
|
46
|
+
for (const file of readdirSync(join(codexHome(), 'desktop-router-runs'))) if (/^\d+\.json$/.test(file)) {
|
|
47
|
+
try { const run = JSON.parse(readFileSync(join(codexHome(), 'desktop-router-runs', file), 'utf8')); process.kill(run.pid, 0); process.kill(run.childPid, 0); active.push({ pid: run.pid, version: run.version }); } catch { /* stale process */ }
|
|
48
|
+
}
|
|
49
|
+
} catch { /* no active process */ }
|
|
50
|
+
return output({ version: VERSION, enabled: readConfig().enabled, realCodex: resolveRealCodex(self), installed: Boolean(installation()), launchEnvironment: environmentStatus(),
|
|
51
|
+
profiles: profiles.map(r => ({ name: r.profile, provider: r.originalProvider, catalog: r.catalogPath || '继承客户端目录', chat: r.chat, keyAvailable: r.providerDefinition?.env_key ? Boolean(env[r.providerDefinition.env_key]) : null })),
|
|
52
|
+
update: await checkForUpdates(), active, restartRequired: active.length === 0 || active.some(r => r.version !== VERSION) });
|
|
53
|
+
}
|
|
54
|
+
process.exitCode = await runProxy(args, self);
|
|
55
|
+
}
|
|
56
|
+
main().then(async () => {
|
|
57
|
+
if (['install', 'on'].includes(args[0])) {
|
|
58
|
+
const update = await checkForUpdates();
|
|
59
|
+
if (update.available) process.stderr.write(`新版 ${update.latest} 可用:${update.command}\n升级后请重启 Desktop。\n`);
|
|
60
|
+
}
|
|
61
|
+
}).catch(error => { process.stderr.write(`codex-desktop-router: ${error.message}\n`); process.exitCode = 1; });
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ailuntz/codex-desktop-router",
|
|
3
|
+
"version": "0.6.1",
|
|
4
|
+
"description": "Add custom-provider routes to the native Codex Desktop model picker without maintaining a model catalog.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT AND Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.16"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"codex-desktop-router": "bin/codex-desktop-router.mjs"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"bin/",
|
|
15
|
+
"src/",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "node --test test/*.test.mjs"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"smol-toml": "1.8.0"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org/"
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/chat.mjs
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import { Readable, Transform } from 'node:stream';
|
|
3
|
+
import { pipeline } from 'node:stream/promises';
|
|
4
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
5
|
+
import { chatProviderId } from './config.mjs';
|
|
6
|
+
|
|
7
|
+
const instructions = 'You are a helpful conversational assistant. Answer the user directly. No tools are available.';
|
|
8
|
+
const limit = 16 * 1024 * 1024;
|
|
9
|
+
const textMessage = (role, text) => ({ type: 'message', role, content: [{ type: role === 'assistant' ? 'output_text' : 'input_text', text }] });
|
|
10
|
+
function userText(content) {
|
|
11
|
+
if (!Array.isArray(content) || content.some(p => p.type !== 'text' || typeof p.text !== 'string')) throw new Error('Chat 模式目前只支持文字;图片、附件和技能请使用普通模型。');
|
|
12
|
+
return content.map(p => p.text).join('\n');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Check each complete SSE event before Codex can receive a tool-call item.
|
|
16
|
+
function textEvents() {
|
|
17
|
+
const decoder = new StringDecoder('utf8');
|
|
18
|
+
let pending = '';
|
|
19
|
+
function inspect(frame) {
|
|
20
|
+
const data = frame.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
|
|
21
|
+
if (!data || data === '[DONE]') return;
|
|
22
|
+
const event = JSON.parse(data);
|
|
23
|
+
const items = [...(event.item ? [event.item] : []), ...(event.response?.output || [])];
|
|
24
|
+
if (items.some(item => !['message', 'reasoning'].includes(item.type) || (item.type === 'message' && item.role !== 'assistant'))) throw new Error('Chat upstream returned a non-text item');
|
|
25
|
+
}
|
|
26
|
+
return new Transform({
|
|
27
|
+
transform(chunk, encoding, done) {
|
|
28
|
+
try {
|
|
29
|
+
pending += decoder.write(chunk);
|
|
30
|
+
let match;
|
|
31
|
+
while ((match = /\r?\n\r?\n/.exec(pending))) {
|
|
32
|
+
const end = match.index + match[0].length, frame = pending.slice(0, end);
|
|
33
|
+
if (Buffer.byteLength(frame) > limit) throw new Error('Chat response event too large');
|
|
34
|
+
inspect(frame); this.push(frame); pending = pending.slice(end);
|
|
35
|
+
}
|
|
36
|
+
if (Buffer.byteLength(pending) > limit) throw new Error('Chat response event too large');
|
|
37
|
+
done();
|
|
38
|
+
} catch (error) { done(error); }
|
|
39
|
+
},
|
|
40
|
+
flush(done) {
|
|
41
|
+
try { pending += decoder.end(); if (pending) { inspect(pending); this.push(pending); } done(); }
|
|
42
|
+
catch (error) { done(error); }
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class Chat {
|
|
48
|
+
constructor({ config, key, env = {} }) {
|
|
49
|
+
this.config = config; this.key = key;
|
|
50
|
+
this.headers = { ...config.providerDefinition.http_headers };
|
|
51
|
+
for (const [name, variable] of Object.entries(config.providerDefinition.env_http_headers || {})) if (env[variable]) this.headers[name] = env[variable];
|
|
52
|
+
this.path = `/chat-${randomBytes(24).toString('hex')}`;
|
|
53
|
+
this.envKey = `CDR_CHAT_${randomBytes(8).toString('hex')}`;
|
|
54
|
+
this.providers = new Set([chatProviderId(config), ...(config.legacyProvider ? [`cdr_chat_${config.legacyProvider}`] : [])]);
|
|
55
|
+
this.token = randomBytes(32).toString('hex');
|
|
56
|
+
this.contexts = new Map(); this.pending = new Map(); this.starts = new Set(); this.fresh = new Set();
|
|
57
|
+
}
|
|
58
|
+
definition(port) {
|
|
59
|
+
return { name: `${this.config.providerDefinition.name} Chat`, base_url: `http://127.0.0.1:${port}${this.path}`, env_key: this.envKey,
|
|
60
|
+
wire_api: 'responses', requires_openai_auth: false, supports_websockets: false };
|
|
61
|
+
}
|
|
62
|
+
async prepare(message) {
|
|
63
|
+
if (!message || !Object.hasOwn(message, 'id')) return message;
|
|
64
|
+
const { method, params } = message || {};
|
|
65
|
+
if (method === 'thread/start' && this.providers.has(params?.modelProvider)) {
|
|
66
|
+
if (params.ephemeral) throw new Error('Chat 模式需要保存任务历史,不支持临时任务。');
|
|
67
|
+
this.starts.add(message.id);
|
|
68
|
+
}
|
|
69
|
+
if (!params?.threadId || !this.providers.has(this.menu.threads.get(params.threadId))) return message;
|
|
70
|
+
if (method === 'turn/steer' || method === 'thread/compact/start') throw new Error('Chat 模式请等回复结束后再发送;暂不支持中途追加和手动压缩。');
|
|
71
|
+
if (method !== 'turn/start') return message;
|
|
72
|
+
if (this.contexts.has(params.threadId)) throw new Error('请等当前 Chat 回复结束后再发送。');
|
|
73
|
+
const current = userText(params.input);
|
|
74
|
+
// Native list_turns is unavailable before a fresh task's first turn. Only
|
|
75
|
+
// tasks created on this connection may skip that read; never omit old history.
|
|
76
|
+
const { thread } = await this.bridge.rpc('thread/read', { threadId: params.threadId, includeTurns: !this.fresh.has(params.threadId) });
|
|
77
|
+
if (thread.modelProvider && !this.providers.has(thread.modelProvider)) throw new Error('任务提供商已经改变,请重新打开任务。');
|
|
78
|
+
const input = [];
|
|
79
|
+
for (const turn of thread.turns || []) for (const item of turn.items || []) {
|
|
80
|
+
if (item.type === 'userMessage') input.push(textMessage('user', userText(item.content)));
|
|
81
|
+
if (item.type === 'agentMessage' && typeof item.text === 'string') input.push(textMessage('assistant', item.text));
|
|
82
|
+
}
|
|
83
|
+
input.push(textMessage('user', current));
|
|
84
|
+
if (Buffer.byteLength(JSON.stringify(input)) > limit) throw new Error('这段 Chat 历史过长,请新建任务继续。');
|
|
85
|
+
const context = { input, model: params.model || params.collaborationMode?.settings?.model || thread.model, requests: new Set() };
|
|
86
|
+
this.contexts.set(params.threadId, context);
|
|
87
|
+
this.pending.set(message.id, params.threadId);
|
|
88
|
+
return message;
|
|
89
|
+
}
|
|
90
|
+
response(message) {
|
|
91
|
+
if (!message?.method && this.starts.delete(message?.id) && message.result?.thread?.id) this.fresh.add(message.result.thread.id);
|
|
92
|
+
const id = !message?.method && this.pending.get(message?.id);
|
|
93
|
+
if (id) {
|
|
94
|
+
this.pending.delete(message.id);
|
|
95
|
+
if (message.error) this.clear(id);
|
|
96
|
+
else {
|
|
97
|
+
this.fresh.delete(id);
|
|
98
|
+
if (this.contexts.has(id)) this.contexts.get(id).turnId = message.result?.turn?.id;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (message?.method === 'turn/completed') {
|
|
102
|
+
const context = this.contexts.get(message.params?.threadId);
|
|
103
|
+
if (context && (!context.turnId || context.turnId === message.params.turn?.id)) this.clear(message.params.threadId);
|
|
104
|
+
}
|
|
105
|
+
if (message?.method === 'thread/closed') { this.clear(message.params?.threadId); this.fresh.delete(message.params?.threadId); }
|
|
106
|
+
}
|
|
107
|
+
clear(id) {
|
|
108
|
+
const context = this.contexts.get(id);
|
|
109
|
+
for (const controller of context?.requests || []) controller.abort();
|
|
110
|
+
this.contexts.delete(id);
|
|
111
|
+
}
|
|
112
|
+
async handle(req, res) {
|
|
113
|
+
const reply = (status, message) => { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify({ error: { message, type: 'chat_gateway_error' } })); };
|
|
114
|
+
if (req.headers.authorization !== `Bearer ${this.token}`) return reply(401, 'Chat 入口已失效。');
|
|
115
|
+
if (req.method !== 'POST' || req.url !== `${this.path}/responses`) return reply(400, 'Chat 仅支持文字 Responses 请求;历史过长时请新建任务。');
|
|
116
|
+
const context = this.contexts.get(req.headers['thread-id']);
|
|
117
|
+
if (!context || !this.key) return reply(400, '未找到当前 Chat 请求或提供商密钥。');
|
|
118
|
+
const controller = new AbortController();
|
|
119
|
+
const abort = () => controller.abort();
|
|
120
|
+
context.requests.add(controller); res.once('close', abort);
|
|
121
|
+
try {
|
|
122
|
+
const chunks = []; let size = 0;
|
|
123
|
+
for await (const chunk of req) {
|
|
124
|
+
size += chunk.length;
|
|
125
|
+
if (size > limit) return reply(413, 'Chat 请求过大,请新建任务。');
|
|
126
|
+
chunks.push(chunk);
|
|
127
|
+
}
|
|
128
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
129
|
+
if (body.model !== context.model) return reply(400, 'Chat 模型与当前任务不匹配,请重新选择。');
|
|
130
|
+
// Allow only generation options. Agent instructions, tools, cache/history
|
|
131
|
+
// handles and workspace metadata never cross this boundary.
|
|
132
|
+
const outgoing = { model: body.model, input: context.input, instructions, stream: true, store: false, tool_choice: 'none', parallel_tool_calls: false,
|
|
133
|
+
prompt_cache_key: `cdr:chat:${createHash('sha256').update(`${body.model}\0${instructions}`).digest('hex').slice(0, 32)}` };
|
|
134
|
+
for (const field of ['reasoning', 'text', 'service_tier']) if (body[field] != null) outgoing[field] = body[field];
|
|
135
|
+
const headers = { authorization: `Bearer ${this.key}`, 'content-type': 'application/json', accept: 'text/event-stream' };
|
|
136
|
+
// Preserve the actual native client's protocol identity. Some providers
|
|
137
|
+
// require it; do not invent a UA or forward workspace/account metadata.
|
|
138
|
+
for (const name of ['user-agent', 'originator', 'version', 'openai-beta', 'x-codex-window-id']) if (typeof req.headers[name] === 'string') headers[name] = req.headers[name];
|
|
139
|
+
for (const [name, value] of Object.entries(this.headers)) if (!['authorization', 'host', 'connection', 'content-length', 'accept-encoding'].includes(name.toLowerCase())) headers[name.toLowerCase()] = value;
|
|
140
|
+
const upstream = await fetch(`${this.config.providerDefinition.base_url.replace(/\/+$/, '')}/responses`, {
|
|
141
|
+
method: 'POST', headers,
|
|
142
|
+
body: JSON.stringify(outgoing), signal: controller.signal, redirect: 'error'
|
|
143
|
+
});
|
|
144
|
+
if (!upstream.ok || !upstream.headers.get('content-type')?.includes('text/event-stream')) {
|
|
145
|
+
await upstream.body?.cancel();
|
|
146
|
+
return reply(upstream.ok ? 502 : upstream.status, `Chat 上游请求失败(HTTP ${upstream.status})。`);
|
|
147
|
+
}
|
|
148
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
|
|
149
|
+
await pipeline(Readable.fromWeb(upstream.body), textEvents(), res, { signal: controller.signal });
|
|
150
|
+
} catch {
|
|
151
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
152
|
+
if (res.headersSent) res.destroy();
|
|
153
|
+
else reply(502, 'Chat 请求未完成,请检查提供商连接后重试。');
|
|
154
|
+
}
|
|
155
|
+
} finally { context.requests.delete(controller); res.removeListener('close', abort); controller.abort(); }
|
|
156
|
+
}
|
|
157
|
+
close() { for (const id of this.contexts.keys()) this.clear(id); this.pending.clear(); this.starts.clear(); this.fresh.clear(); }
|
|
158
|
+
}
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, rmSync, existsSync, realpathSync, accessSync, constants } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { resolve, join, dirname, isAbsolute } from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { parseEnv } from 'node:util';
|
|
6
|
+
import { parse } from 'smol-toml';
|
|
7
|
+
|
|
8
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
9
|
+
export const defaults = { version: 1, enabled: false };
|
|
10
|
+
export const codexHome = () => resolve(process.env.CODEX_HOME || join(homedir(), '.codex'));
|
|
11
|
+
export const configPath = () => resolve(process.env.CODEX_DESKTOP_ROUTER_CONFIG || join(codexHome(), 'desktop-router.json'));
|
|
12
|
+
export const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
13
|
+
export const chatProviderId = route => `cdr_chat_${route.provider}`;
|
|
14
|
+
export const findRoute = (provider, config) => config.routes.find(r => [r.provider, chatProviderId(r), r.legacyProvider, r.legacyProvider && `cdr_chat_${r.legacyProvider}`].filter(Boolean).includes(provider));
|
|
15
|
+
export const isRoutedProvider = (provider, config) => Boolean(findRoute(provider, config));
|
|
16
|
+
export const isChatProvider = (provider, config) => { const r = findRoute(provider, config); return Boolean(r && provider !== r.provider && provider !== r.legacyProvider); };
|
|
17
|
+
|
|
18
|
+
export function atomicJSON(path, value) {
|
|
19
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
20
|
+
const tmp = `${path}.${randomUUID()}.tmp`;
|
|
21
|
+
try { writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' }); renameSync(tmp, path); }
|
|
22
|
+
finally { rmSync(tmp, { force: true }); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function readConfig(path = configPath()) {
|
|
26
|
+
let raw;
|
|
27
|
+
try { raw = readFileSync(path, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return { ...defaults }; throw new Error('无法读取路由开关。'); }
|
|
28
|
+
let value;
|
|
29
|
+
try { value = JSON.parse(raw); } catch { throw new Error('路由开关文件不是有效 JSON。'); }
|
|
30
|
+
if (value?.version !== 1 || typeof value.enabled !== 'boolean') throw new Error('路由开关文件格式错误。');
|
|
31
|
+
return { version: 1, enabled: value.enabled };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function merge(base, overlay) {
|
|
35
|
+
const result = { ...base };
|
|
36
|
+
for (const [key, value] of Object.entries(overlay)) result[key] = object(value) && object(base[key]) ? merge(base[key], value) : value;
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function discoverProfiles(home = codexHome()) {
|
|
41
|
+
const read = file => {
|
|
42
|
+
try { return parse(readFileSync(join(home, file), 'utf8')); }
|
|
43
|
+
catch (e) { if (file === 'config.toml' && e.code === 'ENOENT') return {}; throw new Error(`${file} 无法解析,请在客户端修复。`); }
|
|
44
|
+
};
|
|
45
|
+
const base = read('config.toml');
|
|
46
|
+
let files;
|
|
47
|
+
try { files = readdirSync(home); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
|
|
48
|
+
const routes = files.filter(f => /^[A-Za-z0-9_-]+\.config\.toml$/.test(f)).sort().map(file => {
|
|
49
|
+
const profile = file.slice(0, -12), layer = read(file), effective = merge(base, layer);
|
|
50
|
+
const originalProvider = effective.model_provider || 'openai';
|
|
51
|
+
const providerDefinition = effective.model_providers?.[originalProvider] || (originalProvider === 'openai' ? { name: 'OpenAI', wire_api: 'responses', requires_openai_auth: true, supports_websockets: true } : null);
|
|
52
|
+
const catalogPath = effective.model_catalog_json == null ? null : resolve(home, effective.model_catalog_json);
|
|
53
|
+
return { profile, provider: `cdr_profile_${profile}`, originalProvider, providerDefinition,
|
|
54
|
+
catalogPath, layer, fingerprint: JSON.stringify({ originalProvider, providerDefinition, catalogPath }),
|
|
55
|
+
chat: Boolean(providerDefinition?.base_url && providerDefinition?.env_key && providerDefinition.requires_openai_auth !== true && (providerDefinition.wire_api || 'responses') === 'responses') };
|
|
56
|
+
});
|
|
57
|
+
for (const route of routes) {
|
|
58
|
+
// Existing tasks keep their old provider metadata until their next switch.
|
|
59
|
+
if (/^[A-Za-z0-9_-]+$/.test(route.originalProvider) && !route.originalProvider.startsWith('cdr_') && route.originalProvider !== (base.model_provider || 'openai') && routes.filter(r => r.originalProvider === route.originalProvider).length === 1) route.legacyProvider = route.originalProvider;
|
|
60
|
+
}
|
|
61
|
+
return routes;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function findApp() {
|
|
65
|
+
return [process.env.CODEX_DESKTOP_APP, '/Applications/ChatGPT.app', '/Applications/Codex.app', join(homedir(), 'Applications/ChatGPT.app'), join(homedir(), 'Applications/Codex.app')].filter(Boolean).find(p => existsSync(join(p, 'Contents/Resources/codex')));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function resolveRealCodex(selfPath) {
|
|
69
|
+
const app = findApp();
|
|
70
|
+
const candidate = process.env.CODEX_DESKTOP_ROUTER_REAL_CODEX || (app && join(app, 'Contents/Resources/codex'));
|
|
71
|
+
if (!candidate || !isAbsolute(candidate)) throw new Error('找不到内置 Codex;可用 CODEX_DESKTOP_ROUTER_REAL_CODEX 指定绝对路径。');
|
|
72
|
+
let actual;
|
|
73
|
+
try { actual = realpathSync(candidate); accessSync(actual, constants.X_OK); } catch { throw new Error('真正的 Codex 不存在或不可执行。'); }
|
|
74
|
+
if (actual === realpathSync(selfPath) || actual === realpathSync(process.execPath)) throw new Error('检测到路由递归调用。');
|
|
75
|
+
return actual;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function childEnvironment(routes = []) {
|
|
79
|
+
const env = { ...process.env, CODEX_DESKTOP_ROUTER_ACTIVE: String((Number.parseInt(process.env.CODEX_DESKTOP_ROUTER_ACTIVE, 10) || 0) + 1) };
|
|
80
|
+
let values = {};
|
|
81
|
+
try { values = parseEnv(readFileSync(join(codexHome(), '.env'), 'utf8')); }
|
|
82
|
+
catch (e) { if (e.code !== 'ENOENT') throw new Error('无法读取 CODEX_HOME/.env。'); }
|
|
83
|
+
for (const { providerDefinition: d } of routes) {
|
|
84
|
+
const names = [d?.env_key, ...Object.values(d?.env_http_headers || {})];
|
|
85
|
+
for (const key of names) if (typeof key === 'string' && !env[key] && values[key]) env[key] = values[key];
|
|
86
|
+
}
|
|
87
|
+
return env;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function providerArgs(routes, chats = new Map()) {
|
|
91
|
+
const inline = value => object(value) ? `{ ${Object.entries(value).map(([k, v]) => `${JSON.stringify(k)} = ${inline(v)}`).join(', ')} }` : Array.isArray(value) ? `[${value.map(inline).join(', ')}]` : JSON.stringify(value);
|
|
92
|
+
return routes.flatMap(route => {
|
|
93
|
+
const pairs = route.providerDefinition ? [[route.provider, route.providerDefinition]] : [];
|
|
94
|
+
if (route.legacyProvider && route.providerDefinition) pairs.push([route.legacyProvider, route.providerDefinition]);
|
|
95
|
+
const chat = chats.get(route.provider);
|
|
96
|
+
if (chat) { pairs.push([chatProviderId(route), chat]); if (route.legacyProvider) pairs.push([`cdr_chat_${route.legacyProvider}`, chat]); }
|
|
97
|
+
return pairs.flatMap(([id, definition]) => ['-c', `model_providers.${id}=${inline(definition)}`]);
|
|
98
|
+
});
|
|
99
|
+
}
|