@pikecode/api-key-manager 2.0.0 → 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 +444 -151
- package/bin/akm.js +340 -11
- package/package.json +29 -12
- package/src/CommandRegistry.js +58 -3
- package/src/commands/BaseCommand.js +68 -1
- package/src/commands/add/prompts.js +280 -0
- package/src/commands/add/providerSaver.js +74 -0
- package/src/commands/add/summaryPrinter.js +29 -0
- package/src/commands/add.js +54 -439
- package/src/commands/backup.js +396 -0
- package/src/commands/batch.js +313 -0
- package/src/commands/benchmark.js +323 -0
- package/src/commands/claude-clean.js +253 -0
- package/src/commands/clone.js +265 -0
- package/src/commands/current.js +89 -41
- package/src/commands/edit.js +3 -207
- package/src/commands/health.js +264 -0
- package/src/commands/list.js +120 -35
- package/src/commands/mcp.js +467 -0
- package/src/commands/remove.js +89 -26
- package/src/commands/stats.js +281 -0
- package/src/commands/switch/claude-settings-compatibility.js +113 -0
- package/src/commands/switch/launch-args-helper.js +84 -0
- package/src/commands/switch/provider-choices-helper.js +72 -0
- package/src/commands/switch/provider-details-helper.js +46 -0
- package/src/commands/switch/provider-edit-questions-helper.js +124 -0
- package/src/commands/switch/provider-launcher.js +20 -0
- package/src/commands/switch/provider-manager.js +214 -0
- package/src/commands/switch/status-helper.js +124 -0
- package/src/commands/switch/ui-screen-renderer.js +77 -0
- package/src/commands/switch.js +471 -958
- package/src/commands/validate.js +310 -0
- package/src/config.js +541 -55
- package/src/constants/index.js +234 -0
- package/src/constants/ui.js +108 -0
- package/src/index.js +11 -4
- package/src/navigation/EscNavigationManager.js +5 -5
- package/src/utils/atomic-file.js +47 -0
- package/src/utils/claude-settings.js +4 -4
- package/src/utils/codex-files.js +418 -0
- package/src/utils/codex-launcher.js +104 -0
- package/src/utils/concurrency.js +30 -0
- package/src/utils/config-opener.js +22 -2
- package/src/utils/env-launcher.js +50 -44
- package/src/utils/env-utils.js +52 -0
- package/src/utils/error-handler.js +27 -28
- package/src/utils/health-checker.js +350 -0
- package/src/utils/import-validator.js +210 -0
- package/src/utils/inquirer-setup.js +11 -0
- package/src/utils/launch-args.js +155 -0
- package/src/utils/logger.js +0 -1
- package/src/utils/provider-status-checker.js +211 -64
- package/src/utils/secrets.js +22 -0
- package/src/utils/shell-snippets.js +32 -0
- package/src/utils/terminal-format.js +22 -4
- package/src/utils/ui-helper.js +96 -86
- package/src/utils/update-checker.js +41 -12
- package/src/utils/validator.js +115 -88
- package/bin/cc.js +0 -101
- package/src/utils/storage.js +0 -55
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Benchmark Command
|
|
3
|
+
* 多供应商性能测试和对比
|
|
4
|
+
* @module commands/benchmark
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const chalk = require('chalk');
|
|
8
|
+
const fs = require('fs-extra');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const os = require('os');
|
|
11
|
+
const { configManager } = require('../config');
|
|
12
|
+
const { Logger } = require('../utils/logger');
|
|
13
|
+
const { ProviderStatusChecker } = require('../utils/provider-status-checker');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 性能测试器
|
|
17
|
+
*/
|
|
18
|
+
class BenchmarkRunner {
|
|
19
|
+
constructor() {
|
|
20
|
+
this.statusChecker = new ProviderStatusChecker();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 运行单个供应商的性能测试
|
|
25
|
+
* @param {Object} provider - 供应商配置
|
|
26
|
+
* @param {number} rounds - 测试轮数
|
|
27
|
+
* @returns {Promise<Object>} 测试结果
|
|
28
|
+
*/
|
|
29
|
+
async runTest(provider, rounds = 3) {
|
|
30
|
+
const results = {
|
|
31
|
+
provider: provider.name,
|
|
32
|
+
displayName: provider.displayName,
|
|
33
|
+
ideName: provider.ideName,
|
|
34
|
+
rounds: [],
|
|
35
|
+
average: 0,
|
|
36
|
+
min: Infinity,
|
|
37
|
+
max: 0,
|
|
38
|
+
successRate: 0,
|
|
39
|
+
errors: []
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
for (let i = 0; i < rounds; i++) {
|
|
43
|
+
try {
|
|
44
|
+
const status = await this.statusChecker.check(provider, { skipCache: true });
|
|
45
|
+
|
|
46
|
+
const result = {
|
|
47
|
+
round: i + 1,
|
|
48
|
+
latency: status.latency,
|
|
49
|
+
state: status.state,
|
|
50
|
+
success: status.state === 'online'
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
results.rounds.push(result);
|
|
54
|
+
|
|
55
|
+
if (status.latency !== null) {
|
|
56
|
+
results.min = Math.min(results.min, status.latency);
|
|
57
|
+
results.max = Math.max(results.max, status.latency);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 间隔一下避免频繁请求
|
|
61
|
+
if (i < rounds - 1) {
|
|
62
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
63
|
+
}
|
|
64
|
+
} catch (error) {
|
|
65
|
+
results.rounds.push({
|
|
66
|
+
round: i + 1,
|
|
67
|
+
latency: null,
|
|
68
|
+
state: 'error',
|
|
69
|
+
success: false,
|
|
70
|
+
error: error.message
|
|
71
|
+
});
|
|
72
|
+
results.errors.push(error.message);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 计算统计
|
|
77
|
+
const successfulRounds = results.rounds.filter(r => r.success);
|
|
78
|
+
results.successRate = (successfulRounds.length / rounds) * 100;
|
|
79
|
+
|
|
80
|
+
if (successfulRounds.length > 0) {
|
|
81
|
+
const totalLatency = successfulRounds.reduce((sum, r) => sum + r.latency, 0);
|
|
82
|
+
results.average = totalLatency / successfulRounds.length;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (results.min === Infinity) {
|
|
86
|
+
results.min = 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return results;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 运行多个供应商的性能测试
|
|
94
|
+
* @param {Array} providers - 供应商列表
|
|
95
|
+
* @param {Object} options - 选项
|
|
96
|
+
* @returns {Promise<Array>} 测试结果
|
|
97
|
+
*/
|
|
98
|
+
async runBenchmark(providers, options = {}) {
|
|
99
|
+
const { rounds = 3, parallel = false } = options;
|
|
100
|
+
const results = [];
|
|
101
|
+
|
|
102
|
+
if (parallel) {
|
|
103
|
+
// 并行测试
|
|
104
|
+
const testPromises = providers.map(provider => this.runTest(provider, rounds));
|
|
105
|
+
results.push(...await Promise.all(testPromises));
|
|
106
|
+
} else {
|
|
107
|
+
// 串行测试
|
|
108
|
+
for (const provider of providers) {
|
|
109
|
+
const result = await this.runTest(provider, rounds);
|
|
110
|
+
results.push(result);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 按平均延迟排序
|
|
115
|
+
results.sort((a, b) => {
|
|
116
|
+
if (a.successRate === 0) return 1;
|
|
117
|
+
if (b.successRate === 0) return -1;
|
|
118
|
+
return a.average - b.average;
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
return results;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 生成性能测试报告
|
|
126
|
+
* @param {Array} results - 测试结果
|
|
127
|
+
* @returns {string} 报告内容
|
|
128
|
+
*/
|
|
129
|
+
generateReport(results) {
|
|
130
|
+
const lines = [];
|
|
131
|
+
|
|
132
|
+
lines.push('# 供应商性能测试报告');
|
|
133
|
+
lines.push('');
|
|
134
|
+
lines.push(`测试时间: ${new Date().toLocaleString('zh-CN')}`);
|
|
135
|
+
lines.push(`测试供应商数: ${results.length}`);
|
|
136
|
+
lines.push(`测试轮数: ${results[0]?.rounds.length || 0}`);
|
|
137
|
+
lines.push('');
|
|
138
|
+
lines.push('---');
|
|
139
|
+
lines.push('');
|
|
140
|
+
|
|
141
|
+
// 排行榜
|
|
142
|
+
lines.push('## 性能排行榜');
|
|
143
|
+
lines.push('');
|
|
144
|
+
lines.push('| 排名 | 供应商 | 平均延迟 | 最小延迟 | 最大延迟 | 成功率 |');
|
|
145
|
+
lines.push('|------|--------|----------|----------|----------|--------|');
|
|
146
|
+
|
|
147
|
+
results.forEach((result, index) => {
|
|
148
|
+
const rank = index + 1;
|
|
149
|
+
const rankMedal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : rank;
|
|
150
|
+
const avgLatency = result.average > 0 ? `${Math.round(result.average)}ms` : 'N/A';
|
|
151
|
+
const minLatency = result.min > 0 ? `${Math.round(result.min)}ms` : 'N/A';
|
|
152
|
+
const maxLatency = result.max > 0 ? `${Math.round(result.max)}ms` : 'N/A';
|
|
153
|
+
const successRate = `${Math.round(result.successRate)}%`;
|
|
154
|
+
|
|
155
|
+
lines.push(`| ${rankMedal} | ${result.displayName} (${result.provider}) | ${avgLatency} | ${minLatency} | ${maxLatency} | ${successRate} |`);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
lines.push('');
|
|
159
|
+
lines.push('---');
|
|
160
|
+
lines.push('');
|
|
161
|
+
|
|
162
|
+
// 详细测试结果
|
|
163
|
+
lines.push('## 详细测试结果');
|
|
164
|
+
lines.push('');
|
|
165
|
+
|
|
166
|
+
results.forEach(result => {
|
|
167
|
+
lines.push(`### ${result.displayName} (${result.provider})`);
|
|
168
|
+
lines.push('');
|
|
169
|
+
lines.push(`- **IDE类型**: ${result.ideName === 'codex' ? 'Codex CLI' : 'Claude Code'}`);
|
|
170
|
+
lines.push(`- **平均延迟**: ${result.average > 0 ? Math.round(result.average) + 'ms' : 'N/A'}`);
|
|
171
|
+
lines.push(`- **延迟范围**: ${result.min > 0 ? Math.round(result.min) : 'N/A'}ms ~ ${result.max > 0 ? Math.round(result.max) : 'N/A'}ms`);
|
|
172
|
+
lines.push(`- **成功率**: ${Math.round(result.successRate)}%`);
|
|
173
|
+
lines.push('');
|
|
174
|
+
|
|
175
|
+
// 各轮测试结果
|
|
176
|
+
lines.push('**各轮测试结果:**');
|
|
177
|
+
lines.push('');
|
|
178
|
+
lines.push('| 轮次 | 状态 | 延迟 |');
|
|
179
|
+
lines.push('|------|------|------|');
|
|
180
|
+
|
|
181
|
+
result.rounds.forEach(round => {
|
|
182
|
+
const status = round.success ? '✓ 成功' : '✗ 失败';
|
|
183
|
+
const latency = round.latency !== null ? `${Math.round(round.latency)}ms` : 'N/A';
|
|
184
|
+
lines.push(`| ${round.round} | ${status} | ${latency} |`);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
if (result.errors.length > 0) {
|
|
188
|
+
lines.push('');
|
|
189
|
+
lines.push('**错误信息:**');
|
|
190
|
+
result.errors.forEach(error => {
|
|
191
|
+
lines.push(`- ${error}`);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
lines.push('');
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
lines.push('---');
|
|
199
|
+
lines.push('');
|
|
200
|
+
lines.push('_报告由 AKM (API Key Manager) 生成_');
|
|
201
|
+
|
|
202
|
+
return lines.join('\n');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 显示性能测试结果
|
|
207
|
+
* @param {Array} results - 测试结果
|
|
208
|
+
*/
|
|
209
|
+
displayResults(results) {
|
|
210
|
+
console.log(chalk.blue('\n📊 性能测试排行榜'));
|
|
211
|
+
console.log(chalk.gray('═'.repeat(80)));
|
|
212
|
+
console.log();
|
|
213
|
+
|
|
214
|
+
const currentProvider = configManager.getCurrentProvider();
|
|
215
|
+
|
|
216
|
+
results.forEach((result, index) => {
|
|
217
|
+
const rank = index + 1;
|
|
218
|
+
const rankMedal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : `${rank}.`;
|
|
219
|
+
const isCurrent = result.provider === currentProvider?.name;
|
|
220
|
+
const statusIcon = isCurrent ? '✅' : '🔹';
|
|
221
|
+
const ideTag = result.ideName === 'codex' ? chalk.cyan('[Codex]') : chalk.magenta('[Claude]');
|
|
222
|
+
const nameColor = isCurrent ? chalk.green : chalk.white;
|
|
223
|
+
|
|
224
|
+
console.log(`${rankMedal} ${statusIcon} ${ideTag} ${nameColor(result.provider)} (${result.displayName})`);
|
|
225
|
+
|
|
226
|
+
if (result.successRate > 0) {
|
|
227
|
+
const avgColor = result.average < 1000 ? chalk.green : result.average < 3000 ? chalk.yellow : chalk.red;
|
|
228
|
+
console.log(` 平均延迟: ${avgColor(Math.round(result.average) + 'ms')} | 范围: ${Math.round(result.min)}ms ~ ${Math.round(result.max)}ms | 成功率: ${chalk.cyan(Math.round(result.successRate) + '%')}`);
|
|
229
|
+
} else {
|
|
230
|
+
console.log(` ${chalk.red('所有测试失败')}`);
|
|
231
|
+
if (result.errors.length > 0) {
|
|
232
|
+
console.log(` 错误: ${chalk.red(result.errors[0])}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
console.log();
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
// 统计总结
|
|
240
|
+
console.log(chalk.gray('═'.repeat(80)));
|
|
241
|
+
console.log(chalk.blue('统计总结:'));
|
|
242
|
+
|
|
243
|
+
const successful = results.filter(r => r.successRate > 0);
|
|
244
|
+
const fastest = results[0];
|
|
245
|
+
const slowest = results[results.length - 1];
|
|
246
|
+
|
|
247
|
+
console.log(` 可用供应商: ${chalk.cyan(successful.length)}/${results.length}`);
|
|
248
|
+
if (successful.length > 0) {
|
|
249
|
+
console.log(` 最快: ${chalk.green(fastest.displayName)} (${Math.round(fastest.average)}ms)`);
|
|
250
|
+
if (successful.length > 1 && slowest.successRate > 0) {
|
|
251
|
+
console.log(` 最慢: ${chalk.yellow(slowest.displayName)} (${Math.round(slowest.average)}ms)`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 性能测试命令
|
|
259
|
+
* @param {Object} options - 选项
|
|
260
|
+
*/
|
|
261
|
+
async function benchmarkCommand(options = {}) {
|
|
262
|
+
try {
|
|
263
|
+
await configManager.ensureLoaded();
|
|
264
|
+
let providers = configManager.listProviders();
|
|
265
|
+
|
|
266
|
+
// 应用过滤器
|
|
267
|
+
if (options.filter === 'codex') {
|
|
268
|
+
providers = providers.filter(p => p.ideName === 'codex');
|
|
269
|
+
} else if (options.filter === 'claude') {
|
|
270
|
+
providers = providers.filter(p => p.ideName !== 'codex');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (providers.length === 0) {
|
|
274
|
+
Logger.warning('暂无可测试的供应商');
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const titleSuffix = options.filter === 'codex' ? ' (Codex CLI)' : (options.filter === 'claude' ? ' (Claude Code)' : '');
|
|
279
|
+
console.log(chalk.blue(`\n🏁 性能测试${titleSuffix}`));
|
|
280
|
+
console.log(chalk.gray('═'.repeat(80)));
|
|
281
|
+
console.log();
|
|
282
|
+
|
|
283
|
+
const rounds = options.rounds || 3;
|
|
284
|
+
const parallel = options.parallel || false;
|
|
285
|
+
|
|
286
|
+
console.log(chalk.yellow(`将测试 ${providers.length} 个供应商, 每个供应商 ${rounds} 轮`));
|
|
287
|
+
console.log(chalk.yellow(`测试模式: ${parallel ? '并行' : '串行'}`));
|
|
288
|
+
console.log();
|
|
289
|
+
|
|
290
|
+
const runner = new BenchmarkRunner();
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
const results = await runner.runBenchmark(providers, {
|
|
294
|
+
rounds,
|
|
295
|
+
parallel
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
// 显示结果
|
|
299
|
+
runner.displayResults(results);
|
|
300
|
+
|
|
301
|
+
// 保存报告
|
|
302
|
+
if (options.report) {
|
|
303
|
+
const reportContent = runner.generateReport(results);
|
|
304
|
+
const reportPath = options.report === true
|
|
305
|
+
? path.join(os.homedir(), `.akm-benchmark-${Date.now()}.md`)
|
|
306
|
+
: options.report;
|
|
307
|
+
|
|
308
|
+
await fs.writeFile(reportPath, reportContent, 'utf8');
|
|
309
|
+
console.log();
|
|
310
|
+
console.log(chalk.green(`✓ 报告已保存到: ${reportPath}`));
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
} catch (error) {
|
|
314
|
+
Logger.error(`性能测试失败: ${error.message}`);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
} catch (error) {
|
|
318
|
+
Logger.error(`性能测试执行失败: ${error.message}`);
|
|
319
|
+
throw error;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
module.exports = { benchmarkCommand, BenchmarkRunner };
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Clean Command
|
|
3
|
+
* 分析并清理 ~/.claude.json 文件
|
|
4
|
+
* @module commands/claude-clean
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const fs = require('fs-extra');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
const chalk = require('chalk');
|
|
11
|
+
const inquirer = require('inquirer');
|
|
12
|
+
const { Logger } = require('../utils/logger');
|
|
13
|
+
const { BaseCommand } = require('./BaseCommand');
|
|
14
|
+
|
|
15
|
+
const CLAUDE_JSON_PATH = path.join(os.homedir(), '.claude.json');
|
|
16
|
+
|
|
17
|
+
// 可清理的全局缓存字段(Claude Code 会自动重建)
|
|
18
|
+
const GLOBAL_CACHE_FIELDS = [
|
|
19
|
+
'cachedStatsigGates',
|
|
20
|
+
'cachedDynamicConfigs',
|
|
21
|
+
'cachedGrowthBookFeatures',
|
|
22
|
+
'clientDataCache'
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
// 可清理的项目统计字段(历史数据,不影响功能)
|
|
26
|
+
const PROJECT_STAT_FIELDS = [
|
|
27
|
+
'lastAPIDuration', 'lastCost', 'lastDuration',
|
|
28
|
+
'lastLinesAdded', 'lastLinesRemoved', 'lastSessionId',
|
|
29
|
+
'lastToolDuration', 'lastTotalCacheCreationInputTokens',
|
|
30
|
+
'lastTotalCacheReadInputTokens', 'lastTotalInputTokens',
|
|
31
|
+
'lastTotalOutputTokens', 'lastTotalWebSearchRequests',
|
|
32
|
+
'lastAPIDurationWithoutRetries', 'lastModelUsage',
|
|
33
|
+
'lastFpsAverage', 'lastFpsLow1Pct', 'lastSessionMetrics'
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
// 可清理的项目缓存字段(会自动重建)
|
|
37
|
+
const PROJECT_CACHE_FIELDS = [
|
|
38
|
+
'reactVulnerabilityCache',
|
|
39
|
+
'exampleFiles',
|
|
40
|
+
'exampleFilesGeneratedAt'
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
class ClaudeCleaner extends BaseCommand {
|
|
44
|
+
constructor() {
|
|
45
|
+
super();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 分析 ~/.claude.json 并显示清理建议
|
|
50
|
+
*/
|
|
51
|
+
async analyze() {
|
|
52
|
+
if (!await fs.pathExists(CLAUDE_JSON_PATH)) {
|
|
53
|
+
Logger.warning('~/.claude.json 不存在');
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const data = await fs.readJson(CLAUDE_JSON_PATH);
|
|
58
|
+
const totalSize = JSON.stringify(data).length;
|
|
59
|
+
const projects = data.projects || {};
|
|
60
|
+
const projectCount = Object.keys(projects).length;
|
|
61
|
+
|
|
62
|
+
console.log(chalk.bold('\n📊 ~/.claude.json 分析报告\n'));
|
|
63
|
+
console.log(chalk.gray(` 文件路径: ${CLAUDE_JSON_PATH}`));
|
|
64
|
+
console.log(chalk.gray(` 文件大小: ${this._formatSize(totalSize)}`));
|
|
65
|
+
console.log(chalk.gray(` 项目数量: ${projectCount} 个`));
|
|
66
|
+
console.log();
|
|
67
|
+
|
|
68
|
+
// 计算各方案可节省空间
|
|
69
|
+
const globalCacheSize = this._calcFieldsSize(data, GLOBAL_CACHE_FIELDS);
|
|
70
|
+
const statSize = this._calcProjectFieldsSize(projects, PROJECT_STAT_FIELDS);
|
|
71
|
+
const projCacheSize = this._calcProjectFieldsSize(projects, PROJECT_CACHE_FIELDS);
|
|
72
|
+
const staleProjects = this._findStaleProjects(projects);
|
|
73
|
+
const staleSize = staleProjects.reduce((sum, p) => sum + JSON.stringify(projects[p]).length, 0);
|
|
74
|
+
|
|
75
|
+
console.log(chalk.bold(' 清理方案预估:'));
|
|
76
|
+
console.log(chalk.green(` ✦ 保守清理 - 清理全局缓存 节省 ${this._formatSize(globalCacheSize)}`));
|
|
77
|
+
console.log(chalk.yellow(` ✦ 中等清理 - 清理缓存 + 项目统计 节省 ${this._formatSize(globalCacheSize + statSize)}`));
|
|
78
|
+
console.log(chalk.red(` ✦ 激进清理 - 清理所有 + 删除过期项目 节省 ${this._formatSize(globalCacheSize + statSize + projCacheSize + staleSize)}`));
|
|
79
|
+
console.log();
|
|
80
|
+
|
|
81
|
+
if (staleProjects.length > 0) {
|
|
82
|
+
console.log(chalk.gray(` 过期项目(路径不存在): ${staleProjects.length} 个`));
|
|
83
|
+
staleProjects.forEach(p => console.log(chalk.gray(` - ${p}`)));
|
|
84
|
+
console.log();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
console.log(chalk.gray(' 运行 akm claude clean 执行清理'));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 交互式清理
|
|
92
|
+
*/
|
|
93
|
+
async clean() {
|
|
94
|
+
if (!await fs.pathExists(CLAUDE_JSON_PATH)) {
|
|
95
|
+
Logger.warning('~/.claude.json 不存在');
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const data = await fs.readJson(CLAUDE_JSON_PATH);
|
|
100
|
+
const totalSize = JSON.stringify(data).length;
|
|
101
|
+
const projects = data.projects || {};
|
|
102
|
+
|
|
103
|
+
const globalCacheSize = this._calcFieldsSize(data, GLOBAL_CACHE_FIELDS);
|
|
104
|
+
const statSize = this._calcProjectFieldsSize(projects, PROJECT_STAT_FIELDS);
|
|
105
|
+
const projCacheSize = this._calcProjectFieldsSize(projects, PROJECT_CACHE_FIELDS);
|
|
106
|
+
const staleProjects = this._findStaleProjects(projects);
|
|
107
|
+
const staleSize = staleProjects.reduce((sum, p) => sum + JSON.stringify(projects[p]).length, 0);
|
|
108
|
+
|
|
109
|
+
console.log(chalk.bold('\n🧹 清理 ~/.claude.json\n'));
|
|
110
|
+
console.log(chalk.gray(` 当前大小: ${this._formatSize(totalSize)}`));
|
|
111
|
+
console.log();
|
|
112
|
+
|
|
113
|
+
let selection;
|
|
114
|
+
try {
|
|
115
|
+
selection = await this.prompt([
|
|
116
|
+
{
|
|
117
|
+
type: 'list',
|
|
118
|
+
name: 'mode',
|
|
119
|
+
message: '选择清理方案:',
|
|
120
|
+
choices: [
|
|
121
|
+
{
|
|
122
|
+
name: `保守清理 - 只清理全局缓存 ${chalk.green('(节省 ' + this._formatSize(globalCacheSize) + ')')}`,
|
|
123
|
+
value: 'conservative'
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
name: `中等清理 - 清理缓存 + 项目统计 ${chalk.yellow('(节省 ' + this._formatSize(globalCacheSize + statSize) + ')')}`,
|
|
127
|
+
value: 'moderate'
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
name: `激进清理 - 清理所有 + 删除过期项目 ${chalk.red('(节省 ' + this._formatSize(globalCacheSize + statSize + projCacheSize + staleSize) + ')')}`,
|
|
131
|
+
value: 'aggressive'
|
|
132
|
+
},
|
|
133
|
+
new inquirer.Separator(),
|
|
134
|
+
{ name: '取消', value: null }
|
|
135
|
+
]
|
|
136
|
+
}
|
|
137
|
+
]);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (this.isEscCancelled(error)) return;
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (!selection.mode) {
|
|
144
|
+
Logger.info('操作已取消。');
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 二次确认
|
|
149
|
+
let confirm;
|
|
150
|
+
try {
|
|
151
|
+
confirm = await this.prompt([
|
|
152
|
+
{
|
|
153
|
+
type: 'confirm',
|
|
154
|
+
name: 'ok',
|
|
155
|
+
message: `确认执行${selection.mode === 'conservative' ? '保守' : selection.mode === 'moderate' ? '中等' : '激进'}清理?(会自动备份)`,
|
|
156
|
+
default: false
|
|
157
|
+
}
|
|
158
|
+
]);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (this.isEscCancelled(error)) return;
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (!confirm.ok) {
|
|
165
|
+
Logger.info('操作已取消。');
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 备份
|
|
170
|
+
const backupPath = CLAUDE_JSON_PATH + `.backup-${Date.now()}`;
|
|
171
|
+
await fs.copy(CLAUDE_JSON_PATH, backupPath);
|
|
172
|
+
Logger.success(`已备份到: ${backupPath}`);
|
|
173
|
+
|
|
174
|
+
// 执行清理
|
|
175
|
+
const cleaned = JSON.parse(JSON.stringify(data)); // 深拷贝
|
|
176
|
+
|
|
177
|
+
// 所有方案都清理全局缓存
|
|
178
|
+
GLOBAL_CACHE_FIELDS.forEach(f => { delete cleaned[f]; });
|
|
179
|
+
|
|
180
|
+
if (selection.mode === 'moderate' || selection.mode === 'aggressive') {
|
|
181
|
+
// 清理项目统计
|
|
182
|
+
Object.keys(cleaned.projects || {}).forEach(p => {
|
|
183
|
+
PROJECT_STAT_FIELDS.forEach(f => { delete cleaned.projects[p][f]; });
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (selection.mode === 'aggressive') {
|
|
188
|
+
// 清理项目缓存
|
|
189
|
+
Object.keys(cleaned.projects || {}).forEach(p => {
|
|
190
|
+
PROJECT_CACHE_FIELDS.forEach(f => { delete cleaned.projects[p][f]; });
|
|
191
|
+
});
|
|
192
|
+
// 删除过期项目
|
|
193
|
+
staleProjects.forEach(p => { delete cleaned.projects[p]; });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
await fs.writeJson(CLAUDE_JSON_PATH, cleaned, { spaces: 2 });
|
|
197
|
+
|
|
198
|
+
const newSize = JSON.stringify(cleaned).length;
|
|
199
|
+
const saved = totalSize - newSize;
|
|
200
|
+
|
|
201
|
+
Logger.success('清理完成!');
|
|
202
|
+
console.log(chalk.gray(` 清理前: ${this._formatSize(totalSize)}`));
|
|
203
|
+
console.log(chalk.gray(` 清理后: ${this._formatSize(newSize)}`));
|
|
204
|
+
console.log(chalk.green(` 节省了: ${this._formatSize(saved)} (${((saved / totalSize) * 100).toFixed(1)}%)`));
|
|
205
|
+
if (selection.mode === 'aggressive' && staleProjects.length > 0) {
|
|
206
|
+
console.log(chalk.gray(` 删除过期项目: ${staleProjects.length} 个`));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
_calcFieldsSize(obj, fields) {
|
|
211
|
+
return fields.reduce((sum, f) => {
|
|
212
|
+
return sum + (obj[f] !== undefined ? JSON.stringify(obj[f]).length : 0);
|
|
213
|
+
}, 0);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
_calcProjectFieldsSize(projects, fields) {
|
|
217
|
+
let total = 0;
|
|
218
|
+
Object.values(projects).forEach(proj => {
|
|
219
|
+
fields.forEach(f => {
|
|
220
|
+
if (proj[f] !== undefined) total += JSON.stringify(proj[f]).length;
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
return total;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
_findStaleProjects(projects) {
|
|
227
|
+
return Object.keys(projects).filter(p => !fs.pathExistsSync('/' + p));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
_formatSize(bytes) {
|
|
231
|
+
if (bytes < 1024) return bytes + ' B';
|
|
232
|
+
return (bytes / 1024).toFixed(1) + ' KB';
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function claudeCleanCommand(subcommand) {
|
|
237
|
+
const cleaner = new ClaudeCleaner();
|
|
238
|
+
try {
|
|
239
|
+
if (subcommand === 'analyze') {
|
|
240
|
+
await cleaner.analyze();
|
|
241
|
+
} else {
|
|
242
|
+
await cleaner.clean();
|
|
243
|
+
}
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (!cleaner.isEscCancelled(error)) {
|
|
246
|
+
Logger.error(`操作失败: ${error.message}`);
|
|
247
|
+
}
|
|
248
|
+
} finally {
|
|
249
|
+
cleaner.destroy();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
module.exports = { claudeCleanCommand, ClaudeCleaner };
|