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