@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
|
@@ -2,7 +2,8 @@ class ProviderEditQuestionsHelper {
|
|
|
2
2
|
static buildQuestions(provider, validator) {
|
|
3
3
|
const isCodex = provider.ideName === 'codex';
|
|
4
4
|
const questions = [
|
|
5
|
-
this.buildNameQuestion(provider, validator)
|
|
5
|
+
this.buildNameQuestion(provider, validator),
|
|
6
|
+
this.buildDisplayNameQuestion(provider, validator)
|
|
6
7
|
];
|
|
7
8
|
|
|
8
9
|
if (!isCodex) {
|
|
@@ -10,8 +11,8 @@ class ProviderEditQuestionsHelper {
|
|
|
10
11
|
}
|
|
11
12
|
|
|
12
13
|
questions.push(
|
|
13
|
-
this.buildBaseUrlQuestion(provider, isCodex),
|
|
14
|
-
this.buildAuthTokenQuestion(provider, isCodex)
|
|
14
|
+
this.buildBaseUrlQuestion(provider, isCodex, validator),
|
|
15
|
+
this.buildAuthTokenQuestion(provider, isCodex, validator)
|
|
15
16
|
);
|
|
16
17
|
|
|
17
18
|
return questions;
|
|
@@ -31,6 +32,19 @@ class ProviderEditQuestionsHelper {
|
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
34
|
|
|
35
|
+
static buildDisplayNameQuestion(provider, validator) {
|
|
36
|
+
return {
|
|
37
|
+
type: 'input',
|
|
38
|
+
name: 'displayName',
|
|
39
|
+
message: '请输入显示名称:',
|
|
40
|
+
default: provider.displayName || provider.name,
|
|
41
|
+
validate: input => {
|
|
42
|
+
if (typeof validator?.validateDisplayName !== 'function') return true;
|
|
43
|
+
return validator.validateDisplayName(input) || true;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
34
48
|
static buildClaudeQuestions(provider, validator) {
|
|
35
49
|
return [
|
|
36
50
|
{
|
|
@@ -72,17 +86,21 @@ class ProviderEditQuestionsHelper {
|
|
|
72
86
|
];
|
|
73
87
|
}
|
|
74
88
|
|
|
75
|
-
static buildBaseUrlQuestion(provider, isCodex) {
|
|
89
|
+
static buildBaseUrlQuestion(provider, isCodex, validator) {
|
|
76
90
|
return {
|
|
77
91
|
type: 'input',
|
|
78
92
|
name: 'baseUrl',
|
|
79
93
|
message: isCodex ? '基础URL (OPENAI_BASE_URL):' : '基础URL:',
|
|
80
94
|
default: provider.baseUrl,
|
|
81
|
-
prefillDefault: true
|
|
95
|
+
prefillDefault: true,
|
|
96
|
+
validate: input => {
|
|
97
|
+
if (typeof validator?.validateUrl !== 'function') return true;
|
|
98
|
+
return validator.validateUrl(input, false) || true;
|
|
99
|
+
}
|
|
82
100
|
};
|
|
83
101
|
}
|
|
84
102
|
|
|
85
|
-
static buildAuthTokenQuestion(provider, isCodex) {
|
|
103
|
+
static buildAuthTokenQuestion(provider, isCodex, validator) {
|
|
86
104
|
return {
|
|
87
105
|
type: 'input',
|
|
88
106
|
name: 'authToken',
|
|
@@ -94,7 +112,11 @@ class ProviderEditQuestionsHelper {
|
|
|
94
112
|
return `Token (${envVar}):`;
|
|
95
113
|
},
|
|
96
114
|
default: provider.authToken,
|
|
97
|
-
prefillDefault: true
|
|
115
|
+
prefillDefault: true,
|
|
116
|
+
validate: input => {
|
|
117
|
+
if (typeof validator?.validateToken !== 'function') return true;
|
|
118
|
+
return validator.validateToken(input) || true;
|
|
119
|
+
}
|
|
98
120
|
};
|
|
99
121
|
}
|
|
100
122
|
}
|
|
@@ -84,7 +84,7 @@ class ProviderManager {
|
|
|
84
84
|
async editProvider(providerName, onComplete) {
|
|
85
85
|
try {
|
|
86
86
|
await this.configManager.load();
|
|
87
|
-
|
|
87
|
+
const provider = this.configManager.getProvider(providerName);
|
|
88
88
|
|
|
89
89
|
if (!provider) {
|
|
90
90
|
Logger.error(`供应商 '${providerName}' 不存在`);
|
|
@@ -110,55 +110,54 @@ class ProviderManager {
|
|
|
110
110
|
throw error;
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
+
const originalConfig = this.configManager.config;
|
|
113
114
|
const originalName = provider.name;
|
|
114
115
|
const newName = answers.name;
|
|
115
116
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
await
|
|
119
|
-
const providersMap = this.configManager.config.providers;
|
|
120
|
-
|
|
121
|
-
if (providersMap[newName]) {
|
|
122
|
-
Logger.error(`供应商名称 '${newName}' 已存在,请使用其他名称`);
|
|
123
|
-
return await onComplete();
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
providersMap[newName] = {
|
|
127
|
-
...provider,
|
|
128
|
-
name: newName
|
|
129
|
-
};
|
|
130
|
-
|
|
131
|
-
delete providersMap[originalName];
|
|
132
|
-
|
|
133
|
-
if (this.configManager.config.currentProvider === originalName) {
|
|
134
|
-
this.configManager.config.currentProvider = newName;
|
|
135
|
-
providersMap[newName].current = true;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
provider = providersMap[newName];
|
|
117
|
+
if (newName !== originalName && originalConfig.providers[newName]) {
|
|
118
|
+
Logger.error(`供应商名称 '${newName}' 已存在,请使用其他名称`);
|
|
119
|
+
return await onComplete();
|
|
139
120
|
}
|
|
140
121
|
|
|
141
|
-
//
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
122
|
+
// 在内存中构造快照,校验和保存失败时不污染当前配置对象。
|
|
123
|
+
const updatedProvider = {
|
|
124
|
+
...provider,
|
|
125
|
+
name: newName,
|
|
126
|
+
displayName: answers.displayName || provider.displayName || newName,
|
|
127
|
+
baseUrl: answers.baseUrl || null,
|
|
128
|
+
authToken: answers.authToken,
|
|
129
|
+
launchArgs: Array.isArray(answers.launchArgs)
|
|
130
|
+
? answers.launchArgs
|
|
131
|
+
: (provider.launchArgs || [])
|
|
132
|
+
};
|
|
145
133
|
|
|
146
134
|
if (!isCodex) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
provider.models.smallFast = answers.smallFastModel || null;
|
|
135
|
+
updatedProvider.authMode = answers.authMode;
|
|
136
|
+
updatedProvider.models = {
|
|
137
|
+
...(provider.models || {}),
|
|
138
|
+
primary: answers.primaryModel || null,
|
|
139
|
+
smallFast: answers.smallFastModel || null
|
|
140
|
+
};
|
|
154
141
|
} else {
|
|
155
|
-
|
|
156
|
-
|
|
142
|
+
updatedProvider.authMode = null;
|
|
143
|
+
updatedProvider.models = null;
|
|
157
144
|
}
|
|
158
145
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
146
|
+
updatedProvider.ideName = isCodex ? 'codex' : 'claude';
|
|
147
|
+
|
|
148
|
+
const providers = { ...originalConfig.providers };
|
|
149
|
+
delete providers[originalName];
|
|
150
|
+
providers[newName] = updatedProvider;
|
|
151
|
+
const nextConfig = {
|
|
152
|
+
...originalConfig,
|
|
153
|
+
currentProvider:
|
|
154
|
+
originalConfig.currentProvider === originalName
|
|
155
|
+
? newName
|
|
156
|
+
: originalConfig.currentProvider,
|
|
157
|
+
providers
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
await this.configManager.save(nextConfig);
|
|
162
161
|
Logger.success(`供应商 '${newName}' 已更新`);
|
|
163
162
|
|
|
164
163
|
return await onComplete();
|
package/src/commands/switch.js
CHANGED
|
@@ -11,14 +11,10 @@ const { configManager } = require('../config');
|
|
|
11
11
|
const { Logger } = require('../utils/logger');
|
|
12
12
|
const { UIHelper } = require('../utils/ui-helper');
|
|
13
13
|
const { BaseCommand } = require('./BaseCommand');
|
|
14
|
-
const { validator } = require('../utils/validator');
|
|
15
14
|
const { ProviderStatusChecker } = require('../utils/provider-status-checker');
|
|
16
|
-
const { AUTH_MODE_DISPLAY, BASE_URL } = require('../constants');
|
|
17
15
|
const { StatusHelper } = require('./switch/status-helper');
|
|
18
16
|
const { LaunchArgsHelper } = require('./switch/launch-args-helper');
|
|
19
17
|
const { ProviderChoicesHelper } = require('./switch/provider-choices-helper');
|
|
20
|
-
const { ProviderDetailsHelper } = require('./switch/provider-details-helper');
|
|
21
|
-
const { ProviderEditQuestionsHelper } = require('./switch/provider-edit-questions-helper');
|
|
22
18
|
const { ensureClaudeSettingsCompatibility } = require('./switch/claude-settings-compatibility');
|
|
23
19
|
const { launchProviderProcess, markProviderAsCurrent } = require('./switch/provider-launcher');
|
|
24
20
|
const { ProviderManager } = require('./switch/provider-manager');
|
|
@@ -375,7 +371,8 @@ class EnvSwitcher extends BaseCommand {
|
|
|
375
371
|
switch (selection) {
|
|
376
372
|
case '__ADD__': {
|
|
377
373
|
const { registry } = require('../CommandRegistry');
|
|
378
|
-
|
|
374
|
+
await registry.executeCommand('add', { returnToParent: true });
|
|
375
|
+
return await this.showProviderSelection();
|
|
379
376
|
}
|
|
380
377
|
case '__MANAGE__':
|
|
381
378
|
return await this.showManageMenu();
|
|
@@ -468,8 +465,8 @@ class EnvSwitcher extends BaseCommand {
|
|
|
468
465
|
const searchResults = providers.filter(p => {
|
|
469
466
|
const q = answer.search.toLowerCase();
|
|
470
467
|
return p.name.toLowerCase().includes(q) ||
|
|
471
|
-
p.displayName.toLowerCase().includes(q) ||
|
|
472
|
-
(p.alias
|
|
468
|
+
(p.displayName || '').toLowerCase().includes(q) ||
|
|
469
|
+
(p.alias || '').toLowerCase().includes(q);
|
|
473
470
|
});
|
|
474
471
|
|
|
475
472
|
if (searchResults.length === 0) {
|
|
@@ -981,7 +978,11 @@ async function editCommand(providerName) {
|
|
|
981
978
|
const switcher = new EnvSwitcher();
|
|
982
979
|
|
|
983
980
|
try {
|
|
984
|
-
|
|
981
|
+
if (providerName) {
|
|
982
|
+
await switcher.editProvider(providerName);
|
|
983
|
+
} else {
|
|
984
|
+
await switcher.showManageMenu();
|
|
985
|
+
}
|
|
985
986
|
} finally {
|
|
986
987
|
// 确保资源清理
|
|
987
988
|
switcher.destroy();
|
package/src/config.js
CHANGED
|
@@ -2,6 +2,8 @@ const fs = require('fs-extra');
|
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const os = require('os');
|
|
4
4
|
const chalk = require('chalk');
|
|
5
|
+
const { writeJsonAtomic } = require('./utils/atomic-file');
|
|
6
|
+
const { validateAndNormalizeConfigData } = require('./utils/import-validator');
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* @typedef {Object} ProviderConfig
|
|
@@ -114,14 +116,14 @@ class ConfigManager {
|
|
|
114
116
|
let data;
|
|
115
117
|
try {
|
|
116
118
|
data = await fs.readJSON(this.configPath);
|
|
117
|
-
} catch
|
|
119
|
+
} catch {
|
|
118
120
|
// 配置文件损坏,创建备份并重置
|
|
119
121
|
const backupPath = `${this.configPath}.corrupted.${Date.now()}`;
|
|
120
122
|
await fs.copy(this.configPath, backupPath);
|
|
121
123
|
console.log(chalk.yellow('⚠️ 配置文件损坏,已备份到:'), backupPath);
|
|
122
124
|
|
|
123
125
|
this.config = this.getDefaultConfig();
|
|
124
|
-
await this._performSave();
|
|
126
|
+
await this._performSave(this.config, { skipConflictCheck: true });
|
|
125
127
|
this.isLoaded = true;
|
|
126
128
|
return this.config;
|
|
127
129
|
}
|
|
@@ -129,9 +131,9 @@ class ConfigManager {
|
|
|
129
131
|
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
130
132
|
// 配置文件被写成非对象内容时,重置为默认配置
|
|
131
133
|
this.config = this.getDefaultConfig();
|
|
132
|
-
await this._performSave();
|
|
134
|
+
await this._performSave(this.config, { skipConflictCheck: true });
|
|
133
135
|
} else {
|
|
134
|
-
this.config = { ...this.getDefaultConfig(), ...data };
|
|
136
|
+
this.config = validateAndNormalizeConfigData({ ...this.getDefaultConfig(), ...data });
|
|
135
137
|
}
|
|
136
138
|
|
|
137
139
|
// 迁移旧的认证模式
|
|
@@ -143,7 +145,7 @@ class ConfigManager {
|
|
|
143
145
|
this.lastModified = stat.mtime;
|
|
144
146
|
} else {
|
|
145
147
|
this.config = this.getDefaultConfig();
|
|
146
|
-
await this._performSave();
|
|
148
|
+
await this._performSave(this.config, { skipConflictCheck: true });
|
|
147
149
|
}
|
|
148
150
|
this.isLoaded = true;
|
|
149
151
|
return this.config;
|
|
@@ -151,7 +153,7 @@ class ConfigManager {
|
|
|
151
153
|
if (error.message.includes('Unexpected end of JSON input')) {
|
|
152
154
|
// 处理空文件或损坏的JSON文件
|
|
153
155
|
this.config = this.getDefaultConfig();
|
|
154
|
-
await this._performSave();
|
|
156
|
+
await this._performSave(this.config, { skipConflictCheck: true });
|
|
155
157
|
this.isLoaded = true;
|
|
156
158
|
return this.config;
|
|
157
159
|
}
|
|
@@ -172,17 +174,21 @@ class ConfigManager {
|
|
|
172
174
|
|
|
173
175
|
// 检查权限是否为 600 (仅所有者可读写) 或 400 (仅所有者可读)
|
|
174
176
|
if (mode !== 0o600 && mode !== 0o400) {
|
|
175
|
-
console.log(
|
|
177
|
+
console.log(
|
|
178
|
+
chalk.yellow('⚠️ 配置文件权限不安全:'),
|
|
179
|
+
mode.toString(8),
|
|
180
|
+
chalk.gray('建议: 0600')
|
|
181
|
+
);
|
|
176
182
|
|
|
177
183
|
try {
|
|
178
184
|
await fs.chmod(this.configPath, 0o600);
|
|
179
185
|
console.log(chalk.green('✅ 已自动修复文件权限为: 0600'));
|
|
180
|
-
} catch
|
|
186
|
+
} catch {
|
|
181
187
|
console.log(chalk.red('❌ 无法自动修复权限,请手动执行:'));
|
|
182
188
|
console.log(chalk.gray(` chmod 600 ${this.configPath}`));
|
|
183
189
|
}
|
|
184
190
|
}
|
|
185
|
-
} catch
|
|
191
|
+
} catch {
|
|
186
192
|
// 忽略权限检查错误,不影响主流程
|
|
187
193
|
}
|
|
188
194
|
}
|
|
@@ -208,12 +214,12 @@ class ConfigManager {
|
|
|
208
214
|
|
|
209
215
|
async checkIfModified() {
|
|
210
216
|
try {
|
|
211
|
-
if (!this.lastModified || !await fs.pathExists(this.configPath)) {
|
|
217
|
+
if (!this.lastModified || !(await fs.pathExists(this.configPath))) {
|
|
212
218
|
return true;
|
|
213
219
|
}
|
|
214
220
|
const stat = await fs.stat(this.configPath);
|
|
215
|
-
return stat.mtime
|
|
216
|
-
} catch
|
|
221
|
+
return stat.mtime.getTime() !== this.lastModified.getTime();
|
|
222
|
+
} catch {
|
|
217
223
|
return true; // 出错时重新加载
|
|
218
224
|
}
|
|
219
225
|
}
|
|
@@ -221,22 +227,17 @@ class ConfigManager {
|
|
|
221
227
|
async save(config = this.config) {
|
|
222
228
|
// 确保配置已加载
|
|
223
229
|
await this.ensureLoaded();
|
|
224
|
-
|
|
225
|
-
this.config = config;
|
|
226
|
-
}
|
|
227
|
-
return await this._performSave();
|
|
230
|
+
return await this._performSave(config);
|
|
228
231
|
}
|
|
229
232
|
|
|
230
|
-
async _performSave() {
|
|
233
|
+
async _performSave(config = this.config, options = {}) {
|
|
231
234
|
try {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
// 设置文件权限为 600 (仅所有者可读写)
|
|
237
|
-
if (process.platform !== 'win32') {
|
|
238
|
-
await fs.chmod(this.configPath, 0o600);
|
|
235
|
+
const normalizedConfig = validateAndNormalizeConfigData(config);
|
|
236
|
+
if (!options.skipConflictCheck) {
|
|
237
|
+
await this._assertConfigUnchanged();
|
|
239
238
|
}
|
|
239
|
+
await writeJsonAtomic(this.configPath, normalizedConfig, { spaces: 2, mode: 0o600 });
|
|
240
|
+
this.config = normalizedConfig;
|
|
240
241
|
|
|
241
242
|
// 更新最后修改时间
|
|
242
243
|
const stat = await fs.stat(this.configPath);
|
|
@@ -248,6 +249,21 @@ class ConfigManager {
|
|
|
248
249
|
}
|
|
249
250
|
}
|
|
250
251
|
|
|
252
|
+
async _assertConfigUnchanged() {
|
|
253
|
+
if (!this.lastModified) {
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (!(await fs.pathExists(this.configPath))) {
|
|
258
|
+
throw new Error('配置文件已被其他进程删除,请重新执行当前操作');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const stat = await fs.stat(this.configPath);
|
|
262
|
+
if (stat.mtime.getTime() !== this.lastModified.getTime()) {
|
|
263
|
+
throw new Error('配置文件已被其他进程修改,请重新执行当前操作以避免覆盖最新配置');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
251
267
|
// 确保配置已加载的辅助方法
|
|
252
268
|
async ensureLoaded() {
|
|
253
269
|
if (!this.isLoaded) {
|
|
@@ -268,14 +284,14 @@ class ConfigManager {
|
|
|
268
284
|
const updatedProviders = {};
|
|
269
285
|
|
|
270
286
|
if (current && providers[current]) {
|
|
271
|
-
keys.forEach(
|
|
287
|
+
keys.forEach(key => {
|
|
272
288
|
updatedProviders[key] = {
|
|
273
289
|
...providers[key],
|
|
274
290
|
current: key === current
|
|
275
291
|
};
|
|
276
292
|
});
|
|
277
293
|
} else {
|
|
278
|
-
keys.forEach(
|
|
294
|
+
keys.forEach(key => {
|
|
279
295
|
updatedProviders[key] = {
|
|
280
296
|
...providers[key],
|
|
281
297
|
current: false
|
|
@@ -303,16 +319,18 @@ class ConfigManager {
|
|
|
303
319
|
providerConfig.baseUrl !== undefined ? providerConfig.baseUrl : existing?.baseUrl
|
|
304
320
|
);
|
|
305
321
|
|
|
306
|
-
const authToken =
|
|
322
|
+
const authToken =
|
|
323
|
+
providerConfig.authToken !== undefined ? providerConfig.authToken : existing?.authToken;
|
|
307
324
|
|
|
308
325
|
const launchArgs = Array.isArray(providerConfig.launchArgs)
|
|
309
326
|
? providerConfig.launchArgs
|
|
310
|
-
:
|
|
327
|
+
: existing?.launchArgs || [];
|
|
311
328
|
|
|
312
329
|
// 处理别名
|
|
313
|
-
const alias =
|
|
314
|
-
|
|
315
|
-
|
|
330
|
+
const alias =
|
|
331
|
+
providerConfig.alias !== undefined
|
|
332
|
+
? this._normalizeOptionalString(providerConfig.alias)
|
|
333
|
+
: existing?.alias || null;
|
|
316
334
|
|
|
317
335
|
// 创建新的 provider 对象
|
|
318
336
|
const newProvider = {
|
|
@@ -333,12 +351,14 @@ class ConfigManager {
|
|
|
333
351
|
// Claude Code 特定字段
|
|
334
352
|
if (!isCodex) {
|
|
335
353
|
const authMode = providerConfig.authMode || existing?.authMode || 'api_key';
|
|
336
|
-
const primaryModel =
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
354
|
+
const primaryModel =
|
|
355
|
+
providerConfig.primaryModel !== undefined
|
|
356
|
+
? providerConfig.primaryModel
|
|
357
|
+
: (existing?.models?.primary ?? null);
|
|
358
|
+
const smallFastModel =
|
|
359
|
+
providerConfig.smallFastModel !== undefined
|
|
360
|
+
? providerConfig.smallFastModel
|
|
361
|
+
: (existing?.models?.smallFast ?? null);
|
|
342
362
|
|
|
343
363
|
newProvider.authMode = authMode;
|
|
344
364
|
newProvider.models = {
|
|
@@ -352,7 +372,8 @@ class ConfigManager {
|
|
|
352
372
|
}
|
|
353
373
|
|
|
354
374
|
// 如果是第一个供应商或设置为默认,则设为当前供应商
|
|
355
|
-
const shouldSetCurrent =
|
|
375
|
+
const shouldSetCurrent =
|
|
376
|
+
(!existing && Object.keys(this.config.providers).length === 0) || providerConfig.setAsDefault;
|
|
356
377
|
|
|
357
378
|
let newCurrentProvider = this.config.currentProvider;
|
|
358
379
|
if (shouldSetCurrent) {
|
|
@@ -384,10 +405,12 @@ class ConfigManager {
|
|
|
384
405
|
}
|
|
385
406
|
|
|
386
407
|
// 创建新的 providers 对象,排除要删除的供应商
|
|
387
|
-
const
|
|
408
|
+
const remainingProviders = { ...this.config.providers };
|
|
409
|
+
delete remainingProviders[name];
|
|
388
410
|
|
|
389
411
|
// 如果删除的是当前供应商,清空当前供应商
|
|
390
|
-
const newCurrentProvider =
|
|
412
|
+
const newCurrentProvider =
|
|
413
|
+
this.config.currentProvider === name ? null : this.config.currentProvider;
|
|
391
414
|
|
|
392
415
|
// 使用不可变方式更新 config
|
|
393
416
|
this.config = {
|
|
@@ -615,7 +638,8 @@ class ConfigManager {
|
|
|
615
638
|
|
|
616
639
|
// 最近使用时间权重 (30%)
|
|
617
640
|
if (provider.lastUsed) {
|
|
618
|
-
const daysSinceLastUse =
|
|
641
|
+
const daysSinceLastUse =
|
|
642
|
+
(Date.now() - new Date(provider.lastUsed).getTime()) / (1000 * 60 * 60 * 24);
|
|
619
643
|
// 越近使用分数越高,超过30天分数衰减
|
|
620
644
|
const recencyScore = Math.max(0, 30 - daysSinceLastUse) / 30;
|
|
621
645
|
score += recencyScore * 30;
|
|
@@ -641,9 +665,7 @@ class ConfigManager {
|
|
|
641
665
|
});
|
|
642
666
|
|
|
643
667
|
// 按推荐分数降序排序并限制数量
|
|
644
|
-
return scoredProviders
|
|
645
|
-
.sort((a, b) => b.recommendScore - a.recommendScore)
|
|
646
|
-
.slice(0, limit);
|
|
668
|
+
return scoredProviders.sort((a, b) => b.recommendScore - a.recommendScore).slice(0, limit);
|
|
647
669
|
}
|
|
648
670
|
|
|
649
671
|
getProvider(name) {
|
|
@@ -672,7 +694,8 @@ class ConfigManager {
|
|
|
672
694
|
|
|
673
695
|
// 再尝试按别名查找
|
|
674
696
|
const providerEntry = Object.entries(this.config.providers).find(
|
|
675
|
-
([_, provider]) =>
|
|
697
|
+
([_, provider]) =>
|
|
698
|
+
provider.alias && provider.alias.toLowerCase() === nameOrAlias.toLowerCase()
|
|
676
699
|
);
|
|
677
700
|
|
|
678
701
|
return providerEntry ? providerEntry[1] : null;
|
package/src/index.js
CHANGED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
const fs = require('fs-extra');
|
|
2
|
+
const nodeFs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
let tempSequence = 0;
|
|
6
|
+
|
|
7
|
+
function buildTempPath(filePath) {
|
|
8
|
+
const directory = path.dirname(filePath);
|
|
9
|
+
const fileName = path.basename(filePath);
|
|
10
|
+
return path.join(directory, `.${fileName}.${process.pid}.${Date.now()}.${tempSequence++}.tmp`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function writeFileAtomic(filePath, content, options = {}) {
|
|
14
|
+
const mode = options.mode ?? 0o600;
|
|
15
|
+
const encoding = options.encoding ?? (Buffer.isBuffer(content) ? undefined : 'utf8');
|
|
16
|
+
const tempPath = buildTempPath(filePath);
|
|
17
|
+
let handle;
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
handle = await nodeFs.promises.open(tempPath, 'wx', mode);
|
|
21
|
+
await handle.writeFile(content, encoding ? { encoding } : undefined);
|
|
22
|
+
await handle.sync();
|
|
23
|
+
await handle.close();
|
|
24
|
+
handle = null;
|
|
25
|
+
await nodeFs.promises.rename(tempPath, filePath);
|
|
26
|
+
if (process.platform !== 'win32') {
|
|
27
|
+
await nodeFs.promises.chmod(filePath, mode);
|
|
28
|
+
}
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (handle) {
|
|
31
|
+
await handle.close().catch(() => {});
|
|
32
|
+
}
|
|
33
|
+
await fs.remove(tempPath).catch(() => {});
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function writeJsonAtomic(filePath, data, options = {}) {
|
|
39
|
+
const spaces = options.spaces ?? 2;
|
|
40
|
+
const content = JSON.stringify(data, null, spaces);
|
|
41
|
+
await writeFileAtomic(filePath, content, {
|
|
42
|
+
encoding: 'utf8',
|
|
43
|
+
mode: options.mode ?? 0o600
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { writeFileAtomic, writeJsonAtomic };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const fs = require('fs-extra');
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const os = require('os');
|
|
4
|
+
const { writeJsonAtomic } = require('./atomic-file');
|
|
4
5
|
|
|
5
6
|
const CONFLICT_ENV_KEYS = [
|
|
6
7
|
'ANTHROPIC_API_KEY',
|
|
@@ -18,7 +19,7 @@ function unique(array) {
|
|
|
18
19
|
|
|
19
20
|
function timestampSuffix() {
|
|
20
21
|
const now = new Date();
|
|
21
|
-
const pad =
|
|
22
|
+
const pad = num => String(num).padStart(2, '0');
|
|
22
23
|
return [
|
|
23
24
|
now.getFullYear(),
|
|
24
25
|
pad(now.getMonth() + 1),
|
|
@@ -90,7 +91,7 @@ function detectConflictKeys(settings) {
|
|
|
90
91
|
return [];
|
|
91
92
|
}
|
|
92
93
|
|
|
93
|
-
return CONFLICT_ENV_KEYS.filter(
|
|
94
|
+
return CONFLICT_ENV_KEYS.filter(key => Object.prototype.hasOwnProperty.call(env, key));
|
|
94
95
|
}
|
|
95
96
|
|
|
96
97
|
async function backupSettingsFile(filePath) {
|
|
@@ -120,7 +121,7 @@ function clearConflictKeys(settings, keys) {
|
|
|
120
121
|
}
|
|
121
122
|
|
|
122
123
|
async function saveSettingsFile(filePath, data) {
|
|
123
|
-
await
|
|
124
|
+
await writeJsonAtomic(filePath, data, { spaces: 2, mode: 0o600 });
|
|
124
125
|
}
|
|
125
126
|
|
|
126
127
|
async function findSettingsConflict() {
|