ccjk 12.0.7 → 12.0.8

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 (299) hide show
  1. package/package.json +1 -1
  2. package/dist/chunks/agent-teams.mjs +0 -136
  3. package/dist/chunks/agent.mjs +0 -1439
  4. package/dist/chunks/agents.mjs +0 -3778
  5. package/dist/chunks/api-cli.mjs +0 -132
  6. package/dist/chunks/api-providers.mjs +0 -129
  7. package/dist/chunks/api.mjs +0 -112
  8. package/dist/chunks/auto-bootstrap.mjs +0 -358
  9. package/dist/chunks/auto-init.mjs +0 -7584
  10. package/dist/chunks/auto-updater.mjs +0 -410
  11. package/dist/chunks/banner.mjs +0 -188
  12. package/dist/chunks/bash.mjs +0 -187
  13. package/dist/chunks/boost.mjs +0 -397
  14. package/dist/chunks/ccjk-agents.mjs +0 -414
  15. package/dist/chunks/ccjk-all.mjs +0 -1028
  16. package/dist/chunks/ccjk-config.mjs +0 -261
  17. package/dist/chunks/ccjk-hooks.mjs +0 -1074
  18. package/dist/chunks/ccjk-mcp.mjs +0 -761
  19. package/dist/chunks/ccjk-setup.mjs +0 -763
  20. package/dist/chunks/ccjk-skills.mjs +0 -514
  21. package/dist/chunks/ccr.mjs +0 -98
  22. package/dist/chunks/ccu.mjs +0 -40
  23. package/dist/chunks/check-updates.mjs +0 -108
  24. package/dist/chunks/claude-code-config-manager.mjs +0 -750
  25. package/dist/chunks/claude-code-incremental-manager.mjs +0 -623
  26. package/dist/chunks/claude-config.mjs +0 -236
  27. package/dist/chunks/claude-wrapper.mjs +0 -85
  28. package/dist/chunks/cleanup-migration.mjs +0 -20
  29. package/dist/chunks/cli-hook.mjs +0 -2285
  30. package/dist/chunks/cloud-sync.mjs +0 -29
  31. package/dist/chunks/codex-config-switch.mjs +0 -451
  32. package/dist/chunks/codex-provider-manager.mjs +0 -236
  33. package/dist/chunks/codex-uninstaller.mjs +0 -404
  34. package/dist/chunks/codex.mjs +0 -2077
  35. package/dist/chunks/commands.mjs +0 -108
  36. package/dist/chunks/commands2.mjs +0 -413
  37. package/dist/chunks/commit.mjs +0 -138
  38. package/dist/chunks/completion.mjs +0 -515
  39. package/dist/chunks/config-consolidator.mjs +0 -172
  40. package/dist/chunks/config-switch.mjs +0 -317
  41. package/dist/chunks/config.mjs +0 -379
  42. package/dist/chunks/config2.mjs +0 -477
  43. package/dist/chunks/config3.mjs +0 -470
  44. package/dist/chunks/constants.mjs +0 -133
  45. package/dist/chunks/context-loader.mjs +0 -343
  46. package/dist/chunks/context.mjs +0 -372
  47. package/dist/chunks/convoy-manager.mjs +0 -880
  48. package/dist/chunks/dashboard.mjs +0 -476
  49. package/dist/chunks/doctor.mjs +0 -964
  50. package/dist/chunks/evolution.mjs +0 -382
  51. package/dist/chunks/features.mjs +0 -698
  52. package/dist/chunks/fish.mjs +0 -181
  53. package/dist/chunks/fs-operations.mjs +0 -192
  54. package/dist/chunks/health-alerts.mjs +0 -304
  55. package/dist/chunks/health-check.mjs +0 -532
  56. package/dist/chunks/help.mjs +0 -340
  57. package/dist/chunks/hook-installer.mjs +0 -45
  58. package/dist/chunks/index.mjs +0 -24
  59. package/dist/chunks/index10.mjs +0 -1171
  60. package/dist/chunks/index11.mjs +0 -1008
  61. package/dist/chunks/index12.mjs +0 -193
  62. package/dist/chunks/index13.mjs +0 -218
  63. package/dist/chunks/index14.mjs +0 -663
  64. package/dist/chunks/index2.mjs +0 -19
  65. package/dist/chunks/index3.mjs +0 -19092
  66. package/dist/chunks/index4.mjs +0 -8
  67. package/dist/chunks/index5.mjs +0 -7600
  68. package/dist/chunks/index6.mjs +0 -171
  69. package/dist/chunks/index7.mjs +0 -3583
  70. package/dist/chunks/index8.mjs +0 -19
  71. package/dist/chunks/index9.mjs +0 -616
  72. package/dist/chunks/init.mjs +0 -1606
  73. package/dist/chunks/installer.mjs +0 -690
  74. package/dist/chunks/installer2.mjs +0 -179
  75. package/dist/chunks/interview.mjs +0 -2927
  76. package/dist/chunks/json-config.mjs +0 -60
  77. package/dist/chunks/linux.mjs +0 -3863
  78. package/dist/chunks/macos.mjs +0 -69
  79. package/dist/chunks/main.mjs +0 -635
  80. package/dist/chunks/manager.mjs +0 -1048
  81. package/dist/chunks/marketplace.mjs +0 -949
  82. package/dist/chunks/mcp-cli.mjs +0 -204
  83. package/dist/chunks/mcp-performance.mjs +0 -187
  84. package/dist/chunks/mcp.mjs +0 -1231
  85. package/dist/chunks/menu.mjs +0 -652
  86. package/dist/chunks/metrics-display.mjs +0 -153
  87. package/dist/chunks/migrator.mjs +0 -178
  88. package/dist/chunks/monitor.mjs +0 -1856
  89. package/dist/chunks/notification.mjs +0 -1864
  90. package/dist/chunks/onboarding.mjs +0 -385
  91. package/dist/chunks/package.mjs +0 -3
  92. package/dist/chunks/paradigm.mjs +0 -74
  93. package/dist/chunks/permission-manager.mjs +0 -132
  94. package/dist/chunks/permissions.mjs +0 -265
  95. package/dist/chunks/persistence-manager.mjs +0 -794
  96. package/dist/chunks/persistence.mjs +0 -667
  97. package/dist/chunks/platform.mjs +0 -391
  98. package/dist/chunks/plugin.mjs +0 -1936
  99. package/dist/chunks/powershell.mjs +0 -213
  100. package/dist/chunks/prompts.mjs +0 -241
  101. package/dist/chunks/providers.mjs +0 -260
  102. package/dist/chunks/quick-actions.mjs +0 -320
  103. package/dist/chunks/quick-provider.mjs +0 -682
  104. package/dist/chunks/quick-setup.mjs +0 -412
  105. package/dist/chunks/remote.mjs +0 -497
  106. package/dist/chunks/session.mjs +0 -878
  107. package/dist/chunks/sessions.mjs +0 -106
  108. package/dist/chunks/silent-updater.mjs +0 -396
  109. package/dist/chunks/simple-config.mjs +0 -98
  110. package/dist/chunks/skill.mjs +0 -117
  111. package/dist/chunks/skill2.mjs +0 -9003
  112. package/dist/chunks/skills-sync.mjs +0 -6460
  113. package/dist/chunks/skills.mjs +0 -567
  114. package/dist/chunks/slash-commands.mjs +0 -207
  115. package/dist/chunks/smart-defaults.mjs +0 -412
  116. package/dist/chunks/smart-guide.mjs +0 -194
  117. package/dist/chunks/startup.mjs +0 -487
  118. package/dist/chunks/stats.mjs +0 -410
  119. package/dist/chunks/status.mjs +0 -289
  120. package/dist/chunks/team.mjs +0 -63
  121. package/dist/chunks/thinking.mjs +0 -626
  122. package/dist/chunks/trace.mjs +0 -57
  123. package/dist/chunks/uninstall.mjs +0 -849
  124. package/dist/chunks/update.mjs +0 -167
  125. package/dist/chunks/upgrade-manager.mjs +0 -204
  126. package/dist/chunks/version-checker.mjs +0 -881
  127. package/dist/chunks/vim.mjs +0 -903
  128. package/dist/chunks/windows.mjs +0 -14
  129. package/dist/chunks/workflows.mjs +0 -633
  130. package/dist/chunks/wsl.mjs +0 -129
  131. package/dist/chunks/zero-config.mjs +0 -374
  132. package/dist/chunks/zsh.mjs +0 -182
  133. package/dist/cli.d.mts +0 -1
  134. package/dist/cli.d.ts +0 -1
  135. package/dist/cli.mjs +0 -2199
  136. package/dist/i18n/locales/en/agent-teams.json +0 -18
  137. package/dist/i18n/locales/en/agentBrowser.json +0 -79
  138. package/dist/i18n/locales/en/agents.json +0 -135
  139. package/dist/i18n/locales/en/api.json +0 -63
  140. package/dist/i18n/locales/en/ccjk-agents.json +0 -33
  141. package/dist/i18n/locales/en/ccjk-all.json +0 -23
  142. package/dist/i18n/locales/en/ccjk-skills.json +0 -22
  143. package/dist/i18n/locales/en/ccjk.json +0 -276
  144. package/dist/i18n/locales/en/ccr.json +0 -65
  145. package/dist/i18n/locales/en/claude-md.json +0 -73
  146. package/dist/i18n/locales/en/cli.json +0 -152
  147. package/dist/i18n/locales/en/cloud-setup.json +0 -31
  148. package/dist/i18n/locales/en/cloud-sync.json +0 -147
  149. package/dist/i18n/locales/en/cloud.json +0 -40
  150. package/dist/i18n/locales/en/cloudPlugins.json +0 -118
  151. package/dist/i18n/locales/en/codex.json +0 -127
  152. package/dist/i18n/locales/en/cometix.json +0 -29
  153. package/dist/i18n/locales/en/common.json +0 -68
  154. package/dist/i18n/locales/en/config.json +0 -108
  155. package/dist/i18n/locales/en/configuration.json +0 -226
  156. package/dist/i18n/locales/en/context.json +0 -85
  157. package/dist/i18n/locales/en/dashboard.json +0 -78
  158. package/dist/i18n/locales/en/errors.json +0 -26
  159. package/dist/i18n/locales/en/evolution.json +0 -54
  160. package/dist/i18n/locales/en/hooks.json +0 -74
  161. package/dist/i18n/locales/en/hooksSync.json +0 -133
  162. package/dist/i18n/locales/en/installation.json +0 -83
  163. package/dist/i18n/locales/en/interview.json +0 -104
  164. package/dist/i18n/locales/en/language.json +0 -19
  165. package/dist/i18n/locales/en/lsp.json +0 -78
  166. package/dist/i18n/locales/en/marketplace.json +0 -116
  167. package/dist/i18n/locales/en/mcp.json +0 -178
  168. package/dist/i18n/locales/en/memory.json +0 -92
  169. package/dist/i18n/locales/en/menu.json +0 -143
  170. package/dist/i18n/locales/en/multi-config.json +0 -79
  171. package/dist/i18n/locales/en/notification.json +0 -307
  172. package/dist/i18n/locales/en/permissions.json +0 -95
  173. package/dist/i18n/locales/en/persistence.json +0 -127
  174. package/dist/i18n/locales/en/plugins.json +0 -146
  175. package/dist/i18n/locales/en/quick-actions.json +0 -78
  176. package/dist/i18n/locales/en/registry.json +0 -54
  177. package/dist/i18n/locales/en/remote.json +0 -93
  178. package/dist/i18n/locales/en/sandbox.json +0 -44
  179. package/dist/i18n/locales/en/setup.json +0 -44
  180. package/dist/i18n/locales/en/shencha.json +0 -14
  181. package/dist/i18n/locales/en/skills.json +0 -100
  182. package/dist/i18n/locales/en/skillsSync.json +0 -74
  183. package/dist/i18n/locales/en/smartGuide.json +0 -49
  184. package/dist/i18n/locales/en/stats.json +0 -20
  185. package/dist/i18n/locales/en/subagent.json +0 -69
  186. package/dist/i18n/locales/en/superpowers.json +0 -117
  187. package/dist/i18n/locales/en/team.json +0 -7
  188. package/dist/i18n/locales/en/thinking.json +0 -65
  189. package/dist/i18n/locales/en/tools.json +0 -42
  190. package/dist/i18n/locales/en/uninstall.json +0 -56
  191. package/dist/i18n/locales/en/updater.json +0 -29
  192. package/dist/i18n/locales/en/vim.json +0 -169
  193. package/dist/i18n/locales/en/workflow.json +0 -55
  194. package/dist/i18n/locales/en/workspace.json +0 -108
  195. package/dist/i18n/locales/zh-CN/agent-teams.json +0 -18
  196. package/dist/i18n/locales/zh-CN/agentBrowser.json +0 -79
  197. package/dist/i18n/locales/zh-CN/agents.json +0 -135
  198. package/dist/i18n/locales/zh-CN/api.json +0 -63
  199. package/dist/i18n/locales/zh-CN/ccjk-agents.json +0 -33
  200. package/dist/i18n/locales/zh-CN/ccjk-all.json +0 -23
  201. package/dist/i18n/locales/zh-CN/ccjk-skills.json +0 -22
  202. package/dist/i18n/locales/zh-CN/ccjk.json +0 -276
  203. package/dist/i18n/locales/zh-CN/ccr.json +0 -65
  204. package/dist/i18n/locales/zh-CN/claude-md.json +0 -73
  205. package/dist/i18n/locales/zh-CN/cli.json +0 -152
  206. package/dist/i18n/locales/zh-CN/cloud-setup.json +0 -31
  207. package/dist/i18n/locales/zh-CN/cloud-sync.json +0 -147
  208. package/dist/i18n/locales/zh-CN/cloud.json +0 -40
  209. package/dist/i18n/locales/zh-CN/cloudPlugins.json +0 -118
  210. package/dist/i18n/locales/zh-CN/codex.json +0 -127
  211. package/dist/i18n/locales/zh-CN/cometix.json +0 -29
  212. package/dist/i18n/locales/zh-CN/common.json +0 -68
  213. package/dist/i18n/locales/zh-CN/config.json +0 -108
  214. package/dist/i18n/locales/zh-CN/configuration.json +0 -224
  215. package/dist/i18n/locales/zh-CN/context.json +0 -85
  216. package/dist/i18n/locales/zh-CN/dashboard.json +0 -78
  217. package/dist/i18n/locales/zh-CN/errors.json +0 -26
  218. package/dist/i18n/locales/zh-CN/evolution.json +0 -54
  219. package/dist/i18n/locales/zh-CN/hooks.json +0 -74
  220. package/dist/i18n/locales/zh-CN/hooksSync.json +0 -133
  221. package/dist/i18n/locales/zh-CN/installation.json +0 -83
  222. package/dist/i18n/locales/zh-CN/interview.json +0 -104
  223. package/dist/i18n/locales/zh-CN/language.json +0 -19
  224. package/dist/i18n/locales/zh-CN/lsp.json +0 -78
  225. package/dist/i18n/locales/zh-CN/marketplace.json +0 -116
  226. package/dist/i18n/locales/zh-CN/mcp.json +0 -178
  227. package/dist/i18n/locales/zh-CN/memory.json +0 -92
  228. package/dist/i18n/locales/zh-CN/menu.json +0 -143
  229. package/dist/i18n/locales/zh-CN/multi-config.json +0 -79
  230. package/dist/i18n/locales/zh-CN/notification.json +0 -307
  231. package/dist/i18n/locales/zh-CN/permissions.json +0 -95
  232. package/dist/i18n/locales/zh-CN/persistence.json +0 -127
  233. package/dist/i18n/locales/zh-CN/plugins.json +0 -146
  234. package/dist/i18n/locales/zh-CN/quick-actions.json +0 -78
  235. package/dist/i18n/locales/zh-CN/registry.json +0 -54
  236. package/dist/i18n/locales/zh-CN/remote.json +0 -93
  237. package/dist/i18n/locales/zh-CN/sandbox.json +0 -44
  238. package/dist/i18n/locales/zh-CN/setup.json +0 -44
  239. package/dist/i18n/locales/zh-CN/shencha.json +0 -14
  240. package/dist/i18n/locales/zh-CN/skills.json +0 -100
  241. package/dist/i18n/locales/zh-CN/skillsSync.json +0 -74
  242. package/dist/i18n/locales/zh-CN/smartGuide.json +0 -49
  243. package/dist/i18n/locales/zh-CN/stats.json +0 -20
  244. package/dist/i18n/locales/zh-CN/subagent.json +0 -69
  245. package/dist/i18n/locales/zh-CN/superpowers.json +0 -117
  246. package/dist/i18n/locales/zh-CN/team.json +0 -7
  247. package/dist/i18n/locales/zh-CN/thinking.json +0 -65
  248. package/dist/i18n/locales/zh-CN/tools.json +0 -42
  249. package/dist/i18n/locales/zh-CN/uninstall.json +0 -56
  250. package/dist/i18n/locales/zh-CN/updater.json +0 -29
  251. package/dist/i18n/locales/zh-CN/vim.json +0 -169
  252. package/dist/i18n/locales/zh-CN/workflow.json +0 -55
  253. package/dist/i18n/locales/zh-CN/workspace.json +0 -108
  254. package/dist/index.d.mts +0 -5295
  255. package/dist/index.d.ts +0 -5295
  256. package/dist/index.mjs +0 -4941
  257. package/dist/shared/ccjk.B364Fu0N.mjs +0 -1819
  258. package/dist/shared/ccjk.BAGoDD49.mjs +0 -36
  259. package/dist/shared/ccjk.BBtCGd_g.mjs +0 -899
  260. package/dist/shared/ccjk.BFQ7yr5S.mjs +0 -16
  261. package/dist/shared/ccjk.BFxsJM0k.mjs +0 -599
  262. package/dist/shared/ccjk.BIxuVL3_.mjs +0 -25
  263. package/dist/shared/ccjk.BRZ9ww8S.mjs +0 -142
  264. package/dist/shared/ccjk.BoApaI4j.mjs +0 -28
  265. package/dist/shared/ccjk.BrPUmTqm.mjs +0 -266
  266. package/dist/shared/ccjk.BtB1e5jm.mjs +0 -171
  267. package/dist/shared/ccjk.BwfbSKN2.mjs +0 -1051
  268. package/dist/shared/ccjk.BxSmJ8B7.mjs +0 -243
  269. package/dist/shared/ccjk.Bx_rmYfN.mjs +0 -69
  270. package/dist/shared/ccjk.C2jHOZVP.mjs +0 -52
  271. package/dist/shared/ccjk.CL4Yat0G.mjs +0 -303
  272. package/dist/shared/ccjk.COweQ1RR.mjs +0 -5
  273. package/dist/shared/ccjk.CePkJq2S.mjs +0 -223
  274. package/dist/shared/ccjk.CfKKcvWy.mjs +0 -126
  275. package/dist/shared/ccjk.Cjgrln_h.mjs +0 -297
  276. package/dist/shared/ccjk.Cjj8SVrn.mjs +0 -54
  277. package/dist/shared/ccjk.CxpGa6MC.mjs +0 -2724
  278. package/dist/shared/ccjk.D5MFQT7w.mjs +0 -400
  279. package/dist/shared/ccjk.D6ycHbak.mjs +0 -270
  280. package/dist/shared/ccjk.D8ZLYSZZ.mjs +0 -299
  281. package/dist/shared/ccjk.DG_o24cZ.mjs +0 -88
  282. package/dist/shared/ccjk.DLLw-h4Y.mjs +0 -460
  283. package/dist/shared/ccjk.DOwtZMk8.mjs +0 -4019
  284. package/dist/shared/ccjk.DS7UESmF.mjs +0 -2451
  285. package/dist/shared/ccjk.DTdjs-qK.mjs +0 -1447
  286. package/dist/shared/ccjk.DXRAZcix.mjs +0 -66
  287. package/dist/shared/ccjk.DsYaCCx4.mjs +0 -317
  288. package/dist/shared/ccjk.J8YiPsOw.mjs +0 -259
  289. package/dist/shared/ccjk.KfSWcGlE.mjs +0 -38
  290. package/dist/shared/ccjk.RyizuzOI.mjs +0 -21
  291. package/dist/shared/ccjk.SPoXMvZD.mjs +0 -1242
  292. package/dist/shared/ccjk.T_cX87dY.mjs +0 -15
  293. package/dist/shared/ccjk.UIvifqNE.mjs +0 -1486
  294. package/dist/shared/ccjk._dESH4Rk.mjs +0 -111
  295. package/dist/shared/ccjk.bQ7Dh1g4.mjs +0 -249
  296. package/dist/shared/ccjk.c-ETfBZ_.mjs +0 -617
  297. package/dist/shared/ccjk.gDEDGD_t.mjs +0 -38
  298. package/dist/shared/ccjk.hoqrwWdN.mjs +0 -333
  299. package/dist/shared/ccjk.waa2ikKJ.mjs +0 -351
@@ -1,2077 +0,0 @@
1
- import process__default from 'node:process';
2
- import { fileURLToPath } from 'node:url';
3
- import a from './index2.mjs';
4
- import { d as dayjs } from '../shared/ccjk.RyizuzOI.mjs';
5
- import { i as inquirer } from './index3.mjs';
6
- import ora from './index7.mjs';
7
- import { a as semver } from '../shared/ccjk.CxpGa6MC.mjs';
8
- import { p as parse } from '../shared/ccjk.BBtCGd_g.mjs';
9
- import { x as K } from './main.mjs';
10
- import { CODEX_AUTH_FILE, SUPPORTED_LANGS, CODEX_DIR, CODEX_AGENTS_FILE, CODEX_PROMPTS_DIR, CODEX_CONFIG_FILE, AI_OUTPUT_LANGUAGES, ZCF_CONFIG_FILE } from './constants.mjs';
11
- import { ensureI18nInitialized, i18n, format } from './index5.mjs';
12
- import { updateZcfConfig, readZcfConfig, readDefaultTomlConfig, updateTomlConfig } from './ccjk-config.mjs';
13
- import { a as applyAiLanguageDirective } from './config.mjs';
14
- import { exists, readFile, ensureDir, writeFileAtomic, writeFile, copyFile, copyDir } from './fs-operations.mjs';
15
- import { readJsonConfig, writeJsonConfig } from './json-config.mjs';
16
- import { i as isWindows, m as getMcpCommand, l as getSystemRoot, w as wrapCommandWithSudo, n as normalizeTomlPath } from './platform.mjs';
17
- import { a as addNumbersToChoices } from '../shared/ccjk.BFQ7yr5S.mjs';
18
- import { resolveAiOutputLanguage } from './prompts.mjs';
19
- import { p as promptBoolean } from '../shared/ccjk.DOwtZMk8.mjs';
20
- import 'node:child_process';
21
- import { homedir } from 'node:os';
22
- import { j as join, d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';
23
-
24
- const PLAYWRIGHT_PROFILES_DIR = join(homedir(), ".ccjk", "playwright");
25
- function createPlaywrightMcpConfig(options = {}) {
26
- const {
27
- profile = "default",
28
- headless = false,
29
- browser = "chromium",
30
- userDataDir
31
- } = options;
32
- const resolvedUserDataDir = userDataDir || join(PLAYWRIGHT_PROFILES_DIR, profile);
33
- const args = ["-y", "@playwright/mcp@latest"];
34
- args.push("--browser", browser);
35
- args.push("--user-data-dir", resolvedUserDataDir);
36
- if (headless) {
37
- args.push("--headless");
38
- }
39
- return {
40
- type: "stdio",
41
- command: "npx",
42
- args,
43
- env: {}
44
- };
45
- }
46
- const MCP_SERVICE_CONFIGS = [
47
- // Documentation and Search Services - Universal (no GUI required)
48
- {
49
- id: "context7",
50
- requiresApiKey: false,
51
- config: {
52
- type: "stdio",
53
- command: "npx",
54
- args: ["-y", "@upstash/context7-mcp@latest"],
55
- env: {}
56
- }
57
- // Works on all platforms - no special requirements
58
- },
59
- {
60
- id: "open-websearch",
61
- requiresApiKey: false,
62
- config: {
63
- type: "stdio",
64
- command: "npx",
65
- args: ["-y", "open-websearch@latest"],
66
- env: {
67
- MODE: "stdio",
68
- DEFAULT_SEARCH_ENGINE: "duckduckgo",
69
- ALLOWED_SEARCH_ENGINES: "duckduckgo,bing,brave"
70
- }
71
- }
72
- // Works on all platforms - no special requirements
73
- },
74
- {
75
- id: "mcp-deepwiki",
76
- requiresApiKey: false,
77
- config: {
78
- type: "stdio",
79
- command: "npx",
80
- args: ["-y", "mcp-deepwiki@latest"],
81
- env: {}
82
- }
83
- // Works on all platforms - no special requirements
84
- },
85
- // Development Workflow Services
86
- {
87
- id: "spec-workflow",
88
- requiresApiKey: false,
89
- config: {
90
- type: "stdio",
91
- command: "npx",
92
- args: ["-y", "@pimzino/spec-workflow-mcp@latest"],
93
- env: {}
94
- }
95
- // Works on all platforms - no special requirements
96
- },
97
- {
98
- id: "serena",
99
- requiresApiKey: false,
100
- config: {
101
- type: "stdio",
102
- command: "uvx",
103
- args: ["--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server", "--context", "ide-assistant", "--enable-web-dashboard", "false"],
104
- env: {}
105
- },
106
- platformRequirements: {
107
- requiredCommands: ["uvx"]
108
- // Requires uv/uvx to be installed
109
- }
110
- },
111
- // Browser and Automation Services - Require GUI environment
112
- {
113
- id: "Playwright",
114
- requiresApiKey: false,
115
- config: createPlaywrightMcpConfig(),
116
- // Uses default profile with chromium browser
117
- platformRequirements: {
118
- platforms: ["macos", "windows"],
119
- // GUI required - exclude headless Linux/WSL/Termux
120
- requiresGui: true
121
- }
122
- },
123
- // Cross-session Memory Services
124
- {
125
- id: "intent-engine",
126
- requiresApiKey: false,
127
- defaultSelected: true,
128
- config: {
129
- type: "stdio",
130
- command: "npx",
131
- args: ["-y", "@origintask/intent-engine@latest", "mcp"],
132
- env: {}
133
- }
134
- // Works on all platforms - no special requirements
135
- },
136
- // Anthropic Official MCP Services - Universal
137
- // Note: Removed low-value services: filesystem (buggy), puppeteer (duplicate of Playwright),
138
- // memory (Claude has built-in memory), fetch (Claude has WebFetch), sequential-thinking (limited value)
139
- {
140
- id: "sqlite",
141
- requiresApiKey: false,
142
- config: {
143
- type: "stdio",
144
- command: "npx",
145
- args: ["-y", "@anthropic-ai/mcp-server-sqlite@latest"],
146
- env: {}
147
- }
148
- // Works on all platforms - no special requirements
149
- }
150
- ];
151
- async function getMcpServices() {
152
- ensureI18nInitialized();
153
- const mcpServiceList = [
154
- // Documentation and Search Services
155
- {
156
- id: "context7",
157
- name: i18n.t("mcp:services.context7.name"),
158
- description: i18n.t("mcp:services.context7.description")
159
- },
160
- {
161
- id: "open-websearch",
162
- name: i18n.t("mcp:services.open-websearch.name"),
163
- description: i18n.t("mcp:services.open-websearch.description")
164
- },
165
- {
166
- id: "mcp-deepwiki",
167
- name: i18n.t("mcp:services.mcp-deepwiki.name"),
168
- description: i18n.t("mcp:services.mcp-deepwiki.description")
169
- },
170
- // Development Workflow Services
171
- {
172
- id: "spec-workflow",
173
- name: i18n.t("mcp:services.spec-workflow.name"),
174
- description: i18n.t("mcp:services.spec-workflow.description")
175
- },
176
- {
177
- id: "serena",
178
- name: i18n.t("mcp:services.serena.name"),
179
- description: i18n.t("mcp:services.serena.description")
180
- },
181
- // Browser and Automation Services
182
- {
183
- id: "Playwright",
184
- name: i18n.t("mcp:services.playwright.name"),
185
- description: i18n.t("mcp:services.playwright.description")
186
- },
187
- // Cross-session Memory Services
188
- {
189
- id: "intent-engine",
190
- name: i18n.t("mcp:services.intent-engine.name"),
191
- description: i18n.t("mcp:services.intent-engine.description")
192
- },
193
- // Anthropic Official MCP Services
194
- // Note: Removed low-value services: filesystem (buggy), puppeteer (duplicate),
195
- // memory (Claude built-in), fetch (Claude WebFetch), sequential-thinking (limited value)
196
- {
197
- id: "sqlite",
198
- name: i18n.t("mcp:services.sqlite.name"),
199
- description: i18n.t("mcp:services.sqlite.description")
200
- }
201
- ];
202
- return MCP_SERVICE_CONFIGS.map((config) => {
203
- const serviceInfo = mcpServiceList.find((s) => s.id === config.id);
204
- const service = {
205
- id: config.id,
206
- name: serviceInfo?.name || config.id,
207
- description: serviceInfo?.description || "",
208
- requiresApiKey: config.requiresApiKey,
209
- config: config.config
210
- };
211
- if (config.apiKeyEnvVar) {
212
- service.apiKeyEnvVar = config.apiKeyEnvVar;
213
- }
214
- return service;
215
- });
216
- }
217
- async function getMcpService(id) {
218
- const services = await getMcpServices();
219
- return services.find((service) => service.id === id);
220
- }
221
- const DEFAULT_MCP_TOOL_SEARCH_CONFIG = {
222
- mcpAutoEnableThreshold: 10,
223
- excludedServices: ["mcp-search", "context7", "sqlite"]
224
- };
225
- function getMcpToolSearchConfig() {
226
- const env = process__default.env;
227
- return {
228
- mcpAutoEnableThreshold: env.MCP_AUTO_THRESHOLD || DEFAULT_MCP_TOOL_SEARCH_CONFIG.mcpAutoEnableThreshold,
229
- dynamicServiceDiscovery: env.MCP_DYNAMIC_DISCOVERY !== "false",
230
- listChangedNotifications: env.MCP_LIST_CHANGED !== "false",
231
- excludedServices: env.MCP_EXCLUDED_SERVICES?.split(",").map((s) => s.trim()).filter(Boolean) || DEFAULT_MCP_TOOL_SEARCH_CONFIG.excludedServices
232
- };
233
- }
234
- class DynamicMcpServiceRegistry {
235
- _services = /* @__PURE__ */ new Map();
236
- _listeners = /* @__PURE__ */ new Set();
237
- _enabled = false;
238
- /**
239
- * Enable dynamic service discovery
240
- */
241
- enable() {
242
- this._enabled = true;
243
- }
244
- /**
245
- * Disable dynamic service discovery
246
- */
247
- disable() {
248
- this._enabled = false;
249
- }
250
- /**
251
- * Check if dynamic discovery is enabled
252
- */
253
- isEnabled() {
254
- return this._enabled;
255
- }
256
- /**
257
- * Add a service dynamically
258
- */
259
- addService(serviceId, config) {
260
- if (!this._enabled) {
261
- return false;
262
- }
263
- const isUpdate = this._services.has(serviceId);
264
- this._services.set(serviceId, config);
265
- this._notify({
266
- type: isUpdate ? "updated" : "added",
267
- serviceId,
268
- timestamp: Date.now(),
269
- config
270
- });
271
- return true;
272
- }
273
- /**
274
- * Remove a service dynamically
275
- */
276
- removeService(serviceId) {
277
- if (!this._enabled || !this._services.has(serviceId)) {
278
- return false;
279
- }
280
- const config = this._services.get(serviceId);
281
- this._services.delete(serviceId);
282
- this._notify({
283
- type: "removed",
284
- serviceId,
285
- timestamp: Date.now(),
286
- config
287
- });
288
- return true;
289
- }
290
- /**
291
- * Get a service configuration
292
- */
293
- getService(serviceId) {
294
- return this._services.get(serviceId);
295
- }
296
- /**
297
- * List all dynamically registered services
298
- */
299
- listServices() {
300
- return new Map(this._services);
301
- }
302
- /**
303
- * Subscribe to list change notifications
304
- */
305
- subscribe(listener) {
306
- this._listeners.add(listener);
307
- return () => this._listeners.delete(listener);
308
- }
309
- /**
310
- * Notify all listeners of a change
311
- */
312
- _notify(notification) {
313
- const toolSearchConfig = getMcpToolSearchConfig();
314
- if (toolSearchConfig.listChangedNotifications) {
315
- for (const listener of Array.from(this._listeners)) {
316
- try {
317
- listener(notification);
318
- } catch (error) {
319
- console.error("Error notifying MCP list change listener:", error);
320
- }
321
- }
322
- }
323
- }
324
- }
325
- const dynamicMcpRegistry = new DynamicMcpServiceRegistry();
326
-
327
- async function selectMcpServices() {
328
- ensureI18nInitialized();
329
- const mcpServices = await getMcpServices();
330
- const defaultSelectedIds = new Set(
331
- MCP_SERVICE_CONFIGS.filter((c) => c.defaultSelected).map((c) => c.id)
332
- );
333
- const choices = mcpServices.map((service) => ({
334
- name: `${service.name} - ${a.gray(service.description)}`,
335
- value: service.id,
336
- checked: defaultSelectedIds.has(service.id)
337
- }));
338
- const { services } = await inquirer.prompt({
339
- type: "checkbox",
340
- name: "services",
341
- message: `${i18n.t("mcp:selectMcpServices")}${i18n.t("common:multiSelectHint")}`,
342
- choices
343
- });
344
- if (services === void 0) {
345
- console.log(a.yellow(i18n.t("common:cancelled")));
346
- return void 0;
347
- }
348
- return services;
349
- }
350
-
351
- function detectConfigManagementMode() {
352
- try {
353
- const config = readCodexConfig();
354
- if (!config || !config.providers || config.providers.length === 0) {
355
- return {
356
- mode: "initial",
357
- hasProviders: false,
358
- providerCount: 0
359
- };
360
- }
361
- return {
362
- mode: "management",
363
- hasProviders: true,
364
- providerCount: config.providers.length,
365
- currentProvider: config.modelProvider,
366
- providers: config.providers,
367
- isUnmanaged: config.managed === false ? true : void 0
368
- };
369
- } catch (error) {
370
- return {
371
- mode: "initial",
372
- hasProviders: false,
373
- providerCount: 0,
374
- error: error instanceof Error ? error.message : "Unknown error"
375
- };
376
- }
377
- }
378
-
379
- function applyCodexPlatformCommand(config) {
380
- if (isWindows() && config.command) {
381
- const mcpCmd = getMcpCommand(config.command);
382
- if (mcpCmd[0] === "cmd") {
383
- config.command = mcpCmd[0];
384
- config.args = [...mcpCmd.slice(1), ...config.args || []];
385
- }
386
- }
387
- }
388
-
389
- async function configureCodexMcp(options) {
390
- ensureI18nInitialized();
391
- const { skipPrompt = false } = options ?? {};
392
- const existingConfig = readCodexConfig();
393
- const backupPath = backupCodexComplete();
394
- if (backupPath)
395
- console.log(a.gray(getBackupMessage(backupPath)));
396
- if (skipPrompt) {
397
- const { runCodexWorkflowSelection } = await Promise.resolve().then(function () { return codex; });
398
- await runCodexWorkflowSelection({ skipPrompt: true, workflows: options?.workflows ?? [] });
399
- if (options?.mcpServices === false) {
400
- updateZcfConfig({ codeToolType: "codex" });
401
- console.log(a.green(i18n.t("codex:mcpConfigured")));
402
- return;
403
- }
404
- const defaultServiceIds = Array.isArray(options?.mcpServices) ? options.mcpServices : MCP_SERVICE_CONFIGS.filter((service) => !service.requiresApiKey).map((service) => service.id);
405
- const baseProviders2 = existingConfig?.providers || [];
406
- const existingServices2 = existingConfig?.mcpServices || [];
407
- const selection2 = [];
408
- for (const id of defaultServiceIds) {
409
- const configInfo = MCP_SERVICE_CONFIGS.find((service) => service.id === id);
410
- if (!configInfo)
411
- continue;
412
- let command = configInfo.config.command || id;
413
- let args = (configInfo.config.args || []).map((arg) => String(arg));
414
- if (id === "serena") {
415
- const idx = args.indexOf("--context");
416
- if (idx >= 0 && idx + 1 < args.length)
417
- args[idx + 1] = "codex";
418
- else
419
- args.push("--context", "codex");
420
- }
421
- const serviceConfig = { id: id.toLowerCase(), command, args };
422
- applyCodexPlatformCommand(serviceConfig);
423
- command = serviceConfig.command;
424
- args = serviceConfig.args || [];
425
- const env = { ...configInfo.config.env || {} };
426
- if (isWindows()) {
427
- const systemRoot = getSystemRoot();
428
- if (systemRoot)
429
- env.SYSTEMROOT = systemRoot;
430
- }
431
- selection2.push({
432
- id: id.toLowerCase(),
433
- command,
434
- args,
435
- env: Object.keys(env).length > 0 ? env : void 0,
436
- startup_timeout_sec: 30
437
- });
438
- }
439
- const mergedMap2 = /* @__PURE__ */ new Map();
440
- for (const svc of existingServices2)
441
- mergedMap2.set(svc.id.toLowerCase(), { ...svc });
442
- for (const svc of selection2)
443
- mergedMap2.set(svc.id.toLowerCase(), { ...svc });
444
- const finalServices2 = Array.from(mergedMap2.values()).map((svc) => {
445
- if (isWindows()) {
446
- const systemRoot = getSystemRoot();
447
- if (systemRoot) {
448
- return {
449
- ...svc,
450
- env: {
451
- ...svc.env || {},
452
- SYSTEMROOT: systemRoot
453
- }
454
- };
455
- }
456
- }
457
- return svc;
458
- });
459
- writeCodexConfig({
460
- model: existingConfig?.model || null,
461
- modelProvider: existingConfig?.modelProvider || null,
462
- providers: baseProviders2,
463
- mcpServices: finalServices2,
464
- otherConfig: existingConfig?.otherConfig || []
465
- });
466
- updateZcfConfig({ codeToolType: "codex" });
467
- console.log(a.green(i18n.t("codex:mcpConfigured")));
468
- return;
469
- }
470
- const selectedIds = await selectMcpServices();
471
- if (!selectedIds)
472
- return;
473
- const servicesMeta = await getMcpServices();
474
- const baseProviders = existingConfig?.providers || [];
475
- const selection = [];
476
- const existingServices = existingConfig?.mcpServices || [];
477
- if (selectedIds.length === 0) {
478
- console.log(a.yellow(i18n.t("codex:noMcpConfigured")));
479
- const preserved = (existingServices || []).map((svc) => {
480
- if (isWindows()) {
481
- const systemRoot = getSystemRoot();
482
- if (systemRoot) {
483
- return {
484
- ...svc,
485
- env: {
486
- ...svc.env || {},
487
- SYSTEMROOT: systemRoot
488
- }
489
- };
490
- }
491
- }
492
- return svc;
493
- });
494
- writeCodexConfig({
495
- model: existingConfig?.model || null,
496
- modelProvider: existingConfig?.modelProvider || null,
497
- providers: baseProviders,
498
- mcpServices: preserved,
499
- otherConfig: existingConfig?.otherConfig || []
500
- });
501
- updateZcfConfig({ codeToolType: "codex" });
502
- return;
503
- }
504
- for (const id of selectedIds) {
505
- const configInfo = MCP_SERVICE_CONFIGS.find((service) => service.id === id);
506
- if (!configInfo)
507
- continue;
508
- const serviceMeta = servicesMeta.find((service) => service.id === id);
509
- let command = configInfo.config.command || id;
510
- let args = (configInfo.config.args || []).map((arg) => String(arg));
511
- if (id === "serena") {
512
- const idx = args.indexOf("--context");
513
- if (idx >= 0 && idx + 1 < args.length) {
514
- args[idx + 1] = "codex";
515
- } else {
516
- args.push("--context", "codex");
517
- }
518
- }
519
- const serviceConfig = { id: id.toLowerCase(), command, args };
520
- applyCodexPlatformCommand(serviceConfig);
521
- command = serviceConfig.command;
522
- args = serviceConfig.args || [];
523
- const env = { ...configInfo.config.env || {} };
524
- if (isWindows()) {
525
- const systemRoot = getSystemRoot();
526
- if (systemRoot)
527
- env.SYSTEMROOT = systemRoot;
528
- }
529
- if (configInfo.requiresApiKey && configInfo.apiKeyEnvVar) {
530
- const promptMessage = serviceMeta?.apiKeyPrompt || i18n.t("mcp:apiKeyPrompt");
531
- const { apiKey } = await inquirer.prompt([{
532
- type: "input",
533
- name: "apiKey",
534
- message: promptMessage,
535
- validate: (input) => !!input || i18n.t("api:keyRequired")
536
- }]);
537
- if (!apiKey)
538
- continue;
539
- env[configInfo.apiKeyEnvVar] = apiKey;
540
- }
541
- selection.push({
542
- id: id.toLowerCase(),
543
- command: serviceConfig.command,
544
- args: serviceConfig.args,
545
- env: Object.keys(env).length > 0 ? env : void 0,
546
- startup_timeout_sec: 30
547
- });
548
- }
549
- const mergedMap = /* @__PURE__ */ new Map();
550
- for (const svc of existingServices)
551
- mergedMap.set(svc.id.toLowerCase(), { ...svc });
552
- for (const svc of selection)
553
- mergedMap.set(svc.id.toLowerCase(), { ...svc });
554
- const finalServices = Array.from(mergedMap.values()).map((svc) => {
555
- if (isWindows()) {
556
- const systemRoot = getSystemRoot();
557
- if (systemRoot) {
558
- return {
559
- ...svc,
560
- env: {
561
- ...svc.env || {},
562
- SYSTEMROOT: systemRoot
563
- }
564
- };
565
- }
566
- }
567
- return svc;
568
- });
569
- writeCodexConfig({
570
- model: existingConfig?.model || null,
571
- modelProvider: existingConfig?.modelProvider || null,
572
- providers: baseProviders,
573
- mcpServices: finalServices,
574
- otherConfig: existingConfig?.otherConfig || []
575
- });
576
- updateZcfConfig({ codeToolType: "codex" });
577
- console.log(a.green(i18n.t("codex:mcpConfigured")));
578
- }
579
-
580
- let cachedSkipPromptBackup = null;
581
- function getRootDir() {
582
- const currentFilePath = fileURLToPath(import.meta.url);
583
- let dir = dirname(currentFilePath);
584
- while (dir !== dirname(dir)) {
585
- if (exists(join(dir, "templates"))) {
586
- return dir;
587
- }
588
- dir = dirname(dir);
589
- }
590
- return dirname(currentFilePath);
591
- }
592
- async function detectCodexInstallMethod() {
593
- try {
594
- const brewResult = await K("brew", ["list", "--cask", "codex"], { throwOnError: false });
595
- if (brewResult.exitCode === 0) {
596
- return "homebrew";
597
- }
598
- } catch {
599
- }
600
- try {
601
- const npmResult = await K("npm", ["list", "-g", "@openai/codex"], { throwOnError: false });
602
- if (npmResult.exitCode === 0 && npmResult.stdout.includes("@openai/codex")) {
603
- return "npm";
604
- }
605
- } catch {
606
- }
607
- return "unknown";
608
- }
609
- async function executeCodexInstallation(isUpdate, skipMethodSelection = false) {
610
- if (isUpdate) {
611
- console.log(a.green(i18n.t("codex:updatingCli")));
612
- const installMethod = await detectCodexInstallMethod();
613
- if (installMethod === "homebrew") {
614
- console.log(a.gray(i18n.t("codex:detectedHomebrew")));
615
- const result = await K("brew", ["upgrade", "--cask", "codex"]);
616
- if (result.exitCode !== 0) {
617
- throw new Error(`Failed to update codex via Homebrew: exit code ${result.exitCode}`);
618
- }
619
- } else if (installMethod === "npm") {
620
- console.log(a.gray(i18n.t("codex:detectedNpm")));
621
- const { command, args, usedSudo } = wrapCommandWithSudo("npm", ["install", "-g", "@openai/codex@latest"]);
622
- if (usedSudo)
623
- console.log(a.yellow(i18n.t("codex:usingSudo")));
624
- const result = await K(command, args);
625
- if (result.exitCode !== 0) {
626
- throw new Error(`Failed to update codex CLI: exit code ${result.exitCode}`);
627
- }
628
- } else {
629
- console.log(a.yellow(i18n.t("codex:unknownInstallMethod")));
630
- console.log(a.gray(i18n.t("codex:fallingBackToNpm")));
631
- const { command, args, usedSudo } = wrapCommandWithSudo("npm", ["install", "-g", "@openai/codex@latest"]);
632
- if (usedSudo)
633
- console.log(a.yellow(i18n.t("codex:usingSudo")));
634
- const result = await K(command, args);
635
- if (result.exitCode !== 0) {
636
- throw new Error(`Failed to update codex CLI: exit code ${result.exitCode}`);
637
- }
638
- }
639
- console.log(a.green(i18n.t("codex:updateSuccess")));
640
- } else {
641
- const { installCodex } = await import('./installer.mjs');
642
- await installCodex(skipMethodSelection);
643
- }
644
- }
645
- function getUninstallOptions() {
646
- return [
647
- { name: i18n.t("codex:uninstallItemConfig"), value: "config" },
648
- { name: i18n.t("codex:uninstallItemAuth"), value: "auth" },
649
- { name: i18n.t("codex:uninstallItemApiConfig"), value: "api-config" },
650
- { name: i18n.t("codex:uninstallItemMcpConfig"), value: "mcp-config" },
651
- { name: i18n.t("codex:uninstallItemSystemPrompt"), value: "system-prompt" },
652
- { name: i18n.t("codex:uninstallItemWorkflow"), value: "workflow" },
653
- { name: i18n.t("codex:uninstallItemCliPackage"), value: "cli-package" },
654
- { name: i18n.t("codex:uninstallItemBackups"), value: "backups" }
655
- ];
656
- }
657
- function handleUninstallCancellation() {
658
- console.log(a.yellow(i18n.t("codex:uninstallCancelled")));
659
- }
660
- function createBackupDirectory(timestamp) {
661
- const backupBaseDir = join(CODEX_DIR, "backup");
662
- const backupDir = join(backupBaseDir, `backup_${timestamp}`);
663
- ensureDir(backupDir);
664
- return backupDir;
665
- }
666
- function backupCodexFiles() {
667
- if (!exists(CODEX_DIR))
668
- return null;
669
- if (process__default.env.CCJK_CODEX_SKIP_PROMPT_SINGLE_BACKUP === "true" && cachedSkipPromptBackup)
670
- return cachedSkipPromptBackup;
671
- const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
672
- const backupDir = createBackupDirectory(timestamp);
673
- const filter = (path) => {
674
- return !path.includes("/backup");
675
- };
676
- copyDir(CODEX_DIR, backupDir, { filter });
677
- if (process__default.env.CCJK_CODEX_SKIP_PROMPT_SINGLE_BACKUP === "true")
678
- cachedSkipPromptBackup = backupDir;
679
- return backupDir;
680
- }
681
- function backupCodexComplete() {
682
- return backupCodexFiles();
683
- }
684
- function backupCodexConfig() {
685
- if (!exists(CODEX_CONFIG_FILE))
686
- return null;
687
- try {
688
- const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
689
- const backupDir = createBackupDirectory(timestamp);
690
- const backupPath = join(backupDir, "config.toml");
691
- copyFile(CODEX_CONFIG_FILE, backupPath);
692
- return backupPath;
693
- } catch {
694
- return null;
695
- }
696
- }
697
- function backupCodexAgents() {
698
- if (process__default.env.CCJK_CODEX_SKIP_PROMPT_SINGLE_BACKUP === "true" && cachedSkipPromptBackup)
699
- return cachedSkipPromptBackup;
700
- if (!exists(CODEX_AGENTS_FILE))
701
- return null;
702
- try {
703
- const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
704
- const backupDir = createBackupDirectory(timestamp);
705
- const backupPath = join(backupDir, "AGENTS.md");
706
- copyFile(CODEX_AGENTS_FILE, backupPath);
707
- return backupPath;
708
- } catch {
709
- return null;
710
- }
711
- }
712
- function backupCodexPrompts() {
713
- if (process__default.env.CCJK_CODEX_SKIP_PROMPT_SINGLE_BACKUP === "true" && cachedSkipPromptBackup)
714
- return cachedSkipPromptBackup;
715
- if (!exists(CODEX_PROMPTS_DIR))
716
- return null;
717
- try {
718
- const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
719
- const backupDir = createBackupDirectory(timestamp);
720
- const backupPath = join(backupDir, "prompts");
721
- copyDir(CODEX_PROMPTS_DIR, backupPath);
722
- return backupPath;
723
- } catch {
724
- return null;
725
- }
726
- }
727
- function getBackupMessage(path) {
728
- if (!path)
729
- return "";
730
- if (!i18n.isInitialized) {
731
- return `Backup created: ${path}`;
732
- }
733
- return i18n.t("codex:backupSuccess", { path });
734
- }
735
- function needsEnvKeyMigration() {
736
- if (!exists(CODEX_CONFIG_FILE))
737
- return false;
738
- try {
739
- const content = readFile(CODEX_CONFIG_FILE);
740
- const hasOldEnvKey = /^\s*env_key\s*=/m.test(content);
741
- return hasOldEnvKey;
742
- } catch {
743
- return false;
744
- }
745
- }
746
- function migrateEnvKeyToTempEnvKey() {
747
- if (!exists(CODEX_CONFIG_FILE))
748
- return false;
749
- try {
750
- const content = readFile(CODEX_CONFIG_FILE);
751
- if (!needsEnvKeyMigration())
752
- return false;
753
- const backupPath = backupCodexConfig();
754
- if (backupPath) {
755
- console.log(a.gray(getBackupMessage(backupPath)));
756
- }
757
- const migratedContent = migrateEnvKeyInContent(content);
758
- writeFileAtomic(CODEX_CONFIG_FILE, migratedContent);
759
- updateTomlConfig(ZCF_CONFIG_FILE, {
760
- codex: {
761
- envKeyMigrated: true
762
- }
763
- });
764
- const message = i18n.isInitialized ? i18n.t("codex:envKeyMigrationComplete") : "\u2714 env_key to temp_env_key migration completed";
765
- console.log(a.green(message));
766
- return true;
767
- } catch (error) {
768
- console.error(a.yellow(`env_key migration warning: ${error.message}`));
769
- return false;
770
- }
771
- }
772
- function migrateEnvKeyInContent(content) {
773
- const lines = content.split("\n");
774
- const result = [];
775
- let currentSectionHasTempEnvKey = false;
776
- let currentSection = "";
777
- const sectionHasTempEnvKey = /* @__PURE__ */ new Map();
778
- let tempSection = "";
779
- for (const line of lines) {
780
- const sectionMatch = line.match(/^\s*\[([^\]]+)\]/);
781
- if (sectionMatch) {
782
- tempSection = sectionMatch[1];
783
- }
784
- if (tempSection && /^\s*temp_env_key\s*=/.test(line)) {
785
- sectionHasTempEnvKey.set(tempSection, true);
786
- }
787
- }
788
- for (const line of lines) {
789
- const sectionMatch = line.match(/^\s*\[([^\]]+)\]/);
790
- if (sectionMatch) {
791
- currentSection = sectionMatch[1];
792
- currentSectionHasTempEnvKey = sectionHasTempEnvKey.get(currentSection) || false;
793
- }
794
- const envKeyMatch = line.match(/^(\s*)env_key(\s*=.*)$/);
795
- if (envKeyMatch) {
796
- if (currentSectionHasTempEnvKey) {
797
- continue;
798
- } else {
799
- result.push(`${envKeyMatch[1]}temp_env_key${envKeyMatch[2]}`);
800
- continue;
801
- }
802
- }
803
- result.push(line);
804
- }
805
- return result.join("\n");
806
- }
807
- function ensureEnvKeyMigration() {
808
- const tomlConfig = readDefaultTomlConfig();
809
- if (tomlConfig?.codex?.envKeyMigrated)
810
- return;
811
- if (needsEnvKeyMigration()) {
812
- migrateEnvKeyToTempEnvKey();
813
- }
814
- }
815
- function sanitizeProviderName(input) {
816
- const cleaned = input.trim();
817
- if (!cleaned)
818
- return "";
819
- return cleaned.toLowerCase().replace(/\./g, "-").replace(/\s+/g, "-").replace(/[^a-z0-9\-]/g, "");
820
- }
821
- function parseCodexConfig(content) {
822
- if (!content.trim()) {
823
- return {
824
- model: null,
825
- modelProvider: null,
826
- providers: [],
827
- mcpServices: [],
828
- managed: false,
829
- otherConfig: [],
830
- modelProviderCommented: void 0
831
- };
832
- }
833
- try {
834
- const normalizedContent = content.replace(/(SYSTEMROOT\s*=\s*")[^"\n]+("?)/g, (match) => {
835
- return match.replace(/\\\\/g, "/").replace(/\\/g, "/").replace('C:/Windows"?', 'C:/Windows"');
836
- });
837
- const tomlData = parse(normalizedContent);
838
- const providers = [];
839
- if (tomlData.model_providers) {
840
- for (const [id, providerData] of Object.entries(tomlData.model_providers)) {
841
- const provider = providerData;
842
- providers.push({
843
- id,
844
- name: provider.name || id,
845
- baseUrl: provider.base_url || "",
846
- wireApi: provider.wire_api || "responses",
847
- tempEnvKey: provider.temp_env_key || "OPENAI_API_KEY",
848
- requiresOpenaiAuth: provider.requires_openai_auth !== false,
849
- model: provider.model || void 0
850
- // Parse model field from provider
851
- });
852
- }
853
- }
854
- const mcpServices = [];
855
- if (tomlData.mcp_servers) {
856
- const KNOWN_MCP_FIELDS = /* @__PURE__ */ new Set(["command", "args", "env", "startup_timeout_sec"]);
857
- for (const [id, mcpData] of Object.entries(tomlData.mcp_servers)) {
858
- const mcp = mcpData;
859
- const extraFields = {};
860
- for (const [key, value] of Object.entries(mcp)) {
861
- if (!KNOWN_MCP_FIELDS.has(key)) {
862
- extraFields[key] = value;
863
- }
864
- }
865
- mcpServices.push({
866
- id,
867
- command: mcp.command || id,
868
- args: mcp.args || [],
869
- env: Object.keys(mcp.env || {}).length > 0 ? mcp.env : void 0,
870
- startup_timeout_sec: mcp.startup_timeout_sec,
871
- // Only add extraFields if there are any extra fields
872
- extraFields: Object.keys(extraFields).length > 0 ? extraFields : void 0
873
- });
874
- }
875
- }
876
- const model = tomlData.model || null;
877
- let modelProvider = null;
878
- let modelProviderCommented;
879
- const commentedMatch = content.match(/^(\s*)#\s*model_provider\s*=\s*"([^"]+)"/m);
880
- if (commentedMatch) {
881
- modelProvider = commentedMatch[2];
882
- modelProviderCommented = true;
883
- } else {
884
- const lines2 = content.split("\n");
885
- let inSection = false;
886
- for (const line of lines2) {
887
- const trimmedLine = line.trim();
888
- if (!trimmedLine)
889
- continue;
890
- if (trimmedLine.startsWith("[")) {
891
- inSection = true;
892
- continue;
893
- }
894
- if (trimmedLine.startsWith("#")) {
895
- if (trimmedLine.includes("--- model provider added by CCJK ---")) {
896
- inSection = false;
897
- }
898
- continue;
899
- }
900
- if (!inSection && trimmedLine.startsWith("model_provider")) {
901
- const match = trimmedLine.match(/model_provider\s*=\s*"([^"]+)"/);
902
- if (match) {
903
- modelProvider = match[1];
904
- modelProviderCommented = false;
905
- break;
906
- }
907
- }
908
- }
909
- if (!modelProvider) {
910
- modelProvider = tomlData.model_provider || null;
911
- modelProviderCommented = false;
912
- }
913
- }
914
- const otherConfig = [];
915
- const lines = content.split("\n");
916
- let skipCurrentSection = false;
917
- for (const line of lines) {
918
- const trimmed = line.trim();
919
- if (!trimmed)
920
- continue;
921
- if (/^#\s*---\s*model provider added by CCJK\s*---\s*$/i.test(trimmed))
922
- continue;
923
- if (/^#\s*---\s*MCP servers added by CCJK\s*---\s*$/i.test(trimmed))
924
- continue;
925
- if (/Managed by CCJK/i.test(trimmed))
926
- continue;
927
- const sec = trimmed.match(/^\[([^\]]+)\]/);
928
- if (sec) {
929
- const name = sec[1];
930
- skipCurrentSection = name.startsWith("model_providers.") || name.startsWith("mcp_servers.");
931
- if (skipCurrentSection)
932
- continue;
933
- otherConfig.push(line);
934
- continue;
935
- }
936
- if (/^#?\s*model_provider\s*=/.test(trimmed))
937
- continue;
938
- if (/^model\s*=/.test(trimmed))
939
- continue;
940
- if (!skipCurrentSection) {
941
- otherConfig.push(line);
942
- }
943
- }
944
- const managed = providers.length > 0 || mcpServices.length > 0 || modelProvider !== null || model !== null;
945
- return {
946
- model,
947
- modelProvider,
948
- providers,
949
- mcpServices,
950
- managed,
951
- otherConfig,
952
- modelProviderCommented
953
- };
954
- } catch (error) {
955
- if (process__default.env.NODE_ENV === "development" || process__default.env.DEBUG) {
956
- console.warn("TOML parsing failed, falling back to basic parsing:", error);
957
- }
958
- const cleaned = content.replace(/^\s*#\s*---\s*model provider added by CCJK\s*---\s*$/gim, "").replace(/^\s*#\s*---\s*MCP servers added by CCJK\s*---\s*$/gim, "").replace(/^\[model_providers\.[^\]]+\][\s\S]*?(?=^\[|$)/gim, "").replace(/^\[mcp_servers\.[^\]]+\][\s\S]*?(?=^\[|$)/gim, "").replace(/^\s*(?:#\s*)?model_provider\s*=.*$/gim, "").replace(/^\s*model\s*=.*$/gim, "").replace(/\n{3,}/g, "\n\n");
959
- const otherConfig = cleaned.split("\n").map((l) => l.replace(/\s+$/g, "")).filter((l) => l.trim().length > 0);
960
- return {
961
- model: null,
962
- modelProvider: null,
963
- providers: [],
964
- mcpServices: [],
965
- managed: false,
966
- otherConfig,
967
- modelProviderCommented: void 0
968
- };
969
- }
970
- }
971
- function formatInlineTableValue(value) {
972
- if (value === null || value === void 0) {
973
- return "";
974
- }
975
- if (typeof value === "string") {
976
- const normalized = normalizeTomlPath(value);
977
- return `'${normalized}'`;
978
- }
979
- if (typeof value === "number" || typeof value === "boolean") {
980
- return String(value);
981
- }
982
- if (Array.isArray(value)) {
983
- const items = value.map((item) => {
984
- if (typeof item === "string") {
985
- const normalized = normalizeTomlPath(item);
986
- return `'${normalized}'`;
987
- }
988
- if (typeof item === "object" && item !== null && !Array.isArray(item)) {
989
- return formatInlineTable(item);
990
- }
991
- return String(item);
992
- }).join(", ");
993
- return `[${items}]`;
994
- }
995
- if (typeof value === "object") {
996
- return formatInlineTable(value);
997
- }
998
- return String(value);
999
- }
1000
- function formatInlineTable(obj) {
1001
- const entries = Object.entries(obj).filter(([_, v]) => v !== null && v !== void 0).map(([k, v]) => `${k} = ${formatInlineTableValue(v)}`).join(", ");
1002
- return `{${entries}}`;
1003
- }
1004
- function formatTomlField(key, value) {
1005
- if (value === null || value === void 0) {
1006
- return "";
1007
- }
1008
- if (typeof value === "string") {
1009
- const normalized = normalizeTomlPath(value);
1010
- const escaped = normalized.replace(/"/g, '\\"');
1011
- return `${key} = "${escaped}"`;
1012
- }
1013
- if (typeof value === "number" || typeof value === "boolean") {
1014
- return `${key} = ${value}`;
1015
- }
1016
- if (Array.isArray(value)) {
1017
- const items = value.map((item) => {
1018
- if (typeof item === "string") {
1019
- const normalized = normalizeTomlPath(item);
1020
- const escaped = normalized.replace(/"/g, '\\"');
1021
- return `"${escaped}"`;
1022
- }
1023
- if (typeof item === "object" && item !== null && !Array.isArray(item)) {
1024
- return formatInlineTable(item);
1025
- }
1026
- return String(item);
1027
- }).join(", ");
1028
- return `${key} = [${items}]`;
1029
- }
1030
- if (typeof value === "object") {
1031
- return `${key} = ${formatInlineTable(value)}`;
1032
- }
1033
- return "";
1034
- }
1035
- function readCodexConfig() {
1036
- if (!exists(CODEX_CONFIG_FILE))
1037
- return null;
1038
- ensureEnvKeyMigration();
1039
- try {
1040
- const content = readFile(CODEX_CONFIG_FILE);
1041
- return parseCodexConfig(content);
1042
- } catch {
1043
- return null;
1044
- }
1045
- }
1046
- function renderCodexConfig(data) {
1047
- const lines = [];
1048
- if (data.model || data.modelProvider || data.providers.length > 0 || data.modelProviderCommented) {
1049
- lines.push("# --- model provider added by CCJK ---");
1050
- if (data.model) {
1051
- lines.push(`model = "${data.model}"`);
1052
- }
1053
- if (data.modelProvider) {
1054
- const commentPrefix = data.modelProviderCommented ? "# " : "";
1055
- lines.push(`${commentPrefix}model_provider = "${data.modelProvider}"`);
1056
- }
1057
- lines.push("");
1058
- }
1059
- if (data.otherConfig && data.otherConfig.length > 0) {
1060
- const preserved = data.otherConfig.filter((raw) => {
1061
- const l = String(raw).trim();
1062
- if (!l)
1063
- return false;
1064
- if (/^#\s*---\s*model provider added by CCJK\s*---\s*$/i.test(l))
1065
- return false;
1066
- if (/^#\s*---\s*MCP servers added by CCJK\s*---\s*$/i.test(l))
1067
- return false;
1068
- if (/^\[\s*mcp_servers\./i.test(l))
1069
- return false;
1070
- if (/^\[\s*model_providers\./i.test(l))
1071
- return false;
1072
- if (/^#?\s*model_provider\s*=/.test(l))
1073
- return false;
1074
- if (/^\s*model\s*=/.test(l) && !l.includes("["))
1075
- return false;
1076
- return true;
1077
- });
1078
- if (preserved.length > 0) {
1079
- lines.push(...preserved);
1080
- if (data.providers.length > 0 || data.mcpServices.length > 0) {
1081
- lines.push("");
1082
- }
1083
- }
1084
- }
1085
- if (data.providers.length > 0) {
1086
- for (const provider of data.providers) {
1087
- lines.push("");
1088
- lines.push(`[model_providers.${provider.id}]`);
1089
- lines.push(`name = "${provider.name}"`);
1090
- lines.push(`base_url = "${provider.baseUrl}"`);
1091
- lines.push(`wire_api = "${provider.wireApi}"`);
1092
- lines.push(`temp_env_key = "${provider.tempEnvKey}"`);
1093
- lines.push(`requires_openai_auth = ${provider.requiresOpenaiAuth}`);
1094
- if (provider.model) {
1095
- lines.push(`model = "${provider.model}"`);
1096
- }
1097
- }
1098
- }
1099
- if (data.mcpServices.length > 0) {
1100
- lines.push("");
1101
- lines.push("# --- MCP servers added by CCJK ---");
1102
- for (const service of data.mcpServices) {
1103
- lines.push(`[mcp_servers.${service.id}]`);
1104
- const normalizedCommand = normalizeTomlPath(service.command);
1105
- lines.push(`command = "${normalizedCommand}"`);
1106
- const argsString = service.args.length > 0 ? service.args.map((arg) => `"${arg}"`).join(", ") : "";
1107
- lines.push(`args = [${argsString}]`);
1108
- if (service.env && Object.keys(service.env).length > 0) {
1109
- const envEntries = Object.entries(service.env).map(([key, value]) => `${key} = '${value}'`).join(", ");
1110
- lines.push(`env = {${envEntries}}`);
1111
- }
1112
- if (service.startup_timeout_sec) {
1113
- lines.push(`startup_timeout_sec = ${service.startup_timeout_sec}`);
1114
- }
1115
- if (service.extraFields) {
1116
- for (const [key, value] of Object.entries(service.extraFields)) {
1117
- const formatted = formatTomlField(key, value);
1118
- if (formatted) {
1119
- lines.push(formatted);
1120
- }
1121
- }
1122
- }
1123
- lines.push("");
1124
- }
1125
- if (lines[lines.length - 1] === "") {
1126
- lines.pop();
1127
- }
1128
- }
1129
- let result = lines.join("\n");
1130
- if (result && !result.endsWith("\n")) {
1131
- result += "\n";
1132
- }
1133
- return result;
1134
- }
1135
- function writeCodexConfig(data) {
1136
- ensureEnvKeyMigration();
1137
- ensureDir(CODEX_DIR);
1138
- writeFileAtomic(CODEX_CONFIG_FILE, renderCodexConfig(data));
1139
- }
1140
- function writeAuthFile(newEntries) {
1141
- ensureDir(CODEX_DIR);
1142
- const existing = readJsonConfig(CODEX_AUTH_FILE, { defaultValue: {} }) || {};
1143
- const merged = { ...existing, ...newEntries };
1144
- writeJsonConfig(CODEX_AUTH_FILE, merged, { pretty: true });
1145
- }
1146
- async function isCodexInstalled() {
1147
- try {
1148
- const npmResult = await K("npm", ["list", "-g", "--depth=0"]);
1149
- if (npmResult.exitCode === 0 && npmResult.stdout.includes("@openai/codex@")) {
1150
- return true;
1151
- }
1152
- } catch {
1153
- }
1154
- try {
1155
- const brewResult = await K("brew", ["list", "--cask", "codex"], { throwOnError: false });
1156
- if (brewResult.exitCode === 0) {
1157
- return true;
1158
- }
1159
- } catch {
1160
- }
1161
- return false;
1162
- }
1163
- async function getCodexVersion() {
1164
- try {
1165
- const npmResult = await K("npm", ["list", "-g", "--depth=0"]);
1166
- if (npmResult.exitCode === 0) {
1167
- const match = npmResult.stdout.match(/@openai\/codex@(\S+)/);
1168
- if (match) {
1169
- return match[1];
1170
- }
1171
- }
1172
- } catch {
1173
- }
1174
- try {
1175
- const brewResult = await K("brew", ["info", "--cask", "codex", "--json=v2"], { throwOnError: false });
1176
- if (brewResult.exitCode === 0) {
1177
- const info = JSON.parse(brewResult.stdout);
1178
- if (info.casks && Array.isArray(info.casks) && info.casks.length > 0) {
1179
- const cask = info.casks[0];
1180
- if (cask.installed && typeof cask.installed === "string") {
1181
- return cask.installed;
1182
- }
1183
- }
1184
- }
1185
- } catch {
1186
- }
1187
- return null;
1188
- }
1189
- async function checkCodexUpdate() {
1190
- try {
1191
- const currentVersion = await getCodexVersion();
1192
- if (!currentVersion) {
1193
- return {
1194
- installed: false,
1195
- currentVersion: null,
1196
- latestVersion: null,
1197
- needsUpdate: false
1198
- };
1199
- }
1200
- const result = await K("npm", ["view", "@openai/codex", "--json"]);
1201
- if (result.exitCode !== 0) {
1202
- return {
1203
- installed: true,
1204
- currentVersion,
1205
- latestVersion: null,
1206
- needsUpdate: false
1207
- };
1208
- }
1209
- const packageInfo = JSON.parse(result.stdout);
1210
- const latestVersion = packageInfo["dist-tags"]?.latest;
1211
- if (!latestVersion) {
1212
- return {
1213
- installed: true,
1214
- currentVersion,
1215
- latestVersion: null,
1216
- needsUpdate: false
1217
- };
1218
- }
1219
- const needsUpdate = semver.gt(latestVersion, currentVersion);
1220
- return {
1221
- installed: true,
1222
- currentVersion,
1223
- latestVersion,
1224
- needsUpdate
1225
- };
1226
- } catch {
1227
- return {
1228
- installed: false,
1229
- currentVersion: null,
1230
- latestVersion: null,
1231
- needsUpdate: false
1232
- };
1233
- }
1234
- }
1235
- async function installCodexCli(skipMethodSelection = false) {
1236
- ensureI18nInitialized();
1237
- if (await isCodexInstalled()) {
1238
- const { needsUpdate } = await checkCodexUpdate();
1239
- if (needsUpdate) {
1240
- await executeCodexInstallation(true, skipMethodSelection);
1241
- return;
1242
- } else {
1243
- console.log(a.yellow(i18n.t("codex:alreadyInstalled")));
1244
- return;
1245
- }
1246
- }
1247
- await executeCodexInstallation(false, skipMethodSelection);
1248
- }
1249
- async function runCodexWorkflowImportWithLanguageSelection(options) {
1250
- ensureI18nInitialized();
1251
- const zcfConfig = readZcfConfig();
1252
- const { aiOutputLang: commandLineOption, skipPrompt = false } = options ?? {};
1253
- const aiOutputLang = await resolveAiOutputLanguage(
1254
- i18n.language,
1255
- commandLineOption,
1256
- zcfConfig,
1257
- skipPrompt
1258
- );
1259
- updateZcfConfig({ aiOutputLang });
1260
- applyAiLanguageDirective(aiOutputLang);
1261
- await runCodexSystemPromptSelection(skipPrompt);
1262
- ensureCodexAgentsLanguageDirective(aiOutputLang);
1263
- await runCodexWorkflowSelection(options);
1264
- console.log(a.green(i18n.t("codex:workflowInstall")));
1265
- return aiOutputLang;
1266
- }
1267
- async function runCodexSystemPromptSelection(skipPrompt = false) {
1268
- ensureI18nInitialized();
1269
- const rootDir = getRootDir();
1270
- const zcfConfig = readZcfConfig();
1271
- const { readDefaultTomlConfig: readDefaultTomlConfig2 } = await import('./ccjk-config.mjs');
1272
- const tomlConfig = readDefaultTomlConfig2();
1273
- const { resolveTemplateLanguage } = await import('./prompts.mjs');
1274
- const preferredLang = await resolveTemplateLanguage(
1275
- void 0,
1276
- // No command line option for this function
1277
- zcfConfig,
1278
- skipPrompt
1279
- // Pass skipPrompt flag
1280
- );
1281
- updateZcfConfig({ templateLang: preferredLang });
1282
- let systemPromptSrc = join(rootDir, "templates", "common", "output-styles", preferredLang);
1283
- if (!exists(systemPromptSrc))
1284
- systemPromptSrc = join(rootDir, "templates", "common", "output-styles", "zh-CN");
1285
- if (!exists(systemPromptSrc))
1286
- return;
1287
- const availablePrompts = [
1288
- {
1289
- id: "speed-coder",
1290
- name: i18n.t("configuration:outputStyles.speed-coder.name"),
1291
- description: i18n.t("configuration:outputStyles.speed-coder.description")
1292
- },
1293
- {
1294
- id: "senior-architect",
1295
- name: i18n.t("configuration:outputStyles.senior-architect.name"),
1296
- description: i18n.t("configuration:outputStyles.senior-architect.description")
1297
- },
1298
- {
1299
- id: "pair-programmer",
1300
- name: i18n.t("configuration:outputStyles.pair-programmer.name"),
1301
- description: i18n.t("configuration:outputStyles.pair-programmer.description")
1302
- }
1303
- ].filter((style) => exists(join(systemPromptSrc, `${style.id}.md`)));
1304
- if (availablePrompts.length === 0)
1305
- return;
1306
- const { resolveSystemPromptStyle } = await import('./prompts.mjs');
1307
- const systemPrompt = await resolveSystemPromptStyle(
1308
- availablePrompts,
1309
- void 0,
1310
- // No command line option for this function
1311
- tomlConfig,
1312
- skipPrompt
1313
- // Pass skipPrompt flag
1314
- );
1315
- if (!systemPrompt)
1316
- return;
1317
- const promptFile = join(systemPromptSrc, `${systemPrompt}.md`);
1318
- const content = readFile(promptFile);
1319
- ensureDir(CODEX_DIR);
1320
- const backupPath = backupCodexAgents();
1321
- if (backupPath) {
1322
- console.log(a.gray(getBackupMessage(backupPath)));
1323
- }
1324
- writeFileAtomic(CODEX_AGENTS_FILE, content);
1325
- try {
1326
- const { updateTomlConfig: updateTomlConfig2 } = await import('./ccjk-config.mjs');
1327
- const { ZCF_CONFIG_FILE: ZCF_CONFIG_FILE2 } = await import('./constants.mjs');
1328
- updateTomlConfig2(ZCF_CONFIG_FILE2, {
1329
- codex: {
1330
- systemPromptStyle: systemPrompt
1331
- }
1332
- });
1333
- } catch (error) {
1334
- console.error("Failed to update CCJK config:", error);
1335
- }
1336
- }
1337
- async function runCodexWorkflowSelection(options) {
1338
- ensureI18nInitialized();
1339
- const { skipPrompt = false, workflows: presetWorkflows = [] } = options ?? {};
1340
- const rootDir = getRootDir();
1341
- const zcfConfig = readZcfConfig();
1342
- const templateLang = zcfConfig?.templateLang || zcfConfig?.preferredLang || "en";
1343
- let preferredLang = templateLang === "en" ? "en" : "zh-CN";
1344
- const workflowSrc = join(rootDir, "templates", "common", "workflow");
1345
- if (!exists(workflowSrc))
1346
- return;
1347
- let allWorkflows = getAllWorkflowFiles(workflowSrc, preferredLang);
1348
- if (allWorkflows.length === 0 && preferredLang === "en") {
1349
- preferredLang = "zh-CN";
1350
- allWorkflows = getAllWorkflowFiles(workflowSrc, preferredLang);
1351
- }
1352
- if (allWorkflows.length === 0)
1353
- return;
1354
- if (skipPrompt) {
1355
- ensureDir(CODEX_PROMPTS_DIR);
1356
- const backupPath2 = backupCodexPrompts();
1357
- if (backupPath2) {
1358
- console.log(a.gray(getBackupMessage(backupPath2)));
1359
- }
1360
- let workflowsToInstall;
1361
- if (presetWorkflows.length > 0) {
1362
- const selectedWorkflows = allWorkflows.filter(
1363
- (workflow) => presetWorkflows.includes(workflow.name)
1364
- );
1365
- workflowsToInstall = expandSelectedWorkflowPaths(selectedWorkflows.map((w) => w.path), workflowSrc, preferredLang);
1366
- } else {
1367
- workflowsToInstall = expandSelectedWorkflowPaths(allWorkflows.map((w) => w.path), workflowSrc, preferredLang);
1368
- }
1369
- for (const workflowPath of workflowsToInstall) {
1370
- const content = readFile(workflowPath);
1371
- const filename = workflowPath.split("/").pop() || "workflow.md";
1372
- const targetPath = join(CODEX_PROMPTS_DIR, filename);
1373
- writeFile(targetPath, content);
1374
- }
1375
- return;
1376
- }
1377
- const { workflows } = await inquirer.prompt([{
1378
- type: "checkbox",
1379
- name: "workflows",
1380
- message: i18n.t("codex:workflowSelectionPrompt"),
1381
- choices: addNumbersToChoices(allWorkflows.map((workflow) => ({
1382
- name: workflow.name,
1383
- value: workflow.path,
1384
- checked: true
1385
- // Default all selected
1386
- })))
1387
- }]);
1388
- if (!workflows || workflows.length === 0)
1389
- return;
1390
- ensureDir(CODEX_PROMPTS_DIR);
1391
- const backupPath = backupCodexPrompts();
1392
- if (backupPath) {
1393
- console.log(a.gray(getBackupMessage(backupPath)));
1394
- }
1395
- const finalWorkflowPaths = expandSelectedWorkflowPaths(workflows, workflowSrc, preferredLang);
1396
- for (const workflowPath of finalWorkflowPaths) {
1397
- const content = readFile(workflowPath);
1398
- const filename = workflowPath.split("/").pop() || "workflow.md";
1399
- const targetPath = join(CODEX_PROMPTS_DIR, filename);
1400
- writeFile(targetPath, content);
1401
- }
1402
- }
1403
- const GIT_GROUP_SENTINEL = "::gitGroup";
1404
- function getAllWorkflowFiles(workflowSrc, preferredLang) {
1405
- const workflows = [];
1406
- const sixStepFile = join(workflowSrc, "sixStep", preferredLang, "workflow.md");
1407
- if (exists(sixStepFile)) {
1408
- workflows.push({
1409
- name: i18n.t("workflow:workflowOption.sixStepsWorkflow"),
1410
- path: sixStepFile
1411
- });
1412
- }
1413
- const gitPromptsDir = join(workflowSrc, "git", preferredLang);
1414
- if (exists(gitPromptsDir)) {
1415
- workflows.push({
1416
- name: i18n.t("workflow:workflowOption.gitWorkflow"),
1417
- // Use sentinel path for grouped selection; expanded later
1418
- path: GIT_GROUP_SENTINEL
1419
- });
1420
- }
1421
- return workflows;
1422
- }
1423
- function expandSelectedWorkflowPaths(paths, workflowSrc, preferredLang) {
1424
- const expanded = [];
1425
- for (const p of paths) {
1426
- if (p === GIT_GROUP_SENTINEL) {
1427
- expanded.push(...getGitPromptFiles(workflowSrc, preferredLang));
1428
- } else {
1429
- expanded.push(p);
1430
- }
1431
- }
1432
- return expanded;
1433
- }
1434
- function getGitPromptFiles(workflowSrc, preferredLang) {
1435
- const gitPromptsDir = join(workflowSrc, "git", preferredLang);
1436
- const files = [
1437
- "git-commit.md",
1438
- "git-rollback.md",
1439
- "git-cleanBranches.md",
1440
- "git-worktree.md"
1441
- ];
1442
- const resolved = [];
1443
- for (const f of files) {
1444
- const full = join(gitPromptsDir, f);
1445
- if (exists(full))
1446
- resolved.push(full);
1447
- }
1448
- return resolved;
1449
- }
1450
- function toProvidersList(providers) {
1451
- return providers.map((provider) => ({ name: provider.name || provider.id, value: provider.id }));
1452
- }
1453
- function createApiConfigChoices(providers, currentProvider, isCommented) {
1454
- const choices = [];
1455
- const isOfficialMode = !currentProvider || isCommented;
1456
- choices.push({
1457
- name: isOfficialMode ? `${a.green("\u25CF ")}${i18n.t("codex:useOfficialLogin")} ${a.yellow("(\u5F53\u524D)")}` : ` ${i18n.t("codex:useOfficialLogin")}`,
1458
- value: "official"
1459
- });
1460
- providers.forEach((provider) => {
1461
- const isCurrent = currentProvider === provider.id && !isCommented;
1462
- choices.push({
1463
- name: isCurrent ? `${a.green("\u25CF ")}${provider.name} - ${a.gray(provider.id)} ${a.yellow("(\u5F53\u524D)")}` : ` ${provider.name} - ${a.gray(provider.id)}`,
1464
- value: provider.id
1465
- });
1466
- });
1467
- return choices;
1468
- }
1469
- async function applyCustomApiConfig(customApiConfig) {
1470
- const { type, token, baseUrl, model } = customApiConfig;
1471
- const backupPath = backupCodexComplete();
1472
- if (backupPath) {
1473
- console.log(a.gray(getBackupMessage(backupPath)));
1474
- }
1475
- const existingConfig = readCodexConfig();
1476
- const existingAuth = readJsonConfig(CODEX_AUTH_FILE, { defaultValue: {} }) || {};
1477
- const providers = [];
1478
- const authEntries = { ...existingAuth };
1479
- const providerId = type === "auth_token" ? "official-auth-token" : "custom-api-key";
1480
- const providerName = type === "auth_token" ? "Official Auth Token" : "Custom API Key";
1481
- const existingProvider = existingConfig?.providers.find((p) => p.id === providerId);
1482
- providers.push({
1483
- id: providerId,
1484
- name: providerName,
1485
- baseUrl: baseUrl || existingProvider?.baseUrl || "https://api.anthropic.com",
1486
- wireApi: existingProvider?.wireApi || "responses",
1487
- tempEnvKey: existingProvider?.tempEnvKey || `${providerId.toUpperCase()}_API_KEY`,
1488
- requiresOpenaiAuth: existingProvider?.requiresOpenaiAuth ?? false,
1489
- model: model || existingProvider?.model
1490
- });
1491
- if (existingConfig?.providers) {
1492
- providers.push(...existingConfig.providers.filter((p) => p.id !== providerId));
1493
- }
1494
- if (token) {
1495
- authEntries[providerId] = token;
1496
- authEntries.OPENAI_API_KEY = token;
1497
- }
1498
- const configData = {
1499
- model: model || existingConfig?.model || "claude-3-5-sonnet-20241022",
1500
- // Prefer provided model, then existing, fallback default
1501
- modelProvider: providerId,
1502
- modelProviderCommented: false,
1503
- providers,
1504
- mcpServices: existingConfig?.mcpServices || [],
1505
- otherConfig: existingConfig?.otherConfig || []
1506
- };
1507
- writeCodexConfig(configData);
1508
- writeJsonConfig(CODEX_AUTH_FILE, authEntries);
1509
- updateZcfConfig({ codeToolType: "codex" });
1510
- console.log(a.green(`\u2714 ${i18n.t("codex:apiConfigured")}`));
1511
- }
1512
- async function configureCodexApi(options) {
1513
- ensureI18nInitialized();
1514
- const { skipPrompt = false, apiMode, customApiConfig } = options ?? {};
1515
- const existingConfig = readCodexConfig();
1516
- const existingAuth = readJsonConfig(CODEX_AUTH_FILE, { defaultValue: {} }) || {};
1517
- if (skipPrompt) {
1518
- if (apiMode === "skip") {
1519
- return;
1520
- }
1521
- if (apiMode === "custom" && customApiConfig) {
1522
- await applyCustomApiConfig(customApiConfig);
1523
- return;
1524
- }
1525
- if (apiMode === "official") {
1526
- const success = await switchToOfficialLogin();
1527
- if (success) {
1528
- updateZcfConfig({ codeToolType: "codex" });
1529
- }
1530
- return;
1531
- }
1532
- }
1533
- const hasProviders = existingConfig?.providers && existingConfig.providers.length > 0;
1534
- const modeChoices = [
1535
- { name: i18n.t("codex:apiModeOfficial"), value: "official" },
1536
- { name: i18n.t("codex:apiModeCustom"), value: "custom" }
1537
- ];
1538
- if (hasProviders) {
1539
- modeChoices.push({ name: i18n.t("codex:configSwitchMode"), value: "switch" });
1540
- }
1541
- const { mode } = await inquirer.prompt([{
1542
- type: "list",
1543
- name: "mode",
1544
- message: i18n.t("codex:apiModePrompt"),
1545
- choices: addNumbersToChoices(modeChoices),
1546
- default: "custom"
1547
- }]);
1548
- if (!mode) {
1549
- console.log(a.yellow(i18n.t("common:cancelled")));
1550
- return;
1551
- }
1552
- if (mode === "official") {
1553
- const success = await switchToOfficialLogin();
1554
- if (success) {
1555
- updateZcfConfig({ codeToolType: "codex" });
1556
- }
1557
- return;
1558
- }
1559
- if (mode === "switch") {
1560
- if (!hasProviders) {
1561
- console.log(a.yellow(i18n.t("codex:noProvidersAvailable")));
1562
- return;
1563
- }
1564
- const currentProvider = existingConfig?.modelProvider;
1565
- const isCommented = existingConfig?.modelProviderCommented;
1566
- const choices = createApiConfigChoices(existingConfig.providers, currentProvider, isCommented);
1567
- const { selectedConfig } = await inquirer.prompt([{
1568
- type: "list",
1569
- name: "selectedConfig",
1570
- message: i18n.t("codex:apiConfigSwitchPrompt"),
1571
- choices: addNumbersToChoices(choices)
1572
- }]);
1573
- if (!selectedConfig) {
1574
- console.log(a.yellow(i18n.t("common:cancelled")));
1575
- return;
1576
- }
1577
- let success = false;
1578
- if (selectedConfig === "official") {
1579
- success = await switchToOfficialLogin();
1580
- } else {
1581
- success = await switchToProvider(selectedConfig);
1582
- }
1583
- if (success) {
1584
- updateZcfConfig({ codeToolType: "codex" });
1585
- }
1586
- return;
1587
- }
1588
- const managementMode = detectConfigManagementMode();
1589
- if (managementMode.mode === "management" && managementMode.hasProviders) {
1590
- const { default: { configureIncrementalManagement } } = await import('./codex-config-switch.mjs');
1591
- await configureIncrementalManagement();
1592
- return;
1593
- }
1594
- const backupPath = backupCodexComplete();
1595
- if (backupPath) {
1596
- console.log(a.gray(getBackupMessage(backupPath)));
1597
- }
1598
- const providers = [];
1599
- const authEntries = {};
1600
- const existingMap = new Map(existingConfig?.providers.map((provider) => [provider.id, provider]));
1601
- const currentSessionProviders = /* @__PURE__ */ new Map();
1602
- let addMore = true;
1603
- const existingValues = existingMap.size ? Array.from(existingMap.values()) : [];
1604
- const firstExisting = existingValues.length === 1 ? existingValues[0] : void 0;
1605
- while (addMore) {
1606
- const { getApiProviders } = await import('./api-providers.mjs');
1607
- const apiProviders = getApiProviders("codex");
1608
- const providerChoices = [
1609
- { name: i18n.t("api:customProvider"), value: "custom" },
1610
- ...apiProviders.map((p) => ({ name: p.name, value: p.id }))
1611
- ];
1612
- const { selectedProvider: selectedProvider2 } = await inquirer.prompt([{
1613
- type: "list",
1614
- name: "selectedProvider",
1615
- message: i18n.t("api:selectApiProvider"),
1616
- choices: addNumbersToChoices(providerChoices)
1617
- }]);
1618
- let prefilledBaseUrl;
1619
- let prefilledWireApi;
1620
- let prefilledModel;
1621
- if (selectedProvider2 !== "custom") {
1622
- const provider = apiProviders.find((p) => p.id === selectedProvider2);
1623
- if (provider?.codex) {
1624
- prefilledBaseUrl = provider.codex.baseUrl;
1625
- prefilledWireApi = provider.codex.wireApi;
1626
- prefilledModel = provider.codex.defaultModel;
1627
- console.log(a.gray(i18n.t("api:providerSelected", { name: provider.name })));
1628
- }
1629
- }
1630
- const answers = await inquirer.prompt([
1631
- {
1632
- type: "input",
1633
- name: "providerName",
1634
- message: i18n.t("codex:providerNamePrompt"),
1635
- default: selectedProvider2 !== "custom" ? apiProviders.find((p) => p.id === selectedProvider2)?.name : firstExisting?.name,
1636
- validate: (input) => {
1637
- const sanitized = sanitizeProviderName(input);
1638
- if (!sanitized)
1639
- return i18n.t("codex:providerNameRequired");
1640
- if (sanitized !== input.trim())
1641
- return i18n.t("codex:providerNameInvalid");
1642
- return true;
1643
- }
1644
- },
1645
- {
1646
- type: "input",
1647
- name: "baseUrl",
1648
- message: i18n.t("codex:providerBaseUrlPrompt"),
1649
- default: prefilledBaseUrl || ((answers2) => existingMap.get(answers2.providerId)?.baseUrl || "https://api.openai.com/v1"),
1650
- when: () => selectedProvider2 === "custom",
1651
- validate: (input) => !!input || i18n.t("codex:providerBaseUrlRequired")
1652
- },
1653
- {
1654
- type: "list",
1655
- name: "wireApi",
1656
- message: i18n.t("codex:providerProtocolPrompt"),
1657
- choices: [
1658
- { name: i18n.t("codex:protocolResponses"), value: "responses" },
1659
- { name: i18n.t("codex:protocolChat"), value: "chat" }
1660
- ],
1661
- default: prefilledWireApi || ((answers2) => existingMap.get(sanitizeProviderName(answers2.providerName))?.wireApi || "responses"),
1662
- when: () => selectedProvider2 === "custom"
1663
- // Only ask if custom
1664
- },
1665
- {
1666
- type: "input",
1667
- name: "apiKey",
1668
- message: selectedProvider2 !== "custom" ? i18n.t("api:enterProviderApiKey", { provider: apiProviders.find((p) => p.id === selectedProvider2)?.name || selectedProvider2 }) : i18n.t("codex:providerApiKeyPrompt"),
1669
- validate: (input) => !!input || i18n.t("codex:providerApiKeyRequired")
1670
- }
1671
- ]);
1672
- let customModel;
1673
- if (selectedProvider2 === "custom") {
1674
- const { model } = await inquirer.prompt([{
1675
- type: "input",
1676
- name: "model",
1677
- message: `${i18n.t("configuration:enterCustomModel")}${i18n.t("common:emptyToSkip")}`,
1678
- default: "gpt-5-codex"
1679
- }]);
1680
- if (model.trim()) {
1681
- customModel = model.trim();
1682
- }
1683
- }
1684
- const providerId = sanitizeProviderName(answers.providerName);
1685
- const tempEnvKey = `${providerId.toUpperCase().replace(/-/g, "_")}_API_KEY`;
1686
- const existingProvider = existingMap.get(providerId);
1687
- const sessionProvider = currentSessionProviders.get(providerId);
1688
- if (existingProvider || sessionProvider) {
1689
- const sourceType = existingProvider ? "existing" : "session";
1690
- const sourceProvider = existingProvider || sessionProvider;
1691
- const shouldOverwrite = await promptBoolean({
1692
- message: i18n.t("codex:providerDuplicatePrompt", {
1693
- name: sourceProvider.name,
1694
- source: sourceType === "existing" ? i18n.t("codex:existingConfig") : i18n.t("codex:currentSession")
1695
- }),
1696
- defaultValue: false
1697
- });
1698
- if (!shouldOverwrite) {
1699
- console.log(a.yellow(i18n.t("codex:providerDuplicateSkipped")));
1700
- continue;
1701
- }
1702
- if (sessionProvider) {
1703
- currentSessionProviders.delete(providerId);
1704
- const sessionIndex = providers.findIndex((p) => p.id === providerId);
1705
- if (sessionIndex !== -1) {
1706
- providers.splice(sessionIndex, 1);
1707
- }
1708
- }
1709
- }
1710
- const newProvider = {
1711
- id: providerId,
1712
- name: answers.providerName,
1713
- baseUrl: selectedProvider2 === "custom" ? answers.baseUrl : prefilledBaseUrl,
1714
- wireApi: selectedProvider2 === "custom" ? answers.wireApi || "responses" : prefilledWireApi,
1715
- tempEnvKey,
1716
- requiresOpenaiAuth: true,
1717
- model: customModel || prefilledModel || "gpt-5-codex"
1718
- // Use custom model, provider's default model, or fallback
1719
- };
1720
- providers.push(newProvider);
1721
- currentSessionProviders.set(providerId, newProvider);
1722
- authEntries[tempEnvKey] = answers.apiKey;
1723
- const addAnother = await promptBoolean({
1724
- message: i18n.t("codex:addProviderPrompt"),
1725
- defaultValue: false
1726
- });
1727
- addMore = addAnother;
1728
- }
1729
- if (providers.length === 0) {
1730
- console.log(a.yellow(i18n.t("codex:noProvidersConfigured")));
1731
- return;
1732
- }
1733
- const { defaultProvider } = await inquirer.prompt([{
1734
- type: "list",
1735
- name: "defaultProvider",
1736
- message: i18n.t("codex:selectDefaultProviderPrompt"),
1737
- choices: addNumbersToChoices(toProvidersList(providers)),
1738
- default: existingConfig?.modelProvider || providers[0].id
1739
- }]);
1740
- const selectedProvider = providers.find((provider) => provider.id === defaultProvider);
1741
- if (selectedProvider) {
1742
- const tempEnvKey = selectedProvider.tempEnvKey;
1743
- const defaultApiKey = authEntries[tempEnvKey] ?? existingAuth[tempEnvKey] ?? null;
1744
- if (defaultApiKey)
1745
- authEntries.OPENAI_API_KEY = defaultApiKey;
1746
- }
1747
- writeCodexConfig({
1748
- model: existingConfig?.model || null,
1749
- modelProvider: defaultProvider,
1750
- providers,
1751
- mcpServices: existingConfig?.mcpServices || [],
1752
- otherConfig: existingConfig?.otherConfig || []
1753
- });
1754
- writeAuthFile(authEntries);
1755
- updateZcfConfig({ codeToolType: "codex" });
1756
- console.log(a.green(i18n.t("codex:apiConfigured")));
1757
- }
1758
- async function runCodexFullInit(options) {
1759
- ensureI18nInitialized();
1760
- await installCodexCli(options?.skipPrompt || false);
1761
- const aiOutputLang = await runCodexWorkflowImportWithLanguageSelection(options);
1762
- await configureCodexApi(options);
1763
- await configureCodexMcp(options);
1764
- return aiOutputLang;
1765
- }
1766
- function ensureCodexAgentsLanguageDirective(aiOutputLang) {
1767
- if (!exists(CODEX_AGENTS_FILE))
1768
- return;
1769
- const content = readFile(CODEX_AGENTS_FILE);
1770
- const targetLabel = resolveCodexLanguageLabel(aiOutputLang);
1771
- const directiveRegex = /\*\*Most Important:\s*Always respond in ([^*]+)\*\*/i;
1772
- const existingMatch = directiveRegex.exec(content);
1773
- if (existingMatch && normalizeLanguageLabel(existingMatch[1]) === normalizeLanguageLabel(targetLabel))
1774
- return;
1775
- let updatedContent = content.replace(/\*\*Most Important:\s*Always respond in [^*]+\*\*\s*/gi, "").trimEnd();
1776
- if (updatedContent.length > 0 && !updatedContent.endsWith("\n"))
1777
- updatedContent += "\n";
1778
- updatedContent += `
1779
- **Most Important:Always respond in ${targetLabel}**
1780
- `;
1781
- const backupPath = backupCodexAgents();
1782
- if (backupPath)
1783
- console.log(a.gray(getBackupMessage(backupPath)));
1784
- writeFileAtomic(CODEX_AGENTS_FILE, updatedContent);
1785
- console.log(a.gray(` ${i18n.t("configuration:addedLanguageDirective")}: ${targetLabel}`));
1786
- }
1787
- function resolveCodexLanguageLabel(aiOutputLang) {
1788
- const directive = AI_OUTPUT_LANGUAGES[aiOutputLang]?.directive;
1789
- if (directive) {
1790
- const match = directive.match(/Always respond in\s+(.+)/i);
1791
- if (match)
1792
- return match[1].trim();
1793
- }
1794
- if (typeof aiOutputLang === "string")
1795
- return aiOutputLang;
1796
- return "English";
1797
- }
1798
- function normalizeLanguageLabel(label) {
1799
- return label.trim().toLowerCase();
1800
- }
1801
- async function runCodexUpdate(force = false, skipPrompt = false) {
1802
- ensureI18nInitialized();
1803
- console.log(a.bold.cyan(`
1804
- \u{1F50D} ${i18n.t("updater:checkingTools")}
1805
- `));
1806
- const spinner = ora(i18n.t("updater:checkingVersion")).start();
1807
- try {
1808
- const { installed, currentVersion, latestVersion, needsUpdate } = await checkCodexUpdate();
1809
- spinner.stop();
1810
- if (!installed) {
1811
- console.log(a.yellow(i18n.t("codex:notInstalled")));
1812
- return false;
1813
- }
1814
- if (!needsUpdate && !force) {
1815
- console.log(a.green(format(i18n.t("codex:upToDate"), { version: currentVersion || "" })));
1816
- return true;
1817
- }
1818
- if (!latestVersion) {
1819
- console.log(a.yellow(i18n.t("codex:cannotCheckVersion")));
1820
- return false;
1821
- }
1822
- console.log(a.green(format(i18n.t("codex:currentVersion"), { version: currentVersion || "" })));
1823
- console.log(a.green(format(i18n.t("codex:latestVersion"), { version: latestVersion })));
1824
- if (!skipPrompt) {
1825
- const confirm = await promptBoolean({
1826
- message: i18n.t("codex:confirmUpdate"),
1827
- defaultValue: true
1828
- });
1829
- if (!confirm) {
1830
- console.log(a.gray(i18n.t("codex:updateSkipped")));
1831
- return true;
1832
- }
1833
- } else {
1834
- console.log(a.green(i18n.t("codex:autoUpdating")));
1835
- }
1836
- const updateSpinner = ora(i18n.t("codex:updating")).start();
1837
- try {
1838
- await executeCodexInstallation(true);
1839
- updateSpinner.succeed(i18n.t("codex:updateSuccess"));
1840
- return true;
1841
- } catch (error) {
1842
- updateSpinner.fail(i18n.t("codex:updateFailed"));
1843
- console.error(a.red(error instanceof Error ? error.message : String(error)));
1844
- return false;
1845
- }
1846
- } catch (error) {
1847
- spinner.fail(i18n.t("codex:checkFailed"));
1848
- console.error(a.red(error instanceof Error ? error.message : String(error)));
1849
- return false;
1850
- }
1851
- }
1852
- async function runCodexUninstall() {
1853
- ensureI18nInitialized();
1854
- const { CodexUninstaller } = await import('./codex-uninstaller.mjs');
1855
- const zcfConfig = readZcfConfig();
1856
- const preferredLang = zcfConfig?.preferredLang;
1857
- const uninstallLang = preferredLang && SUPPORTED_LANGS.includes(preferredLang) ? preferredLang : "en";
1858
- const uninstaller = new CodexUninstaller(uninstallLang);
1859
- const { mode } = await inquirer.prompt([{
1860
- type: "list",
1861
- name: "mode",
1862
- message: i18n.t("codex:uninstallModePrompt"),
1863
- choices: addNumbersToChoices([
1864
- { name: i18n.t("codex:uninstallModeComplete"), value: "complete" },
1865
- { name: i18n.t("codex:uninstallModeCustom"), value: "custom" }
1866
- ]),
1867
- default: "complete"
1868
- }]);
1869
- if (!mode) {
1870
- handleUninstallCancellation();
1871
- return;
1872
- }
1873
- try {
1874
- if (mode === "complete") {
1875
- const confirm = await promptBoolean({
1876
- message: i18n.t("codex:uninstallPrompt"),
1877
- defaultValue: false
1878
- });
1879
- if (!confirm) {
1880
- handleUninstallCancellation();
1881
- return;
1882
- }
1883
- const result = await uninstaller.completeUninstall();
1884
- displayUninstallResults([result]);
1885
- } else if (mode === "custom") {
1886
- const { items } = await inquirer.prompt([{
1887
- type: "checkbox",
1888
- name: "items",
1889
- message: i18n.t("codex:customUninstallPrompt"),
1890
- choices: addNumbersToChoices(getUninstallOptions())
1891
- }]);
1892
- if (!items || items.length === 0) {
1893
- handleUninstallCancellation();
1894
- return;
1895
- }
1896
- const results = await uninstaller.customUninstall(items);
1897
- displayUninstallResults(results);
1898
- }
1899
- console.log(a.green(i18n.t("codex:uninstallSuccess")));
1900
- } catch (error) {
1901
- console.error(a.red(i18n.t("codex:errorDuringUninstall", { error: error.message })));
1902
- throw error;
1903
- }
1904
- }
1905
- function displayUninstallResults(results) {
1906
- for (const result of results) {
1907
- for (const item of result.removed) {
1908
- console.log(a.green(`\u2714 ${i18n.t("codex:removedItem", { item })}`));
1909
- }
1910
- for (const config of result.removedConfigs) {
1911
- console.log(a.green(`\u2714 ${i18n.t("codex:removedConfig", { config })}`));
1912
- }
1913
- for (const warning of result.warnings) {
1914
- console.log(a.yellow(`\u26A0\uFE0F ${warning}`));
1915
- }
1916
- for (const error of result.errors) {
1917
- console.log(a.red(`\u274C ${error}`));
1918
- }
1919
- }
1920
- }
1921
- async function listCodexProviders() {
1922
- const config = readCodexConfig();
1923
- return config?.providers || [];
1924
- }
1925
- async function switchCodexProvider(providerId) {
1926
- ensureI18nInitialized();
1927
- const existingConfig = readCodexConfig();
1928
- if (!existingConfig) {
1929
- console.log(a.red(i18n.t("codex:configNotFound")));
1930
- return false;
1931
- }
1932
- const providerExists = existingConfig.providers.some((provider) => provider.id === providerId);
1933
- if (!providerExists) {
1934
- console.log(a.red(i18n.t("codex:providerNotFound", { provider: providerId })));
1935
- return false;
1936
- }
1937
- const backupPath = backupCodexComplete();
1938
- if (backupPath) {
1939
- console.log(a.gray(getBackupMessage(backupPath)));
1940
- }
1941
- const updatedConfig = {
1942
- ...existingConfig,
1943
- modelProvider: providerId
1944
- };
1945
- try {
1946
- writeCodexConfig(updatedConfig);
1947
- console.log(a.green(i18n.t("codex:providerSwitchSuccess", { provider: providerId })));
1948
- return true;
1949
- } catch (error) {
1950
- console.error(a.red(i18n.t("codex:errorSwitchingProvider", { error: error.message })));
1951
- return false;
1952
- }
1953
- }
1954
- async function switchToOfficialLogin() {
1955
- ensureI18nInitialized();
1956
- const existingConfig = readCodexConfig();
1957
- if (!existingConfig) {
1958
- console.log(a.red(i18n.t("codex:configNotFound")));
1959
- return false;
1960
- }
1961
- const backupPath = backupCodexComplete();
1962
- if (backupPath) {
1963
- console.log(a.gray(getBackupMessage(backupPath)));
1964
- }
1965
- try {
1966
- let preservedModelProvider = existingConfig.modelProvider;
1967
- if (!preservedModelProvider) {
1968
- try {
1969
- const rawContent = readFile(CODEX_CONFIG_FILE);
1970
- const parsedToml = parse(rawContent);
1971
- if (typeof parsedToml.model_provider === "string" && parsedToml.model_provider.trim().length > 0)
1972
- preservedModelProvider = parsedToml.model_provider.trim();
1973
- } catch {
1974
- }
1975
- }
1976
- const shouldCommentModelProvider = typeof preservedModelProvider === "string" && preservedModelProvider.length > 0;
1977
- const updatedConfig = {
1978
- ...existingConfig,
1979
- modelProvider: shouldCommentModelProvider ? preservedModelProvider : existingConfig.modelProvider,
1980
- modelProviderCommented: shouldCommentModelProvider ? true : existingConfig.modelProviderCommented
1981
- };
1982
- writeCodexConfig(updatedConfig);
1983
- const auth = readJsonConfig(CODEX_AUTH_FILE, { defaultValue: {} }) || {};
1984
- auth.OPENAI_API_KEY = null;
1985
- writeJsonConfig(CODEX_AUTH_FILE, auth, { pretty: true });
1986
- console.log(a.green(i18n.t("codex:officialConfigured")));
1987
- return true;
1988
- } catch (error) {
1989
- console.error(a.red(i18n.t("codex:errorSwitchingToOfficialLogin", { error: error.message })));
1990
- return false;
1991
- }
1992
- }
1993
- async function switchToProvider(providerId) {
1994
- ensureI18nInitialized();
1995
- const existingConfig = readCodexConfig();
1996
- if (!existingConfig) {
1997
- console.log(a.red(i18n.t("codex:configNotFound")));
1998
- return false;
1999
- }
2000
- const provider = existingConfig.providers.find((p) => p.id === providerId);
2001
- if (!provider) {
2002
- console.log(a.red(i18n.t("codex:providerNotFound", { provider: providerId })));
2003
- return false;
2004
- }
2005
- const backupPath = backupCodexComplete();
2006
- if (backupPath) {
2007
- console.log(a.gray(getBackupMessage(backupPath)));
2008
- }
2009
- try {
2010
- let targetModel = existingConfig.model;
2011
- if (provider.model) {
2012
- targetModel = provider.model;
2013
- } else {
2014
- const currentModel = existingConfig.model;
2015
- if (currentModel !== "gpt-5" && currentModel !== "gpt-5-codex") {
2016
- targetModel = "gpt-5-codex";
2017
- }
2018
- }
2019
- const updatedConfig = {
2020
- ...existingConfig,
2021
- model: targetModel,
2022
- modelProvider: providerId,
2023
- modelProviderCommented: false
2024
- // Ensure it's not commented
2025
- };
2026
- writeCodexConfig(updatedConfig);
2027
- const auth = readJsonConfig(CODEX_AUTH_FILE, { defaultValue: {} }) || {};
2028
- const envValue = auth[provider.tempEnvKey] || null;
2029
- auth.OPENAI_API_KEY = envValue;
2030
- writeJsonConfig(CODEX_AUTH_FILE, auth, { pretty: true });
2031
- console.log(a.green(i18n.t("codex:providerSwitchSuccess", { provider: providerId })));
2032
- return true;
2033
- } catch (error) {
2034
- console.error(a.red(i18n.t("codex:errorSwitchingProvider", { error: error.message })));
2035
- return false;
2036
- }
2037
- }
2038
-
2039
- const codex = {
2040
- __proto__: null,
2041
- CODEX_DIR: CODEX_DIR,
2042
- applyCodexPlatformCommand: applyCodexPlatformCommand,
2043
- backupCodexAgents: backupCodexAgents,
2044
- backupCodexComplete: backupCodexComplete,
2045
- backupCodexConfig: backupCodexConfig,
2046
- backupCodexFiles: backupCodexFiles,
2047
- backupCodexPrompts: backupCodexPrompts,
2048
- checkCodexUpdate: checkCodexUpdate,
2049
- configureCodexApi: configureCodexApi,
2050
- configureCodexMcp: configureCodexMcp,
2051
- createBackupDirectory: createBackupDirectory,
2052
- ensureEnvKeyMigration: ensureEnvKeyMigration,
2053
- getBackupMessage: getBackupMessage,
2054
- getCodexVersion: getCodexVersion,
2055
- installCodexCli: installCodexCli,
2056
- isCodexInstalled: isCodexInstalled,
2057
- listCodexProviders: listCodexProviders,
2058
- migrateEnvKeyInContent: migrateEnvKeyInContent,
2059
- migrateEnvKeyToTempEnvKey: migrateEnvKeyToTempEnvKey,
2060
- needsEnvKeyMigration: needsEnvKeyMigration,
2061
- parseCodexConfig: parseCodexConfig,
2062
- readCodexConfig: readCodexConfig,
2063
- renderCodexConfig: renderCodexConfig,
2064
- runCodexFullInit: runCodexFullInit,
2065
- runCodexSystemPromptSelection: runCodexSystemPromptSelection,
2066
- runCodexUninstall: runCodexUninstall,
2067
- runCodexUpdate: runCodexUpdate,
2068
- runCodexWorkflowImportWithLanguageSelection: runCodexWorkflowImportWithLanguageSelection,
2069
- runCodexWorkflowSelection: runCodexWorkflowSelection,
2070
- switchCodexProvider: switchCodexProvider,
2071
- switchToOfficialLogin: switchToOfficialLogin,
2072
- switchToProvider: switchToProvider,
2073
- writeAuthFile: writeAuthFile,
2074
- writeCodexConfig: writeCodexConfig
2075
- };
2076
-
2077
- export { MCP_SERVICE_CONFIGS as M, readCodexConfig as a, switchToOfficialLogin as b, switchToProvider as c, selectMcpServices as d, backupCodexComplete as e, writeAuthFile as f, getMcpServices as g, detectConfigManagementMode as h, getMcpService as i, dynamicMcpRegistry as j, applyCodexPlatformCommand as k, listCodexProviders as l, runCodexFullInit as m, codex as n, runCodexUpdate as r, switchCodexProvider as s, writeCodexConfig as w };