coding-tool-x 3.2.0

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.
Files changed (185) hide show
  1. package/CHANGELOG.md +599 -0
  2. package/LICENSE +21 -0
  3. package/README.md +439 -0
  4. package/bin/ctx.js +8 -0
  5. package/dist/web/assets/Analytics-DN_YsnkW.js +39 -0
  6. package/dist/web/assets/Analytics-DuYvId7u.css +1 -0
  7. package/dist/web/assets/ConfigTemplates-Bidwfdf2.css +1 -0
  8. package/dist/web/assets/ConfigTemplates-DpXIMy0p.js +1 -0
  9. package/dist/web/assets/Home-38JTUlYt.js +1 -0
  10. package/dist/web/assets/Home-CjupSEWE.css +1 -0
  11. package/dist/web/assets/PluginManager-CX2tgq2H.js +1 -0
  12. package/dist/web/assets/PluginManager-ROyoZ-6m.css +1 -0
  13. package/dist/web/assets/ProjectList-C1lDcsn6.js +1 -0
  14. package/dist/web/assets/ProjectList-oJIyIRkP.css +1 -0
  15. package/dist/web/assets/SessionList-C55tjV7i.css +1 -0
  16. package/dist/web/assets/SessionList-CZ7T6rVx.js +1 -0
  17. package/dist/web/assets/SkillManager-D7pd-d_P.css +1 -0
  18. package/dist/web/assets/SkillManager-DLN9f79y.js +1 -0
  19. package/dist/web/assets/WorkspaceManager-CrwgQgmP.css +1 -0
  20. package/dist/web/assets/WorkspaceManager-DxlHZkpZ.js +1 -0
  21. package/dist/web/assets/icons-DRrXwWZi.js +1 -0
  22. package/dist/web/assets/index-CetESrXw.css +1 -0
  23. package/dist/web/assets/index-Cfvn-2Gb.js +2 -0
  24. package/dist/web/assets/markdown-BfC0goYb.css +10 -0
  25. package/dist/web/assets/markdown-C9MYpaSi.js +1 -0
  26. package/dist/web/assets/naive-ui-DlpKk-8M.js +1 -0
  27. package/dist/web/assets/vendors-DMjSfzlv.js +7 -0
  28. package/dist/web/assets/vue-vendor-DET08QYg.js +45 -0
  29. package/dist/web/favicon.ico +0 -0
  30. package/dist/web/index.html +20 -0
  31. package/dist/web/logo.png +0 -0
  32. package/docs/bannel.png +0 -0
  33. package/docs/home.png +0 -0
  34. package/docs/logo.png +0 -0
  35. package/docs/model-redirection.md +251 -0
  36. package/docs/multi-channel-load-balancing.md +249 -0
  37. package/package.json +80 -0
  38. package/src/commands/channels.js +551 -0
  39. package/src/commands/cli-type.js +101 -0
  40. package/src/commands/daemon.js +365 -0
  41. package/src/commands/doctor.js +333 -0
  42. package/src/commands/export-config.js +205 -0
  43. package/src/commands/list.js +222 -0
  44. package/src/commands/logs.js +261 -0
  45. package/src/commands/plugin.js +585 -0
  46. package/src/commands/port-config.js +135 -0
  47. package/src/commands/proxy-control.js +264 -0
  48. package/src/commands/proxy.js +152 -0
  49. package/src/commands/resume.js +137 -0
  50. package/src/commands/search.js +190 -0
  51. package/src/commands/security.js +37 -0
  52. package/src/commands/stats.js +398 -0
  53. package/src/commands/switch.js +48 -0
  54. package/src/commands/toggle-proxy.js +247 -0
  55. package/src/commands/ui.js +99 -0
  56. package/src/commands/update.js +97 -0
  57. package/src/commands/workspace.js +454 -0
  58. package/src/config/default.js +69 -0
  59. package/src/config/loader.js +149 -0
  60. package/src/config/model-metadata.js +167 -0
  61. package/src/config/model-metadata.json +125 -0
  62. package/src/config/model-pricing.js +35 -0
  63. package/src/config/paths.js +190 -0
  64. package/src/index.js +680 -0
  65. package/src/plugins/constants.js +15 -0
  66. package/src/plugins/event-bus.js +54 -0
  67. package/src/plugins/manifest-validator.js +129 -0
  68. package/src/plugins/plugin-api.js +128 -0
  69. package/src/plugins/plugin-installer.js +601 -0
  70. package/src/plugins/plugin-loader.js +229 -0
  71. package/src/plugins/plugin-manager.js +170 -0
  72. package/src/plugins/registry.js +152 -0
  73. package/src/plugins/schema/plugin-manifest.json +115 -0
  74. package/src/reset-config.js +94 -0
  75. package/src/server/api/agents.js +826 -0
  76. package/src/server/api/aliases.js +36 -0
  77. package/src/server/api/channels.js +368 -0
  78. package/src/server/api/claude-hooks.js +480 -0
  79. package/src/server/api/codex-channels.js +417 -0
  80. package/src/server/api/codex-projects.js +104 -0
  81. package/src/server/api/codex-proxy.js +195 -0
  82. package/src/server/api/codex-sessions.js +483 -0
  83. package/src/server/api/codex-statistics.js +57 -0
  84. package/src/server/api/commands.js +482 -0
  85. package/src/server/api/config-export.js +212 -0
  86. package/src/server/api/config-registry.js +357 -0
  87. package/src/server/api/config-sync.js +155 -0
  88. package/src/server/api/config-templates.js +248 -0
  89. package/src/server/api/config.js +521 -0
  90. package/src/server/api/convert.js +260 -0
  91. package/src/server/api/dashboard.js +142 -0
  92. package/src/server/api/env.js +144 -0
  93. package/src/server/api/favorites.js +77 -0
  94. package/src/server/api/gemini-channels.js +366 -0
  95. package/src/server/api/gemini-projects.js +91 -0
  96. package/src/server/api/gemini-proxy.js +173 -0
  97. package/src/server/api/gemini-sessions.js +376 -0
  98. package/src/server/api/gemini-statistics.js +57 -0
  99. package/src/server/api/health-check.js +31 -0
  100. package/src/server/api/mcp.js +399 -0
  101. package/src/server/api/opencode-channels.js +419 -0
  102. package/src/server/api/opencode-projects.js +99 -0
  103. package/src/server/api/opencode-proxy.js +207 -0
  104. package/src/server/api/opencode-sessions.js +327 -0
  105. package/src/server/api/opencode-statistics.js +57 -0
  106. package/src/server/api/plugins.js +463 -0
  107. package/src/server/api/pm2-autostart.js +269 -0
  108. package/src/server/api/projects.js +124 -0
  109. package/src/server/api/prompts.js +279 -0
  110. package/src/server/api/proxy.js +306 -0
  111. package/src/server/api/security.js +53 -0
  112. package/src/server/api/sessions.js +514 -0
  113. package/src/server/api/settings.js +142 -0
  114. package/src/server/api/skills.js +570 -0
  115. package/src/server/api/statistics.js +238 -0
  116. package/src/server/api/ui-config.js +64 -0
  117. package/src/server/api/workspaces.js +456 -0
  118. package/src/server/codex-proxy-server.js +681 -0
  119. package/src/server/dev-server.js +26 -0
  120. package/src/server/gemini-proxy-server.js +610 -0
  121. package/src/server/index.js +422 -0
  122. package/src/server/opencode-proxy-server.js +4771 -0
  123. package/src/server/proxy-server.js +669 -0
  124. package/src/server/services/agents-service.js +1137 -0
  125. package/src/server/services/alias.js +71 -0
  126. package/src/server/services/channel-health.js +234 -0
  127. package/src/server/services/channel-scheduler.js +240 -0
  128. package/src/server/services/channels.js +447 -0
  129. package/src/server/services/codex-channels.js +705 -0
  130. package/src/server/services/codex-config.js +90 -0
  131. package/src/server/services/codex-parser.js +322 -0
  132. package/src/server/services/codex-sessions.js +936 -0
  133. package/src/server/services/codex-settings-manager.js +619 -0
  134. package/src/server/services/codex-speed-test-template.json +24 -0
  135. package/src/server/services/codex-statistics-service.js +161 -0
  136. package/src/server/services/commands-service.js +574 -0
  137. package/src/server/services/config-export-service.js +1165 -0
  138. package/src/server/services/config-registry-service.js +828 -0
  139. package/src/server/services/config-sync-manager.js +941 -0
  140. package/src/server/services/config-sync-service.js +504 -0
  141. package/src/server/services/config-templates-service.js +913 -0
  142. package/src/server/services/enhanced-cache.js +196 -0
  143. package/src/server/services/env-checker.js +409 -0
  144. package/src/server/services/env-manager.js +436 -0
  145. package/src/server/services/favorites.js +165 -0
  146. package/src/server/services/format-converter.js +620 -0
  147. package/src/server/services/gemini-channels.js +459 -0
  148. package/src/server/services/gemini-config.js +73 -0
  149. package/src/server/services/gemini-sessions.js +689 -0
  150. package/src/server/services/gemini-settings-manager.js +263 -0
  151. package/src/server/services/gemini-statistics-service.js +157 -0
  152. package/src/server/services/health-check.js +85 -0
  153. package/src/server/services/mcp-client.js +790 -0
  154. package/src/server/services/mcp-service.js +1732 -0
  155. package/src/server/services/model-detector.js +1245 -0
  156. package/src/server/services/network-access.js +80 -0
  157. package/src/server/services/opencode-channels.js +366 -0
  158. package/src/server/services/opencode-gateway-adapters.js +1168 -0
  159. package/src/server/services/opencode-gateway-converter.js +639 -0
  160. package/src/server/services/opencode-sessions.js +931 -0
  161. package/src/server/services/opencode-settings-manager.js +478 -0
  162. package/src/server/services/opencode-statistics-service.js +161 -0
  163. package/src/server/services/plugins-service.js +1268 -0
  164. package/src/server/services/prompts-service.js +534 -0
  165. package/src/server/services/proxy-runtime.js +79 -0
  166. package/src/server/services/repo-scanner-base.js +708 -0
  167. package/src/server/services/request-logger.js +130 -0
  168. package/src/server/services/response-decoder.js +21 -0
  169. package/src/server/services/security-config.js +131 -0
  170. package/src/server/services/session-cache.js +127 -0
  171. package/src/server/services/session-converter.js +577 -0
  172. package/src/server/services/sessions.js +900 -0
  173. package/src/server/services/settings-manager.js +163 -0
  174. package/src/server/services/skill-service.js +1482 -0
  175. package/src/server/services/speed-test.js +1146 -0
  176. package/src/server/services/statistics-service.js +1043 -0
  177. package/src/server/services/ui-config.js +132 -0
  178. package/src/server/services/workspace-service.js +830 -0
  179. package/src/server/utils/pricing.js +73 -0
  180. package/src/server/websocket-server.js +513 -0
  181. package/src/ui/menu.js +139 -0
  182. package/src/ui/prompts.js +100 -0
  183. package/src/utils/format.js +43 -0
  184. package/src/utils/port-helper.js +108 -0
  185. package/src/utils/session.js +240 -0
@@ -0,0 +1,619 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const toml = require('toml');
5
+ const tomlStringify = require('@iarna/toml').stringify;
6
+
7
+ // Codex 配置文件路径
8
+ function getConfigPath() {
9
+ return path.join(os.homedir(), '.codex', 'config.toml');
10
+ }
11
+
12
+ function getAuthPath() {
13
+ return path.join(os.homedir(), '.codex', 'auth.json');
14
+ }
15
+
16
+ // 备份文件路径
17
+ function getConfigBackupPath() {
18
+ return path.join(os.homedir(), '.codex', 'config.toml.cc-tool-backup');
19
+ }
20
+
21
+ function getAuthBackupPath() {
22
+ return path.join(os.homedir(), '.codex', 'auth.json.cc-tool-backup');
23
+ }
24
+
25
+ // 检查配置文件是否存在
26
+ function configExists() {
27
+ return fs.existsSync(getConfigPath());
28
+ }
29
+
30
+ function authExists() {
31
+ return fs.existsSync(getAuthPath());
32
+ }
33
+
34
+ // 检查是否已经有备份
35
+ function hasBackup() {
36
+ return fs.existsSync(getConfigBackupPath()) || fs.existsSync(getAuthBackupPath());
37
+ }
38
+
39
+ const INVALID_ENV_NAME_PATTERN = /[\r\n]/;
40
+ const SHELL_MARKER_PREFIX = '# Added by Coding-Tool for Codex';
41
+
42
+ function normalizeEnvName(envName) {
43
+ const normalized = String(envName || '').trim();
44
+ if (!normalized || INVALID_ENV_NAME_PATTERN.test(normalized)) {
45
+ return null;
46
+ }
47
+ return normalized;
48
+ }
49
+
50
+ function ensureParentDir(filePath) {
51
+ const dirPath = path.dirname(filePath);
52
+ if (!fs.existsSync(dirPath)) {
53
+ fs.mkdirSync(dirPath, { recursive: true });
54
+ }
55
+ }
56
+
57
+ function writeFileAtomic(filePath, content) {
58
+ ensureParentDir(filePath);
59
+ const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
60
+
61
+ try {
62
+ fs.writeFileSync(tempPath, content, 'utf8');
63
+ fs.renameSync(tempPath, filePath);
64
+ } finally {
65
+ if (fs.existsSync(tempPath)) {
66
+ try {
67
+ fs.unlinkSync(tempPath);
68
+ } catch (cleanupErr) {
69
+ // ignore cleanup errors
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ function normalizeHomePath(filePath) {
76
+ const normalizedPath = String(filePath || '').replace(/\\/g, '/');
77
+ const normalizedHome = os.homedir().replace(/\\/g, '/');
78
+ if (normalizedPath.startsWith(normalizedHome)) {
79
+ return `~${normalizedPath.slice(normalizedHome.length)}`;
80
+ }
81
+ return filePath;
82
+ }
83
+
84
+ function compactBlankLines(lines) {
85
+ const compacted = [];
86
+ let previousIsBlank = false;
87
+
88
+ for (const line of lines) {
89
+ const isBlank = line.trim() === '';
90
+ if (isBlank) {
91
+ if (!previousIsBlank) {
92
+ compacted.push('');
93
+ }
94
+ previousIsBlank = true;
95
+ continue;
96
+ }
97
+
98
+ compacted.push(line);
99
+ previousIsBlank = false;
100
+ }
101
+
102
+ while (compacted.length > 0 && compacted[compacted.length - 1].trim() === '') {
103
+ compacted.pop();
104
+ }
105
+
106
+ return compacted;
107
+ }
108
+
109
+ function isPowerShellProfile(filePath) {
110
+ return String(filePath || '').toLowerCase().endsWith('.ps1');
111
+ }
112
+
113
+ function getShellConfigCandidates() {
114
+ const homeDir = os.homedir();
115
+ const shell = String(process.env.SHELL || '').toLowerCase();
116
+ const candidates = [];
117
+
118
+ if (process.platform === 'win32') {
119
+ if (shell.includes('zsh')) {
120
+ candidates.push(path.join(homeDir, '.zshrc'));
121
+ }
122
+
123
+ if (shell.includes('bash')) {
124
+ candidates.push(path.join(homeDir, '.bashrc'));
125
+ candidates.push(path.join(homeDir, '.bash_profile'));
126
+ }
127
+
128
+ candidates.push(path.join(homeDir, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1'));
129
+ candidates.push(path.join(homeDir, 'Documents', 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1'));
130
+ candidates.push(path.join(homeDir, '.bashrc'));
131
+ candidates.push(path.join(homeDir, '.profile'));
132
+ } else if (shell.includes('zsh')) {
133
+ candidates.push(path.join(homeDir, '.zshrc'));
134
+ candidates.push(path.join(homeDir, '.zprofile'));
135
+ candidates.push(path.join(homeDir, '.profile'));
136
+ } else if (shell.includes('bash')) {
137
+ if (process.platform === 'darwin') {
138
+ candidates.push(path.join(homeDir, '.bash_profile'));
139
+ candidates.push(path.join(homeDir, '.bashrc'));
140
+ } else {
141
+ candidates.push(path.join(homeDir, '.bashrc'));
142
+ candidates.push(path.join(homeDir, '.bash_profile'));
143
+ }
144
+ candidates.push(path.join(homeDir, '.profile'));
145
+ } else {
146
+ candidates.push(path.join(homeDir, '.zshrc'));
147
+ candidates.push(path.join(homeDir, '.bashrc'));
148
+ candidates.push(path.join(homeDir, '.bash_profile'));
149
+ candidates.push(path.join(homeDir, '.profile'));
150
+ }
151
+
152
+ return [...new Set(candidates)];
153
+ }
154
+
155
+ function getShellReloadCommand(configPath) {
156
+ if (!configPath) {
157
+ return process.platform === 'win32' ? '重启终端' : 'source ~/.zshrc';
158
+ }
159
+
160
+ const displayPath = normalizeHomePath(configPath);
161
+ const normalized = String(displayPath || '').replace(/\\/g, '/').toLowerCase();
162
+
163
+ if (normalized.endsWith('microsoft.powershell_profile.ps1')) {
164
+ return '. $PROFILE';
165
+ }
166
+ if (normalized.endsWith('/.zshrc')) {
167
+ return 'source ~/.zshrc';
168
+ }
169
+ if (normalized.endsWith('/.bash_profile')) {
170
+ return 'source ~/.bash_profile';
171
+ }
172
+ if (normalized.endsWith('/.bashrc')) {
173
+ return 'source ~/.bashrc';
174
+ }
175
+ if (normalized.endsWith('/.profile')) {
176
+ return 'source ~/.profile';
177
+ }
178
+
179
+ if (process.platform === 'win32') {
180
+ return '. $PROFILE';
181
+ }
182
+
183
+ return `source ${displayPath}`;
184
+ }
185
+
186
+ function escapeShellValue(value) {
187
+ return String(value ?? '')
188
+ .replace(/\\/g, '\\\\')
189
+ .replace(/"/g, '\\"')
190
+ .replace(/\$/g, '\\$')
191
+ .replace(/`/g, '\\`');
192
+ }
193
+
194
+ function escapePowerShellValue(value) {
195
+ return String(value ?? '')
196
+ .replace(/`/g, '``')
197
+ .replace(/"/g, '`"');
198
+ }
199
+
200
+ // 读取 config.toml
201
+ function readConfig() {
202
+ try {
203
+ const content = fs.readFileSync(getConfigPath(), 'utf8');
204
+ return toml.parse(content);
205
+ } catch (err) {
206
+ throw new Error('Failed to read config.toml: ' + err.message);
207
+ }
208
+ }
209
+
210
+ // 将配置对象转换为 TOML 字符串
211
+ function configToToml(config) {
212
+ let content = `# Codex Configuration
213
+ # Managed by Coding-Tool (Proxy Mode)
214
+
215
+ `;
216
+
217
+ // 写入顶级字段
218
+ for (const [key, value] of Object.entries(config)) {
219
+ if (key === 'model_providers') continue; // 稍后处理
220
+ if (typeof value === 'string') {
221
+ content += `${key} = "${value}"\n`;
222
+ } else if (typeof value === 'boolean') {
223
+ content += `${key} = ${value}\n`;
224
+ } else if (typeof value === 'number') {
225
+ content += `${key} = ${value}\n`;
226
+ }
227
+ }
228
+
229
+ content += '\n';
230
+
231
+ // 写入 model_providers
232
+ if (config.model_providers) {
233
+ for (const [providerKey, providerConfig] of Object.entries(config.model_providers)) {
234
+ content += `[model_providers.${providerKey}]\n`;
235
+ for (const [key, value] of Object.entries(providerConfig)) {
236
+ if (typeof value === 'string') {
237
+ content += `${key} = "${value}"\n`;
238
+ } else if (typeof value === 'boolean') {
239
+ content += `${key} = ${value}\n`;
240
+ } else if (typeof value === 'number') {
241
+ content += `${key} = ${value}\n`;
242
+ }
243
+ }
244
+ content += '\n';
245
+ }
246
+ }
247
+
248
+ return content;
249
+ }
250
+
251
+ // 写入 config.toml
252
+ function writeConfig(config) {
253
+ try {
254
+ const safeConfig = JSON.parse(JSON.stringify(config || {}));
255
+ const content = tomlStringify(safeConfig);
256
+ fs.writeFileSync(getConfigPath(), content, 'utf8');
257
+ } catch (err) {
258
+ throw new Error('Failed to write config.toml: ' + err.message);
259
+ }
260
+ }
261
+
262
+ // 读取 auth.json
263
+ function readAuth() {
264
+ try {
265
+ if (!authExists()) {
266
+ return {};
267
+ }
268
+ const content = fs.readFileSync(getAuthPath(), 'utf8');
269
+ return JSON.parse(content);
270
+ } catch (err) {
271
+ throw new Error('Failed to read auth.json: ' + err.message);
272
+ }
273
+ }
274
+
275
+ // 写入 auth.json
276
+ function writeAuth(auth) {
277
+ try {
278
+ const content = JSON.stringify(auth, null, 2);
279
+ fs.writeFileSync(getAuthPath(), content, 'utf8');
280
+ } catch (err) {
281
+ throw new Error('Failed to write auth.json: ' + err.message);
282
+ }
283
+ }
284
+
285
+ // 备份当前配置
286
+ function backupSettings() {
287
+ try {
288
+ if (!configExists()) {
289
+ throw new Error('config.toml not found');
290
+ }
291
+
292
+ // 如果已经有备份,不覆盖
293
+ if (hasBackup()) {
294
+ console.log('Backup already exists, skipping backup');
295
+ return { success: true, alreadyExists: true };
296
+ }
297
+
298
+ // 备份 config.toml
299
+ const configContent = fs.readFileSync(getConfigPath(), 'utf8');
300
+ fs.writeFileSync(getConfigBackupPath(), configContent, 'utf8');
301
+
302
+ // 备份 auth.json (如果存在)
303
+ if (authExists()) {
304
+ const authContent = fs.readFileSync(getAuthPath(), 'utf8');
305
+ fs.writeFileSync(getAuthBackupPath(), authContent, 'utf8');
306
+ }
307
+
308
+ console.log('Codex settings backed up');
309
+ return { success: true, alreadyExists: false };
310
+ } catch (err) {
311
+ throw new Error('Failed to backup settings: ' + err.message);
312
+ }
313
+ }
314
+
315
+ // 恢复配置
316
+ function restoreSettings() {
317
+ try {
318
+ if (!hasBackup()) {
319
+ throw new Error('No backup found');
320
+ }
321
+
322
+ // 恢复 config.toml
323
+ if (fs.existsSync(getConfigBackupPath())) {
324
+ const content = fs.readFileSync(getConfigBackupPath(), 'utf8');
325
+ fs.writeFileSync(getConfigPath(), content, 'utf8');
326
+ fs.unlinkSync(getConfigBackupPath());
327
+ }
328
+
329
+ // 恢复 auth.json
330
+ if (fs.existsSync(getAuthBackupPath())) {
331
+ const content = fs.readFileSync(getAuthBackupPath(), 'utf8');
332
+ fs.writeFileSync(getAuthPath(), content, 'utf8');
333
+ fs.unlinkSync(getAuthBackupPath());
334
+ }
335
+
336
+ // 清理 shell 配置文件中的环境变量(可选,不影响恢复结果)
337
+ removeEnvFromShell('CC_PROXY_KEY');
338
+
339
+ console.log('Codex settings restored from backup');
340
+ return { success: true };
341
+ } catch (err) {
342
+ throw new Error('Failed to restore settings: ' + err.message);
343
+ }
344
+ }
345
+
346
+ // 获取用户的 shell 配置文件路径
347
+ function getShellConfigPath() {
348
+ const candidates = getShellConfigCandidates();
349
+ const existing = candidates.find(filePath => fs.existsSync(filePath));
350
+ return existing || candidates[0];
351
+ }
352
+
353
+ // 注入环境变量到 shell 配置文件
354
+ function injectEnvToShell(envName, envValue) {
355
+ const normalizedEnvName = normalizeEnvName(envName);
356
+ if (!normalizedEnvName) {
357
+ return {
358
+ success: false,
359
+ error: `Invalid environment variable name: ${envName}`,
360
+ isFirstTime: false
361
+ };
362
+ }
363
+
364
+ const configPath = getShellConfigPath();
365
+ const marker = `${SHELL_MARKER_PREFIX} [${normalizedEnvName}]`;
366
+ const usePowerShell = isPowerShellProfile(configPath);
367
+ const exportLine = usePowerShell
368
+ ? `$env:${normalizedEnvName} = "${escapePowerShellValue(envValue)}"`
369
+ : `export ${normalizedEnvName}="${escapeShellValue(envValue)}"`;
370
+
371
+ try {
372
+ let content = '';
373
+ if (fs.existsSync(configPath)) {
374
+ content = fs.readFileSync(configPath, 'utf8');
375
+ }
376
+
377
+ const envKeyEscaped = String(normalizedEnvName).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
378
+ const envLineRegex = usePowerShell
379
+ ? new RegExp(`^\\s*\\$env:${envKeyEscaped}\\s*=`, 'i')
380
+ : new RegExp(`^\\s*(?:export\\s+)?${envKeyEscaped}=`);
381
+
382
+ const originalLines = content ? content.split(/\r?\n/) : [];
383
+ const cleanedLines = [];
384
+ let existed = false;
385
+
386
+ for (let i = 0; i < originalLines.length; i++) {
387
+ const currentLine = originalLines[i];
388
+ const trimmedLine = currentLine.trim();
389
+
390
+ if (trimmedLine === marker) {
391
+ const nextLine = originalLines[i + 1] || '';
392
+ if (envLineRegex.test(nextLine.trim())) {
393
+ i += 1;
394
+ }
395
+ existed = true;
396
+ continue;
397
+ }
398
+
399
+ if (envLineRegex.test(trimmedLine)) {
400
+ existed = true;
401
+ continue;
402
+ }
403
+
404
+ cleanedLines.push(currentLine);
405
+ }
406
+
407
+ while (cleanedLines.length > 0 && cleanedLines[cleanedLines.length - 1].trim() === '') {
408
+ cleanedLines.pop();
409
+ }
410
+
411
+ if (cleanedLines.length > 0) {
412
+ cleanedLines.push('');
413
+ }
414
+
415
+ cleanedLines.push(marker, exportLine);
416
+
417
+ const nextContent = `${cleanedLines.join('\n')}\n`;
418
+ if (nextContent !== content) {
419
+ writeFileAtomic(configPath, nextContent);
420
+ }
421
+
422
+ return { success: true, path: configPath, isFirstTime: !existed };
423
+ } catch (err) {
424
+ // 不抛出错误,只是警告,因为这不是致命问题
425
+ console.warn(`[Codex] Failed to inject env to shell config: ${err.message}`);
426
+ return { success: false, error: err.message, isFirstTime: false };
427
+ }
428
+ }
429
+
430
+ // 从 shell 配置文件移除环境变量
431
+ function removeEnvFromShell(envName) {
432
+ const normalizedEnvName = normalizeEnvName(envName);
433
+ if (!normalizedEnvName) {
434
+ return {
435
+ success: false,
436
+ error: `Invalid environment variable name: ${envName}`
437
+ };
438
+ }
439
+
440
+ const configPath = getShellConfigPath();
441
+
442
+ try {
443
+ if (!fs.existsSync(configPath)) {
444
+ return { success: true };
445
+ }
446
+
447
+ const content = fs.readFileSync(configPath, 'utf8');
448
+ const usePowerShell = isPowerShellProfile(configPath);
449
+ const marker = `${SHELL_MARKER_PREFIX} [${normalizedEnvName}]`;
450
+ const envKeyEscaped = String(normalizedEnvName).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
451
+ const envLineRegex = usePowerShell
452
+ ? new RegExp(`^\\s*\\$env:${envKeyEscaped}\\s*=`, 'i')
453
+ : new RegExp(`^\\s*(?:export\\s+)?${envKeyEscaped}=`);
454
+
455
+ const originalLines = content ? content.split(/\r?\n/) : [];
456
+ const cleanedLines = [];
457
+ let changed = false;
458
+
459
+ for (let i = 0; i < originalLines.length; i++) {
460
+ const currentLine = originalLines[i];
461
+ const trimmedLine = currentLine.trim();
462
+
463
+ if (trimmedLine === marker) {
464
+ const nextLine = originalLines[i + 1] || '';
465
+ if (envLineRegex.test(nextLine.trim())) {
466
+ i += 1;
467
+ }
468
+ changed = true;
469
+ continue;
470
+ }
471
+
472
+ if (envLineRegex.test(trimmedLine)) {
473
+ changed = true;
474
+ continue;
475
+ }
476
+
477
+ cleanedLines.push(currentLine);
478
+ }
479
+
480
+ if (!changed) {
481
+ return { success: true };
482
+ }
483
+
484
+ const normalized = compactBlankLines(cleanedLines);
485
+ const nextContent = normalized.length > 0 ? `${normalized.join('\n')}\n` : '';
486
+ writeFileAtomic(configPath, nextContent);
487
+ return { success: true };
488
+ } catch (err) {
489
+ console.warn(`[Codex] Failed to remove env from shell config: ${err.message}`);
490
+ return { success: false, error: err.message };
491
+ }
492
+ }
493
+
494
+ // 设置代理配置
495
+ function setProxyConfig(proxyPort) {
496
+ try {
497
+ // 先备份
498
+ backupSettings();
499
+
500
+ // 读取当前配置
501
+ const config = readConfig();
502
+
503
+ // 设置 model_provider 为 proxy
504
+ config.model_provider = 'cc-proxy';
505
+
506
+ // 确保 model_providers 对象存在
507
+ if (!config.model_providers) {
508
+ config.model_providers = {};
509
+ }
510
+
511
+ // 添加代理 provider
512
+ config.model_providers['cc-proxy'] = {
513
+ name: 'cc-proxy',
514
+ base_url: `http://127.0.0.1:${proxyPort}/v1`,
515
+ wire_api: 'responses',
516
+ env_key: 'CC_PROXY_KEY'
517
+ };
518
+
519
+ // 写入配置
520
+ writeConfig(config);
521
+
522
+ // 写入 auth.json
523
+ const auth = readAuth();
524
+ auth.CC_PROXY_KEY = 'PROXY_KEY';
525
+ writeAuth(auth);
526
+
527
+ // 注入环境变量到 shell 配置文件(解决某些系统环境变量优先级问题)
528
+ const shellInjectResult = injectEnvToShell('CC_PROXY_KEY', 'PROXY_KEY');
529
+
530
+ // 获取 shell 配置文件路径用于提示信息
531
+ const shellConfigPath = shellInjectResult.path || getShellConfigPath();
532
+ const sourceCommand = getShellReloadCommand(shellConfigPath);
533
+
534
+ console.log(`Codex settings updated to use proxy on port ${proxyPort}`);
535
+ return {
536
+ success: true,
537
+ port: proxyPort,
538
+ envInjected: shellInjectResult.success,
539
+ isFirstTime: shellInjectResult.isFirstTime,
540
+ shellConfigPath: shellConfigPath,
541
+ sourceCommand: sourceCommand
542
+ };
543
+ } catch (err) {
544
+ throw new Error('Failed to set proxy config: ' + err.message);
545
+ }
546
+ }
547
+
548
+ // 检查当前是否是代理配置
549
+ function isProxyConfig() {
550
+ try {
551
+ if (!configExists()) {
552
+ return false;
553
+ }
554
+
555
+ const config = readConfig();
556
+
557
+ // 检查是否使用 cc-proxy provider
558
+ if (config.model_provider === 'cc-proxy') {
559
+ return true;
560
+ }
561
+
562
+ // 检查当前 provider 的 base_url 是否指向本地代理
563
+ const currentProvider = config.model_provider;
564
+ if (currentProvider && config.model_providers && config.model_providers[currentProvider]) {
565
+ const baseUrl = config.model_providers[currentProvider].base_url || '';
566
+ if (baseUrl.includes('127.0.0.1') || baseUrl.includes('localhost')) {
567
+ return true;
568
+ }
569
+ }
570
+
571
+ return false;
572
+ } catch (err) {
573
+ return false;
574
+ }
575
+ }
576
+
577
+ // 获取当前代理端口(如果是代理配置)
578
+ function getCurrentProxyPort() {
579
+ try {
580
+ if (!isProxyConfig()) {
581
+ return null;
582
+ }
583
+
584
+ const config = readConfig();
585
+ const proxyProvider = config.model_providers?.['cc-proxy'];
586
+ if (proxyProvider) {
587
+ const baseUrl = proxyProvider.base_url || '';
588
+ const match = baseUrl.match(/:(\d+)/);
589
+ return match ? parseInt(match[1]) : null;
590
+ }
591
+
592
+ return null;
593
+ } catch (err) {
594
+ return null;
595
+ }
596
+ }
597
+
598
+ module.exports = {
599
+ getConfigPath,
600
+ getAuthPath,
601
+ getConfigBackupPath,
602
+ getAuthBackupPath,
603
+ configExists,
604
+ authExists,
605
+ hasBackup,
606
+ readConfig,
607
+ writeConfig,
608
+ readAuth,
609
+ writeAuth,
610
+ backupSettings,
611
+ restoreSettings,
612
+ setProxyConfig,
613
+ isProxyConfig,
614
+ getCurrentProxyPort,
615
+ // 导出环境变量注入函数供其他模块使用
616
+ getShellConfigPath,
617
+ injectEnvToShell,
618
+ removeEnvFromShell
619
+ };
@@ -0,0 +1,24 @@
1
+ {
2
+ "model": "gpt-5-codex",
3
+ "instructions": "You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.\n\n## General\n\n- The arguments to `shell` will be passed to execvp(). Most terminal commands should be prefixed with [\"bash\", \"-lc\"].\n- Always set the `workdir` param when using the shell function. Do not use `cd` unless absolutely necessary.\n- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)\n\n## Editing constraints\n\n- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.\n- Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like \"Assigns the value to the variable\", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.\n- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).\n- You may be in a dirty git worktree.\n * NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.\n * If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.\n * If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.\n * If the changes are in unrelated files, just ignore them and don't revert them.\n- While you are working, you might notice unexpected changes that you didn't make. If this happens, STOP IMMEDIATELY and ask the user how they would like to proceed.\n- **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested or approved by the user.\n\n## Plan tool\n\nWhen using the planning tool:\n- Skip using the planning tool for straightforward tasks (roughly the easiest 25%).\n- Do not make single-step plans.\n- When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan.\n\n## Codex CLI harness, sandboxing, and approvals\n\nThe Codex CLI harness supports several different configurations for sandboxing and escalation approvals that the user can choose from.\n\nFilesystem sandboxing defines which files can be read or written. The options for `sandbox_mode` are:\n- **read-only**: The sandbox only permits reading files.\n- **workspace-write**: The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Editing files in other directories requires approval.\n- **danger-full-access**: No filesystem sandboxing - all commands are permitted.\n\nNetwork sandboxing defines whether network can be accessed without approval. Options for `network_access` are:\n- **restricted**: Requires approval\n- **enabled**: No approval needed\n\nApprovals are your mechanism to get user consent to run shell commands without the sandbox. Possible configuration options for `approval_policy` are\n- **untrusted**: The harness will escalate most commands for user approval, apart from a limited allowlist of safe \"read\" commands.\n- **on-failure**: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.\n- **on-request**: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the `shell` command description.)\n- **never**: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is paired with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.\n\nWhen you are running with `approval_policy == on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval:\n- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /var)\n- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.\n- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)\n- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval. ALWAYS proceed to use the `with_escalated_permissions` and `justification` parameters - do not message the user before requesting approval for the command.\n- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for\n- (for all of these, you should weigh alternative paths that do not require approval)\n\nWhen `sandbox_mode` is set to read-only, you'll need to request approval for any command that isn't a read.\n\nYou will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing enabled, and approval on-failure.\n\nAlthough they introduce friction to the user because your work is paused until the user responds, you should leverage them when necessary to accomplish important work. If the completing the task requires escalated permissions, Do not let these settings or the sandbox deter you from attempting to accomplish the user's task unless it is set to \"never\", in which case never ask for approvals.\n\nWhen requesting approval to execute a command that will require escalated privileges:\n - Provide the `with_escalated_permissions` parameter with the boolean value true\n - Include a short, 1 sentence explanation for why you need to enable `with_escalated_permissions` in the justification parameter\n\n## Special user requests\n\n- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as `date`), you should do so.\n- If the user asks for a \"review\", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.\n\n## Presenting your work and final message\n\nYou are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.\n\n- Default: be very concise; friendly coding teammate tone.\n- Ask only when needed; suggest ideas; mirror the user's style.\n- For substantial work, summarize clearly; follow final‑answer formatting.\n- Skip heavy formatting for simple confirmations.\n- Don't dump large files you've written; reference paths only.\n- No \"save/copy this file\" - User is on the same machine.\n- Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.\n- For code changes:\n * Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with \"summary\", just jump right in.\n * If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.\n * When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.\n- The user does not command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result.\n\n### Final answer structure and style guidelines\n\n- Plain text; CLI handles styling. Use structure only when it helps scanability.\n- Headers: optional; short Title Case (1-3 words) wrapped in **…**; no blank line before the first bullet; add only if they truly help.\n- Bullets: use - ; merge related points; keep to one line when possible; 4–6 per list ordered by importance; keep phrasing consistent.\n- Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.\n- Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible.\n- Structure: group related bullets; order sections general → specific → supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.\n- Tone: collaborative, concise, factual; present tense, active voice; self‑contained; no \"above/below\"; parallel wording.\n- Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short—wrap/reformat if long; avoid naming formatting styles in answers.\n- Adaptation: code explanations → precise, structured with code refs; simple tasks → lead with outcome; big changes → logical walkthrough + rationale + next actions; casual one-offs → plain sentences, no headers/bullets.\n- File References: When referencing files in your response, make sure to include the relevant start line and always follow the below rules:\n * Use inline code to make file paths clickable.\n * Each reference should have a stand alone path. Even if it's the same file.\n * Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.\n * Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).\n * Do not use URIs like file://, vscode://, or https://.\n * Do not provide range of lines\n * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5\n",
4
+ "input": [
5
+ {"role": "system", "content": "You are a echo bot. Always say 'pong'."},
6
+ {
7
+ "type": "message",
8
+ "role": "user",
9
+ "content": [{
10
+ "type": "input_text",
11
+ "text": "ping"
12
+ }]
13
+ }],
14
+ "tools": [],
15
+ "tool_choice": "auto",
16
+ "parallel_tool_calls": false,
17
+ "reasoning": {
18
+ "effort": "low",
19
+ "summary": "auto"
20
+ },
21
+ "store": false,
22
+ "stream": true,
23
+ "prompt_cache_key": "019aa041-db00-7df0-af17-f34c7695d024"
24
+ }