@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.
Files changed (60) hide show
  1. package/README.md +444 -151
  2. package/bin/akm.js +340 -11
  3. package/package.json +29 -12
  4. package/src/CommandRegistry.js +58 -3
  5. package/src/commands/BaseCommand.js +68 -1
  6. package/src/commands/add/prompts.js +280 -0
  7. package/src/commands/add/providerSaver.js +74 -0
  8. package/src/commands/add/summaryPrinter.js +29 -0
  9. package/src/commands/add.js +54 -439
  10. package/src/commands/backup.js +396 -0
  11. package/src/commands/batch.js +313 -0
  12. package/src/commands/benchmark.js +323 -0
  13. package/src/commands/claude-clean.js +253 -0
  14. package/src/commands/clone.js +265 -0
  15. package/src/commands/current.js +89 -41
  16. package/src/commands/edit.js +3 -207
  17. package/src/commands/health.js +264 -0
  18. package/src/commands/list.js +120 -35
  19. package/src/commands/mcp.js +467 -0
  20. package/src/commands/remove.js +89 -26
  21. package/src/commands/stats.js +281 -0
  22. package/src/commands/switch/claude-settings-compatibility.js +113 -0
  23. package/src/commands/switch/launch-args-helper.js +84 -0
  24. package/src/commands/switch/provider-choices-helper.js +72 -0
  25. package/src/commands/switch/provider-details-helper.js +46 -0
  26. package/src/commands/switch/provider-edit-questions-helper.js +124 -0
  27. package/src/commands/switch/provider-launcher.js +20 -0
  28. package/src/commands/switch/provider-manager.js +214 -0
  29. package/src/commands/switch/status-helper.js +124 -0
  30. package/src/commands/switch/ui-screen-renderer.js +77 -0
  31. package/src/commands/switch.js +471 -958
  32. package/src/commands/validate.js +310 -0
  33. package/src/config.js +541 -55
  34. package/src/constants/index.js +234 -0
  35. package/src/constants/ui.js +108 -0
  36. package/src/index.js +11 -4
  37. package/src/navigation/EscNavigationManager.js +5 -5
  38. package/src/utils/atomic-file.js +47 -0
  39. package/src/utils/claude-settings.js +4 -4
  40. package/src/utils/codex-files.js +418 -0
  41. package/src/utils/codex-launcher.js +104 -0
  42. package/src/utils/concurrency.js +30 -0
  43. package/src/utils/config-opener.js +22 -2
  44. package/src/utils/env-launcher.js +50 -44
  45. package/src/utils/env-utils.js +52 -0
  46. package/src/utils/error-handler.js +27 -28
  47. package/src/utils/health-checker.js +350 -0
  48. package/src/utils/import-validator.js +210 -0
  49. package/src/utils/inquirer-setup.js +11 -0
  50. package/src/utils/launch-args.js +155 -0
  51. package/src/utils/logger.js +0 -1
  52. package/src/utils/provider-status-checker.js +211 -64
  53. package/src/utils/secrets.js +22 -0
  54. package/src/utils/shell-snippets.js +32 -0
  55. package/src/utils/terminal-format.js +22 -4
  56. package/src/utils/ui-helper.js +96 -86
  57. package/src/utils/update-checker.js +41 -12
  58. package/src/utils/validator.js +115 -88
  59. package/bin/cc.js +0 -101
  60. package/src/utils/storage.js +0 -55
@@ -1,23 +1,117 @@
1
- const { Anthropic, APIConnectionTimeoutError, APIConnectionError, APIError } = require('@anthropic-ai/sdk');
1
+ const {
2
+ Anthropic,
3
+ APIConnectionTimeoutError,
4
+ APIConnectionError,
5
+ APIError
6
+ } = require('@anthropic-ai/sdk');
7
+ const crypto = require('crypto');
8
+ const { API_CONFIG } = require('../constants');
9
+ const { validator } = require('./validator');
10
+ const { mapWithConcurrency } = require('./concurrency');
2
11
 
12
+ const STATUS_CACHE_MAX = 100;
13
+
14
+ // 状态缓存
15
+ const statusCache = new Map();
16
+
17
+ /**
18
+ * @typedef {Object} StatusResult
19
+ * @property {string} status - 状态 ('online', 'offline', 'degraded', 'pending', 'unknown')
20
+ * @property {string} message - 状态消息
21
+ * @property {number|null} responseTime - 响应时间(毫秒)
22
+ */
23
+
24
+ /**
25
+ * 供应商状态检查器
26
+ * 检查 API 供应商的可用性和响应时间
27
+ */
3
28
  class ProviderStatusChecker {
29
+ /**
30
+ * 创建状态检查器实例
31
+ * @param {Object} [options={}] - 配置选项
32
+ * @param {number} [options.timeout] - 请求超时时间
33
+ * @param {string} [options.testMessage] - 测试消息
34
+ * @param {number} [options.maxTokens] - 最大 Token 数
35
+ * @param {number} [options.cacheTTL] - 缓存过期时间
36
+ */
4
37
  constructor(options = {}) {
5
- this.timeout = options.timeout ?? 5000;
6
- this.testMessage = options.testMessage ?? '你好';
7
- this.maxTokens = options.maxTokens ?? 32;
8
- this.defaultModel = 'claude-haiku-4-5-20251001';
38
+ this.timeout = options.timeout ?? API_CONFIG.DEFAULT_TIMEOUT;
39
+ this.testMessage = options.testMessage ?? API_CONFIG.TEST_MESSAGE;
40
+ this.maxTokens = options.maxTokens ?? API_CONFIG.MAX_TOKENS;
41
+ this.defaultModel = API_CONFIG.DEFAULT_MODEL;
42
+ this.cacheTTL = options.cacheTTL ?? API_CONFIG.CACHE_TTL;
43
+ this.maxConcurrency = options.maxConcurrency ?? 4;
44
+ }
45
+
46
+ _getCacheKey(provider) {
47
+ const tokenFingerprint = crypto
48
+ .createHash('sha256')
49
+ .update(String(provider.authToken || ''))
50
+ .digest('hex')
51
+ .slice(0, 16);
52
+ const model = provider.models?.primary || provider.models?.smallFast || this.defaultModel;
53
+ return JSON.stringify([
54
+ provider.name,
55
+ provider.ideName || 'claude',
56
+ provider.authMode,
57
+ provider.baseUrl || '',
58
+ model,
59
+ tokenFingerprint
60
+ ]);
61
+ }
62
+
63
+ _getCachedStatus(provider) {
64
+ const key = this._getCacheKey(provider);
65
+ const cached = statusCache.get(key);
66
+ if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
67
+ return cached.status;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ _setCachedStatus(provider, status) {
73
+ const key = this._getCacheKey(provider);
74
+ if (statusCache.size >= STATUS_CACHE_MAX) {
75
+ const oldest = [...statusCache.keys()].slice(0, 20);
76
+ oldest.forEach(k => statusCache.delete(k));
77
+ }
78
+ statusCache.set(key, { status, timestamp: Date.now() });
9
79
  }
10
80
 
11
- async check(provider) {
81
+ clearCache() {
82
+ statusCache.clear();
83
+ }
84
+
85
+ async check(provider, options = {}) {
12
86
  if (!provider) {
13
87
  return this._result('unknown', '未找到配置', null);
14
88
  }
15
89
 
16
- if (provider.authMode === 'oauth_token') {
17
- return this._result('unknown', '暂不支持 OAuth 令牌检测', null);
90
+ const baseUrlError = validator.validateUrl(provider.baseUrl, false);
91
+ if (baseUrlError) {
92
+ return this._result('unknown', `基础 URL 无效: ${baseUrlError}`, null);
93
+ }
94
+
95
+ // 检查缓存(除非明确跳过)
96
+ if (!options.skipCache) {
97
+ const cached = this._getCachedStatus(provider);
98
+ if (cached) {
99
+ return cached;
100
+ }
101
+ }
102
+
103
+ if (provider.ideName === 'codex') {
104
+ const result = await this._checkCodex(provider);
105
+ this._setCachedStatus(provider, result);
106
+ return result;
18
107
  }
19
108
 
20
- if (!provider.baseUrl) {
109
+ // auth_token 模式可留空 baseUrl(使用官方默认 API)
110
+ // api_key 模式需要 baseUrl(用于自定义端点/代理)
111
+ if (provider.authMode === 'auth_token' && !provider.baseUrl) {
112
+ // 对于官方 Anthropic API 的 auth_token 模式,不需要 baseUrl
113
+ // 直接使用官方 API
114
+ } else if (!provider.baseUrl && provider.authMode !== 'auth_token') {
21
115
  return this._result('unknown', '未配置基础地址', null);
22
116
  }
23
117
 
@@ -27,48 +121,57 @@ class ProviderStatusChecker {
27
121
 
28
122
  const model = this._resolveModel(provider);
29
123
  try {
30
- const client = this._createClient(provider);
31
- if (!client) {
32
- return this._result('unknown', '认证模式不受支持', null);
33
- }
124
+ const performCheck = async () => {
125
+ const client = this._createClient(provider);
126
+ if (!client) {
127
+ return this._result('unknown', '认证模式不受支持', null);
128
+ }
34
129
 
35
- const start = process.hrtime.bigint();
36
- const response = await client.messages.create({
37
- model,
38
- max_tokens: this.maxTokens,
39
- messages: [
130
+ const start = process.hrtime.bigint();
131
+ const response = await client.messages.create(
40
132
  {
41
- role: 'user',
42
- content: this.testMessage
43
- }
44
- ]
45
- }, { timeout: this.timeout });
46
- const latency = Number(process.hrtime.bigint() - start) / 1e6;
133
+ model,
134
+ max_tokens: this.maxTokens,
135
+ messages: [
136
+ {
137
+ role: 'user',
138
+ content: this.testMessage
139
+ }
140
+ ]
141
+ },
142
+ { timeout: this.timeout }
143
+ );
144
+ const latency = Number(process.hrtime.bigint() - start) / 1e6;
47
145
 
48
- const text = this._extractText(response);
49
- if (!text) {
50
- return this._result('online', `可用 ${latency.toFixed(0)}ms (无文本响应)`, latency);
51
- }
146
+ const text = this._extractText(response);
147
+ if (!text) {
148
+ return this._result('online', `可用 ${latency.toFixed(0)}ms (无文本响应)`, latency);
149
+ }
52
150
 
53
- return this._result('online', `可用 ${latency.toFixed(0)}ms`, latency);
151
+ return this._result('online', `可用 ${latency.toFixed(0)}ms`, latency);
152
+ };
153
+
154
+ const result = await performCheck();
155
+ this._setCachedStatus(provider, result);
156
+ return result;
54
157
  } catch (error) {
55
- return this._handleError(error);
158
+ const result = this._handleError(error);
159
+ this._setCachedStatus(provider, result);
160
+ return result;
56
161
  }
57
162
  }
58
163
 
59
164
  async checkAll(providers) {
60
- const entries = await Promise.all(
61
- providers.map(async provider => {
62
- const status = await this.check(provider);
63
- return [provider.name, status];
64
- })
65
- );
165
+ const entries = await mapWithConcurrency(providers, this.maxConcurrency, async provider => {
166
+ const status = await this.check(provider);
167
+ return [provider.name, status];
168
+ });
66
169
  return Object.fromEntries(entries);
67
170
  }
68
171
 
69
172
  checkAllStreaming(providers, onUpdate) {
70
173
  const results = {};
71
- const tasks = providers.map(async provider => {
174
+ return mapWithConcurrency(providers, this.maxConcurrency, async provider => {
72
175
  try {
73
176
  const status = await this.check(provider);
74
177
  results[provider.name] = status;
@@ -82,18 +185,23 @@ class ProviderStatusChecker {
82
185
  onUpdate(provider.name, fallback, error);
83
186
  }
84
187
  }
85
- });
86
-
87
- return Promise.all(tasks).then(() => results);
188
+ }).then(() => results);
88
189
  }
89
190
 
90
191
  _createClient(provider) {
91
- const clientOptions = { baseURL: provider.baseUrl };
192
+ const clientOptions = {};
92
193
 
93
194
  if (provider.authMode === 'api_key') {
195
+ // api_key 模式:使用 ANTHROPIC_API_KEY
196
+ if (provider.baseUrl) {
197
+ clientOptions.baseURL = provider.baseUrl;
198
+ }
94
199
  clientOptions.apiKey = provider.authToken;
95
200
  } else if (provider.authMode === 'auth_token') {
96
201
  clientOptions.authToken = provider.authToken;
202
+ if (provider.baseUrl) {
203
+ clientOptions.baseURL = provider.baseUrl;
204
+ }
97
205
  } else {
98
206
  return null;
99
207
  }
@@ -122,36 +230,22 @@ class ProviderStatusChecker {
122
230
  }
123
231
 
124
232
  if (Array.isArray(response.content)) {
233
+ const textFields = ['text', 'thinking', 'output_text', 'argument', 'result'];
125
234
  const textParts = [];
235
+
126
236
  for (const block of response.content) {
127
- if (!block) {
128
- continue;
129
- }
237
+ if (!block) continue;
130
238
  if (typeof block === 'string') {
131
239
  textParts.push(block);
132
240
  continue;
133
241
  }
134
- if (typeof block.text === 'string' && block.text.trim()) {
135
- textParts.push(block.text);
136
- continue;
137
- }
138
- if (typeof block.thinking === 'string' && block.thinking.trim()) {
139
- textParts.push(block.thinking);
140
- continue;
141
- }
142
- if (typeof block.output_text === 'string' && block.output_text.trim()) {
143
- textParts.push(block.output_text);
144
- continue;
145
- }
146
- if (typeof block.argument === 'string' && block.argument.trim()) {
147
- textParts.push(block.argument);
148
- continue;
149
- }
150
- if (typeof block.result === 'string' && block.result.trim()) {
151
- textParts.push(block.result);
152
- continue;
242
+ for (const field of textFields) {
243
+ if (typeof block[field] === 'string' && block[field].trim()) {
244
+ textParts.push(block[field]);
245
+ }
153
246
  }
154
247
  }
248
+
155
249
  const combined = textParts
156
250
  .map(part => part.replace(/\s+/g, ' ').trim())
157
251
  .filter(Boolean)
@@ -172,7 +266,6 @@ class ProviderStatusChecker {
172
266
  return '';
173
267
  }
174
268
 
175
-
176
269
  _handleError(error) {
177
270
  if (error instanceof APIConnectionTimeoutError) {
178
271
  return this._result('offline', '请求超时', null);
@@ -192,6 +285,14 @@ class ProviderStatusChecker {
192
285
  if (error.status === 404) {
193
286
  return this._result('offline', '接口不存在 (404)', null);
194
287
  }
288
+ if (error.status === 400) {
289
+ // 400 错误可能是因为认证方式不对
290
+ const message = error.message || '';
291
+ if (message.includes('auth') || message.includes('authentication')) {
292
+ return this._result('offline', `认证配置错误 (${error.status})`, null);
293
+ }
294
+ return this._result('offline', `请求参数错误 (${error.status})`, null);
295
+ }
195
296
  return this._result('offline', `请求失败 (${error.status})`, null);
196
297
  }
197
298
 
@@ -205,6 +306,52 @@ class ProviderStatusChecker {
205
306
  _result(state, label, latency) {
206
307
  return { state, label, latency };
207
308
  }
309
+
310
+ async _checkCodex(provider) {
311
+ if (!provider.authToken) {
312
+ return this._result('unknown', '未配置 API Key', null);
313
+ }
314
+
315
+ const baseUrl = provider.baseUrl || 'https://api.openai.com/v1';
316
+ const modelsUrl = `${baseUrl.replace(/\/$/, '')}/models`;
317
+
318
+ try {
319
+ const controller = new AbortController();
320
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
321
+
322
+ const start = process.hrtime.bigint();
323
+ const response = await fetch(modelsUrl, {
324
+ method: 'GET',
325
+ headers: {
326
+ Authorization: `Bearer ${provider.authToken}`,
327
+ 'Content-Type': 'application/json'
328
+ },
329
+ signal: controller.signal
330
+ });
331
+ const latency = Number(process.hrtime.bigint() - start) / 1e6;
332
+
333
+ clearTimeout(timeoutId);
334
+
335
+ if (response.ok) {
336
+ return this._result('online', `可用 ${latency.toFixed(0)}ms`, latency);
337
+ }
338
+
339
+ if (response.status === 401 || response.status === 403) {
340
+ return this._result('offline', `认证失败 (${response.status})`, null);
341
+ }
342
+
343
+ if (response.status >= 500) {
344
+ return this._result('degraded', `服务异常 (${response.status})`, null);
345
+ }
346
+
347
+ return this._result('offline', `请求失败 (${response.status})`, null);
348
+ } catch (error) {
349
+ if (error.name === 'AbortError') {
350
+ return this._result('offline', '请求超时', null);
351
+ }
352
+ return this._result('offline', `检测失败: ${error.message}`, null);
353
+ }
354
+ }
208
355
  }
209
356
 
210
357
  module.exports = { ProviderStatusChecker };
@@ -0,0 +1,22 @@
1
+ function maskToken(token) {
2
+ if (!token || typeof token !== 'string') {
3
+ return token;
4
+ }
5
+
6
+ const value = token.trim();
7
+ if (value.length < 10) {
8
+ return '***';
9
+ }
10
+
11
+ return value.substring(0, 8) + '***' + value.substring(value.length - 4);
12
+ }
13
+
14
+ function maybeMaskToken(token, showToken = false) {
15
+ if (!token) {
16
+ return token;
17
+ }
18
+ return showToken ? token : maskToken(token);
19
+ }
20
+
21
+ module.exports = { maskToken, maybeMaskToken };
22
+
@@ -0,0 +1,32 @@
1
+ const path = require('path');
2
+
3
+ function resolveShell(shell = process.env.SHELL) {
4
+ if (shell) {
5
+ return path.basename(shell).toLowerCase();
6
+ }
7
+ return process.platform === 'win32' ? 'cmd' : 'sh';
8
+ }
9
+
10
+ function quotePosix(value) {
11
+ const escaped = String(value).replace(/'/g, String.raw`'\''`);
12
+ return `'${escaped}'`;
13
+ }
14
+
15
+ function quotePowerShell(value) {
16
+ return `'${String(value).replace(/'/g, "''")}'`;
17
+ }
18
+
19
+ function formatShellAssignment(name, value, shell = resolveShell()) {
20
+ const normalizedShell = resolveShell(shell);
21
+ if (normalizedShell === 'cmd' || normalizedShell === 'cmd.exe') {
22
+ return `set "${name}=${String(value).replace(/["%]/g, char => `%${char}`)}"`;
23
+ }
24
+
25
+ if (normalizedShell === 'powershell' || normalizedShell === 'pwsh') {
26
+ return `$env:${name} = ${quotePowerShell(value)}`;
27
+ }
28
+
29
+ return `export ${name}=${quotePosix(value)}`;
30
+ }
31
+
32
+ module.exports = { resolveShell, formatShellAssignment };
@@ -1,11 +1,25 @@
1
- const supportsColor = require('supports-color');
2
1
  const chalk = require('chalk');
3
2
 
3
+ const UNSAFE_TERMINAL_PATTERN = /[\x00-\x1F\x7F-\x9F\u202A-\u202E\u2066-\u2069]/;
4
+ const UNSAFE_TERMINAL_GLOBAL_PATTERN = /[\x00-\x1F\x7F-\x9F\u202A-\u202E\u2066-\u2069]/g;
5
+
6
+ function containsUnsafeTerminalCharacters(value) {
7
+ return typeof value === 'string' && UNSAFE_TERMINAL_PATTERN.test(value);
8
+ }
9
+
10
+ function escapeTerminalText(value) {
11
+ return String(value).replace(UNSAFE_TERMINAL_GLOBAL_PATTERN, character => {
12
+ const code = character.charCodeAt(0).toString(16).padStart(4, '0');
13
+ return `\\u${code}`;
14
+ });
15
+ }
16
+
4
17
  function detectTerminalCapabilities() {
5
18
  return {
6
- colors: supportsColor.stdout,
19
+ colors: Boolean(chalk.supportsColor),
7
20
  unicode: Boolean(process.env.WT_SESSION || process.env.TERM_PROGRAM === 'vscode'),
8
- colorDepth: typeof process.stdout.getColorDepth === 'function' ? process.stdout.getColorDepth() : 1
21
+ colorDepth:
22
+ typeof process.stdout.getColorDepth === 'function' ? process.stdout.getColorDepth() : 1
9
23
  };
10
24
  }
11
25
 
@@ -38,4 +52,8 @@ function formatMessage(message, type = 'info') {
38
52
  return formatter(`${symbol} ${message}`);
39
53
  }
40
54
 
41
- module.exports = { formatMessage };
55
+ module.exports = {
56
+ containsUnsafeTerminalCharacters,
57
+ escapeTerminalText,
58
+ formatMessage
59
+ };