@pikecode/api-key-manager 1.3.91 → 2.0.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 +79 -52
- package/bin/akm.js +47 -30
- package/package.json +13 -8
- package/src/CommandRegistry.js +2 -2
- package/src/commands/add/prompts.js +200 -171
- package/src/commands/add/providerSaver.js +6 -7
- package/src/commands/add.js +6 -2
- package/src/commands/backup.js +99 -45
- package/src/commands/current.js +41 -20
- package/src/commands/edit.js +3 -289
- package/src/commands/health.js +75 -31
- package/src/commands/list.js +39 -19
- package/src/commands/remove.js +2 -2
- package/src/commands/switch/provider-edit-questions-helper.js +29 -7
- package/src/commands/switch/provider-manager.js +39 -40
- package/src/commands/switch.js +9 -8
- package/src/config.js +68 -45
- package/src/index.js +1 -1
- package/src/utils/atomic-file.js +47 -0
- package/src/utils/claude-settings.js +4 -3
- package/src/utils/codex-files.js +227 -38
- package/src/utils/codex-launcher.js +16 -8
- package/src/utils/concurrency.js +30 -0
- package/src/utils/env-launcher.js +17 -1
- package/src/utils/import-validator.js +210 -0
- package/src/utils/launch-args.js +60 -1
- package/src/utils/provider-status-checker.js +49 -24
- package/src/utils/shell-snippets.js +32 -0
- package/src/utils/terminal-format.js +22 -4
- package/src/utils/ui-helper.js +0 -1
- package/src/utils/update-checker.js +3 -3
- package/src/utils/validator.js +81 -10
package/src/utils/codex-files.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
const fs = require('fs-extra');
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const os = require('os');
|
|
4
|
+
const { validator } = require('./validator');
|
|
5
|
+
const { writeFileAtomic } = require('./atomic-file');
|
|
4
6
|
|
|
5
7
|
const CODEX_DIR_NAME = '.codex';
|
|
6
8
|
const CONFIG_TOML_FILE = 'config.toml';
|
|
7
9
|
const AUTH_JSON_FILE = 'auth.json';
|
|
8
10
|
const BACKUP_DIR_NAME = 'akm-backups';
|
|
11
|
+
const BACKUP_LIMIT = 10;
|
|
12
|
+
let backupSequence = 0;
|
|
9
13
|
|
|
10
14
|
function resolveCodexHome() {
|
|
11
15
|
return process.env.CODEX_HOME || path.join(os.homedir(), CODEX_DIR_NAME);
|
|
@@ -21,7 +25,7 @@ function buildCodexPaths(codexHome = resolveCodexHome()) {
|
|
|
21
25
|
|
|
22
26
|
function timestampSuffix() {
|
|
23
27
|
const now = new Date();
|
|
24
|
-
const pad =
|
|
28
|
+
const pad = num => String(num).padStart(2, '0');
|
|
25
29
|
return [
|
|
26
30
|
now.getFullYear(),
|
|
27
31
|
pad(now.getMonth() + 1),
|
|
@@ -29,7 +33,8 @@ function timestampSuffix() {
|
|
|
29
33
|
'_',
|
|
30
34
|
pad(now.getHours()),
|
|
31
35
|
pad(now.getMinutes()),
|
|
32
|
-
pad(now.getSeconds())
|
|
36
|
+
pad(now.getSeconds()),
|
|
37
|
+
String(now.getMilliseconds()).padStart(3, '0')
|
|
33
38
|
].join('');
|
|
34
39
|
}
|
|
35
40
|
|
|
@@ -49,12 +54,23 @@ async function setSecurePermissions(filePath) {
|
|
|
49
54
|
}
|
|
50
55
|
}
|
|
51
56
|
|
|
57
|
+
async function setSecureDirectoryPermissions(directoryPath) {
|
|
58
|
+
if (process.platform === 'win32') {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
await fs.chmod(directoryPath, 0o700);
|
|
63
|
+
} catch {
|
|
64
|
+
// 权限收紧失败不应掩盖原始文件备份结果。
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
52
68
|
async function readCodexFiles(codexHome = resolveCodexHome()) {
|
|
53
69
|
const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
|
|
54
|
-
const configToml = await fs.pathExists(configTomlPath)
|
|
70
|
+
const configToml = (await fs.pathExists(configTomlPath))
|
|
55
71
|
? await fs.readFile(configTomlPath, 'utf8')
|
|
56
72
|
: null;
|
|
57
|
-
const authJson = await fs.pathExists(authJsonPath)
|
|
73
|
+
const authJson = (await fs.pathExists(authJsonPath))
|
|
58
74
|
? await fs.readFile(authJsonPath, 'utf8')
|
|
59
75
|
: null;
|
|
60
76
|
|
|
@@ -74,16 +90,34 @@ async function backupCodexFiles(codexHome = resolveCodexHome()) {
|
|
|
74
90
|
}
|
|
75
91
|
|
|
76
92
|
const backupRoot = path.join(codexHome, BACKUP_DIR_NAME);
|
|
77
|
-
const backupDir = path.join(
|
|
93
|
+
const backupDir = path.join(
|
|
94
|
+
backupRoot,
|
|
95
|
+
`backup-${timestampSuffix()}-${process.pid}-${backupSequence++}`
|
|
96
|
+
);
|
|
97
|
+
await fs.ensureDir(backupRoot);
|
|
98
|
+
await setSecureDirectoryPermissions(backupRoot);
|
|
78
99
|
await fs.ensureDir(backupDir);
|
|
100
|
+
await setSecureDirectoryPermissions(backupDir);
|
|
79
101
|
|
|
80
102
|
if (hasConfig) {
|
|
81
|
-
|
|
103
|
+
const backupConfigPath = path.join(backupDir, CONFIG_TOML_FILE);
|
|
104
|
+
await fs.copy(configTomlPath, backupConfigPath);
|
|
105
|
+
await setSecurePermissions(backupConfigPath);
|
|
82
106
|
}
|
|
83
107
|
if (hasAuth) {
|
|
84
|
-
|
|
108
|
+
const backupAuthPath = path.join(backupDir, AUTH_JSON_FILE);
|
|
109
|
+
await fs.copy(authJsonPath, backupAuthPath);
|
|
110
|
+
await setSecurePermissions(backupAuthPath);
|
|
85
111
|
}
|
|
86
112
|
|
|
113
|
+
const backupDirectories = (await fs.readdir(backupRoot))
|
|
114
|
+
.filter(name => name.startsWith('backup-'))
|
|
115
|
+
.sort()
|
|
116
|
+
.reverse();
|
|
117
|
+
await Promise.all(
|
|
118
|
+
backupDirectories.slice(BACKUP_LIMIT).map(name => fs.remove(path.join(backupRoot, name)))
|
|
119
|
+
);
|
|
120
|
+
|
|
87
121
|
return backupDir;
|
|
88
122
|
}
|
|
89
123
|
|
|
@@ -104,6 +138,95 @@ function removeTopLevelApiBaseUrl(configToml) {
|
|
|
104
138
|
return cleaned + rest;
|
|
105
139
|
}
|
|
106
140
|
|
|
141
|
+
/**
|
|
142
|
+
* 清理 AKM 写入的 model_provider 和对应 section,不修改用户自定义配置。
|
|
143
|
+
* @param {string} configToml - 现有的 config.toml 内容
|
|
144
|
+
* @returns {string} 清理后的 TOML 内容
|
|
145
|
+
*/
|
|
146
|
+
function removeAkmModelProvider(configToml) {
|
|
147
|
+
if (!configToml) return configToml;
|
|
148
|
+
|
|
149
|
+
const lines = configToml.split('\n');
|
|
150
|
+
const result = [];
|
|
151
|
+
let inSection = false;
|
|
152
|
+
let skipAkmSection = false;
|
|
153
|
+
|
|
154
|
+
for (const line of lines) {
|
|
155
|
+
const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);
|
|
156
|
+
if (sectionMatch) {
|
|
157
|
+
inSection = true;
|
|
158
|
+
skipAkmSection = sectionMatch[1] === 'model_providers.akm';
|
|
159
|
+
if (skipAkmSection) {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (skipAkmSection) {
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (!inSection && /^\s*model_provider\s*=\s*["']akm["']\s*(?:#.*)?$/.test(line)) {
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
result.push(line);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return result.join('\n');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function setTopLevelModelProvider(configToml, providerKey) {
|
|
179
|
+
const lines = configToml.split('\n');
|
|
180
|
+
let beforeFirstSection = true;
|
|
181
|
+
let replaced = false;
|
|
182
|
+
|
|
183
|
+
const updated = lines.map(line => {
|
|
184
|
+
if (/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(line)) {
|
|
185
|
+
beforeFirstSection = false;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (beforeFirstSection && /^\s*model_provider\s*=/.test(line)) {
|
|
189
|
+
replaced = true;
|
|
190
|
+
return line.replace(/^(\s*model_provider\s*=\s*)["'][^"'\n]*["']/, `$1"${providerKey}"`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return line;
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
return replaced ? updated.join('\n') : `model_provider = "${providerKey}"\n${configToml}`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function replaceAkmModelProviderSection(configToml, newSection) {
|
|
200
|
+
const lines = configToml.split('\n');
|
|
201
|
+
const result = [];
|
|
202
|
+
let skipAkmSection = false;
|
|
203
|
+
let inserted = false;
|
|
204
|
+
|
|
205
|
+
for (const line of lines) {
|
|
206
|
+
const sectionMatch = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);
|
|
207
|
+
if (sectionMatch) {
|
|
208
|
+
skipAkmSection = sectionMatch[1] === 'model_providers.akm';
|
|
209
|
+
if (skipAkmSection) {
|
|
210
|
+
if (!inserted) {
|
|
211
|
+
result.push(...newSection.split('\n'), '');
|
|
212
|
+
inserted = true;
|
|
213
|
+
}
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (!skipAkmSection) {
|
|
219
|
+
result.push(line);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (inserted) {
|
|
224
|
+
return result.join('\n');
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return result.join('\n').trimEnd() + '\n\n' + newSection + '\n';
|
|
228
|
+
}
|
|
229
|
+
|
|
107
230
|
/**
|
|
108
231
|
* 从 config.toml 中提取当前激活的 model_provider 的 base_url
|
|
109
232
|
* 读取 model_provider 字段,再从对应的 [model_providers.<key>] section 中取 base_url
|
|
@@ -147,20 +270,8 @@ function updateModelProvider(configToml, baseUrl) {
|
|
|
147
270
|
'requires_openai_auth = true'
|
|
148
271
|
].join('\n');
|
|
149
272
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
? configToml.replace(/^model_provider\s*=\s*["'][^"'\n]*["']/m, `model_provider = "${providerKey}"`)
|
|
153
|
-
: `model_provider = "${providerKey}"\n` + configToml;
|
|
154
|
-
|
|
155
|
-
// 替换或追加 [model_providers.akm] section
|
|
156
|
-
const sectionRegex = /\[model_providers\.akm\](?:\n(?!\[)[^\n]*)*\n?/;
|
|
157
|
-
if (result.match(sectionRegex)) {
|
|
158
|
-
result = result.replace(sectionRegex, newSection + '\n');
|
|
159
|
-
} else {
|
|
160
|
-
result = result.trimEnd() + '\n\n' + newSection + '\n';
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
return result;
|
|
273
|
+
const result = setTopLevelModelProvider(configToml, providerKey);
|
|
274
|
+
return replaceAkmModelProviderSection(result, newSection);
|
|
164
275
|
}
|
|
165
276
|
|
|
166
277
|
/**
|
|
@@ -168,7 +279,55 @@ function updateModelProvider(configToml, baseUrl) {
|
|
|
168
279
|
* @returns {string} auth.json 内容
|
|
169
280
|
*/
|
|
170
281
|
function buildAuthJson(apiKey) {
|
|
171
|
-
return JSON.stringify({ OPENAI_API_KEY: apiKey }, null, 2);
|
|
282
|
+
return JSON.stringify({ auth_mode: 'apikey', OPENAI_API_KEY: apiKey }, null, 2);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function readExistingAuthJson(authJsonPath) {
|
|
286
|
+
if (!(await fs.pathExists(authJsonPath))) {
|
|
287
|
+
return {};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
const data = await fs.readJson(authJsonPath);
|
|
292
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
293
|
+
throw new Error('认证文件必须是 JSON 对象');
|
|
294
|
+
}
|
|
295
|
+
return data;
|
|
296
|
+
} catch (error) {
|
|
297
|
+
throw new Error(`Codex auth.json 格式无效,已停止写入: ${error.message}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function readFileSnapshot(filePath) {
|
|
302
|
+
if (!(await fs.pathExists(filePath))) {
|
|
303
|
+
return { exists: false, content: null, mode: 0o600 };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const [content, stat] = await Promise.all([
|
|
307
|
+
fs.readFile(filePath),
|
|
308
|
+
fs.stat(filePath)
|
|
309
|
+
]);
|
|
310
|
+
return {
|
|
311
|
+
exists: true,
|
|
312
|
+
content,
|
|
313
|
+
mode: stat.mode & 0o777
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async function restoreFileSnapshot(filePath, snapshot) {
|
|
318
|
+
if (!snapshot.exists) {
|
|
319
|
+
await fs.remove(filePath);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
await writeFileAtomic(filePath, snapshot.content, { mode: snapshot.mode });
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async function rollbackCodexFiles(paths, snapshots) {
|
|
327
|
+
await Promise.all([
|
|
328
|
+
restoreFileSnapshot(paths.authJsonPath, snapshots.authJson),
|
|
329
|
+
restoreFileSnapshot(paths.configTomlPath, snapshots.configToml)
|
|
330
|
+
]);
|
|
172
331
|
}
|
|
173
332
|
|
|
174
333
|
/**
|
|
@@ -186,31 +345,60 @@ async function applyCodexConfig(config, options = {}) {
|
|
|
186
345
|
throw new Error('Codex 配置缺少 API Key');
|
|
187
346
|
}
|
|
188
347
|
|
|
348
|
+
if (config.baseUrl) {
|
|
349
|
+
const baseUrlError = validator.validateUrl(config.baseUrl);
|
|
350
|
+
if (baseUrlError) {
|
|
351
|
+
throw new Error(`Codex 基础 URL 无效: ${baseUrlError}`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
189
355
|
const codexHome = await ensureCodexHome(options.codexHome);
|
|
190
356
|
const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
|
|
191
357
|
|
|
192
|
-
|
|
358
|
+
const snapshots = {
|
|
359
|
+
authJson: await readFileSnapshot(authJsonPath),
|
|
360
|
+
configToml: await readFileSnapshot(configTomlPath)
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
// 所有旧文件必须在任何写入发生前完成校验和目标内容计算。
|
|
364
|
+
await readExistingAuthJson(authJsonPath);
|
|
193
365
|
const authJsonContent = buildAuthJson(config.authToken);
|
|
194
|
-
|
|
195
|
-
|
|
366
|
+
let nextConfigToml = null;
|
|
367
|
+
const existingToml = snapshots.configToml.exists
|
|
368
|
+
? snapshots.configToml.content.toString('utf8')
|
|
369
|
+
: '';
|
|
196
370
|
|
|
197
|
-
// 更新 config.toml:设置 model_provider + [model_providers.akm],清理旧的顶层 api_base_url
|
|
198
371
|
if (config.baseUrl) {
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
let updatedToml = removeTopLevelApiBaseUrl(existingToml);
|
|
203
|
-
updatedToml = updateModelProvider(updatedToml, config.baseUrl);
|
|
204
|
-
await fs.writeFile(configTomlPath, updatedToml, 'utf8');
|
|
205
|
-
await setSecurePermissions(configTomlPath);
|
|
206
|
-
} else if (await fs.pathExists(configTomlPath)) {
|
|
207
|
-
// 没有 baseUrl,只清理旧的顶层 api_base_url
|
|
208
|
-
const existingToml = await fs.readFile(configTomlPath, 'utf8');
|
|
209
|
-
const cleanedToml = removeTopLevelApiBaseUrl(existingToml);
|
|
372
|
+
nextConfigToml = updateModelProvider(removeTopLevelApiBaseUrl(existingToml), config.baseUrl);
|
|
373
|
+
} else if (snapshots.configToml.exists) {
|
|
374
|
+
const cleanedToml = removeAkmModelProvider(removeTopLevelApiBaseUrl(existingToml));
|
|
210
375
|
if (cleanedToml !== existingToml) {
|
|
211
|
-
|
|
376
|
+
nextConfigToml = cleanedToml;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// 修改用户 Codex 文件前保留最近备份,便于恢复登录态和自定义配置。
|
|
381
|
+
await backupCodexFiles(codexHome);
|
|
382
|
+
|
|
383
|
+
const writeFile = options.writeFile || writeFileAtomic;
|
|
384
|
+
try {
|
|
385
|
+
await writeFile(authJsonPath, authJsonContent, { encoding: 'utf8', mode: 0o600 });
|
|
386
|
+
await setSecurePermissions(authJsonPath);
|
|
387
|
+
|
|
388
|
+
if (nextConfigToml !== null) {
|
|
389
|
+
await writeFile(configTomlPath, nextConfigToml, { encoding: 'utf8', mode: 0o600 });
|
|
212
390
|
await setSecurePermissions(configTomlPath);
|
|
213
391
|
}
|
|
392
|
+
} catch (error) {
|
|
393
|
+
try {
|
|
394
|
+
await rollbackCodexFiles({ authJsonPath, configTomlPath }, snapshots);
|
|
395
|
+
} catch (rollbackError) {
|
|
396
|
+
throw new Error(
|
|
397
|
+
`应用 Codex 配置失败且回滚失败: ${error.message}; ${rollbackError.message}`,
|
|
398
|
+
{ cause: error }
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
throw new Error(`应用 Codex 配置失败,已恢复原文件: ${error.message}`, { cause: error });
|
|
214
402
|
}
|
|
215
403
|
|
|
216
404
|
return { codexHome };
|
|
@@ -223,6 +411,7 @@ module.exports = {
|
|
|
223
411
|
applyCodexConfig,
|
|
224
412
|
backupCodexFiles,
|
|
225
413
|
removeTopLevelApiBaseUrl,
|
|
414
|
+
removeAkmModelProvider,
|
|
226
415
|
extractBaseUrlFromConfigToml,
|
|
227
416
|
updateModelProvider,
|
|
228
417
|
buildAuthJson
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
const spawn = require('cross-spawn');
|
|
2
2
|
const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
|
|
3
3
|
const { applyCodexConfig } = require('./codex-files');
|
|
4
|
+
const { assertSupportedLaunchArgs } = require('./launch-args');
|
|
5
|
+
const { validator } = require('./validator');
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* 构建 Codex CLI 环境变量
|
|
@@ -10,6 +12,10 @@ const { applyCodexConfig } = require('./codex-files');
|
|
|
10
12
|
function buildCodexEnvVariables(config) {
|
|
11
13
|
const env = { ...process.env };
|
|
12
14
|
|
|
15
|
+
delete env.OPENAI_API_KEY;
|
|
16
|
+
delete env.OPENAI_BASE_URL;
|
|
17
|
+
delete env.OPENAI_MODEL;
|
|
18
|
+
|
|
13
19
|
try {
|
|
14
20
|
// Codex CLI 使用 OpenAI 环境变量
|
|
15
21
|
if (config.authToken) {
|
|
@@ -17,10 +23,11 @@ function buildCodexEnvVariables(config) {
|
|
|
17
23
|
}
|
|
18
24
|
|
|
19
25
|
if (config.baseUrl) {
|
|
26
|
+
const baseUrlError = validator.validateUrl(config.baseUrl);
|
|
27
|
+
if (baseUrlError) {
|
|
28
|
+
throw new Error(baseUrlError);
|
|
29
|
+
}
|
|
20
30
|
env.OPENAI_BASE_URL = sanitizeEnvValue(config.baseUrl);
|
|
21
|
-
} else {
|
|
22
|
-
// 未配置基础地址时必须清理父进程遗留值,避免切换到官方默认时仍走旧代理。
|
|
23
|
-
delete env.OPENAI_BASE_URL;
|
|
24
31
|
}
|
|
25
32
|
|
|
26
33
|
// 支持自定义模型
|
|
@@ -49,15 +56,16 @@ async function executeCodexWithEnv(config, launchArgs = []) {
|
|
|
49
56
|
throw new Error(`供应商 '${config.name}' 未配置 API Key,请使用 'akm edit ${config.name}' 添加`);
|
|
50
57
|
}
|
|
51
58
|
|
|
59
|
+
assertSupportedLaunchArgs('codex', launchArgs);
|
|
60
|
+
|
|
61
|
+
// 在写入 Codex 配置文件前完成全部输入校验。
|
|
62
|
+
const env = buildCodexEnvVariables(config);
|
|
63
|
+
|
|
52
64
|
// 写入 ~/.codex/config.toml 和 ~/.codex/auth.json
|
|
53
65
|
// 确保 Codex CLI 使用 API Key 认证方式
|
|
54
66
|
// 这样用户也可以直接运行 `codex` 命令而无需通过 akm
|
|
55
67
|
await applyCodexConfig(config);
|
|
56
68
|
|
|
57
|
-
// 同时设置环境变量,确保兼容性
|
|
58
|
-
// 环境变量优先级更高,作为双重保障
|
|
59
|
-
const env = buildCodexEnvVariables(config);
|
|
60
|
-
|
|
61
69
|
// 处理参数:子命令放前面,选项放后面
|
|
62
70
|
const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
|
|
63
71
|
const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
|
|
@@ -72,7 +80,7 @@ async function executeCodexWithEnv(config, launchArgs = []) {
|
|
|
72
80
|
const child = spawn('codex', args, {
|
|
73
81
|
stdio: 'inherit',
|
|
74
82
|
env,
|
|
75
|
-
shell:
|
|
83
|
+
shell: false
|
|
76
84
|
});
|
|
77
85
|
|
|
78
86
|
child.on('close', (code) => {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
async function mapWithConcurrency(items, limit, mapper) {
|
|
2
|
+
if (!Array.isArray(items)) {
|
|
3
|
+
throw new TypeError('items 必须是数组');
|
|
4
|
+
}
|
|
5
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
6
|
+
throw new TypeError('并发上限必须是正整数');
|
|
7
|
+
}
|
|
8
|
+
if (typeof mapper !== 'function') {
|
|
9
|
+
throw new TypeError('mapper 必须是函数');
|
|
10
|
+
}
|
|
11
|
+
if (items.length === 0) {
|
|
12
|
+
return [];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const results = new Array(items.length);
|
|
16
|
+
let nextIndex = 0;
|
|
17
|
+
|
|
18
|
+
async function worker() {
|
|
19
|
+
while (nextIndex < items.length) {
|
|
20
|
+
const currentIndex = nextIndex++;
|
|
21
|
+
results[currentIndex] = await mapper(items[currentIndex], currentIndex);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const workerCount = Math.min(limit, items.length);
|
|
26
|
+
await Promise.all(Array.from({ length: workerCount }, () => worker()));
|
|
27
|
+
return results;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = { mapWithConcurrency };
|
|
@@ -1,10 +1,25 @@
|
|
|
1
1
|
const spawn = require('cross-spawn');
|
|
2
2
|
const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
|
|
3
|
+
const { assertSupportedLaunchArgs } = require('./launch-args');
|
|
4
|
+
const { validator } = require('./validator');
|
|
3
5
|
|
|
4
6
|
function buildEnvVariables(config) {
|
|
5
7
|
const env = { ...process.env };
|
|
6
8
|
|
|
9
|
+
delete env.ANTHROPIC_API_KEY;
|
|
10
|
+
delete env.ANTHROPIC_AUTH_TOKEN;
|
|
11
|
+
delete env.ANTHROPIC_BASE_URL;
|
|
12
|
+
delete env.ANTHROPIC_MODEL;
|
|
13
|
+
delete env.ANTHROPIC_SMALL_FAST_MODEL;
|
|
14
|
+
|
|
7
15
|
try {
|
|
16
|
+
if (config.baseUrl) {
|
|
17
|
+
const baseUrlError = validator.validateUrl(config.baseUrl);
|
|
18
|
+
if (baseUrlError) {
|
|
19
|
+
throw new Error(baseUrlError);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
8
23
|
// Claude Code 配置
|
|
9
24
|
if (config.authMode === 'auth_token') {
|
|
10
25
|
if (config.baseUrl) {
|
|
@@ -35,6 +50,7 @@ function buildEnvVariables(config) {
|
|
|
35
50
|
}
|
|
36
51
|
|
|
37
52
|
async function executeWithEnv(config, launchArgs = []) {
|
|
53
|
+
assertSupportedLaunchArgs('claude', launchArgs);
|
|
38
54
|
const env = buildEnvVariables(config);
|
|
39
55
|
const args = [...launchArgs];
|
|
40
56
|
|
|
@@ -46,7 +62,7 @@ async function executeWithEnv(config, launchArgs = []) {
|
|
|
46
62
|
const child = spawn('claude', args, {
|
|
47
63
|
stdio: 'inherit',
|
|
48
64
|
env,
|
|
49
|
-
shell:
|
|
65
|
+
shell: false
|
|
50
66
|
});
|
|
51
67
|
|
|
52
68
|
child.on('close', (code) => {
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
const Ajv = require('ajv');
|
|
2
|
+
const { validator } = require('./validator');
|
|
3
|
+
const { assertSafeImportLaunchArgs } = require('./launch-args');
|
|
4
|
+
const { containsUnsafeTerminalCharacters, escapeTerminalText } = require('./terminal-format');
|
|
5
|
+
|
|
6
|
+
const MAX_PROVIDERS = 200;
|
|
7
|
+
|
|
8
|
+
const nullableString = { type: ['string', 'null'], maxLength: 100 };
|
|
9
|
+
const launchArgsSchema = {
|
|
10
|
+
type: 'array',
|
|
11
|
+
maxItems: 16,
|
|
12
|
+
uniqueItems: true,
|
|
13
|
+
items: { type: 'string', maxLength: 200 }
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const providerSchema = {
|
|
17
|
+
type: 'object',
|
|
18
|
+
additionalProperties: false,
|
|
19
|
+
properties: {
|
|
20
|
+
name: { type: 'string', maxLength: 100 },
|
|
21
|
+
displayName: nullableString,
|
|
22
|
+
alias: nullableString,
|
|
23
|
+
ideName: { enum: ['claude', 'codex'] },
|
|
24
|
+
authMode: { enum: ['api_key', 'api_token', 'auth_token', 'openai_api_key', null] },
|
|
25
|
+
authToken: { type: ['string', 'null'], maxLength: 16384 },
|
|
26
|
+
baseUrl: { type: ['string', 'null'], maxLength: 2048 },
|
|
27
|
+
models: {
|
|
28
|
+
type: ['object', 'null'],
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
properties: {
|
|
31
|
+
primary: nullableString,
|
|
32
|
+
smallFast: nullableString
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
launchArgs: launchArgsSchema,
|
|
36
|
+
lastUsedArgs: {
|
|
37
|
+
anyOf: [launchArgsSchema, { type: 'null' }]
|
|
38
|
+
},
|
|
39
|
+
current: { type: 'boolean' },
|
|
40
|
+
usageCount: { type: 'integer', minimum: 0 },
|
|
41
|
+
createdAt: nullableString,
|
|
42
|
+
lastUsed: nullableString,
|
|
43
|
+
importedAt: nullableString,
|
|
44
|
+
tokenExpiry: nullableString,
|
|
45
|
+
quota: {
|
|
46
|
+
type: ['object', 'null'],
|
|
47
|
+
additionalProperties: false,
|
|
48
|
+
properties: {
|
|
49
|
+
used: { type: 'number', minimum: 0 },
|
|
50
|
+
limit: { type: 'number', exclusiveMinimum: 0 }
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
stats: {
|
|
54
|
+
type: ['object', 'null'],
|
|
55
|
+
additionalProperties: false,
|
|
56
|
+
properties: {
|
|
57
|
+
totalSessions: { type: 'integer', minimum: 0 },
|
|
58
|
+
totalDurationMs: { type: 'number', minimum: 0 },
|
|
59
|
+
averageDurationMs: { type: 'number', minimum: 0 },
|
|
60
|
+
lastSessionDuration: { type: 'number', minimum: 0 },
|
|
61
|
+
firstUsed: nullableString
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const configSchema = {
|
|
68
|
+
type: 'object',
|
|
69
|
+
additionalProperties: false,
|
|
70
|
+
required: ['providers'],
|
|
71
|
+
properties: {
|
|
72
|
+
version: { type: 'string', maxLength: 20 },
|
|
73
|
+
currentProvider: { type: ['string', 'null'], minLength: 1, maxLength: 100 },
|
|
74
|
+
providers: {
|
|
75
|
+
type: 'object',
|
|
76
|
+
maxProperties: MAX_PROVIDERS,
|
|
77
|
+
additionalProperties: providerSchema
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const importSchema = {
|
|
83
|
+
...configSchema,
|
|
84
|
+
properties: {
|
|
85
|
+
...configSchema.properties,
|
|
86
|
+
exportedAt: { type: 'string', maxLength: 100 },
|
|
87
|
+
secretsIncluded: { type: 'boolean' },
|
|
88
|
+
providers: {
|
|
89
|
+
...configSchema.properties.providers,
|
|
90
|
+
minProperties: 1
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const ajv = new Ajv({ allErrors: true, allowUnionTypes: true });
|
|
96
|
+
const validateImportSchema = ajv.compile(importSchema);
|
|
97
|
+
const validateConfigSchema = ajv.compile(configSchema);
|
|
98
|
+
|
|
99
|
+
function formatSchemaErrors(errors = []) {
|
|
100
|
+
return errors.map(error => `${error.instancePath || '/'} ${error.message}`).join(';');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 校验并标准化从文件读取的配置
|
|
105
|
+
* @param {unknown} data - JSON 配置内容
|
|
106
|
+
* @returns {object} 标准化后的导入数据
|
|
107
|
+
*/
|
|
108
|
+
function validateAndNormalizeData(data, source) {
|
|
109
|
+
const schemaValidator = source === 'import' ? validateImportSchema : validateConfigSchema;
|
|
110
|
+
if (!schemaValidator(data)) {
|
|
111
|
+
throw new Error(`配置 Schema 校验失败: ${formatSchemaErrors(schemaValidator.errors)}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const normalizedProviders = {};
|
|
115
|
+
for (const [name, provider] of Object.entries(data.providers)) {
|
|
116
|
+
const safeName = escapeTerminalText(name);
|
|
117
|
+
const nameError = validator.validateName(name);
|
|
118
|
+
if (nameError) {
|
|
119
|
+
throw new Error(`供应商名称 "${safeName}" 无效: ${nameError}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const ideName = provider.ideName || 'claude';
|
|
123
|
+
const displayNameError = validator.validateDisplayName(provider.displayName);
|
|
124
|
+
if (displayNameError) {
|
|
125
|
+
throw new Error(`供应商 "${safeName}" 的显示名称无效: ${displayNameError}`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (provider.alias) {
|
|
129
|
+
const aliasError = validator.validateName(provider.alias);
|
|
130
|
+
if (aliasError) {
|
|
131
|
+
throw new Error(`供应商 "${safeName}" 的别名无效: ${aliasError}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const launchArgs = provider.launchArgs || [];
|
|
136
|
+
const lastUsedArgs = provider.lastUsedArgs || [];
|
|
137
|
+
|
|
138
|
+
// 本地配置、导入配置和交互式编辑必须共享同一套 URL 规则。
|
|
139
|
+
const baseUrlError = validator.validateUrl(provider.baseUrl, false);
|
|
140
|
+
if (baseUrlError) {
|
|
141
|
+
throw new Error(`供应商 "${safeName}" 的基础 URL 无效: ${baseUrlError}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (source === 'import') {
|
|
145
|
+
assertSafeImportLaunchArgs(ideName, launchArgs);
|
|
146
|
+
assertSafeImportLaunchArgs(ideName, lastUsedArgs);
|
|
147
|
+
if (typeof provider.authToken === 'string' && provider.authToken.includes('***')) {
|
|
148
|
+
throw new Error(`供应商 "${safeName}" 包含脱敏 Token,请重新设置密钥后再导入`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (ideName === 'claude' && provider.authMode === 'openai_api_key') {
|
|
153
|
+
throw new Error(`供应商 "${safeName}" 的认证模式与 IDE 类型不匹配`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (containsUnsafeTerminalCharacters(provider.authToken)) {
|
|
157
|
+
throw new Error(`供应商 "${safeName}" 的 Token 不能包含控制字符`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
normalizedProviders[name] = {
|
|
161
|
+
...provider,
|
|
162
|
+
name,
|
|
163
|
+
ideName,
|
|
164
|
+
authMode:
|
|
165
|
+
ideName === 'codex'
|
|
166
|
+
? null
|
|
167
|
+
: provider.authMode === 'api_token'
|
|
168
|
+
? 'auth_token'
|
|
169
|
+
: provider.authMode || 'api_key',
|
|
170
|
+
launchArgs,
|
|
171
|
+
lastUsedArgs: provider.lastUsedArgs === null ? null : lastUsedArgs
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (
|
|
176
|
+
data.currentProvider !== null &&
|
|
177
|
+
data.currentProvider !== undefined &&
|
|
178
|
+
!Object.prototype.hasOwnProperty.call(normalizedProviders, data.currentProvider)
|
|
179
|
+
) {
|
|
180
|
+
throw new Error(
|
|
181
|
+
`currentProvider 指向不存在的供应商: ${escapeTerminalText(data.currentProvider)}`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const currentProvider = data.currentProvider || null;
|
|
186
|
+
for (const [name, provider] of Object.entries(normalizedProviders)) {
|
|
187
|
+
provider.current = name === currentProvider;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
...data,
|
|
192
|
+
providers: normalizedProviders
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function validateAndNormalizeImportData(data) {
|
|
197
|
+
return validateAndNormalizeData(data, 'import');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function validateAndNormalizeConfigData(data) {
|
|
201
|
+
return validateAndNormalizeData(data, 'local');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = {
|
|
205
|
+
MAX_PROVIDERS,
|
|
206
|
+
configSchema,
|
|
207
|
+
importSchema,
|
|
208
|
+
validateAndNormalizeConfigData,
|
|
209
|
+
validateAndNormalizeImportData
|
|
210
|
+
};
|