ccjk 2.6.1 → 3.0.2

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 (53) hide show
  1. package/dist/chunks/agent.mjs +1412 -0
  2. package/dist/chunks/api.mjs +7 -7
  3. package/dist/chunks/auto-updater.mjs +9 -9
  4. package/dist/chunks/ccr.mjs +4 -4
  5. package/dist/chunks/ccu.mjs +1 -1
  6. package/dist/chunks/claude-code-incremental-manager.mjs +6 -6
  7. package/dist/chunks/claude-wrapper.mjs +18 -5
  8. package/dist/chunks/codex.mjs +4 -4
  9. package/dist/chunks/commands2.mjs +5 -5
  10. package/dist/chunks/commit.mjs +2 -2
  11. package/dist/chunks/config-consolidator.mjs +2 -2
  12. package/dist/chunks/config-switch.mjs +6 -6
  13. package/dist/chunks/config.mjs +1 -1
  14. package/dist/chunks/config2.mjs +14 -14
  15. package/dist/chunks/doctor.mjs +3 -3
  16. package/dist/chunks/features.mjs +12 -12
  17. package/dist/chunks/help.mjs +35 -35
  18. package/dist/chunks/index.mjs +12 -11
  19. package/dist/chunks/init.mjs +21 -21
  20. package/dist/chunks/interview.mjs +33 -33
  21. package/dist/chunks/marketplace.mjs +8 -8
  22. package/dist/chunks/mcp.mjs +8 -8
  23. package/dist/chunks/menu.mjs +302 -293
  24. package/dist/chunks/notification.mjs +5 -5
  25. package/dist/chunks/onboarding.mjs +17 -346
  26. package/dist/chunks/package.mjs +1 -1
  27. package/dist/chunks/permission-manager.mjs +3 -3
  28. package/dist/chunks/plugin.mjs +1937 -0
  29. package/dist/chunks/prompts.mjs +3 -3
  30. package/dist/chunks/providers.mjs +13 -13
  31. package/dist/chunks/session.mjs +17 -17
  32. package/dist/chunks/skill.mjs +304 -0
  33. package/dist/chunks/skills-sync.mjs +4 -4
  34. package/dist/chunks/skills.mjs +2 -2
  35. package/dist/chunks/team.mjs +1 -1
  36. package/dist/chunks/uninstall.mjs +8 -8
  37. package/dist/chunks/update.mjs +4 -4
  38. package/dist/chunks/upgrade-manager.mjs +3 -3
  39. package/dist/chunks/version-checker.mjs +6 -6
  40. package/dist/chunks/workflows.mjs +2 -2
  41. package/dist/cli.mjs +57 -4
  42. package/dist/index.d.mts +157 -14
  43. package/dist/index.d.ts +157 -14
  44. package/dist/index.mjs +6 -5
  45. package/dist/shared/ccjk.B2Aos9HI.mjs +333 -0
  46. package/dist/shared/{ccjk.rLRHmcqD.mjs → ccjk.BQzWKmC3.mjs} +3 -3
  47. package/dist/shared/{ccjk.uVUeWAt8.mjs → ccjk.BZT_f2go.mjs} +7 -7
  48. package/dist/shared/{ccjk.-FoZ3zat.mjs → ccjk.BlPCiSHj.mjs} +10 -10
  49. package/dist/shared/ccjk.DH6cOJsf.mjs +1674 -0
  50. package/dist/shared/{ccjk.tB4-Y4Qb.mjs → ccjk.DrMygfCF.mjs} +1 -1
  51. package/dist/shared/ccjk.tJ08-yZt.mjs +179 -0
  52. package/package.json +1 -1
  53. package/dist/shared/ccjk.BhKlRJ0h.mjs +0 -114
@@ -0,0 +1,1937 @@
1
+ import process__default from 'node:process';
2
+ import ansis from 'ansis';
3
+ import { Buffer } from 'node:buffer';
4
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, readdirSync, statSync, rmSync } from 'node:fs';
5
+ import { join } from 'pathe';
6
+ import { CCJK_CLOUD_PLUGINS_DIR, CCJK_CLOUD_PLUGINS_CACHE_DIR, CCJK_CLOUD_PLUGINS_INSTALLED_DIR } from './constants.mjs';
7
+ import { i18n } from './index2.mjs';
8
+ import { writeFileAtomic } from './fs-operations.mjs';
9
+ import { homedir } from 'node:os';
10
+ import { h as detectProject } from '../shared/ccjk.B2Aos9HI.mjs';
11
+ import 'node:url';
12
+ import 'i18next';
13
+ import 'i18next-fs-backend';
14
+ import 'node:crypto';
15
+ import 'node:fs/promises';
16
+
17
+ const CACHE_CONFIG = {
18
+ /** Cache time-to-live: 24 hours in milliseconds */
19
+ TTL: 24 * 60 * 60 * 1e3,
20
+ /** Maximum number of plugins to cache */
21
+ MAX_PLUGINS: 1e3,
22
+ /** Cache version for compatibility tracking */
23
+ VERSION: "1.0.0",
24
+ /** Maximum size for individual plugin content (5MB) */
25
+ MAX_CONTENT_SIZE: 5 * 1024 * 1024
26
+ };
27
+ const CACHE_BASE_DIR = join(homedir(), ".ccjk", "cloud-plugins", "cache");
28
+ class LocalPluginCache {
29
+ cacheDir;
30
+ cacheFile;
31
+ contentDir;
32
+ cache = null;
33
+ constructor(cacheDir) {
34
+ this.cacheDir = cacheDir || CACHE_BASE_DIR;
35
+ this.cacheFile = join(this.cacheDir, "metadata.json");
36
+ this.contentDir = join(this.cacheDir, "contents");
37
+ }
38
+ // ==========================================================================
39
+ // Initialization
40
+ // ==========================================================================
41
+ /**
42
+ * Ensure cache directory exists
43
+ */
44
+ ensureCacheDir() {
45
+ try {
46
+ if (!existsSync(this.cacheDir)) {
47
+ mkdirSync(this.cacheDir, { recursive: true });
48
+ }
49
+ if (!existsSync(this.contentDir)) {
50
+ mkdirSync(this.contentDir, { recursive: true });
51
+ }
52
+ } catch (error) {
53
+ throw new Error(`Failed to create cache directory: ${error instanceof Error ? error.message : String(error)}`);
54
+ }
55
+ }
56
+ // ==========================================================================
57
+ // Cache Metadata Operations
58
+ // ==========================================================================
59
+ /**
60
+ * Load cache metadata from disk
61
+ *
62
+ * @returns Cache metadata or null if not found or invalid
63
+ */
64
+ loadCache() {
65
+ try {
66
+ if (!existsSync(this.cacheFile)) {
67
+ return null;
68
+ }
69
+ const content = readFileSync(this.cacheFile, "utf-8");
70
+ const cache = JSON.parse(content);
71
+ if (!this.isValidCache(cache)) {
72
+ console.warn("[LocalPluginCache] Invalid cache structure, ignoring");
73
+ return null;
74
+ }
75
+ if (cache.version !== CACHE_CONFIG.VERSION) {
76
+ console.warn(`[LocalPluginCache] Cache version mismatch (${cache.version} vs ${CACHE_CONFIG.VERSION}), ignoring`);
77
+ return null;
78
+ }
79
+ this.cache = cache;
80
+ return cache;
81
+ } catch (error) {
82
+ console.error("[LocalPluginCache] Failed to load cache:", error);
83
+ return null;
84
+ }
85
+ }
86
+ /**
87
+ * Save cache metadata to disk
88
+ *
89
+ * Uses atomic write operation to prevent corruption
90
+ *
91
+ * @param cache - Cache metadata to save
92
+ */
93
+ saveCache(cache) {
94
+ try {
95
+ this.ensureCacheDir();
96
+ if (!this.isValidCache(cache)) {
97
+ throw new Error("Invalid cache structure");
98
+ }
99
+ if (cache.plugins.length > CACHE_CONFIG.MAX_PLUGINS) {
100
+ console.warn(`[LocalPluginCache] Cache exceeds max plugins (${cache.plugins.length}), truncating`);
101
+ cache.plugins = cache.plugins.slice(0, CACHE_CONFIG.MAX_PLUGINS);
102
+ cache.totalPlugins = cache.plugins.length;
103
+ }
104
+ const content = JSON.stringify(cache, null, 2);
105
+ writeFileAtomic(this.cacheFile, content, "utf-8");
106
+ this.cache = cache;
107
+ } catch (error) {
108
+ throw new Error(`Failed to save cache: ${error instanceof Error ? error.message : String(error)}`);
109
+ }
110
+ }
111
+ /**
112
+ * Get cached plugins
113
+ *
114
+ * @returns Array of cached plugins
115
+ */
116
+ getCachedPlugins() {
117
+ if (!this.cache) {
118
+ this.cache = this.loadCache();
119
+ }
120
+ return this.cache?.plugins || [];
121
+ }
122
+ /**
123
+ * Get a single cached plugin by ID
124
+ *
125
+ * @param id - Plugin ID
126
+ * @returns Plugin or undefined if not found
127
+ */
128
+ getCachedPlugin(id) {
129
+ const plugins = this.getCachedPlugins();
130
+ return plugins.find((p) => p.id === id);
131
+ }
132
+ /**
133
+ * Update cache with new plugin list
134
+ *
135
+ * @param plugins - New plugin list
136
+ */
137
+ updateCache(plugins) {
138
+ const now = (/* @__PURE__ */ new Date()).toISOString();
139
+ const expiresAt = new Date(Date.now() + CACHE_CONFIG.TTL).toISOString();
140
+ const cache = {
141
+ version: CACHE_CONFIG.VERSION,
142
+ plugins,
143
+ createdAt: this.cache?.createdAt || now,
144
+ expiresAt,
145
+ lastUpdated: now,
146
+ totalPlugins: plugins.length
147
+ };
148
+ this.saveCache(cache);
149
+ }
150
+ // ==========================================================================
151
+ // Cache Expiration
152
+ // ==========================================================================
153
+ /**
154
+ * Check if cache is expired
155
+ *
156
+ * @returns True if cache is expired or doesn't exist
157
+ */
158
+ isCacheExpired() {
159
+ if (!this.cache) {
160
+ this.cache = this.loadCache();
161
+ }
162
+ if (!this.cache) {
163
+ return true;
164
+ }
165
+ const expiresAt = new Date(this.cache.expiresAt).getTime();
166
+ const now = Date.now();
167
+ return now >= expiresAt;
168
+ }
169
+ /**
170
+ * Clear all cache data
171
+ */
172
+ clearCache() {
173
+ try {
174
+ if (existsSync(this.cacheFile)) {
175
+ unlinkSync(this.cacheFile);
176
+ }
177
+ if (existsSync(this.contentDir)) {
178
+ const files = readdirSync(this.contentDir);
179
+ for (const file of files) {
180
+ const filePath = join(this.contentDir, file);
181
+ if (existsSync(filePath)) {
182
+ unlinkSync(filePath);
183
+ }
184
+ }
185
+ }
186
+ this.cache = null;
187
+ } catch (error) {
188
+ throw new Error(`Failed to clear cache: ${error instanceof Error ? error.message : String(error)}`);
189
+ }
190
+ }
191
+ // ==========================================================================
192
+ // Plugin Content Caching
193
+ // ==========================================================================
194
+ /**
195
+ * Cache plugin content to disk
196
+ *
197
+ * @param pluginId - Plugin ID
198
+ * @param content - Plugin content (code/template)
199
+ * @returns Path to cached content file
200
+ */
201
+ cachePluginContent(pluginId, content) {
202
+ try {
203
+ this.ensureCacheDir();
204
+ const contentSize = Buffer.byteLength(content, "utf-8");
205
+ if (contentSize > CACHE_CONFIG.MAX_CONTENT_SIZE) {
206
+ throw new Error(`Content size (${contentSize} bytes) exceeds maximum (${CACHE_CONFIG.MAX_CONTENT_SIZE} bytes)`);
207
+ }
208
+ const safeId = this.sanitizeFilename(pluginId);
209
+ const contentPath = join(this.contentDir, `${safeId}.txt`);
210
+ writeFileAtomic(contentPath, content, "utf-8");
211
+ return contentPath;
212
+ } catch (error) {
213
+ throw new Error(`Failed to cache plugin content: ${error instanceof Error ? error.message : String(error)}`);
214
+ }
215
+ }
216
+ /**
217
+ * Get cached plugin content
218
+ *
219
+ * @param pluginId - Plugin ID
220
+ * @returns Plugin content or null if not cached
221
+ */
222
+ getPluginContent(pluginId) {
223
+ try {
224
+ const safeId = this.sanitizeFilename(pluginId);
225
+ const contentPath = join(this.contentDir, `${safeId}.txt`);
226
+ if (!existsSync(contentPath)) {
227
+ return null;
228
+ }
229
+ return readFileSync(contentPath, "utf-8");
230
+ } catch (error) {
231
+ console.error(`[LocalPluginCache] Failed to read plugin content: ${error}`);
232
+ return null;
233
+ }
234
+ }
235
+ /**
236
+ * Remove cached plugin content
237
+ *
238
+ * @param pluginId - Plugin ID
239
+ * @returns True if content was removed
240
+ */
241
+ removePluginContent(pluginId) {
242
+ try {
243
+ const safeId = this.sanitizeFilename(pluginId);
244
+ const contentPath = join(this.contentDir, `${safeId}.txt`);
245
+ if (existsSync(contentPath)) {
246
+ unlinkSync(contentPath);
247
+ return true;
248
+ }
249
+ return false;
250
+ } catch (error) {
251
+ console.error(`[LocalPluginCache] Failed to remove plugin content: ${error}`);
252
+ return false;
253
+ }
254
+ }
255
+ // ==========================================================================
256
+ // Cache Statistics
257
+ // ==========================================================================
258
+ /**
259
+ * Get cache statistics
260
+ *
261
+ * @returns Cache statistics
262
+ */
263
+ getCacheStats() {
264
+ if (!this.cache) {
265
+ this.cache = this.loadCache();
266
+ }
267
+ const totalPlugins = this.cache?.totalPlugins || 0;
268
+ const lastUpdated = this.cache?.lastUpdated || null;
269
+ const expiresAt = this.cache?.expiresAt || null;
270
+ const isExpired = this.isCacheExpired();
271
+ let cacheSize = 0;
272
+ let cachedContents = 0;
273
+ try {
274
+ if (existsSync(this.cacheFile)) {
275
+ cacheSize += statSync(this.cacheFile).size;
276
+ }
277
+ if (existsSync(this.contentDir)) {
278
+ const files = readdirSync(this.contentDir);
279
+ for (const file of files) {
280
+ const filePath = join(this.contentDir, file);
281
+ if (existsSync(filePath)) {
282
+ cacheSize += statSync(filePath).size;
283
+ cachedContents++;
284
+ }
285
+ }
286
+ }
287
+ } catch (error) {
288
+ console.error("[LocalPluginCache] Failed to calculate cache size:", error);
289
+ }
290
+ return {
291
+ totalPlugins,
292
+ cacheSize,
293
+ lastUpdated,
294
+ expiresAt,
295
+ isExpired,
296
+ cachedContents
297
+ };
298
+ }
299
+ // ==========================================================================
300
+ // Utility Methods
301
+ // ==========================================================================
302
+ /**
303
+ * Validate cache structure
304
+ *
305
+ * @param cache - Cache to validate
306
+ * @returns True if cache is valid
307
+ */
308
+ isValidCache(cache) {
309
+ return cache && typeof cache === "object" && typeof cache.version === "string" && Array.isArray(cache.plugins) && typeof cache.createdAt === "string" && typeof cache.expiresAt === "string" && typeof cache.lastUpdated === "string" && typeof cache.totalPlugins === "number";
310
+ }
311
+ /**
312
+ * Sanitize filename to prevent path traversal
313
+ *
314
+ * @param filename - Original filename
315
+ * @returns Sanitized filename
316
+ */
317
+ sanitizeFilename(filename) {
318
+ return filename.replace(/[/\\]/g, "_").replace(/[^\w.-]/g, "_").substring(0, 255);
319
+ }
320
+ }
321
+
322
+ const DEFAULT_CLOUD_API_URL = "https://api.claudehome.cn/api/v1/plugins";
323
+ const REQUEST_TIMEOUT = 3e4;
324
+ const MAX_RETRY_ATTEMPTS = 3;
325
+ const RETRY_DELAY = 1e3;
326
+ const CACHE_TTL = 36e5;
327
+ class CloudRecommendationClient {
328
+ baseUrl;
329
+ apiKey;
330
+ timeout;
331
+ offlineMode;
332
+ enableLogging;
333
+ maxRetries;
334
+ retryDelay;
335
+ cache;
336
+ constructor(options = {}) {
337
+ this.baseUrl = options.baseUrl || DEFAULT_CLOUD_API_URL;
338
+ this.apiKey = options.apiKey;
339
+ this.timeout = options.timeout || REQUEST_TIMEOUT;
340
+ this.offlineMode = options.offlineMode || false;
341
+ this.enableLogging = options.enableLogging || false;
342
+ this.maxRetries = options.maxRetries || MAX_RETRY_ATTEMPTS;
343
+ this.retryDelay = options.retryDelay || RETRY_DELAY;
344
+ this.cache = /* @__PURE__ */ new Map();
345
+ }
346
+ // ==========================================================================
347
+ // Public API Methods
348
+ // ==========================================================================
349
+ /**
350
+ * Get personalized plugin recommendations
351
+ *
352
+ * @param context - Recommendation context with user preferences
353
+ * @returns Recommended plugins with reasons and scores
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * const recommendations = await client.getRecommendations({
358
+ * codeToolType: 'claude-code',
359
+ * language: 'zh-CN',
360
+ * installedPlugins: ['git-workflow', 'test-runner'],
361
+ * limit: 10
362
+ * })
363
+ * ```
364
+ */
365
+ async getRecommendations(context) {
366
+ this.log("Getting recommendations with context:", context);
367
+ return this.request("/recommendations", {
368
+ method: "POST",
369
+ body: JSON.stringify(context)
370
+ });
371
+ }
372
+ /**
373
+ * Search plugins with filters and sorting
374
+ *
375
+ * @param params - Search parameters
376
+ * @returns Matching plugins
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * const results = await client.searchPlugins({
381
+ * query: 'git',
382
+ * category: 'workflow',
383
+ * sortBy: 'downloads',
384
+ * sortDir: 'desc',
385
+ * limit: 20
386
+ * })
387
+ * ```
388
+ */
389
+ async searchPlugins(params) {
390
+ this.log("Searching plugins with params:", params);
391
+ return this.request("", {
392
+ method: "GET",
393
+ params
394
+ });
395
+ }
396
+ /**
397
+ * Get detailed information about a specific plugin
398
+ *
399
+ * @param id - Plugin ID
400
+ * @returns Plugin details
401
+ *
402
+ * @example
403
+ * ```typescript
404
+ * const plugin = await client.getPlugin('git-workflow-pro')
405
+ * ```
406
+ */
407
+ async getPlugin(id) {
408
+ this.log("Getting plugin:", id);
409
+ return this.request(`/plugins/${id}`, {
410
+ method: "GET"
411
+ });
412
+ }
413
+ /**
414
+ * Get popular plugins
415
+ *
416
+ * @param limit - Maximum number of plugins to return
417
+ * @returns Popular plugins
418
+ *
419
+ * @example
420
+ * ```typescript
421
+ * const popular = await client.getPopularPlugins(10)
422
+ * ```
423
+ */
424
+ async getPopularPlugins(limit = 10) {
425
+ this.log("Getting popular plugins, limit:", limit);
426
+ return this.request("/popular", {
427
+ method: "GET",
428
+ params: { limit }
429
+ });
430
+ }
431
+ /**
432
+ * Get all plugin categories
433
+ *
434
+ * @returns Category information
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * const categories = await client.getCategories()
439
+ * ```
440
+ */
441
+ async getCategories() {
442
+ this.log("Getting categories");
443
+ return this.request("/categories", {
444
+ method: "GET"
445
+ });
446
+ }
447
+ /**
448
+ * Download a plugin
449
+ *
450
+ * @param id - Plugin ID
451
+ * @returns Plugin download result with content
452
+ *
453
+ * @example
454
+ * ```typescript
455
+ * const download = await client.downloadPlugin('git-workflow-pro')
456
+ * if (download.success && download.data) {
457
+ * const content = require('node:buffer').require('node:buffer').require('node:buffer').require('node:buffer').Buffer.from(download.data.content, 'base64')
458
+ * // Process plugin content
459
+ * }
460
+ * ```
461
+ */
462
+ async downloadPlugin(id) {
463
+ this.log("Downloading plugin:", id);
464
+ return this.request(`/plugins/${id}/download`, {
465
+ method: "GET",
466
+ skipCache: true
467
+ // Always fetch fresh download
468
+ });
469
+ }
470
+ /**
471
+ * Upload a plugin (user contribution)
472
+ *
473
+ * @param plugin - Plugin metadata
474
+ * @param content - Plugin content as Buffer
475
+ * @returns Upload result with plugin ID
476
+ *
477
+ * @example
478
+ * ```typescript
479
+ * const result = await client.uploadPlugin(pluginMetadata, pluginContent)
480
+ * if (result.success && result.data) {
481
+ * console.log('Plugin uploaded with ID:', result.data.id)
482
+ * }
483
+ * ```
484
+ */
485
+ async uploadPlugin(plugin, content) {
486
+ this.log("Uploading plugin:", plugin.id);
487
+ const payload = {
488
+ plugin,
489
+ content: content.toString("base64")
490
+ };
491
+ return this.request("/plugins/upload", {
492
+ method: "POST",
493
+ body: JSON.stringify(payload),
494
+ skipCache: true
495
+ });
496
+ }
497
+ // ==========================================================================
498
+ // Cache Management
499
+ // ==========================================================================
500
+ /**
501
+ * Clear all cached data
502
+ */
503
+ clearCache() {
504
+ this.cache.clear();
505
+ this.log("Cache cleared");
506
+ }
507
+ /**
508
+ * Clear expired cache entries
509
+ */
510
+ clearExpiredCache() {
511
+ const now = Date.now();
512
+ const keysToDelete = [];
513
+ this.cache.forEach((entry, key) => {
514
+ if (now - entry.timestamp > entry.ttl) {
515
+ keysToDelete.push(key);
516
+ }
517
+ });
518
+ keysToDelete.forEach((key) => this.cache.delete(key));
519
+ this.log("Expired cache entries cleared");
520
+ }
521
+ /**
522
+ * Set offline mode
523
+ */
524
+ setOfflineMode(enabled) {
525
+ this.offlineMode = enabled;
526
+ this.log("Offline mode:", enabled ? "enabled" : "disabled");
527
+ }
528
+ // ==========================================================================
529
+ // Private Helper Methods
530
+ // ==========================================================================
531
+ /**
532
+ * Make an HTTP request to the cloud service
533
+ */
534
+ async request(endpoint, options = {}) {
535
+ const url = this.buildUrl(endpoint, options.params);
536
+ const cacheKey = `${options.method || "GET"}:${url}`;
537
+ if (!options.skipCache && (options.method === "GET" || !options.method)) {
538
+ const cached = this.getFromCache(cacheKey);
539
+ if (cached) {
540
+ this.log("Cache hit:", cacheKey);
541
+ return {
542
+ success: true,
543
+ data: cached,
544
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
545
+ };
546
+ }
547
+ }
548
+ if (this.offlineMode) {
549
+ const cached = this.getFromCache(cacheKey);
550
+ if (cached) {
551
+ this.log("Offline mode: returning cached data");
552
+ return {
553
+ success: true,
554
+ data: cached,
555
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
556
+ };
557
+ }
558
+ return {
559
+ success: false,
560
+ error: "Offline mode enabled and no cached data available",
561
+ code: "OFFLINE_MODE"
562
+ };
563
+ }
564
+ let lastError = null;
565
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
566
+ try {
567
+ this.log(`Request attempt ${attempt}/${this.maxRetries}:`, url);
568
+ const response = await this.makeRequest(url, options);
569
+ if (response.success && response.data && (options.method === "GET" || !options.method)) {
570
+ this.setCache(cacheKey, response.data, CACHE_TTL);
571
+ }
572
+ return response;
573
+ } catch (error) {
574
+ lastError = error instanceof Error ? error : new Error(String(error));
575
+ this.log(`Request failed (attempt ${attempt}):`, lastError.message);
576
+ if (lastError.name === "AbortError") {
577
+ break;
578
+ }
579
+ if (attempt < this.maxRetries) {
580
+ await this.sleep(this.retryDelay * attempt);
581
+ }
582
+ }
583
+ }
584
+ return {
585
+ success: false,
586
+ error: lastError?.message || "Request failed after all retries",
587
+ code: "REQUEST_FAILED"
588
+ };
589
+ }
590
+ /**
591
+ * Make a single HTTP request
592
+ */
593
+ async makeRequest(url, options) {
594
+ const timeout = options.timeout || this.timeout;
595
+ const timeoutController = new AbortController();
596
+ const timeoutId = setTimeout(() => timeoutController.abort(), timeout);
597
+ try {
598
+ const response = await fetch(url, {
599
+ method: options.method || "GET",
600
+ headers: this.getHeaders(options.headers),
601
+ body: options.body,
602
+ signal: options.signal || timeoutController.signal
603
+ });
604
+ clearTimeout(timeoutId);
605
+ const data = await response.json();
606
+ if (!response.ok) {
607
+ return {
608
+ success: false,
609
+ error: data.error || `HTTP ${response.status}: ${response.statusText}`,
610
+ code: data.code || `HTTP_${response.status}`
611
+ };
612
+ }
613
+ return {
614
+ ...data,
615
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
616
+ };
617
+ } catch (error) {
618
+ clearTimeout(timeoutId);
619
+ if (error instanceof Error) {
620
+ if (error.name === "AbortError") {
621
+ throw error;
622
+ }
623
+ return {
624
+ success: false,
625
+ error: error.message,
626
+ code: "NETWORK_ERROR"
627
+ };
628
+ }
629
+ return {
630
+ success: false,
631
+ error: String(error),
632
+ code: "UNKNOWN_ERROR"
633
+ };
634
+ }
635
+ }
636
+ /**
637
+ * Build full URL with query parameters
638
+ */
639
+ buildUrl(endpoint, params) {
640
+ const url = new URL(endpoint, this.baseUrl);
641
+ if (params) {
642
+ for (const [key, value] of Object.entries(params)) {
643
+ if (value !== void 0 && value !== null) {
644
+ if (Array.isArray(value)) {
645
+ value.forEach((v) => url.searchParams.append(key, String(v)));
646
+ } else {
647
+ url.searchParams.append(key, String(value));
648
+ }
649
+ }
650
+ }
651
+ }
652
+ return url.toString();
653
+ }
654
+ /**
655
+ * Get request headers
656
+ */
657
+ getHeaders(customHeaders) {
658
+ const headers = {
659
+ "Content-Type": "application/json",
660
+ "User-Agent": "CCJK-Cloud-Client/1.0",
661
+ ...customHeaders
662
+ };
663
+ if (this.apiKey) {
664
+ headers.Authorization = `Bearer ${this.apiKey}`;
665
+ }
666
+ return headers;
667
+ }
668
+ /**
669
+ * Get data from cache
670
+ */
671
+ getFromCache(key) {
672
+ const entry = this.cache.get(key);
673
+ if (!entry) {
674
+ return null;
675
+ }
676
+ const now = Date.now();
677
+ if (now - entry.timestamp > entry.ttl) {
678
+ this.cache.delete(key);
679
+ return null;
680
+ }
681
+ return entry.data;
682
+ }
683
+ /**
684
+ * Set data in cache
685
+ */
686
+ setCache(key, data, ttl) {
687
+ this.cache.set(key, {
688
+ data,
689
+ timestamp: Date.now(),
690
+ ttl
691
+ });
692
+ }
693
+ /**
694
+ * Sleep for specified milliseconds
695
+ */
696
+ sleep(ms) {
697
+ return new Promise((resolve) => setTimeout(resolve, ms));
698
+ }
699
+ /**
700
+ * Log message (if logging is enabled)
701
+ */
702
+ log(...args) {
703
+ if (this.enableLogging) {
704
+ console.log("[CloudRecommendationClient]", ...args);
705
+ }
706
+ }
707
+ }
708
+
709
+ const PROJECT_DETECTORS = [
710
+ {
711
+ type: "nextjs",
712
+ detect: (files, pkg) => files.includes("next.config.js") || files.includes("next.config.mjs") || files.includes("next.config.ts") || pkg?.dependencies?.next || pkg?.devDependencies?.next,
713
+ recommendedCategories: ["dev", "seo", "performance"],
714
+ recommendedTags: ["react", "nextjs", "ssr", "seo", "frontend"],
715
+ priority: 10
716
+ },
717
+ {
718
+ type: "nuxt",
719
+ detect: (files, pkg) => files.includes("nuxt.config.js") || files.includes("nuxt.config.ts") || pkg?.dependencies?.nuxt || pkg?.devDependencies?.nuxt,
720
+ recommendedCategories: ["dev", "seo", "performance"],
721
+ recommendedTags: ["vue", "nuxt", "ssr", "seo", "frontend"],
722
+ priority: 10
723
+ },
724
+ {
725
+ type: "vue",
726
+ detect: (files, pkg) => files.includes("vue.config.js") || files.includes("vite.config.ts") || files.includes("vite.config.js") || pkg?.dependencies?.vue || pkg?.devDependencies?.vue,
727
+ recommendedCategories: ["dev", "testing", "performance"],
728
+ recommendedTags: ["vue", "vite", "frontend", "spa"],
729
+ priority: 9
730
+ },
731
+ {
732
+ type: "react",
733
+ detect: (_files, pkg) => pkg?.dependencies?.react || pkg?.devDependencies?.react,
734
+ recommendedCategories: ["dev", "testing", "performance"],
735
+ recommendedTags: ["react", "frontend", "spa"],
736
+ priority: 9
737
+ },
738
+ {
739
+ type: "angular",
740
+ detect: (files, pkg) => files.includes("angular.json") || pkg?.dependencies?.["@angular/core"] || pkg?.devDependencies?.["@angular/core"],
741
+ recommendedCategories: ["dev", "testing"],
742
+ recommendedTags: ["angular", "frontend", "spa", "typescript"],
743
+ priority: 9
744
+ },
745
+ {
746
+ type: "node-backend",
747
+ detect: (_files, pkg) => {
748
+ const hasBackendFramework = pkg?.dependencies?.express || pkg?.dependencies?.fastify || pkg?.dependencies?.["@nestjs/core"] || pkg?.dependencies?.koa || pkg?.dependencies?.hono;
749
+ const noFrontendFramework = !pkg?.dependencies?.react && !pkg?.dependencies?.vue && !pkg?.dependencies?.next && !pkg?.dependencies?.nuxt;
750
+ return hasBackendFramework && noFrontendFramework;
751
+ },
752
+ recommendedCategories: ["dev", "testing", "devops", "security"],
753
+ recommendedTags: ["nodejs", "backend", "api", "server"],
754
+ priority: 8
755
+ },
756
+ {
757
+ type: "python",
758
+ detect: (files) => files.includes("requirements.txt") || files.includes("pyproject.toml") || files.includes("setup.py") || files.includes("Pipfile"),
759
+ recommendedCategories: ["dev", "ai", "testing"],
760
+ recommendedTags: ["python", "ml", "data", "backend"],
761
+ priority: 8
762
+ },
763
+ {
764
+ type: "django",
765
+ detect: (files, _pkg) => files.includes("manage.py") || files.includes("requirements.txt"),
766
+ recommendedCategories: ["dev", "testing", "security"],
767
+ recommendedTags: ["python", "django", "backend", "web"],
768
+ priority: 9
769
+ },
770
+ {
771
+ type: "fastapi",
772
+ detect: (files) => files.includes("requirements.txt"),
773
+ recommendedCategories: ["dev", "testing", "docs"],
774
+ recommendedTags: ["python", "fastapi", "backend", "api"],
775
+ priority: 8
776
+ },
777
+ {
778
+ type: "rust",
779
+ detect: (files) => files.includes("Cargo.toml"),
780
+ recommendedCategories: ["dev", "testing", "performance"],
781
+ recommendedTags: ["rust", "systems", "performance"],
782
+ priority: 7
783
+ },
784
+ {
785
+ type: "go",
786
+ detect: (files) => files.includes("go.mod"),
787
+ recommendedCategories: ["dev", "testing", "devops"],
788
+ recommendedTags: ["go", "golang", "backend", "microservices"],
789
+ priority: 7
790
+ },
791
+ {
792
+ type: "monorepo",
793
+ detect: (files, pkg) => files.includes("pnpm-workspace.yaml") || files.includes("lerna.json") || files.includes("nx.json") || pkg?.workspaces != null,
794
+ recommendedCategories: ["dev", "devops", "testing"],
795
+ recommendedTags: ["monorepo", "workspace", "tooling"],
796
+ priority: 6
797
+ },
798
+ {
799
+ type: "docker",
800
+ detect: (files) => files.includes("Dockerfile") || files.includes("docker-compose.yml"),
801
+ recommendedCategories: ["devops", "testing"],
802
+ recommendedTags: ["docker", "containers", "deployment"],
803
+ priority: 5
804
+ },
805
+ {
806
+ type: "typescript",
807
+ detect: (files) => files.includes("tsconfig.json"),
808
+ recommendedCategories: ["dev", "testing"],
809
+ recommendedTags: ["typescript", "types", "tooling"],
810
+ priority: 4
811
+ }
812
+ ];
813
+ class RecommendationEngine {
814
+ cloudClient;
815
+ cache;
816
+ /**
817
+ * Create a new recommendation engine
818
+ *
819
+ * @param cloudClient - Client for fetching cloud recommendations
820
+ * @param cache - Local plugin cache
821
+ */
822
+ constructor(cloudClient, cache) {
823
+ this.cloudClient = cloudClient;
824
+ this.cache = cache;
825
+ }
826
+ /**
827
+ * Get plugin recommendations for a project
828
+ *
829
+ * Analyzes the project and returns personalized plugin recommendations
830
+ * with scoring, reasoning, and confidence levels.
831
+ *
832
+ * @param projectPath - Path to project directory (defaults to cwd)
833
+ * @returns Recommendation result with scored plugins
834
+ */
835
+ async getRecommendations(projectPath) {
836
+ const context = await this.detectProjectContext(projectPath || process__default.cwd());
837
+ let recommendations = [];
838
+ let source = "local";
839
+ try {
840
+ const cloudResult = await this.cloudClient.getRecommendations({
841
+ codeToolType: "claude-code",
842
+ language: context.language,
843
+ installedPlugins: context.existingPlugins,
844
+ limit: 20
845
+ });
846
+ if (cloudResult.success && cloudResult.data) {
847
+ recommendations = cloudResult.data.plugins.map((plugin) => ({
848
+ plugin,
849
+ score: cloudResult.data.scores[plugin.id] || 50,
850
+ reason: {
851
+ "en": cloudResult.data.reasons[plugin.id] || "Recommended by cloud service",
852
+ "zh-CN": cloudResult.data.reasons[plugin.id] || "\u4E91\u670D\u52A1\u63A8\u8350"
853
+ },
854
+ confidence: (cloudResult.data.scores[plugin.id] || 50) / 100,
855
+ matchingTags: [],
856
+ matchingCategories: [],
857
+ isInstalled: context.existingPlugins?.includes(plugin.id) || false
858
+ }));
859
+ source = "cloud";
860
+ }
861
+ } catch {
862
+ console.warn("Cloud recommendations unavailable, using local cache");
863
+ }
864
+ if (recommendations.length === 0) {
865
+ const localResult = this.getLocalRecommendations(context);
866
+ recommendations = localResult.recommendations;
867
+ source = "local";
868
+ }
869
+ if (source === "cloud") {
870
+ const localResult = this.getLocalRecommendations(context);
871
+ recommendations = this.mergeRecommendations(
872
+ { recommendations, context, totalEvaluated: 0, source: "cloud", timestamp: "" },
873
+ localResult
874
+ ).recommendations;
875
+ source = "hybrid";
876
+ }
877
+ recommendations = this.filterInstalledPlugins(recommendations);
878
+ recommendations.sort((a, b) => b.score - a.score);
879
+ return {
880
+ recommendations,
881
+ context,
882
+ totalEvaluated: recommendations.length,
883
+ source,
884
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
885
+ };
886
+ }
887
+ /**
888
+ * Detect project context from directory
889
+ *
890
+ * Analyzes project files and structure to determine frameworks,
891
+ * languages, tools, and recommended plugin categories.
892
+ *
893
+ * @param projectPath - Path to project directory
894
+ * @returns Project context for recommendations
895
+ */
896
+ async detectProjectContext(projectPath) {
897
+ const projectInfo = detectProject(projectPath);
898
+ const files = existsSync(projectPath) ? readdirSync(projectPath) : [];
899
+ let packageJson;
900
+ try {
901
+ const pkgPath = join(projectPath, "package.json");
902
+ if (existsSync(pkgPath)) {
903
+ packageJson = JSON.parse(readFileSync(pkgPath, "utf-8"));
904
+ }
905
+ } catch {
906
+ }
907
+ let detectedType;
908
+ const recommendedCategories = [];
909
+ const recommendedTags = [];
910
+ const sortedDetectors = [...PROJECT_DETECTORS].sort(
911
+ (a, b) => (b.priority || 0) - (a.priority || 0)
912
+ );
913
+ for (const detector of sortedDetectors) {
914
+ if (detector.detect(files, packageJson)) {
915
+ if (!detectedType) {
916
+ detectedType = detector.type;
917
+ }
918
+ recommendedCategories.push(...detector.recommendedCategories);
919
+ recommendedTags.push(...detector.recommendedTags);
920
+ }
921
+ }
922
+ const existingPlugins = [];
923
+ return {
924
+ projectType: detectedType || projectInfo.type,
925
+ language: projectInfo.languages[0],
926
+ frameworks: projectInfo.frameworks,
927
+ languages: projectInfo.languages,
928
+ buildTools: projectInfo.buildTools,
929
+ testFrameworks: projectInfo.testFrameworks,
930
+ hasTypeScript: projectInfo.hasTypeScript,
931
+ hasDocker: projectInfo.hasDocker,
932
+ hasMonorepo: projectInfo.hasMonorepo,
933
+ packageManager: projectInfo.packageManager,
934
+ cicd: projectInfo.cicd,
935
+ rootDir: projectPath,
936
+ recommendedCategories: [...new Set(recommendedCategories)],
937
+ recommendedTags: [...new Set(recommendedTags)],
938
+ existingPlugins
939
+ };
940
+ }
941
+ /**
942
+ * Generate local recommendations without cloud service
943
+ *
944
+ * Uses cached plugins and project context to generate recommendations
945
+ * entirely offline.
946
+ *
947
+ * @param context - Project context
948
+ * @returns Local recommendation result
949
+ */
950
+ getLocalRecommendations(context) {
951
+ const allPlugins = this.cache.getCachedPlugins();
952
+ const recommendations = [];
953
+ for (const plugin of allPlugins) {
954
+ const score = this.calculateRelevanceScore(plugin, context);
955
+ if (score > 0) {
956
+ const matchingTags = this.getMatchingTags(plugin, context);
957
+ const matchingCategories = this.getMatchingCategories(plugin, context);
958
+ const confidence = this.calculateConfidence(score, matchingTags.length, matchingCategories.length);
959
+ const isInstalled = context.existingPlugins?.includes(plugin.id) || false;
960
+ recommendations.push({
961
+ plugin,
962
+ score,
963
+ reason: this.generateReason(plugin, context, matchingTags, matchingCategories),
964
+ confidence,
965
+ matchingTags,
966
+ matchingCategories,
967
+ isInstalled
968
+ });
969
+ }
970
+ }
971
+ return {
972
+ recommendations: recommendations.sort((a, b) => b.score - a.score),
973
+ context,
974
+ totalEvaluated: allPlugins.length,
975
+ source: "local",
976
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
977
+ };
978
+ }
979
+ /**
980
+ * Merge cloud and local recommendations
981
+ *
982
+ * Combines recommendations from both sources, deduplicates,
983
+ * and re-scores based on combined signals.
984
+ *
985
+ * @param cloud - Cloud recommendations
986
+ * @param local - Local recommendations
987
+ * @returns Merged recommendation result
988
+ */
989
+ mergeRecommendations(cloud, local) {
990
+ const merged = /* @__PURE__ */ new Map();
991
+ for (const rec of cloud.recommendations) {
992
+ merged.set(rec.plugin.id, rec);
993
+ }
994
+ for (const rec of local.recommendations) {
995
+ const existing = merged.get(rec.plugin.id);
996
+ if (existing) {
997
+ existing.score = Math.round((existing.score + rec.score) / 2);
998
+ existing.confidence = Math.max(existing.confidence, rec.confidence);
999
+ existing.matchingTags = [.../* @__PURE__ */ new Set([...existing.matchingTags, ...rec.matchingTags])];
1000
+ existing.matchingCategories = [.../* @__PURE__ */ new Set([...existing.matchingCategories, ...rec.matchingCategories])];
1001
+ } else {
1002
+ merged.set(rec.plugin.id, rec);
1003
+ }
1004
+ }
1005
+ return {
1006
+ recommendations: Array.from(merged.values()).sort((a, b) => b.score - a.score),
1007
+ context: cloud.context,
1008
+ totalEvaluated: cloud.totalEvaluated + local.totalEvaluated,
1009
+ source: "hybrid",
1010
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1011
+ };
1012
+ }
1013
+ /**
1014
+ * Filter out already installed plugins
1015
+ *
1016
+ * @param recommendations - Plugin recommendations
1017
+ * @returns Filtered recommendations (non-installed only)
1018
+ */
1019
+ filterInstalledPlugins(recommendations) {
1020
+ return recommendations.filter((rec) => !rec.isInstalled);
1021
+ }
1022
+ /**
1023
+ * Calculate relevance score for a plugin
1024
+ *
1025
+ * Scores are based on:
1026
+ * - Category match (40 points)
1027
+ * - Tag match (30 points)
1028
+ * - Framework match (20 points)
1029
+ * - Language match (10 points)
1030
+ *
1031
+ * @param plugin - Plugin to score
1032
+ * @param context - Project context
1033
+ * @returns Relevance score (0-100)
1034
+ */
1035
+ calculateRelevanceScore(plugin, context) {
1036
+ let score = 0;
1037
+ if (context.recommendedCategories?.includes(plugin.category)) {
1038
+ score += 40;
1039
+ }
1040
+ const matchingTags = this.getMatchingTags(plugin, context);
1041
+ score += Math.min(matchingTags.length * 5, 30);
1042
+ if (context.frameworks) {
1043
+ for (const framework of context.frameworks) {
1044
+ if (plugin.tags.some((tag) => tag.toLowerCase().includes(framework.toLowerCase()))) {
1045
+ score += 10;
1046
+ }
1047
+ }
1048
+ score = Math.min(score, 60);
1049
+ }
1050
+ if (context.languages) {
1051
+ for (const lang of context.languages) {
1052
+ if (plugin.tags.some((tag) => tag.toLowerCase().includes(lang.toLowerCase()))) {
1053
+ score += 10;
1054
+ break;
1055
+ }
1056
+ }
1057
+ }
1058
+ return Math.min(score, 100);
1059
+ }
1060
+ /**
1061
+ * Get matching tags between plugin and context
1062
+ *
1063
+ * @param plugin - Plugin to check
1064
+ * @param context - Project context
1065
+ * @returns Array of matching tags
1066
+ */
1067
+ getMatchingTags(plugin, context) {
1068
+ const contextTags = context.recommendedTags || [];
1069
+ return plugin.tags.filter(
1070
+ (tag) => contextTags.some((ctag) => ctag.toLowerCase() === tag.toLowerCase())
1071
+ );
1072
+ }
1073
+ /**
1074
+ * Get matching categories between plugin and context
1075
+ *
1076
+ * @param plugin - Plugin to check
1077
+ * @param context - Project context
1078
+ * @returns Array of matching categories
1079
+ */
1080
+ getMatchingCategories(plugin, context) {
1081
+ const contextCategories = context.recommendedCategories || [];
1082
+ return contextCategories.includes(plugin.category) ? [plugin.category] : [];
1083
+ }
1084
+ /**
1085
+ * Calculate confidence level for recommendation
1086
+ *
1087
+ * Confidence is based on:
1088
+ * - Number of matching signals
1089
+ * - Score magnitude
1090
+ * - Plugin popularity (downloads, rating)
1091
+ *
1092
+ * @param score - Relevance score
1093
+ * @param matchingTagsCount - Number of matching tags
1094
+ * @param matchingCategoriesCount - Number of matching categories
1095
+ * @returns Confidence level (0-1)
1096
+ */
1097
+ calculateConfidence(score, matchingTagsCount, matchingCategoriesCount) {
1098
+ let confidence = score / 100;
1099
+ const signalCount = matchingTagsCount + matchingCategoriesCount;
1100
+ if (signalCount >= 3) {
1101
+ confidence += 0.1;
1102
+ }
1103
+ if (signalCount >= 5) {
1104
+ confidence += 0.1;
1105
+ }
1106
+ return Math.min(confidence, 1);
1107
+ }
1108
+ /**
1109
+ * Generate localized recommendation reason
1110
+ *
1111
+ * Creates human-readable explanation for why a plugin is recommended.
1112
+ *
1113
+ * @param _plugin - Recommended plugin (unused, reserved for future use)
1114
+ * @param context - Project context
1115
+ * @param matchingTags - Matching tags
1116
+ * @param matchingCategories - Matching categories
1117
+ * @returns Localized reason strings
1118
+ */
1119
+ generateReason(_plugin, context, matchingTags, matchingCategories) {
1120
+ const reasons = {
1121
+ "en": "",
1122
+ "zh-CN": ""
1123
+ };
1124
+ const reasonParts = { "en": [], "zh-CN": [] };
1125
+ if (context.projectType) {
1126
+ reasonParts.en.push(`Recommended for ${context.projectType} projects`);
1127
+ reasonParts["zh-CN"].push(`\u63A8\u8350\u7528\u4E8E ${context.projectType} \u9879\u76EE`);
1128
+ }
1129
+ if (matchingCategories.length > 0) {
1130
+ const categoryNames = matchingCategories.join(", ");
1131
+ reasonParts.en.push(`Matches ${categoryNames} category`);
1132
+ reasonParts["zh-CN"].push(`\u5339\u914D ${categoryNames} \u7C7B\u522B`);
1133
+ }
1134
+ if (matchingTags.length > 0) {
1135
+ const tagList = matchingTags.slice(0, 3).join(", ");
1136
+ reasonParts.en.push(`Relevant tags: ${tagList}`);
1137
+ reasonParts["zh-CN"].push(`\u76F8\u5173\u6807\u7B7E: ${tagList}`);
1138
+ }
1139
+ if (context.frameworks && context.frameworks.length > 0) {
1140
+ const frameworks = context.frameworks.slice(0, 2).join(", ");
1141
+ reasonParts.en.push(`Works with ${frameworks}`);
1142
+ reasonParts["zh-CN"].push(`\u9002\u7528\u4E8E ${frameworks}`);
1143
+ }
1144
+ reasons.en = reasonParts.en.join(". ");
1145
+ reasons["zh-CN"] = reasonParts["zh-CN"].join("\u3002");
1146
+ if (!reasons.en) {
1147
+ reasons.en = "General purpose plugin for your project";
1148
+ reasons["zh-CN"] = "\u9002\u7528\u4E8E\u60A8\u9879\u76EE\u7684\u901A\u7528\u63D2\u4EF6";
1149
+ }
1150
+ return reasons;
1151
+ }
1152
+ /**
1153
+ * Get recommendations based on tags
1154
+ *
1155
+ * @param tags - Tags to match
1156
+ * @returns Matching plugins
1157
+ */
1158
+ getTagBasedRecommendations(tags) {
1159
+ const allPlugins = this.cache.getCachedPlugins();
1160
+ return allPlugins.filter(
1161
+ (plugin) => tags.some((tag) => plugin.tags.includes(tag))
1162
+ );
1163
+ }
1164
+ /**
1165
+ * Get recommendations based on category
1166
+ *
1167
+ * @param category - Category to match
1168
+ * @returns Matching plugins
1169
+ */
1170
+ getCategoryBasedRecommendations(category) {
1171
+ const allPlugins = this.cache.getCachedPlugins();
1172
+ return allPlugins.filter((plugin) => plugin.category === category);
1173
+ }
1174
+ }
1175
+
1176
+ let managerInstance = null;
1177
+ function getCloudPluginManager() {
1178
+ if (!managerInstance) {
1179
+ managerInstance = new CloudPluginManager();
1180
+ }
1181
+ return managerInstance;
1182
+ }
1183
+ class CloudPluginManager {
1184
+ client;
1185
+ cache;
1186
+ engine;
1187
+ constructor() {
1188
+ this.ensureDirectories();
1189
+ this.client = new CloudRecommendationClient();
1190
+ this.cache = new LocalPluginCache();
1191
+ this.engine = new RecommendationEngine(this.client, this.cache);
1192
+ }
1193
+ /**
1194
+ * Ensure all required directories exist
1195
+ */
1196
+ ensureDirectories() {
1197
+ const dirs = [
1198
+ CCJK_CLOUD_PLUGINS_DIR,
1199
+ CCJK_CLOUD_PLUGINS_CACHE_DIR,
1200
+ CCJK_CLOUD_PLUGINS_INSTALLED_DIR
1201
+ ];
1202
+ for (const dir of dirs) {
1203
+ if (!existsSync(dir)) {
1204
+ mkdirSync(dir, { recursive: true });
1205
+ }
1206
+ }
1207
+ }
1208
+ /**
1209
+ * Get plugin recommendations for current project
1210
+ */
1211
+ async getRecommendations(projectPath) {
1212
+ return this.engine.getRecommendations(projectPath);
1213
+ }
1214
+ /**
1215
+ * Search for plugins
1216
+ */
1217
+ async searchPlugins(params) {
1218
+ const cloudResult = await this.client.searchPlugins(params);
1219
+ if (cloudResult.success && cloudResult.data) {
1220
+ this.cache.updateCache(cloudResult.data);
1221
+ return cloudResult;
1222
+ }
1223
+ const cachedPlugins = this.cache.getCachedPlugins();
1224
+ let filtered = cachedPlugins;
1225
+ if (params.query) {
1226
+ const query = params.query.toLowerCase();
1227
+ filtered = filtered.filter(
1228
+ (p) => p.name.en.toLowerCase().includes(query) || p.name["zh-CN"].toLowerCase().includes(query) || p.tags.some((t) => t.toLowerCase().includes(query))
1229
+ );
1230
+ }
1231
+ if (params.category) {
1232
+ filtered = filtered.filter((p) => p.category === params.category);
1233
+ }
1234
+ if (params.tags && params.tags.length > 0) {
1235
+ filtered = filtered.filter(
1236
+ (p) => params.tags.some((tag) => p.tags.includes(tag))
1237
+ );
1238
+ }
1239
+ if (params.sortBy) {
1240
+ filtered.sort((a, b) => {
1241
+ const order = params.order === "asc" ? 1 : -1;
1242
+ switch (params.sortBy) {
1243
+ case "downloads":
1244
+ return (a.downloads - b.downloads) * order;
1245
+ case "rating":
1246
+ return (a.rating - b.rating) * order;
1247
+ case "updated":
1248
+ return (new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime()) * order;
1249
+ case "name":
1250
+ return a.name.en.localeCompare(b.name.en) * order;
1251
+ default:
1252
+ return 0;
1253
+ }
1254
+ });
1255
+ }
1256
+ const page = params.page || 1;
1257
+ const pageSize = params.pageSize || 10;
1258
+ const start = (page - 1) * pageSize;
1259
+ const paged = filtered.slice(start, start + pageSize);
1260
+ return {
1261
+ success: true,
1262
+ data: paged
1263
+ };
1264
+ }
1265
+ /**
1266
+ * Get plugin details
1267
+ */
1268
+ async getPlugin(id) {
1269
+ const cloudResult = await this.client.getPlugin(id);
1270
+ if (cloudResult.success && cloudResult.data) {
1271
+ return cloudResult;
1272
+ }
1273
+ const cached = this.cache.getCachedPlugin(id);
1274
+ if (cached) {
1275
+ return { success: true, data: cached };
1276
+ }
1277
+ return {
1278
+ success: false,
1279
+ error: i18n.t("cloudPlugins.errors.notFound")
1280
+ };
1281
+ }
1282
+ /**
1283
+ * Get popular plugins
1284
+ */
1285
+ async getPopularPlugins(limit = 10) {
1286
+ const cloudResult = await this.client.getPopularPlugins(limit);
1287
+ if (cloudResult.success && cloudResult.data) {
1288
+ this.cache.updateCache(cloudResult.data);
1289
+ return cloudResult;
1290
+ }
1291
+ const cached = this.cache.getCachedPlugins().sort((a, b) => b.downloads - a.downloads).slice(0, limit);
1292
+ return { success: true, data: cached };
1293
+ }
1294
+ /**
1295
+ * Get plugin categories
1296
+ */
1297
+ async getCategories() {
1298
+ return this.client.getCategories();
1299
+ }
1300
+ /**
1301
+ * Install a plugin
1302
+ */
1303
+ async installPlugin(id, options = {}) {
1304
+ const installDir = join(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, id);
1305
+ if (existsSync(installDir) && !options.force) {
1306
+ return {
1307
+ pluginId: id,
1308
+ success: false,
1309
+ error: "Plugin already installed. Use --force to reinstall."
1310
+ };
1311
+ }
1312
+ if (options.dryRun) {
1313
+ return {
1314
+ pluginId: id,
1315
+ success: true,
1316
+ installedPath: installDir
1317
+ };
1318
+ }
1319
+ try {
1320
+ const pluginResult = await this.getPlugin(id);
1321
+ if (!pluginResult.success || !pluginResult.data) {
1322
+ return {
1323
+ pluginId: id,
1324
+ success: false,
1325
+ error: pluginResult.error || "Plugin not found"
1326
+ };
1327
+ }
1328
+ const plugin = pluginResult.data;
1329
+ const downloadResult = await this.client.downloadPlugin(id);
1330
+ if (!downloadResult.success || !downloadResult.data) {
1331
+ return {
1332
+ pluginId: id,
1333
+ success: false,
1334
+ error: downloadResult.error || "Failed to download plugin"
1335
+ };
1336
+ }
1337
+ if (existsSync(installDir)) {
1338
+ rmSync(installDir, { recursive: true });
1339
+ }
1340
+ mkdirSync(installDir, { recursive: true });
1341
+ writeFileAtomic(
1342
+ join(installDir, "plugin.json"),
1343
+ JSON.stringify(plugin, null, 2)
1344
+ );
1345
+ const content = Buffer.from(downloadResult.data.content, "base64").toString("utf-8");
1346
+ writeFileAtomic(join(installDir, "content.json"), content);
1347
+ const installedDeps = [];
1348
+ if (!options.skipDependencies && plugin.dependencies) {
1349
+ for (const dep of plugin.dependencies) {
1350
+ const depResult = await this.installPlugin(dep, { skipDependencies: true });
1351
+ if (depResult.success) {
1352
+ installedDeps.push(dep);
1353
+ }
1354
+ }
1355
+ }
1356
+ return {
1357
+ pluginId: id,
1358
+ success: true,
1359
+ installedPath: installDir,
1360
+ dependencies: installedDeps
1361
+ };
1362
+ } catch (error) {
1363
+ return {
1364
+ pluginId: id,
1365
+ success: false,
1366
+ error: error instanceof Error ? error.message : "Unknown error"
1367
+ };
1368
+ }
1369
+ }
1370
+ /**
1371
+ * Uninstall a plugin
1372
+ */
1373
+ async uninstallPlugin(id) {
1374
+ const installDir = join(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, id);
1375
+ if (!existsSync(installDir)) {
1376
+ return {
1377
+ pluginId: id,
1378
+ success: false,
1379
+ error: "Plugin not installed"
1380
+ };
1381
+ }
1382
+ try {
1383
+ rmSync(installDir, { recursive: true });
1384
+ return {
1385
+ pluginId: id,
1386
+ success: true
1387
+ };
1388
+ } catch (error) {
1389
+ return {
1390
+ pluginId: id,
1391
+ success: false,
1392
+ error: error instanceof Error ? error.message : "Unknown error"
1393
+ };
1394
+ }
1395
+ }
1396
+ /**
1397
+ * Get installed plugins
1398
+ */
1399
+ getInstalledPlugins() {
1400
+ if (!existsSync(CCJK_CLOUD_PLUGINS_INSTALLED_DIR)) {
1401
+ return [];
1402
+ }
1403
+ const plugins = [];
1404
+ const dirs = readdirSync(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
1405
+ for (const dir of dirs) {
1406
+ const metaPath = join(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, dir, "plugin.json");
1407
+ if (existsSync(metaPath)) {
1408
+ try {
1409
+ const plugin = JSON.parse(readFileSync(metaPath, "utf-8"));
1410
+ plugins.push(plugin);
1411
+ } catch {
1412
+ }
1413
+ }
1414
+ }
1415
+ return plugins;
1416
+ }
1417
+ /**
1418
+ * Check if a plugin is installed
1419
+ */
1420
+ isPluginInstalled(id) {
1421
+ const installDir = join(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, id);
1422
+ return existsSync(join(installDir, "plugin.json"));
1423
+ }
1424
+ /**
1425
+ * Update installed plugins
1426
+ */
1427
+ async updatePlugins(ids) {
1428
+ const installed = this.getInstalledPlugins();
1429
+ const toUpdate = ids ? installed.filter((p) => ids.includes(p.id)) : installed;
1430
+ const results = [];
1431
+ for (const plugin of toUpdate) {
1432
+ const cloudResult = await this.getPlugin(plugin.id);
1433
+ if (cloudResult.success && cloudResult.data) {
1434
+ const cloudPlugin = cloudResult.data;
1435
+ if (cloudPlugin.version !== plugin.version) {
1436
+ const result = await this.installPlugin(plugin.id, { force: true });
1437
+ results.push(result);
1438
+ } else {
1439
+ results.push({
1440
+ pluginId: plugin.id,
1441
+ success: true,
1442
+ installedPath: join(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, plugin.id)
1443
+ });
1444
+ }
1445
+ }
1446
+ }
1447
+ return results;
1448
+ }
1449
+ /**
1450
+ * Get cache statistics
1451
+ */
1452
+ getCacheStats() {
1453
+ return this.cache.getCacheStats();
1454
+ }
1455
+ /**
1456
+ * Clear cache
1457
+ */
1458
+ clearCache() {
1459
+ this.cache.clearCache();
1460
+ }
1461
+ /**
1462
+ * Refresh cache from cloud
1463
+ */
1464
+ async refreshCache() {
1465
+ const result = await this.client.getPopularPlugins(100);
1466
+ if (result.success && result.data) {
1467
+ this.cache.updateCache(result.data);
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Get plugin info (alias for getPlugin with simplified return)
1472
+ */
1473
+ async getPluginInfo(id) {
1474
+ const result = await this.getPlugin(id);
1475
+ return result.success && result.data ? result.data : null;
1476
+ }
1477
+ /**
1478
+ * Get featured/popular plugins
1479
+ */
1480
+ async getFeaturedPlugins(limit = 10) {
1481
+ const result = await this.getPopularPlugins(limit);
1482
+ return result.success && result.data ? result.data : [];
1483
+ }
1484
+ /**
1485
+ * Update a single plugin
1486
+ */
1487
+ async updatePlugin(id) {
1488
+ if (!this.isPluginInstalled(id)) {
1489
+ return {
1490
+ success: false,
1491
+ pluginId: id,
1492
+ updated: false,
1493
+ error: "Plugin not installed"
1494
+ };
1495
+ }
1496
+ const installDir = join(CCJK_CLOUD_PLUGINS_INSTALLED_DIR, id);
1497
+ const metaPath = join(installDir, "plugin.json");
1498
+ let currentVersion = "0.0.0";
1499
+ try {
1500
+ const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
1501
+ currentVersion = meta.version || "0.0.0";
1502
+ } catch {
1503
+ }
1504
+ const cloudResult = await this.getPlugin(id);
1505
+ if (!cloudResult.success || !cloudResult.data) {
1506
+ return {
1507
+ success: false,
1508
+ pluginId: id,
1509
+ updated: false,
1510
+ error: cloudResult.error || "Failed to fetch plugin info"
1511
+ };
1512
+ }
1513
+ const cloudPlugin = cloudResult.data;
1514
+ if (cloudPlugin.version === currentVersion) {
1515
+ return {
1516
+ success: true,
1517
+ pluginId: id,
1518
+ updated: false,
1519
+ oldVersion: currentVersion,
1520
+ newVersion: currentVersion
1521
+ };
1522
+ }
1523
+ const installResult = await this.installPlugin(id, { force: true });
1524
+ if (!installResult.success) {
1525
+ return {
1526
+ success: false,
1527
+ pluginId: id,
1528
+ updated: false,
1529
+ error: installResult.error
1530
+ };
1531
+ }
1532
+ return {
1533
+ success: true,
1534
+ pluginId: id,
1535
+ updated: true,
1536
+ oldVersion: currentVersion,
1537
+ newVersion: cloudPlugin.version
1538
+ };
1539
+ }
1540
+ /**
1541
+ * Update all installed plugins
1542
+ */
1543
+ async updateAllPlugins() {
1544
+ const installed = this.getInstalledPlugins();
1545
+ const results = [];
1546
+ for (const plugin of installed) {
1547
+ const result = await this.updatePlugin(plugin.id);
1548
+ results.push(result);
1549
+ }
1550
+ return results;
1551
+ }
1552
+ }
1553
+
1554
+ function getPluginName(plugin) {
1555
+ const lang = i18n.language;
1556
+ return plugin.name[lang] || plugin.name.en || plugin.id;
1557
+ }
1558
+ function getPluginDescription(plugin) {
1559
+ const lang = i18n.language;
1560
+ return plugin.description[lang] || plugin.description.en || "";
1561
+ }
1562
+ async function pluginCommand(action = "list", args = [], options = {}) {
1563
+ const isZh = i18n.language === "zh-CN";
1564
+ try {
1565
+ switch (action) {
1566
+ case "list":
1567
+ case "ls":
1568
+ case "l":
1569
+ await listPlugins(options);
1570
+ break;
1571
+ case "install":
1572
+ case "i":
1573
+ case "add":
1574
+ if (args.length === 0) {
1575
+ console.log(ansis.red(isZh ? "\u274C \u8BF7\u6307\u5B9A\u8981\u5B89\u88C5\u7684\u63D2\u4EF6 ID" : "\u274C Please specify a plugin ID to install"));
1576
+ console.log(ansis.gray(isZh ? "\u7528\u6CD5: /plugin install <plugin-id>" : "Usage: /plugin install <plugin-id>"));
1577
+ process__default.exit(1);
1578
+ }
1579
+ await installPlugin(args[0], options);
1580
+ break;
1581
+ case "uninstall":
1582
+ case "remove":
1583
+ case "rm":
1584
+ if (args.length === 0) {
1585
+ console.log(ansis.red(isZh ? "\u274C \u8BF7\u6307\u5B9A\u8981\u5378\u8F7D\u7684\u63D2\u4EF6 ID" : "\u274C Please specify a plugin ID to uninstall"));
1586
+ console.log(ansis.gray(isZh ? "\u7528\u6CD5: /plugin uninstall <plugin-id>" : "Usage: /plugin uninstall <plugin-id>"));
1587
+ process__default.exit(1);
1588
+ }
1589
+ await uninstallPlugin(args[0]);
1590
+ break;
1591
+ case "search":
1592
+ case "s":
1593
+ case "find":
1594
+ if (args.length === 0) {
1595
+ console.log(ansis.red(isZh ? "\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD" : "\u274C Please specify a search query"));
1596
+ console.log(ansis.gray(isZh ? "\u7528\u6CD5: /plugin search <\u5173\u952E\u8BCD>" : "Usage: /plugin search <query>"));
1597
+ process__default.exit(1);
1598
+ }
1599
+ await searchPlugins(args.join(" "), options);
1600
+ break;
1601
+ case "info":
1602
+ case "show":
1603
+ case "details":
1604
+ if (args.length === 0) {
1605
+ console.log(ansis.red(isZh ? "\u274C \u8BF7\u6307\u5B9A\u63D2\u4EF6 ID" : "\u274C Please specify a plugin ID"));
1606
+ console.log(ansis.gray(isZh ? "\u7528\u6CD5: /plugin info <plugin-id>" : "Usage: /plugin info <plugin-id>"));
1607
+ process__default.exit(1);
1608
+ }
1609
+ await showPluginInfo(args[0]);
1610
+ break;
1611
+ case "update":
1612
+ case "upgrade":
1613
+ await updatePlugins(args[0]);
1614
+ break;
1615
+ case "categories":
1616
+ case "cats":
1617
+ await listCategories();
1618
+ break;
1619
+ case "featured":
1620
+ case "popular":
1621
+ case "trending":
1622
+ await showFeaturedPlugins();
1623
+ break;
1624
+ case "help":
1625
+ case "h":
1626
+ case "?":
1627
+ showHelp();
1628
+ break;
1629
+ default:
1630
+ console.log(ansis.red(isZh ? `\u274C \u672A\u77E5\u547D\u4EE4: ${action}` : `\u274C Unknown command: ${action}`));
1631
+ showHelp();
1632
+ process__default.exit(1);
1633
+ }
1634
+ } catch (error) {
1635
+ const errorMessage = error instanceof Error ? error.message : String(error);
1636
+ console.log(ansis.red(`
1637
+ \u274C ${isZh ? "\u9519\u8BEF" : "Error"}: ${errorMessage}`));
1638
+ if (options.verbose) {
1639
+ console.error(error);
1640
+ }
1641
+ process__default.exit(1);
1642
+ }
1643
+ }
1644
+ async function listPlugins(options) {
1645
+ const isZh = i18n.language === "zh-CN";
1646
+ const manager = getCloudPluginManager();
1647
+ console.log(ansis.green.bold(`
1648
+ \u{1F4E6} ${isZh ? "\u5DF2\u5B89\u88C5\u7684\u63D2\u4EF6" : "Installed Plugins"}
1649
+ `));
1650
+ const installed = manager.getInstalledPlugins();
1651
+ if (installed.length === 0) {
1652
+ console.log(ansis.gray(isZh ? "\u6682\u65E0\u5DF2\u5B89\u88C5\u7684\u63D2\u4EF6" : "No plugins installed"));
1653
+ console.log(ansis.gray(`
1654
+ \u{1F4A1} ${isZh ? "\u4F7F\u7528 /plugin search <\u5173\u952E\u8BCD> \u641C\u7D22\u63D2\u4EF6" : "Use /plugin search <query> to find plugins"}`));
1655
+ return;
1656
+ }
1657
+ for (const plugin of installed) {
1658
+ console.log(` ${ansis.green("\u25CF")} ${ansis.bold(getPluginName(plugin))} ${ansis.gray(`v${plugin.version}`)}`);
1659
+ console.log(` ${ansis.gray(getPluginDescription(plugin))}`);
1660
+ if (options.verbose && plugin.author) {
1661
+ console.log(` ${ansis.gray(`by ${plugin.author}`)}`);
1662
+ }
1663
+ console.log("");
1664
+ }
1665
+ console.log(ansis.gray(`${isZh ? "\u5171" : "Total"} ${installed.length} ${isZh ? "\u4E2A\u63D2\u4EF6" : "plugins"}`));
1666
+ }
1667
+ async function installPlugin(pluginId, options) {
1668
+ const isZh = i18n.language === "zh-CN";
1669
+ const manager = getCloudPluginManager();
1670
+ console.log(ansis.green(`
1671
+ \u23F3 ${isZh ? "\u6B63\u5728\u83B7\u53D6\u63D2\u4EF6\u4FE1\u606F..." : "Fetching plugin info..."}`));
1672
+ const pluginInfo = await manager.getPluginInfo(pluginId);
1673
+ if (!pluginInfo) {
1674
+ console.log(ansis.red(`
1675
+ \u274C ${isZh ? "\u63D2\u4EF6\u672A\u627E\u5230" : "Plugin not found"}: ${pluginId}`));
1676
+ console.log(ansis.gray(`
1677
+ \u{1F4A1} ${isZh ? "\u4F7F\u7528 /plugin search <\u5173\u952E\u8BCD> \u641C\u7D22\u53EF\u7528\u63D2\u4EF6" : "Use /plugin search <query> to find available plugins"}`));
1678
+ const searchResult = await manager.searchPlugins({ query: pluginId, pageSize: 3 });
1679
+ if (searchResult.success && searchResult.data && searchResult.data.length > 0) {
1680
+ console.log(ansis.yellow(`
1681
+ ${isZh ? "\u60A8\u662F\u5426\u5728\u627E:" : "Did you mean:"}`));
1682
+ for (const p of searchResult.data) {
1683
+ console.log(` - ${ansis.green(p.id)} - ${getPluginName(p)}`);
1684
+ }
1685
+ }
1686
+ process__default.exit(1);
1687
+ }
1688
+ const isInstalled = manager.isPluginInstalled(pluginId);
1689
+ if (isInstalled && !options.force) {
1690
+ console.log(ansis.yellow(`
1691
+ \u26A0\uFE0F ${isZh ? "\u63D2\u4EF6\u5DF2\u5B89\u88C5" : "Plugin already installed"}: ${getPluginName(pluginInfo)}`));
1692
+ console.log(ansis.gray(`\u{1F4A1} ${isZh ? "\u4F7F\u7528 --force \u5F3A\u5236\u91CD\u65B0\u5B89\u88C5" : "Use --force to reinstall"}`));
1693
+ return;
1694
+ }
1695
+ console.log(ansis.green.bold(`
1696
+ \u{1F4E6} ${getPluginName(pluginInfo)}`));
1697
+ console.log(ansis.gray(` ${getPluginDescription(pluginInfo)}`));
1698
+ console.log(ansis.gray(` ${isZh ? "\u7248\u672C" : "Version"}: ${pluginInfo.version}`));
1699
+ if (pluginInfo.author) {
1700
+ console.log(ansis.gray(` ${isZh ? "\u4F5C\u8005" : "Author"}: ${pluginInfo.author}`));
1701
+ }
1702
+ console.log("");
1703
+ console.log(ansis.green(`\u23F3 ${isZh ? "\u6B63\u5728\u5B89\u88C5..." : "Installing..."}`));
1704
+ const result = await manager.installPlugin(pluginId, {
1705
+ force: options.force
1706
+ });
1707
+ if (result.success) {
1708
+ console.log(ansis.green(`
1709
+ \u2705 ${isZh ? "\u5B89\u88C5\u6210\u529F" : "Installation successful"}!`));
1710
+ console.log(ansis.gray(` ${isZh ? "\u8DEF\u5F84" : "Path"}: ${result.installedPath}`));
1711
+ if (result.dependencies && result.dependencies.length > 0) {
1712
+ console.log(ansis.gray(` ${isZh ? "\u4F9D\u8D56" : "Dependencies"}: ${result.dependencies.join(", ")}`));
1713
+ }
1714
+ } else {
1715
+ console.log(ansis.red(`
1716
+ \u274C ${isZh ? "\u5B89\u88C5\u5931\u8D25" : "Installation failed"}: ${result.error}`));
1717
+ process__default.exit(1);
1718
+ }
1719
+ }
1720
+ async function uninstallPlugin(pluginId) {
1721
+ const isZh = i18n.language === "zh-CN";
1722
+ const manager = getCloudPluginManager();
1723
+ const isInstalled = manager.isPluginInstalled(pluginId);
1724
+ if (!isInstalled) {
1725
+ console.log(ansis.yellow(`
1726
+ \u26A0\uFE0F ${isZh ? "\u63D2\u4EF6\u672A\u5B89\u88C5" : "Plugin not installed"}: ${pluginId}`));
1727
+ return;
1728
+ }
1729
+ console.log(ansis.green(`
1730
+ \u23F3 ${isZh ? "\u6B63\u5728\u5378\u8F7D..." : "Uninstalling..."}`));
1731
+ const result = await manager.uninstallPlugin(pluginId);
1732
+ if (result.success) {
1733
+ console.log(ansis.green(`
1734
+ \u2705 ${isZh ? "\u5378\u8F7D\u6210\u529F" : "Uninstallation successful"}!`));
1735
+ } else {
1736
+ console.log(ansis.red(`
1737
+ \u274C ${isZh ? "\u5378\u8F7D\u5931\u8D25" : "Uninstallation failed"}: ${result.error}`));
1738
+ process__default.exit(1);
1739
+ }
1740
+ }
1741
+ async function searchPlugins(query, options) {
1742
+ const isZh = i18n.language === "zh-CN";
1743
+ const manager = getCloudPluginManager();
1744
+ console.log(ansis.green(`
1745
+ \u{1F50D} ${isZh ? "\u641C\u7D22" : "Searching"}: "${query}"
1746
+ `));
1747
+ const result = await manager.searchPlugins({ query, pageSize: 20 });
1748
+ if (!result.success || !result.data || result.data.length === 0) {
1749
+ console.log(ansis.yellow(isZh ? "\u672A\u627E\u5230\u5339\u914D\u7684\u63D2\u4EF6" : "No plugins found"));
1750
+ console.log(ansis.gray(`
1751
+ \u{1F4A1} ${isZh ? "\u5C1D\u8BD5\u4F7F\u7528\u4E0D\u540C\u7684\u5173\u952E\u8BCD" : "Try different keywords"}`));
1752
+ return;
1753
+ }
1754
+ console.log(ansis.bold(isZh ? "\u641C\u7D22\u7ED3\u679C:" : "Search Results:"));
1755
+ console.log("");
1756
+ for (const plugin of result.data) {
1757
+ const installed = manager.isPluginInstalled(plugin.id);
1758
+ const statusIcon = installed ? ansis.green("\u25CF") : ansis.gray("\u25CB");
1759
+ console.log(` ${statusIcon} ${ansis.bold(getPluginName(plugin))} ${ansis.gray(`(${plugin.id})`)} ${ansis.gray(`v${plugin.version}`)}`);
1760
+ console.log(` ${ansis.gray(getPluginDescription(plugin))}`);
1761
+ if (options.verbose) {
1762
+ if (plugin.downloads) {
1763
+ console.log(` ${ansis.gray(`\u2B07\uFE0F ${plugin.downloads.toLocaleString()} downloads`)}`);
1764
+ }
1765
+ if (plugin.rating) {
1766
+ console.log(` ${ansis.gray(`\u2B50 ${plugin.rating.toFixed(1)}`)}`);
1767
+ }
1768
+ }
1769
+ console.log("");
1770
+ }
1771
+ console.log(ansis.gray(`${isZh ? "\u5171\u627E\u5230" : "Found"} ${result.data.length} ${isZh ? "\u4E2A\u63D2\u4EF6" : "plugins"}`));
1772
+ console.log(ansis.gray(`
1773
+ \u{1F4A1} ${isZh ? "\u4F7F\u7528 /plugin install <id> \u5B89\u88C5\u63D2\u4EF6" : "Use /plugin install <id> to install a plugin"}`));
1774
+ }
1775
+ async function showPluginInfo(pluginId) {
1776
+ const isZh = i18n.language === "zh-CN";
1777
+ const manager = getCloudPluginManager();
1778
+ const plugin = await manager.getPluginInfo(pluginId);
1779
+ if (!plugin) {
1780
+ console.log(ansis.red(`
1781
+ \u274C ${isZh ? "\u63D2\u4EF6\u672A\u627E\u5230" : "Plugin not found"}: ${pluginId}`));
1782
+ process__default.exit(1);
1783
+ }
1784
+ const installed = manager.isPluginInstalled(pluginId);
1785
+ console.log(ansis.green.bold(`
1786
+ \u{1F4E6} ${getPluginName(plugin)}`));
1787
+ console.log(ansis.dim("\u2500".repeat(50)));
1788
+ console.log(`${ansis.bold(isZh ? "\u63CF\u8FF0" : "Description")}: ${getPluginDescription(plugin)}`);
1789
+ console.log(`${ansis.bold("ID")}: ${plugin.id}`);
1790
+ console.log(`${ansis.bold(isZh ? "\u7248\u672C" : "Version")}: ${plugin.version}`);
1791
+ console.log(`${ansis.bold(isZh ? "\u72B6\u6001" : "Status")}: ${installed ? ansis.green(isZh ? "\u5DF2\u5B89\u88C5" : "Installed") : ansis.gray(isZh ? "\u672A\u5B89\u88C5" : "Not installed")}`);
1792
+ if (plugin.author) {
1793
+ console.log(`${ansis.bold(isZh ? "\u4F5C\u8005" : "Author")}: ${plugin.author}`);
1794
+ }
1795
+ if (plugin.category) {
1796
+ console.log(`${ansis.bold(isZh ? "\u5206\u7C7B" : "Category")}: ${plugin.category}`);
1797
+ }
1798
+ if (plugin.tags && plugin.tags.length > 0) {
1799
+ console.log(`${ansis.bold(isZh ? "\u6807\u7B7E" : "Tags")}: ${plugin.tags.join(", ")}`);
1800
+ }
1801
+ if (plugin.downloads) {
1802
+ console.log(`${ansis.bold(isZh ? "\u4E0B\u8F7D\u91CF" : "Downloads")}: ${plugin.downloads.toLocaleString()}`);
1803
+ }
1804
+ if (plugin.rating) {
1805
+ console.log(`${ansis.bold(isZh ? "\u8BC4\u5206" : "Rating")}: \u2B50 ${plugin.rating.toFixed(1)}`);
1806
+ }
1807
+ console.log(ansis.dim("\u2500".repeat(50)));
1808
+ if (!installed) {
1809
+ console.log(ansis.gray(`
1810
+ \u{1F4A1} ${isZh ? "\u4F7F\u7528 /plugin install" : "Use /plugin install"} ${pluginId} ${isZh ? "\u5B89\u88C5\u6B64\u63D2\u4EF6" : "to install this plugin"}`));
1811
+ }
1812
+ }
1813
+ async function updatePlugins(pluginId) {
1814
+ const isZh = i18n.language === "zh-CN";
1815
+ const manager = getCloudPluginManager();
1816
+ if (pluginId) {
1817
+ console.log(ansis.green(`
1818
+ \u23F3 ${isZh ? "\u6B63\u5728\u66F4\u65B0" : "Updating"} ${pluginId}...`));
1819
+ const result = await manager.updatePlugin(pluginId);
1820
+ if (result.success) {
1821
+ if (result.updated) {
1822
+ console.log(ansis.green(`
1823
+ \u2705 ${isZh ? "\u66F4\u65B0\u6210\u529F" : "Update successful"}! ${result.oldVersion} \u2192 ${result.newVersion}`));
1824
+ } else {
1825
+ console.log(ansis.gray(`
1826
+ \u2713 ${isZh ? "\u5DF2\u662F\u6700\u65B0\u7248\u672C" : "Already up to date"}`));
1827
+ }
1828
+ } else {
1829
+ console.log(ansis.red(`
1830
+ \u274C ${isZh ? "\u66F4\u65B0\u5931\u8D25" : "Update failed"}: ${result.error}`));
1831
+ process__default.exit(1);
1832
+ }
1833
+ } else {
1834
+ console.log(ansis.green(`
1835
+ \u23F3 ${isZh ? "\u6B63\u5728\u68C0\u67E5\u66F4\u65B0..." : "Checking for updates..."}`));
1836
+ const results = await manager.updateAllPlugins();
1837
+ let updatedCount = 0;
1838
+ for (const result of results) {
1839
+ if (result.success && result.updated) {
1840
+ console.log(ansis.green(` \u2705 ${result.pluginId}: ${result.oldVersion} \u2192 ${result.newVersion}`));
1841
+ updatedCount++;
1842
+ }
1843
+ }
1844
+ if (updatedCount === 0) {
1845
+ console.log(ansis.gray(`
1846
+ \u2713 ${isZh ? "\u6240\u6709\u63D2\u4EF6\u5DF2\u662F\u6700\u65B0\u7248\u672C" : "All plugins are up to date"}`));
1847
+ } else {
1848
+ console.log(ansis.green(`
1849
+ \u2705 ${isZh ? "\u5DF2\u66F4\u65B0" : "Updated"} ${updatedCount} ${isZh ? "\u4E2A\u63D2\u4EF6" : "plugins"}`));
1850
+ }
1851
+ }
1852
+ }
1853
+ async function listCategories() {
1854
+ const isZh = i18n.language === "zh-CN";
1855
+ const manager = getCloudPluginManager();
1856
+ console.log(ansis.green.bold(`
1857
+ \u{1F4C2} ${isZh ? "\u63D2\u4EF6\u5206\u7C7B" : "Plugin Categories"}
1858
+ `));
1859
+ const result = await manager.getCategories();
1860
+ if (!result.success || !result.data || result.data.length === 0) {
1861
+ console.log(ansis.gray(isZh ? "\u6682\u65E0\u5206\u7C7B\u4FE1\u606F" : "No categories available"));
1862
+ return;
1863
+ }
1864
+ for (const cat of result.data) {
1865
+ const name = isZh ? cat.name["zh-CN"] || cat.name.en : cat.name.en;
1866
+ console.log(` \u{1F4E6} ${ansis.bold(name)} ${ansis.gray(`(${cat.count} ${isZh ? "\u4E2A\u63D2\u4EF6" : "plugins"})`)}`);
1867
+ }
1868
+ }
1869
+ async function showFeaturedPlugins() {
1870
+ const isZh = i18n.language === "zh-CN";
1871
+ const manager = getCloudPluginManager();
1872
+ console.log(ansis.green.bold(`
1873
+ \u2B50 ${isZh ? "\u7CBE\u9009\u63D2\u4EF6" : "Featured Plugins"}
1874
+ `));
1875
+ const featured = await manager.getFeaturedPlugins();
1876
+ if (!featured || featured.length === 0) {
1877
+ console.log(ansis.gray(isZh ? "\u6682\u65E0\u7CBE\u9009\u63D2\u4EF6" : "No featured plugins available"));
1878
+ return;
1879
+ }
1880
+ for (const plugin of featured) {
1881
+ const installed = manager.isPluginInstalled(plugin.id);
1882
+ const statusIcon = installed ? ansis.green("\u25CF") : ansis.gray("\u25CB");
1883
+ console.log(` ${statusIcon} ${ansis.bold(getPluginName(plugin))} ${ansis.gray(`v${plugin.version}`)}`);
1884
+ console.log(` ${ansis.gray(getPluginDescription(plugin))}`);
1885
+ console.log("");
1886
+ }
1887
+ console.log(ansis.gray(`
1888
+ \u{1F4A1} ${isZh ? "\u4F7F\u7528 /plugin install <id> \u5B89\u88C5\u63D2\u4EF6" : "Use /plugin install <id> to install a plugin"}`));
1889
+ }
1890
+ function showHelp() {
1891
+ const isZh = i18n.language === "zh-CN";
1892
+ console.log(ansis.green.bold(`
1893
+ \u{1F4E6} ${isZh ? "CCJK \u63D2\u4EF6\u7BA1\u7406" : "CCJK Plugin Manager"}
1894
+ `));
1895
+ console.log(ansis.dim("\u2500".repeat(50)));
1896
+ console.log("");
1897
+ console.log(ansis.bold(isZh ? "\u7528\u6CD5:" : "Usage:"));
1898
+ console.log(" /plugin <command> [options]");
1899
+ console.log("");
1900
+ console.log(ansis.bold(isZh ? "\u547D\u4EE4:" : "Commands:"));
1901
+ console.log(` ${ansis.green("list")} ${isZh ? "\u5217\u51FA\u5DF2\u5B89\u88C5\u7684\u63D2\u4EF6" : "List installed plugins"}`);
1902
+ console.log(` ${ansis.green("install")} <id> ${isZh ? "\u5B89\u88C5\u63D2\u4EF6" : "Install a plugin"}`);
1903
+ console.log(` ${ansis.green("uninstall")} <id> ${isZh ? "\u5378\u8F7D\u63D2\u4EF6" : "Uninstall a plugin"}`);
1904
+ console.log(` ${ansis.green("search")} <query> ${isZh ? "\u641C\u7D22\u63D2\u4EF6" : "Search for plugins"}`);
1905
+ console.log(` ${ansis.green("info")} <id> ${isZh ? "\u663E\u793A\u63D2\u4EF6\u8BE6\u60C5" : "Show plugin details"}`);
1906
+ console.log(` ${ansis.green("update")} [id] ${isZh ? "\u66F4\u65B0\u63D2\u4EF6" : "Update plugin(s)"}`);
1907
+ console.log(` ${ansis.green("categories")} ${isZh ? "\u5217\u51FA\u63D2\u4EF6\u5206\u7C7B" : "List plugin categories"}`);
1908
+ console.log(` ${ansis.green("featured")} ${isZh ? "\u663E\u793A\u7CBE\u9009\u63D2\u4EF6" : "Show featured plugins"}`);
1909
+ console.log(` ${ansis.green("help")} ${isZh ? "\u663E\u793A\u5E2E\u52A9" : "Show this help"}`);
1910
+ console.log("");
1911
+ console.log(ansis.bold(isZh ? "\u793A\u4F8B:" : "Examples:"));
1912
+ console.log(` /plugin search git ${ansis.gray(isZh ? "# \u641C\u7D22 git \u76F8\u5173\u63D2\u4EF6" : "# Search for git plugins")}`);
1913
+ console.log(` /plugin install code-simplifier ${ansis.gray(isZh ? "# \u5B89\u88C5\u63D2\u4EF6" : "# Install a plugin")}`);
1914
+ console.log(` /plugin info code-simplifier ${ansis.gray(isZh ? "# \u67E5\u770B\u63D2\u4EF6\u8BE6\u60C5" : "# View plugin details")}`);
1915
+ console.log(` /plugin update ${ansis.gray(isZh ? "# \u66F4\u65B0\u6240\u6709\u63D2\u4EF6" : "# Update all plugins")}`);
1916
+ console.log("");
1917
+ console.log(ansis.dim("\u2500".repeat(50)));
1918
+ console.log(ansis.gray(`${isZh ? "\u63D2\u4EF6\u5E02\u573A" : "Plugin Marketplace"}: https://claudehome.cn/plugins`));
1919
+ }
1920
+ async function handlePluginCommand(args) {
1921
+ const action = args[0] || "list";
1922
+ const restArgs = args.slice(1);
1923
+ const options = {
1924
+ verbose: restArgs.includes("--verbose") || restArgs.includes("-v"),
1925
+ force: restArgs.includes("--force") || restArgs.includes("-f")
1926
+ };
1927
+ const versionIndex = restArgs.findIndex((a) => a === "--version" || a === "-V");
1928
+ if (versionIndex !== -1 && restArgs[versionIndex + 1]) {
1929
+ options.version = restArgs[versionIndex + 1];
1930
+ }
1931
+ const cleanArgs = restArgs.filter(
1932
+ (a) => !a.startsWith("-") && a !== options.version
1933
+ );
1934
+ await pluginCommand(action, cleanArgs, options);
1935
+ }
1936
+
1937
+ export { handlePluginCommand, pluginCommand };