ccjk 5.2.0 → 5.2.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/api.mjs +6 -6
  2. package/dist/chunks/auto-updater.mjs +80 -133
  3. package/dist/chunks/ccm.mjs +7 -7
  4. package/dist/chunks/ccr.mjs +7 -4
  5. package/dist/chunks/ccu.mjs +6 -6
  6. package/dist/chunks/check-updates.mjs +3 -3
  7. package/dist/chunks/claude-code-incremental-manager.mjs +38 -38
  8. package/dist/chunks/cloud-v5.mjs +1651 -0
  9. package/dist/chunks/codex.mjs +70 -70
  10. package/dist/chunks/commands.mjs +25 -25
  11. package/dist/chunks/commit.mjs +16 -16
  12. package/dist/chunks/config-consolidator.mjs +9 -9
  13. package/dist/chunks/config-switch.mjs +39 -39
  14. package/dist/chunks/config.mjs +5 -5
  15. package/dist/chunks/config2.mjs +85 -85
  16. package/dist/chunks/context.mjs +2 -2
  17. package/dist/chunks/doctor.mjs +31 -31
  18. package/dist/chunks/features.mjs +84 -83
  19. package/dist/chunks/help.mjs +116 -116
  20. package/dist/chunks/index4.mjs +46 -46
  21. package/dist/chunks/init.mjs +214 -191
  22. package/dist/chunks/interview.mjs +102 -102
  23. package/dist/chunks/manager.mjs +238 -0
  24. package/dist/chunks/marketplace.mjs +59 -59
  25. package/dist/chunks/mcp.mjs +82 -82
  26. package/dist/chunks/menu.mjs +441 -379
  27. package/dist/chunks/notification.mjs +112 -112
  28. package/dist/chunks/onboarding.mjs +7 -7
  29. package/dist/chunks/package.mjs +1 -1
  30. package/dist/chunks/permission-manager.mjs +8 -8
  31. package/dist/chunks/plugin.mjs +100 -100
  32. package/dist/chunks/prompts.mjs +15 -15
  33. package/dist/chunks/providers.mjs +65 -65
  34. package/dist/chunks/session.mjs +83 -83
  35. package/dist/chunks/skills-sync.mjs +72 -72
  36. package/dist/chunks/skills.mjs +88 -88
  37. package/dist/chunks/team.mjs +6 -6
  38. package/dist/chunks/uninstall.mjs +35 -35
  39. package/dist/chunks/update.mjs +6 -6
  40. package/dist/chunks/upgrade-manager.mjs +4 -4
  41. package/dist/chunks/workflows2.mjs +13 -13
  42. package/dist/cli.mjs +21 -0
  43. package/dist/i18n/locales/en/menu.json +16 -1
  44. package/dist/i18n/locales/en/skills.json +29 -0
  45. package/dist/i18n/locales/zh-CN/menu.json +16 -1
  46. package/dist/i18n/locales/zh-CN/skills.json +29 -0
  47. package/dist/index.mjs +4 -4
  48. package/dist/shared/{ccjk.f40us0yY.mjs → ccjk.BiJujy5w.mjs} +4 -4
  49. package/dist/shared/{ccjk.CQzwtnZ1.mjs → ccjk.C_3BYaWc.mjs} +50 -50
  50. package/dist/shared/{ccjk.Zwx-YR_P.mjs → ccjk.DjD9Rzxq.mjs} +32 -32
  51. package/dist/shared/{ccjk.DtWIPt8E.mjs → ccjk.XgW1H2t3.mjs} +68 -68
  52. package/dist/shared/{ccjk.BlPCiSHj.mjs → ccjk.tI4PJA0c.mjs} +30 -30
  53. package/package.json +3 -3
@@ -0,0 +1,1651 @@
1
+ import process__default from 'node:process';
2
+ import { select, spinner, confirm } from '@clack/prompts';
3
+ import * as ansis from 'ansis';
4
+
5
+ class AgentOrchestratorClient {
6
+ baseUrl;
7
+ apiKey;
8
+ timeout;
9
+ constructor(config = {}) {
10
+ this.baseUrl = config.baseUrl ?? "https://claude.iccjk.com";
11
+ this.apiKey = config.apiKey;
12
+ this.timeout = config.timeout ?? 3e5;
13
+ }
14
+ /**
15
+ * Set API key for authentication
16
+ */
17
+ setApiKey(apiKey) {
18
+ this.apiKey = apiKey;
19
+ }
20
+ /**
21
+ * Get request headers
22
+ */
23
+ getHeaders() {
24
+ const headers = {
25
+ "Content-Type": "application/json"
26
+ };
27
+ if (this.apiKey) {
28
+ headers.Authorization = `Bearer ${this.apiKey}`;
29
+ }
30
+ return headers;
31
+ }
32
+ /**
33
+ * Make API request
34
+ */
35
+ async request(path, options = {}) {
36
+ const url = `${this.baseUrl}/api/v1/agents${path}`;
37
+ const controller = new AbortController();
38
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
39
+ try {
40
+ const response = await fetch(url, {
41
+ ...options,
42
+ headers: {
43
+ ...this.getHeaders(),
44
+ ...options.headers
45
+ },
46
+ signal: controller.signal
47
+ });
48
+ clearTimeout(timeoutId);
49
+ if (!response.ok) {
50
+ const error = await response.json().catch(() => ({ message: response.statusText }));
51
+ throw new Error(`API Error: ${error.message || response.statusText}`);
52
+ }
53
+ return await response.json();
54
+ } catch (error) {
55
+ clearTimeout(timeoutId);
56
+ throw error;
57
+ }
58
+ }
59
+ // ========================================================================
60
+ // Orchestration APIs
61
+ // ========================================================================
62
+ /**
63
+ * Orchestrate a complex task with Cowork-style multi-agent execution
64
+ * POST /api/v1/agents/orchestrate
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const result = await client.orchestrate({
69
+ * task: 'Review pull request and suggest improvements',
70
+ * breakdown: true,
71
+ * parallel: true,
72
+ * subAgents: 2
73
+ * })
74
+ * ```
75
+ */
76
+ async orchestrate(request) {
77
+ return this.request("/orchestrate", {
78
+ method: "POST",
79
+ body: JSON.stringify(request)
80
+ });
81
+ }
82
+ /**
83
+ * Get orchestration progress
84
+ * GET /api/v1/agents/:id/progress
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const progress = await client.getProgress('orch-id')
89
+ * console.log(`Progress: ${progress.progress}%`)
90
+ * console.log(`Current phase: ${progress.currentPhase}`)
91
+ * ```
92
+ */
93
+ async getProgress(orchestrationId) {
94
+ return this.request(`/${orchestrationId}/progress`);
95
+ }
96
+ /**
97
+ * Get queue status
98
+ * GET /api/v1/agents/queue-status
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const status = await client.getQueueStatus()
103
+ * console.log(`Pending: ${status.pending}`)
104
+ * console.log(`Est. wait: ${status.estimatedWaitTime}ms`)
105
+ * ```
106
+ */
107
+ async getQueueStatus() {
108
+ return this.request("/queue-status");
109
+ }
110
+ /**
111
+ * Cancel orchestration
112
+ * POST /api/v1/agents/:id/cancel
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * await client.cancelOrchestration('orch-id')
117
+ * ```
118
+ */
119
+ async cancelOrchestration(orchestrationId) {
120
+ return this.request(`/${orchestrationId}/cancel`, {
121
+ method: "POST"
122
+ });
123
+ }
124
+ /**
125
+ * Get available orchestration phases
126
+ * GET /api/v1/agents/phases
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * const phases = await client.getPhases()
131
+ * phases.forEach(p => console.log(p.name))
132
+ * ```
133
+ */
134
+ async getPhases() {
135
+ return this.request("/phases");
136
+ }
137
+ // ========================================================================
138
+ // Utility Methods
139
+ // ========================================================================
140
+ /**
141
+ * Orchestrate and wait for completion (polling)
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const result = await client.orchestrateAndWait({
146
+ * task: 'Generate API documentation',
147
+ * breakdown: true
148
+ * })
149
+ * ```
150
+ */
151
+ async orchestrateAndWait(request, options = {}) {
152
+ const {
153
+ pollInterval = 2e3,
154
+ maxWaitTime = 6e5,
155
+ // 10 minutes
156
+ onProgress
157
+ } = options;
158
+ const orchestration = await this.orchestrate(request);
159
+ const startTime = Date.now();
160
+ while (Date.now() - startTime < maxWaitTime) {
161
+ const progress = await this.getProgress(orchestration.id);
162
+ onProgress?.(progress);
163
+ if (progress.status === "completed" || progress.status === "failed" || progress.status === "cancelled") {
164
+ return progress;
165
+ }
166
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
167
+ }
168
+ throw new Error("Orchestration timeout");
169
+ }
170
+ /**
171
+ * Stream orchestration progress using Server-Sent Events
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * for await (const event of client.streamProgress('orch-id')) {
176
+ * console.log(`Progress: ${event.progress}%`)
177
+ * }
178
+ * ```
179
+ */
180
+ async *streamProgress(orchestrationId) {
181
+ const url = `${this.baseUrl}/api/v1/agents/${orchestrationId}/progress/stream`;
182
+ const headers = this.getHeaders();
183
+ const response = await fetch(url, { headers });
184
+ if (!response.ok) {
185
+ throw new Error(`Failed to stream: ${response.statusText}`);
186
+ }
187
+ const reader = response.body?.getReader();
188
+ if (!reader) {
189
+ throw new Error("Response body is not readable");
190
+ }
191
+ const decoder = new TextDecoder();
192
+ let buffer = "";
193
+ while (true) {
194
+ const { done, value } = await reader.read();
195
+ if (done)
196
+ break;
197
+ buffer += decoder.decode(value, { stream: true });
198
+ const lines = buffer.split("\n");
199
+ buffer = lines.pop() || "";
200
+ for (const line of lines) {
201
+ if (line.startsWith("data: ")) {
202
+ try {
203
+ const data = JSON.parse(line.slice(6));
204
+ yield data;
205
+ } catch {
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ /**
212
+ * Get sub-agent status
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const subAgents = await client.getSubAgentStatus('orch-id')
217
+ * subAgents.forEach(sa => {
218
+ * console.log(`${sa.name}: ${sa.status} (${sa.progress}%)`)
219
+ * })
220
+ * ```
221
+ */
222
+ async getSubAgentStatus(orchestrationId) {
223
+ const progress = await this.getProgress(orchestrationId);
224
+ return progress.subAgents;
225
+ }
226
+ /**
227
+ * Get phase details
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * const phases = await client.getPhaseDetails('orch-id')
232
+ * phases.forEach(p => {
233
+ * console.log(`${p.name}: ${p.status} (${p.progress}%)`)
234
+ * })
235
+ * ```
236
+ */
237
+ async getPhaseDetails(orchestrationId) {
238
+ const progress = await this.getProgress(orchestrationId);
239
+ return progress.phases;
240
+ }
241
+ }
242
+ function createAgentOrchestratorClient(config) {
243
+ return new AgentOrchestratorClient(config);
244
+ }
245
+
246
+ class McpGatewayClient {
247
+ baseUrl;
248
+ apiKey;
249
+ timeout;
250
+ constructor(config = {}) {
251
+ this.baseUrl = config.baseUrl ?? "https://claude.iccjk.com";
252
+ this.apiKey = config.apiKey;
253
+ this.timeout = config.timeout ?? 3e4;
254
+ }
255
+ /**
256
+ * Set API key for authentication
257
+ */
258
+ setApiKey(apiKey) {
259
+ this.apiKey = apiKey;
260
+ }
261
+ /**
262
+ * Get request headers
263
+ */
264
+ getHeaders() {
265
+ const headers = {
266
+ "Content-Type": "application/json"
267
+ };
268
+ if (this.apiKey) {
269
+ headers.Authorization = `Bearer ${this.apiKey}`;
270
+ }
271
+ return headers;
272
+ }
273
+ /**
274
+ * Make API request
275
+ */
276
+ async request(path, options = {}) {
277
+ const url = `${this.baseUrl}/api/v1/mcp/gateway${path}`;
278
+ const controller = new AbortController();
279
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
280
+ try {
281
+ const response = await fetch(url, {
282
+ ...options,
283
+ headers: {
284
+ ...this.getHeaders(),
285
+ ...options.headers
286
+ },
287
+ signal: controller.signal
288
+ });
289
+ clearTimeout(timeoutId);
290
+ if (!response.ok) {
291
+ const error = await response.json().catch(() => ({ message: response.statusText }));
292
+ throw new Error(`API Error: ${error.message || response.statusText}`);
293
+ }
294
+ return await response.json();
295
+ } catch (error) {
296
+ clearTimeout(timeoutId);
297
+ throw error;
298
+ }
299
+ }
300
+ // ========================================================================
301
+ // Gateway Info APIs
302
+ // ========================================================================
303
+ /**
304
+ * Get gateway information
305
+ * GET /api/v1/mcp/gateway
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * const info = await client.getGatewayInfo()
310
+ * console.log(`Total servers: ${info.totalServers}`)
311
+ * console.log(`Total tools: ${info.totalTools}`)
312
+ * ```
313
+ */
314
+ async getGatewayInfo() {
315
+ return this.request("");
316
+ }
317
+ /**
318
+ * Get all MCP servers
319
+ * GET /api/v1/mcp/gateway/servers
320
+ *
321
+ * @example
322
+ * ```ts
323
+ * const servers = await client.getAllServers()
324
+ * console.log(`Found ${servers.length} servers`)
325
+ * ```
326
+ */
327
+ async getAllServers() {
328
+ return this.request("/servers");
329
+ }
330
+ /**
331
+ * Get Top 10 MCP servers
332
+ * GET /api/v1/mcp/gateway/top10
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * const top10 = await client.getTop10()
337
+ * top10.forEach((server, index) => {
338
+ * console.log(`${index + 1}. ${server.name}`)
339
+ * })
340
+ * ```
341
+ */
342
+ async getTop10() {
343
+ return this.request("/top10");
344
+ }
345
+ /**
346
+ * Get trending servers
347
+ * GET /api/v1/mcp/gateway/trending
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * const trending = await client.getTrending()
352
+ * trending.forEach(t => {
353
+ * console.log(`${t.server.name}: +${t.growth}%`)
354
+ * })
355
+ * ```
356
+ */
357
+ async getTrending() {
358
+ return this.request("/trending");
359
+ }
360
+ // ========================================================================
361
+ // Tool Search APIs
362
+ // ========================================================================
363
+ /**
364
+ * Search for tools across all servers
365
+ * GET /api/v1/mcp/gateway/tools/search
366
+ *
367
+ * @example
368
+ * ```ts
369
+ * const tools = await client.searchTools({
370
+ * query: 'database query',
371
+ * category: 'data',
372
+ * limit: 10
373
+ * })
374
+ * ```
375
+ */
376
+ async searchTools(filters = {}) {
377
+ const params = new URLSearchParams();
378
+ if (filters.query)
379
+ params.append("q", filters.query);
380
+ if (filters.category)
381
+ params.append("category", filters.category);
382
+ if (filters.server)
383
+ params.append("server", filters.server);
384
+ if (filters.limit)
385
+ params.append("limit", filters.limit.toString());
386
+ const query = params.toString();
387
+ return this.request(`/tools/search${query ? `?${query}` : ""}`);
388
+ }
389
+ /**
390
+ * Get categories
391
+ * GET /api/v1/mcp/gateway/categories
392
+ *
393
+ * @example
394
+ * ```ts
395
+ * const categories = await client.getCategories()
396
+ * categories.forEach(cat => {
397
+ * console.log(`${cat.name}: ${cat.count} tools`)
398
+ * })
399
+ * ```
400
+ */
401
+ async getCategories() {
402
+ return this.request("/categories");
403
+ }
404
+ // ========================================================================
405
+ // Tool Invocation APIs
406
+ // ========================================================================
407
+ /**
408
+ * Invoke a tool through the gateway
409
+ * POST /api/v1/mcp/gateway/invoke
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * const result = await client.invokeTool({
414
+ * tool: 'read_file',
415
+ * server: 'mcp-filesystem',
416
+ * args: { path: '/path/to/file.txt' }
417
+ * })
418
+ * ```
419
+ */
420
+ async invokeTool(request) {
421
+ return this.request("/invoke", {
422
+ method: "POST",
423
+ body: JSON.stringify(request)
424
+ });
425
+ }
426
+ /**
427
+ * Batch invoke multiple tools
428
+ * POST /api/v1/mcp/gateway/invoke/batch
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * const results = await client.invokeToolsBatch([
433
+ * { tool: 'read_file', server: 'mcp-filesystem', args: { path: 'a.txt' } },
434
+ * { tool: 'read_file', server: 'mcp-filesystem', args: { path: 'b.txt' } }
435
+ * ])
436
+ * ```
437
+ */
438
+ async invokeToolsBatch(requests) {
439
+ return this.request("/invoke/batch", {
440
+ method: "POST",
441
+ body: JSON.stringify({ requests })
442
+ });
443
+ }
444
+ // ========================================================================
445
+ // Compatibility APIs
446
+ // ========================================================================
447
+ /**
448
+ * Check tool compatibility
449
+ * POST /api/v1/mcp/gateway/compatibility
450
+ *
451
+ * @example
452
+ * ```ts
453
+ * const compatibility = await client.checkCompatibility({
454
+ * tool: 'read_file',
455
+ * server: 'mcp-filesystem'
456
+ * })
457
+ *
458
+ * if (!compatibility.compatible) {
459
+ * console.log('Requirements:', compatibility.requirements)
460
+ * }
461
+ * ```
462
+ */
463
+ async checkCompatibility(request) {
464
+ return this.request("/compatibility", {
465
+ method: "POST",
466
+ body: JSON.stringify(request)
467
+ });
468
+ }
469
+ // ========================================================================
470
+ // Token Analysis APIs
471
+ // ========================================================================
472
+ /**
473
+ * Analyze token usage and get optimization suggestions
474
+ * POST /api/v1/mcp/gateway/analyze-tokens
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const analysis = await client.analyzeTokens({
479
+ * content: 'Large document or codebase content...',
480
+ * optimize: true
481
+ * })
482
+ *
483
+ * console.log(`Savings: ${analysis.savings} tokens`)
484
+ * console.log('Suggestions:', analysis.suggestions)
485
+ * ```
486
+ */
487
+ async analyzeTokens(content, optimize = true) {
488
+ return this.request("/analyze-tokens", {
489
+ method: "POST",
490
+ body: JSON.stringify({ content, optimize })
491
+ });
492
+ }
493
+ // ========================================================================
494
+ // Utility Methods
495
+ // ========================================================================
496
+ /**
497
+ * Get tools by server
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * const tools = await client.getToolsByServer('mcp-filesystem')
502
+ * ```
503
+ */
504
+ async getToolsByServer(serverId) {
505
+ return this.request(`/servers/${serverId}/tools`);
506
+ }
507
+ /**
508
+ * Get server details
509
+ *
510
+ * @example
511
+ * ```ts
512
+ * const server = await client.getServerDetails('mcp-filesystem')
513
+ * console.log(server.name, server.description)
514
+ * ```
515
+ */
516
+ async getServerDetails(serverId) {
517
+ return this.request(`/servers/${serverId}`);
518
+ }
519
+ /**
520
+ * Invoke tool with automatic retry
521
+ *
522
+ * @example
523
+ * ```ts
524
+ * const result = await client.invokeToolWithRetry({
525
+ * tool: 'query',
526
+ * server: 'mcp-documentdb',
527
+ * args: { query: 'SELECT * FROM users' }
528
+ * }, { maxRetries: 3 })
529
+ * ```
530
+ */
531
+ async invokeToolWithRetry(request, options = {}) {
532
+ const { maxRetries = 3, retryDelay = 1e3 } = options;
533
+ let lastError;
534
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
535
+ try {
536
+ return await this.invokeTool(request);
537
+ } catch (error) {
538
+ lastError = error instanceof Error ? error : new Error(String(error));
539
+ if (lastError.message.includes("HTTP 4") || lastError.message.includes("validation")) {
540
+ throw lastError;
541
+ }
542
+ if (attempt < maxRetries) {
543
+ await new Promise((resolve) => setTimeout(resolve, retryDelay * (attempt + 1)));
544
+ }
545
+ }
546
+ }
547
+ throw new Error(String(lastError));
548
+ }
549
+ }
550
+ function createMcpGatewayClient(config) {
551
+ return new McpGatewayClient(config);
552
+ }
553
+
554
+ class MemorySystemClient {
555
+ baseUrl;
556
+ apiKey;
557
+ timeout;
558
+ constructor(config = {}) {
559
+ this.baseUrl = config.baseUrl ?? "https://claude.iccjk.com";
560
+ this.apiKey = config.apiKey;
561
+ this.timeout = config.timeout ?? 3e4;
562
+ }
563
+ /**
564
+ * Set API key for authentication
565
+ */
566
+ setApiKey(apiKey) {
567
+ this.apiKey = apiKey;
568
+ }
569
+ /**
570
+ * Get request headers
571
+ */
572
+ getHeaders() {
573
+ const headers = {
574
+ "Content-Type": "application/json"
575
+ };
576
+ if (this.apiKey) {
577
+ headers.Authorization = `Bearer ${this.apiKey}`;
578
+ }
579
+ return headers;
580
+ }
581
+ /**
582
+ * Make API request
583
+ */
584
+ async request(path, options = {}) {
585
+ const url = `${this.baseUrl}/api/v1/memory${path}`;
586
+ const controller = new AbortController();
587
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
588
+ try {
589
+ const response = await fetch(url, {
590
+ ...options,
591
+ headers: {
592
+ ...this.getHeaders(),
593
+ ...options.headers
594
+ },
595
+ signal: controller.signal
596
+ });
597
+ clearTimeout(timeoutId);
598
+ if (!response.ok) {
599
+ const error = await response.json().catch(() => ({ message: response.statusText }));
600
+ throw new Error(`API Error: ${error.message || response.statusText}`);
601
+ }
602
+ return await response.json();
603
+ } catch (error) {
604
+ clearTimeout(timeoutId);
605
+ throw error;
606
+ }
607
+ }
608
+ // ========================================================================
609
+ // Memory Capture APIs
610
+ // ========================================================================
611
+ /**
612
+ * Capture a memory
613
+ * POST /api/v1/memory/capture
614
+ *
615
+ * @example
616
+ * ```ts
617
+ * const memory = await client.captureMemory({
618
+ * context: {
619
+ * userAction: 'configured-theme',
620
+ * theme: 'dark',
621
+ * timestamp: new Date().toISOString()
622
+ * },
623
+ * tags: ['preference', 'theme'],
624
+ * ttl: 86400 // 24 hours
625
+ * })
626
+ * ```
627
+ */
628
+ async captureMemory(request) {
629
+ return this.request("/capture", {
630
+ method: "POST",
631
+ body: JSON.stringify(request)
632
+ });
633
+ }
634
+ /**
635
+ * Batch capture memories
636
+ * POST /api/v1/memory/capture-bulk
637
+ *
638
+ * @example
639
+ * ```ts
640
+ * const results = await client.captureMemoriesBatch({
641
+ * memories: [
642
+ * { context: { event: 'click', element: 'button' }, tags: ['interaction'] },
643
+ * { context: { event: 'scroll', position: 500 }, tags: ['interaction'] }
644
+ * ]
645
+ * })
646
+ * ```
647
+ */
648
+ async captureMemoriesBatch(request) {
649
+ return this.request("/capture-bulk", {
650
+ method: "POST",
651
+ body: JSON.stringify(request)
652
+ });
653
+ }
654
+ // ========================================================================
655
+ // Memory Recall APIs
656
+ // ========================================================================
657
+ /**
658
+ * Recall/search memories
659
+ * GET /api/v1/memory/recall
660
+ *
661
+ * @example
662
+ * ```ts
663
+ * const results = await client.recallMemories('user preferences')
664
+ * console.log(`Found ${results.memories.length} memories`)
665
+ * ```
666
+ */
667
+ async recallMemories(query, options = {}) {
668
+ const params = new URLSearchParams();
669
+ params.append("q", query);
670
+ if (options.limit)
671
+ params.append("limit", options.limit.toString());
672
+ if (options.sessionId)
673
+ params.append("sessionId", options.sessionId);
674
+ return this.request(`/recall?${params}`);
675
+ }
676
+ /**
677
+ * Search memories with filters
678
+ * GET /api/v1/memory/search
679
+ *
680
+ * @example
681
+ * ```ts
682
+ * const results = await client.searchMemories('theme', {
683
+ * tags: ['preference'],
684
+ * limit: 10
685
+ * })
686
+ * ```
687
+ */
688
+ async searchMemories(query, filters = {}) {
689
+ const params = new URLSearchParams();
690
+ params.append("q", query);
691
+ if (filters.limit)
692
+ params.append("limit", filters.limit.toString());
693
+ if (filters.sessionId)
694
+ params.append("sessionId", filters.sessionId);
695
+ if (filters.tags?.length)
696
+ params.append("tags", filters.tags.join(","));
697
+ return this.request(`/search?${params}`);
698
+ }
699
+ /**
700
+ * Surface related memories for a given memory
701
+ * GET /api/v1/memory/:id/surface
702
+ *
703
+ * @example
704
+ * ```ts
705
+ * const related = await client.surfaceRelatedMemories('memory-id', {
706
+ * limit: 5,
707
+ * threshold: 0.7
708
+ * })
709
+ * ```
710
+ */
711
+ async surfaceRelatedMemories(memoryId, options = {}) {
712
+ const params = new URLSearchParams();
713
+ if (options.limit)
714
+ params.append("limit", options.limit.toString());
715
+ if (options.threshold)
716
+ params.append("threshold", options.threshold.toString());
717
+ return this.request(`/${memoryId}/surface?${params}`);
718
+ }
719
+ // ========================================================================
720
+ // Memory Management APIs
721
+ // ========================================================================
722
+ /**
723
+ * Delete a memory
724
+ * DELETE /api/v1/memory/:id
725
+ *
726
+ * @example
727
+ * ```ts
728
+ * await client.deleteMemory('memory-id')
729
+ * ```
730
+ */
731
+ async deleteMemory(memoryId) {
732
+ return this.request(`/${memoryId}`, {
733
+ method: "DELETE"
734
+ });
735
+ }
736
+ /**
737
+ * Delete memories by tags
738
+ * DELETE /api/v1/memory/tags/:tag
739
+ *
740
+ * @example
741
+ * ```ts
742
+ * await client.deleteMemoriesByTag('temp')
743
+ * ```
744
+ */
745
+ async deleteMemoriesByTag(tag) {
746
+ return this.request(`/tags/${tag}`, {
747
+ method: "DELETE"
748
+ });
749
+ }
750
+ /**
751
+ * Get memory statistics
752
+ * GET /api/v1/memory/stats
753
+ *
754
+ * @example
755
+ * ```ts
756
+ * const stats = await client.getMemoryStats()
757
+ * console.log(`Total memories: ${stats.totalMemories}`)
758
+ * console.log(`Total clusters: ${stats.totalClusters}`)
759
+ * ```
760
+ */
761
+ async getMemoryStats() {
762
+ return this.request("/stats");
763
+ }
764
+ /**
765
+ * Get session memories
766
+ * GET /api/v1/memory/session/:sessionId
767
+ *
768
+ * @example
769
+ * ```ts
770
+ * const memories = await client.getSessionMemories('session-123')
771
+ * ```
772
+ */
773
+ async getSessionMemories(sessionId) {
774
+ return this.request(`/session/${sessionId}`);
775
+ }
776
+ // ========================================================================
777
+ // Memory Clustering APIs
778
+ // ========================================================================
779
+ /**
780
+ * Get memory clusters
781
+ * GET /api/v1/memory/clusters
782
+ *
783
+ * @example
784
+ * ```ts
785
+ * const clusters = await client.getClusters()
786
+ * clusters.forEach(c => {
787
+ * console.log(`${c.name}: ${c.count} memories`)
788
+ * })
789
+ * ```
790
+ */
791
+ async getClusters() {
792
+ return this.request("/clusters");
793
+ }
794
+ /**
795
+ * Trigger manual clustering
796
+ * POST /api/v1/memory/cluster
797
+ *
798
+ * @example
799
+ * ```ts
800
+ * await client.triggerClustering({
801
+ * algorithm: 'kmeans',
802
+ * params: { clusters: 5 }
803
+ * })
804
+ * ```
805
+ */
806
+ async triggerClustering(request = {}) {
807
+ return this.request("/cluster", {
808
+ method: "POST",
809
+ body: JSON.stringify(request)
810
+ });
811
+ }
812
+ /**
813
+ * Get cluster details
814
+ * GET /api/v1/memory/clusters/:clusterId
815
+ *
816
+ * @example
817
+ * ```ts
818
+ * const cluster = await client.getCluster('cluster-id')
819
+ * console.log(cluster.name, cluster.memories)
820
+ * ```
821
+ */
822
+ async getCluster(clusterId) {
823
+ return this.request(`/clusters/${clusterId}`);
824
+ }
825
+ // ========================================================================
826
+ // Maintenance APIs
827
+ // ========================================================================
828
+ /**
829
+ * Clean up expired memories
830
+ * POST /api/v1/memory/cleanup
831
+ *
832
+ * @example
833
+ * ```ts
834
+ * const result = await client.cleanupExpired()
835
+ * console.log(`Cleaned up ${result.deleted} memories`)
836
+ * ```
837
+ */
838
+ async cleanupExpired() {
839
+ return this.request("/cleanup", {
840
+ method: "POST"
841
+ });
842
+ }
843
+ /**
844
+ * Clean up by criteria
845
+ * POST /api/v1/memory/cleanup/advanced
846
+ *
847
+ * @example
848
+ * ```ts
849
+ * const result = await client.cleanup({
850
+ * olderThan: '2026-01-01',
851
+ * tags: ['temp']
852
+ * })
853
+ * ```
854
+ */
855
+ async cleanup(request) {
856
+ return this.request("/cleanup/advanced", {
857
+ method: "POST",
858
+ body: JSON.stringify(request)
859
+ });
860
+ }
861
+ // ========================================================================
862
+ // Utility Methods
863
+ // ========================================================================
864
+ /**
865
+ * Auto-capture context during session
866
+ *
867
+ * @example
868
+ * ```ts
869
+ * // Capture user actions automatically
870
+ * client.autoCapture('session-123', {
871
+ * captureTags: ['interaction', 'preference'],
872
+ * captureInterval: 60000 // every minute
873
+ * })
874
+ * ```
875
+ */
876
+ async autoCapture(sessionId, options = {}) {
877
+ await this.captureMemory({
878
+ context: {
879
+ type: "auto-capture",
880
+ sessionId,
881
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
882
+ },
883
+ tags: options.captureTags || ["auto"],
884
+ sessionId,
885
+ ttl: options.ttl
886
+ });
887
+ }
888
+ /**
889
+ * Build context from memories for AI
890
+ *
891
+ * @example
892
+ * ```ts
893
+ * const context = await client.buildContext('session-123', {
894
+ * maxTokens: 2000,
895
+ * includeTags: ['preference', 'important']
896
+ * })
897
+ * ```
898
+ */
899
+ async buildContext(sessionId, options = {}) {
900
+ const memories = await this.getSessionMemories(sessionId);
901
+ let filtered = memories;
902
+ if (options.includeTags?.length) {
903
+ filtered = memories.filter(
904
+ (m) => options.includeTags.some((tag) => m.tags.includes(tag))
905
+ );
906
+ }
907
+ const estimateTokens = (text) => Math.ceil(text.length / 4);
908
+ let context = "";
909
+ let tokensUsed = 0;
910
+ const maxTokens = options.maxTokens || 2e3;
911
+ for (const memory of filtered) {
912
+ const memoryText = JSON.stringify(memory.content);
913
+ const memoryTokens = estimateTokens(memoryText);
914
+ if (tokensUsed + memoryTokens > maxTokens) {
915
+ break;
916
+ }
917
+ context += `${memoryText}
918
+ `;
919
+ tokensUsed += memoryTokens;
920
+ }
921
+ return {
922
+ context,
923
+ memoriesUsed: filtered.length,
924
+ tokensUsed
925
+ };
926
+ }
927
+ }
928
+ function createMemorySystemClient(config) {
929
+ return new MemorySystemClient(config);
930
+ }
931
+
932
+ class SessionTeleportationClient {
933
+ baseUrl;
934
+ apiKey;
935
+ timeout;
936
+ constructor(config = {}) {
937
+ this.baseUrl = config.baseUrl ?? "https://claude.iccjk.com";
938
+ this.apiKey = config.apiKey;
939
+ this.timeout = config.timeout ?? 3e4;
940
+ }
941
+ setApiKey(apiKey) {
942
+ this.apiKey = apiKey;
943
+ }
944
+ getHeaders() {
945
+ const headers = {
946
+ "Content-Type": "application/json"
947
+ };
948
+ if (this.apiKey) {
949
+ headers.Authorization = `Bearer ${this.apiKey}`;
950
+ }
951
+ return headers;
952
+ }
953
+ async request(path, options = {}) {
954
+ const url = `${this.baseUrl}/api/v1/sessions${path}`;
955
+ const controller = new AbortController();
956
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
957
+ try {
958
+ const response = await fetch(url, {
959
+ ...options,
960
+ headers: { ...this.getHeaders(), ...options.headers },
961
+ signal: controller.signal
962
+ });
963
+ clearTimeout(timeoutId);
964
+ if (!response.ok) {
965
+ const error = await response.json().catch(() => ({ message: response.statusText }));
966
+ throw new Error(`API Error: ${error.message || response.statusText}`);
967
+ }
968
+ return await response.json();
969
+ } catch (error) {
970
+ clearTimeout(timeoutId);
971
+ throw error;
972
+ }
973
+ }
974
+ // ========================================================================
975
+ // Session Management APIs
976
+ // ========================================================================
977
+ /**
978
+ * Create a new session
979
+ * POST /api/v1/sessions
980
+ */
981
+ async createSession(request) {
982
+ return this.request("", {
983
+ method: "POST",
984
+ body: JSON.stringify(request)
985
+ });
986
+ }
987
+ /**
988
+ * Get session by ID
989
+ * GET /api/v1/sessions/:id
990
+ */
991
+ async getSession(sessionId) {
992
+ return this.request(`/${sessionId}`);
993
+ }
994
+ /**
995
+ * List sessions
996
+ * GET /api/v1/sessions
997
+ */
998
+ async listSessions(filters) {
999
+ const params = new URLSearchParams();
1000
+ if (filters?.type)
1001
+ params.append("type", filters.type);
1002
+ if (filters?.active !== void 0)
1003
+ params.append("active", filters.active.toString());
1004
+ if (filters?.limit)
1005
+ params.append("limit", filters.limit.toString());
1006
+ const query = params.toString();
1007
+ return this.request(query ? `?${query}` : "");
1008
+ }
1009
+ /**
1010
+ * Delete a session
1011
+ * DELETE /api/v1/sessions/:id
1012
+ */
1013
+ async deleteSession(sessionId) {
1014
+ return this.request(`/${sessionId}`, {
1015
+ method: "DELETE"
1016
+ });
1017
+ }
1018
+ // ========================================================================
1019
+ // Teleportation APIs
1020
+ // ========================================================================
1021
+ /**
1022
+ * Teleport session to another environment
1023
+ * POST /api/v1/sessions/:id/teleport
1024
+ */
1025
+ async teleportSession(sessionId, request) {
1026
+ return this.request(`/${sessionId}/teleport`, {
1027
+ method: "POST",
1028
+ body: JSON.stringify(request)
1029
+ });
1030
+ }
1031
+ /**
1032
+ * Activate a session
1033
+ * POST /api/v1/sessions/:id/activate
1034
+ */
1035
+ async activateSession(sessionId) {
1036
+ return this.request(`/${sessionId}/activate`, {
1037
+ method: "POST"
1038
+ });
1039
+ }
1040
+ /**
1041
+ * Deactivate a session
1042
+ * POST /api/v1/sessions/:id/deactivate
1043
+ */
1044
+ async deactivateSession(sessionId) {
1045
+ return this.request(`/${sessionId}/deactivate`, {
1046
+ method: "POST"
1047
+ });
1048
+ }
1049
+ // ========================================================================
1050
+ // Statistics APIs
1051
+ // ========================================================================
1052
+ /**
1053
+ * Get session statistics
1054
+ * GET /api/v1/sessions/stats
1055
+ */
1056
+ async getStats() {
1057
+ return this.request("/stats");
1058
+ }
1059
+ // ========================================================================
1060
+ // Utility Methods
1061
+ // ========================================================================
1062
+ /**
1063
+ * Get active sessions
1064
+ */
1065
+ async getActiveSessions() {
1066
+ return this.listSessions({ active: true });
1067
+ }
1068
+ /**
1069
+ * Get sessions by type
1070
+ */
1071
+ async getSessionsByType(type) {
1072
+ return this.listSessions({ type });
1073
+ }
1074
+ /**
1075
+ * Quick teleport (create and teleport in one call)
1076
+ */
1077
+ async quickTeleport(fromType, toType, context) {
1078
+ const session = await this.createSession({
1079
+ type: fromType,
1080
+ initialContext: context
1081
+ });
1082
+ const result = await this.teleportSession(session.id, {
1083
+ target: toType,
1084
+ preserveContext: true
1085
+ });
1086
+ if (result.success && result.newSessionId) {
1087
+ return this.getSession(result.newSessionId);
1088
+ }
1089
+ return session;
1090
+ }
1091
+ }
1092
+ function createSessionTeleportationClient(config) {
1093
+ return new SessionTeleportationClient(config);
1094
+ }
1095
+
1096
+ const DEFAULT_ENDPOINT = "https://claude.iccjk.com";
1097
+ function loadConfig() {
1098
+ return {
1099
+ endpoint: process__default.env.CCJK_CLOUD_ENDPOINT || DEFAULT_ENDPOINT,
1100
+ apiKey: process__default.env.CCJK_CLOUD_TOKEN,
1101
+ timeout: Number.parseInt(process__default.env.CCJK_REQUEST_TIMEOUT || "30000", 10)
1102
+ };
1103
+ }
1104
+ function printHeader(title, icon = "\u2601\uFE0F") {
1105
+ console.log("");
1106
+ console.log(ansis.bold.cyan("\u2501".repeat(60)));
1107
+ console.log(ansis.bold.cyan(` ${icon} ${title}`));
1108
+ console.log(ansis.bold.cyan("\u2501".repeat(60)));
1109
+ console.log("");
1110
+ }
1111
+ function printSuccess(message) {
1112
+ console.log(ansis.green(` \u2705 ${message}`));
1113
+ }
1114
+ function printError(message) {
1115
+ console.log(ansis.red(` \u274C ${message}`));
1116
+ }
1117
+ function printWarning(message) {
1118
+ console.log(ansis.yellow(` \u26A0\uFE0F ${message}`));
1119
+ }
1120
+ function printInfo(message) {
1121
+ console.log(ansis.dim(` \u2139\uFE0F ${message}`));
1122
+ }
1123
+ async function orchestrateCommand(args) {
1124
+ printHeader("Agent Orchestrator", "\u{1F916}");
1125
+ const config = loadConfig();
1126
+ const client = createAgentOrchestratorClient(config);
1127
+ let task = args.task;
1128
+ if (!task) {
1129
+ const result = await select({
1130
+ message: "Select a task template:",
1131
+ options: [
1132
+ { value: "custom", label: "\u{1F4DD} Custom task..." },
1133
+ { value: "analyze-codebase", label: "\u{1F50D} Analyze codebase and generate documentation" },
1134
+ { value: "review-pr", label: "\u{1F440} Review pull request with detailed analysis" },
1135
+ { value: "refactor", label: "\u267B\uFE0F Refactor code with multiple agents" },
1136
+ { value: "test-generation", label: "\u{1F9EA} Generate comprehensive test suite" },
1137
+ { value: "debug-issue", label: "\u{1F41B} Debug complex issue with parallel analysis" }
1138
+ ]
1139
+ });
1140
+ if (typeof result === "symbol")
1141
+ return;
1142
+ task = result === "custom" ? void 0 : result;
1143
+ }
1144
+ if (task !== "custom" && !task) {
1145
+ printWarning("Please provide a task description");
1146
+ return;
1147
+ }
1148
+ const breakdown = args.breakdown ?? await confirm({
1149
+ message: "Auto-breakdown task into phases?",
1150
+ initialValue: true
1151
+ });
1152
+ if (typeof breakdown === "symbol")
1153
+ return;
1154
+ const parallel = args.parallel ?? await confirm({
1155
+ message: "Enable parallel sub-agent execution?",
1156
+ initialValue: true
1157
+ });
1158
+ if (typeof parallel === "symbol")
1159
+ return;
1160
+ const subAgents = args.subAgents ?? (parallel ? 3 : 1);
1161
+ const request = {
1162
+ task: task || (args.task || ""),
1163
+ breakdown,
1164
+ parallel,
1165
+ subAgents,
1166
+ projectContext: {
1167
+ rootDir: process__default.cwd()
1168
+ }
1169
+ };
1170
+ console.log(ansis.dim(`
1171
+ Task: ${request.task}`));
1172
+ console.log(ansis.dim(` Breakdown: ${request.breakdown}`));
1173
+ console.log(ansis.dim(` Parallel: ${request.parallel}`));
1174
+ console.log(ansis.dim(` Sub-agents: ${request.subAgents}`));
1175
+ console.log("");
1176
+ const shouldStart = await confirm({ message: "Start orchestration?", initialValue: true });
1177
+ if (typeof shouldStart === "symbol" || !shouldStart)
1178
+ return;
1179
+ const s = spinner();
1180
+ s.start("Submitting task to cloud orchestrator...");
1181
+ try {
1182
+ const orchestration = await client.orchestrate(request);
1183
+ s.stop("Task submitted successfully!");
1184
+ console.log(`
1185
+ \u{1F4CB} Orchestration ID: ${orchestration.id}`);
1186
+ console.log(` \u{1F4CA} Status: ${orchestration.status}`);
1187
+ if (args.watch) {
1188
+ await watchOrchestrationProgress(client, orchestration.id);
1189
+ } else {
1190
+ printInfo(`Use --watch to monitor progress, or check status later`);
1191
+ console.log(` ccjk cloud status ${orchestration.id}`);
1192
+ }
1193
+ } catch (error) {
1194
+ s.stop("Failed to submit task");
1195
+ printError(error instanceof Error ? error.message : String(error));
1196
+ }
1197
+ }
1198
+ async function watchOrchestrationProgress(client, orchestrationId) {
1199
+ console.log("\n \u{1F440} Watching orchestration progress...\n");
1200
+ try {
1201
+ for await (const progress of client.streamProgress(orchestrationId)) {
1202
+ const statusIcon = {
1203
+ pending: "\u23F3",
1204
+ running: "\u{1F504}",
1205
+ completed: "\u2705",
1206
+ failed: "\u274C",
1207
+ cancelled: "\u{1F6AB}"
1208
+ }[progress.status] || "\u2753";
1209
+ console.log(`\r ${statusIcon} Progress: ${progress.progress}% | Phase: ${progress.currentPhase || "N/A"} | Sub-agents: ${progress.subAgents.filter((s) => s.status === "running").length}/${progress.subAgents.length} `);
1210
+ if (progress.status === "completed") {
1211
+ console.log("\n");
1212
+ printSuccess("Orchestration completed!");
1213
+ if (progress.phases.length > 0) {
1214
+ console.log("\n \u{1F4CA} Phases:");
1215
+ for (const phase of progress.phases) {
1216
+ const icon = phase.status === "completed" ? "\u2705" : phase.status === "failed" ? "\u274C" : "\u23F3";
1217
+ console.log(` ${icon} ${phase.name} ${phase.progress !== void 0 ? `(${phase.progress}%)` : ""}`);
1218
+ }
1219
+ }
1220
+ break;
1221
+ }
1222
+ if (progress.status === "failed") {
1223
+ console.log("\n");
1224
+ printError("Orchestration failed");
1225
+ break;
1226
+ }
1227
+ await new Promise((resolve) => setTimeout(resolve, 500));
1228
+ }
1229
+ } catch (error) {
1230
+ printError(`Failed to stream progress: ${error instanceof Error ? error.message : String(error)}`);
1231
+ }
1232
+ }
1233
+ async function orchestrationStatusCommand(args) {
1234
+ printHeader("Orchestration Status", "\u{1F4CA}");
1235
+ const config = loadConfig();
1236
+ const client = createAgentOrchestratorClient(config);
1237
+ const s = spinner();
1238
+ s.start("Fetching orchestration status...");
1239
+ try {
1240
+ const progress = await client.getProgress(args.id);
1241
+ s.stop("Status fetched");
1242
+ console.log(` \u{1F4CB} ID: ${progress.id}`);
1243
+ console.log(` \u{1F4CA} Status: ${progress.status}`);
1244
+ console.log(` \u{1F4C8} Progress: ${progress.progress}%`);
1245
+ console.log(` \u{1F3AF} Current Phase: ${progress.currentPhase || "N/A"}`);
1246
+ console.log("");
1247
+ if (progress.phases.length > 0) {
1248
+ console.log(" \u{1F4CA} Phases:");
1249
+ for (const phase of progress.phases) {
1250
+ const icon = phase.status === "completed" ? "\u2705" : phase.status === "failed" ? "\u274C" : phase.status === "running" ? "\u{1F504}" : "\u23F3";
1251
+ console.log(` ${icon} ${phase.name}: ${phase.status} ${phase.progress !== void 0 ? `(${phase.progress}%)` : ""}`);
1252
+ }
1253
+ }
1254
+ if (progress.subAgents.length > 0) {
1255
+ console.log("\n \u{1F916} Sub-agents:");
1256
+ for (const agent of progress.subAgents) {
1257
+ const icon = agent.status === "running" ? "\u{1F504}" : agent.status === "completed" ? "\u2705" : agent.status === "failed" ? "\u274C" : "\u{1F4A4}";
1258
+ console.log(` ${icon} ${agent.name} (${agent.role}): ${agent.status} ${agent.progress !== void 0 ? `(${agent.progress}%)` : ""}`);
1259
+ }
1260
+ }
1261
+ } catch (error) {
1262
+ s.stop("Failed to fetch status");
1263
+ printError(error instanceof Error ? error.message : String(error));
1264
+ }
1265
+ }
1266
+ async function mcpGatewayCommand(args) {
1267
+ printHeader("MCP Gateway (10K+ Servers)", "\u{1F310}");
1268
+ const config = loadConfig();
1269
+ const client = createMcpGatewayClient(config);
1270
+ const action = args.action || await select({
1271
+ message: "What would you like to do?",
1272
+ options: [
1273
+ { value: "info", label: "\u{1F4CA} Show gateway info" },
1274
+ { value: "top10", label: "\u{1F3C6} Show Top 10 servers" },
1275
+ { value: "search", label: "\u{1F50D} Search tools" },
1276
+ { value: "categories", label: "\u{1F4C1} Show categories" },
1277
+ { value: "invoke", label: "\u26A1 Invoke a tool" }
1278
+ ]
1279
+ });
1280
+ if (typeof action === "symbol")
1281
+ return;
1282
+ const s = spinner();
1283
+ switch (action) {
1284
+ case "info": {
1285
+ s.start("Fetching gateway info...");
1286
+ const info = await client.getGatewayInfo();
1287
+ s.stop("Gateway info fetched");
1288
+ console.log(` \u{1F4CA} Total Servers: ${info.totalServers}`);
1289
+ console.log(` \u{1F527} Total Tools: ${info.totalTools}`);
1290
+ console.log(` \u{1F4C1} Categories: ${info.categories.length}`);
1291
+ console.log(` \u{1F550} Last Updated: ${new Date(info.lastUpdated).toLocaleString()}`);
1292
+ break;
1293
+ }
1294
+ case "top10": {
1295
+ s.start("Fetching Top 10 servers...");
1296
+ const top10 = await client.getTop10();
1297
+ s.stop("Top 10 fetched");
1298
+ console.log("\n \u{1F3C6} Top 10 MCP Servers:");
1299
+ top10.forEach((server, index) => {
1300
+ console.log(`
1301
+ ${index + 1}. ${ansis.bold(server.name)}`);
1302
+ console.log(` ${server.description}`);
1303
+ console.log(` ${ansis.dim(`Category: ${server.category}${server.rank ? ` | Rank: #${server.rank}` : ""}`)}`);
1304
+ });
1305
+ break;
1306
+ }
1307
+ case "search": {
1308
+ const query = args.query;
1309
+ if (!query) {
1310
+ printWarning("Please provide a search query with --query");
1311
+ return;
1312
+ }
1313
+ s.start(`Searching for "${query}"...`);
1314
+ const tools = await client.searchTools({ query, limit: 20 });
1315
+ s.stop(`Found ${tools.length} tools`);
1316
+ console.log("\n \u{1F50D} Search Results:");
1317
+ tools.forEach((tool) => {
1318
+ console.log(`
1319
+ ${ansis.bold(tool.name)} ${ansis.dim(`(${tool.server})`)}`);
1320
+ console.log(` ${tool.description}`);
1321
+ });
1322
+ break;
1323
+ }
1324
+ case "categories": {
1325
+ s.start("Fetching categories...");
1326
+ const categories = await client.getCategories();
1327
+ s.stop("Categories fetched");
1328
+ console.log("\n \u{1F4C1} Categories:");
1329
+ categories.forEach((cat) => {
1330
+ console.log(` ${cat.name}: ${cat.count} tools`);
1331
+ });
1332
+ break;
1333
+ }
1334
+ case "invoke": {
1335
+ printInfo("Tool invocation requires --server and --tool parameters");
1336
+ console.log(" Example: ccjk cloud mcp invoke --server mcp-filesystem --tool read_file");
1337
+ break;
1338
+ }
1339
+ }
1340
+ console.log("");
1341
+ }
1342
+ async function memoryCommand(args) {
1343
+ printHeader("Memory System (Recallium)", "\u{1F9E0}");
1344
+ const config = loadConfig();
1345
+ const client = createMemorySystemClient(config);
1346
+ const action = args.action || await select({
1347
+ message: "What would you like to do?",
1348
+ options: [
1349
+ { value: "search", label: "\u{1F50D} Search memories" },
1350
+ { value: "stats", label: "\u{1F4CA} Show memory statistics" },
1351
+ { value: "clusters", label: "\u{1F5C2}\uFE0F Show memory clusters" },
1352
+ { value: "capture", label: "\u{1F4BE} Capture a memory" },
1353
+ { value: "cleanup", label: "\u{1F9F9} Cleanup expired memories" }
1354
+ ]
1355
+ });
1356
+ if (typeof action === "symbol")
1357
+ return;
1358
+ const s = spinner();
1359
+ switch (action) {
1360
+ case "search": {
1361
+ const query = args.query;
1362
+ if (!query) {
1363
+ printWarning("Please provide a search query with --query");
1364
+ return;
1365
+ }
1366
+ s.start(`Searching for "${query}"...`);
1367
+ const result = await client.searchMemories(query, { limit: 20 });
1368
+ s.stop(`Found ${result.memories.length} memories`);
1369
+ if (result.memories.length === 0) {
1370
+ printInfo("No memories found");
1371
+ break;
1372
+ }
1373
+ console.log("\n \u{1F50D} Search Results:");
1374
+ result.memories.forEach((memory) => {
1375
+ console.log(`
1376
+ \u{1F4DD} ${ansis.bold(JSON.stringify(memory.content).slice(0, 50))}`);
1377
+ console.log(` Tags: ${memory.tags.join(", ") || "none"}`);
1378
+ console.log(` Created: ${new Date(memory.createdAt).toLocaleString()}`);
1379
+ });
1380
+ break;
1381
+ }
1382
+ case "stats": {
1383
+ s.start("Fetching memory statistics...");
1384
+ const stats = await client.getMemoryStats();
1385
+ s.stop("Statistics fetched");
1386
+ console.log(` \u{1F4CA} Total Memories: ${stats.totalMemories}`);
1387
+ console.log(` \u{1F5C2}\uFE0F Total Clusters: ${stats.totalClusters}`);
1388
+ console.log(` \u{1F4C8} Avg Cluster Size: ${stats.avgClusterSize}`);
1389
+ console.log(` \u{1F550} Oldest: ${stats.oldestMemory ? new Date(stats.oldestMemory).toLocaleDateString() : "N/A"}`);
1390
+ console.log(` \u{1F550} Newest: ${stats.newestMemory ? new Date(stats.newestMemory).toLocaleDateString() : "N/A"}`);
1391
+ break;
1392
+ }
1393
+ case "clusters": {
1394
+ s.start("Fetching memory clusters...");
1395
+ const clusters = await client.getClusters();
1396
+ s.stop(`Found ${clusters.length} clusters`);
1397
+ if (clusters.length === 0) {
1398
+ printInfo("No clusters found");
1399
+ break;
1400
+ }
1401
+ console.log("\n \u{1F5C2}\uFE0F Memory Clusters:");
1402
+ clusters.forEach((cluster) => {
1403
+ console.log(`
1404
+ \u{1F4C1} ${ansis.bold(cluster.name)}`);
1405
+ console.log(` Count: ${cluster.count} | Tags: ${cluster.tags.join(", ")}`);
1406
+ });
1407
+ break;
1408
+ }
1409
+ case "capture": {
1410
+ const content = args.capture;
1411
+ if (!content) {
1412
+ printWarning("Please provide content to capture with --capture");
1413
+ return;
1414
+ }
1415
+ s.start("Capturing memory...");
1416
+ const memory = await client.captureMemory({
1417
+ context: { content },
1418
+ tags: args.tags
1419
+ });
1420
+ s.stop("Memory captured");
1421
+ printSuccess(`Memory captured with ID: ${memory.id}`);
1422
+ break;
1423
+ }
1424
+ case "cleanup": {
1425
+ s.start("Cleaning up expired memories...");
1426
+ const result = await client.cleanupExpired();
1427
+ s.stop(`Cleaned up ${result.deleted} memories`);
1428
+ printSuccess(`Cleaned up ${result.deleted} expired memories`);
1429
+ break;
1430
+ }
1431
+ }
1432
+ console.log("");
1433
+ }
1434
+ async function sessionCommand(args) {
1435
+ printHeader("Session Teleportation", "\u{1F300}");
1436
+ const config = loadConfig();
1437
+ const client = createSessionTeleportationClient(config);
1438
+ const action = args.action || await select({
1439
+ message: "What would you like to do?",
1440
+ options: [
1441
+ { value: "list", label: "\u{1F4CB} List sessions" },
1442
+ { value: "create", label: "\u2795 Create session" },
1443
+ { value: "teleport", label: "\u{1F300} Teleport session" },
1444
+ { value: "stats", label: "\u{1F4CA} Session statistics" }
1445
+ ]
1446
+ });
1447
+ if (typeof action === "symbol")
1448
+ return;
1449
+ const s = spinner();
1450
+ switch (action) {
1451
+ case "list": {
1452
+ s.start("Fetching sessions...");
1453
+ const sessions = await client.listSessions();
1454
+ s.stop(`Found ${sessions.length} sessions`);
1455
+ if (sessions.length === 0) {
1456
+ printInfo("No active sessions");
1457
+ break;
1458
+ }
1459
+ console.log("\n \u{1F4CB} Active Sessions:");
1460
+ sessions.forEach((session) => {
1461
+ const icon = session.isActive ? "\u{1F7E2}" : "\u26AA";
1462
+ console.log(`
1463
+ ${icon} ${ansis.bold(session.id)}`);
1464
+ console.log(` Type: ${session.type} | Active: ${session.isActive}`);
1465
+ console.log(` Context: ${session.contextSize} tokens`);
1466
+ console.log(` Created: ${new Date(session.createdAt).toLocaleString()}`);
1467
+ });
1468
+ break;
1469
+ }
1470
+ case "create": {
1471
+ const type = args.type || await select({
1472
+ message: "Session type:",
1473
+ options: [
1474
+ { value: "terminal", label: "\u{1F4BB} Terminal" },
1475
+ { value: "desktop", label: "\u{1F5A5}\uFE0F Desktop" },
1476
+ { value: "web", label: "\u{1F310} Web" }
1477
+ ]
1478
+ });
1479
+ if (typeof type === "symbol")
1480
+ return;
1481
+ s.start("Creating session...");
1482
+ const session = await client.createSession({
1483
+ type,
1484
+ projectPath: process__default.cwd()
1485
+ });
1486
+ s.stop("Session created");
1487
+ printSuccess(`Session created with ID: ${session.id}`);
1488
+ console.log(` Type: ${session.type}`);
1489
+ console.log(` Project: ${session.projectPath || "default"}`);
1490
+ break;
1491
+ }
1492
+ case "teleport": {
1493
+ const sessionId = args.sessionId;
1494
+ if (!sessionId) {
1495
+ printWarning("Please provide session ID with --sessionId");
1496
+ return;
1497
+ }
1498
+ const target = args.target || await select({
1499
+ message: "Target environment:",
1500
+ options: [
1501
+ { value: "terminal", label: "\u{1F4BB} Terminal" },
1502
+ { value: "desktop", label: "\u{1F5A5}\uFE0F Desktop" },
1503
+ { value: "web", label: "\u{1F310} Web" }
1504
+ ]
1505
+ });
1506
+ if (typeof target === "symbol")
1507
+ return;
1508
+ s.start(`Teleporting session to ${target}...`);
1509
+ const result = await client.teleportSession(sessionId, {
1510
+ target,
1511
+ preserveContext: true
1512
+ });
1513
+ s.stop("Session teleported");
1514
+ if (result.success) {
1515
+ printSuccess(`Session teleported successfully!`);
1516
+ if (result.newSessionId) {
1517
+ console.log(` New Session ID: ${result.newSessionId}`);
1518
+ }
1519
+ } else {
1520
+ printError(result.message || "Teleportation failed");
1521
+ }
1522
+ break;
1523
+ }
1524
+ case "stats": {
1525
+ s.start("Fetching session statistics...");
1526
+ const stats = await client.getStats();
1527
+ s.stop("Statistics fetched");
1528
+ console.log(` \u{1F4CA} Total Sessions: ${stats.totalSessions}`);
1529
+ console.log(` \u{1F7E2} Active Sessions: ${stats.activeSessions}`);
1530
+ console.log(" \u{1F4CA} Type Breakdown:");
1531
+ for (const [type, count] of Object.entries(stats.typeBreakdown)) {
1532
+ console.log(` ${type}: ${count}`);
1533
+ }
1534
+ break;
1535
+ }
1536
+ }
1537
+ console.log("");
1538
+ }
1539
+ async function cloudV5Command(subcommand, args = {}) {
1540
+ console.log("");
1541
+ if (!subcommand) {
1542
+ await cloudV5Menu();
1543
+ return;
1544
+ }
1545
+ switch (subcommand) {
1546
+ // Agent Orchestrator
1547
+ case "orchestrate":
1548
+ case "orch":
1549
+ await orchestrateCommand(args);
1550
+ break;
1551
+ case "orchestrate-status":
1552
+ case "status":
1553
+ if (args.id) {
1554
+ await orchestrationStatusCommand({ id: String(args.id) });
1555
+ } else {
1556
+ printWarning("Please provide orchestration ID with --id");
1557
+ }
1558
+ break;
1559
+ // MCP Gateway
1560
+ case "mcp":
1561
+ case "mcp-gateway":
1562
+ await mcpGatewayCommand(args);
1563
+ break;
1564
+ // Memory System
1565
+ case "memory":
1566
+ case "mem":
1567
+ await memoryCommand(args);
1568
+ break;
1569
+ // Session Teleportation
1570
+ case "session":
1571
+ case "teleport":
1572
+ await sessionCommand(args);
1573
+ break;
1574
+ // Help
1575
+ case "help":
1576
+ case "--help":
1577
+ case "-h":
1578
+ showCloudV5Help();
1579
+ break;
1580
+ default:
1581
+ printError(`Unknown subcommand: ${subcommand}`);
1582
+ showCloudV5Help();
1583
+ }
1584
+ }
1585
+ async function cloudV5Menu() {
1586
+ printHeader("CCJK Cloud v5.1.0-2026", "\u2601\uFE0F");
1587
+ const options = [
1588
+ { value: "orchestrate", label: "\u{1F916} Agent Orchestrator - Cowork-inspired multi-agent tasks" },
1589
+ { value: "mcp", label: "\u{1F310} MCP Gateway - Access 10,000+ MCP servers" },
1590
+ { value: "memory", label: "\u{1F9E0} Memory System - Recallium universal memory" },
1591
+ { value: "session", label: "\u{1F300} Session Teleportation - Cross-device sessions" },
1592
+ { value: "help", label: "\u2753 Help" },
1593
+ { value: "exit", label: "\u{1F519} Exit" }
1594
+ ];
1595
+ while (true) {
1596
+ const action = await select({
1597
+ message: "Select a feature:",
1598
+ options
1599
+ });
1600
+ if (typeof action === "symbol")
1601
+ break;
1602
+ switch (action) {
1603
+ case "orchestrate":
1604
+ await orchestrateCommand({});
1605
+ break;
1606
+ case "mcp":
1607
+ await mcpGatewayCommand({});
1608
+ break;
1609
+ case "memory":
1610
+ await memoryCommand({});
1611
+ break;
1612
+ case "session":
1613
+ await sessionCommand({});
1614
+ break;
1615
+ case "help":
1616
+ showCloudV5Help();
1617
+ break;
1618
+ case "exit":
1619
+ console.log("");
1620
+ return;
1621
+ }
1622
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
1623
+ }
1624
+ }
1625
+ function showCloudV5Help() {
1626
+ console.log("");
1627
+ console.log(ansis.bold("Usage:"));
1628
+ console.log(" ccjk cloud <subcommand> [options]");
1629
+ console.log("");
1630
+ console.log(ansis.bold("Subcommands:"));
1631
+ console.log(ansis.cyan(" Agent Orchestrator:"));
1632
+ console.log(" orchestrate Orchestrate a multi-agent task");
1633
+ console.log(" orchestrate-status Show orchestration status");
1634
+ console.log("");
1635
+ console.log(ansis.cyan(" MCP Gateway:"));
1636
+ console.log(" mcp Open MCP Gateway menu");
1637
+ console.log("");
1638
+ console.log(ansis.cyan(" Memory System:"));
1639
+ console.log(" memory Open Memory System menu");
1640
+ console.log("");
1641
+ console.log(ansis.cyan(" Session Teleportation:"));
1642
+ console.log(" session Open Session Teleportation menu");
1643
+ console.log("");
1644
+ console.log(ansis.bold("Options:"));
1645
+ console.log(" --endpoint <url> Cloud service endpoint");
1646
+ console.log(" --token <token> API authentication token");
1647
+ console.log(" --watch Watch progress in real-time");
1648
+ console.log("");
1649
+ }
1650
+
1651
+ export { cloudV5Command, mcpGatewayCommand, memoryCommand, orchestrateCommand, orchestrationStatusCommand, sessionCommand };