stigmergy 1.0.94 → 1.0.95

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 (50) hide show
  1. package/bin/stigmergy +26 -12
  2. package/docs/HASH_TABLE.md +83 -0
  3. package/docs/WEATHER_PROCESSOR_API.md +230 -0
  4. package/docs/best_practices.md +135 -0
  5. package/docs/development_guidelines.md +392 -0
  6. package/docs/requirements_specification.md +148 -0
  7. package/docs/system_design.md +314 -0
  8. package/docs/tdd_implementation_plan.md +384 -0
  9. package/docs/test_report.md +49 -0
  10. package/examples/calculator-example.js +72 -0
  11. package/examples/json-validation-example.js +64 -0
  12. package/examples/rest-client-example.js +52 -0
  13. package/package.json +21 -17
  14. package/scripts/post-deployment-config.js +9 -2
  15. package/src/auth.js +171 -0
  16. package/src/auth_command.js +195 -0
  17. package/src/calculator.js +220 -0
  18. package/src/core/cli_help_analyzer.js +625 -562
  19. package/src/core/cli_parameter_handler.js +121 -0
  20. package/src/core/cli_tools.js +89 -0
  21. package/src/core/error_handler.js +307 -0
  22. package/src/core/memory_manager.js +76 -0
  23. package/src/core/smart_router.js +133 -0
  24. package/src/deploy.js +50 -0
  25. package/src/main_english.js +642 -719
  26. package/src/main_fixed.js +1035 -0
  27. package/src/utils.js +529 -0
  28. package/src/weatherProcessor.js +205 -0
  29. package/test/calculator.test.js +215 -0
  30. package/test/collision-test.js +26 -0
  31. package/test/csv-processing-test.js +36 -0
  32. package/test/e2e/claude-cli-test.js +128 -0
  33. package/test/e2e/collaboration-test.js +75 -0
  34. package/test/e2e/comprehensive-test.js +431 -0
  35. package/test/e2e/error-handling-test.js +90 -0
  36. package/test/e2e/individual-tool-test.js +143 -0
  37. package/test/e2e/other-cli-test.js +130 -0
  38. package/test/e2e/qoder-cli-test.js +128 -0
  39. package/test/e2e/run-e2e-tests.js +73 -0
  40. package/test/e2e/test-data.js +88 -0
  41. package/test/e2e/test-utils.js +222 -0
  42. package/test/hash-table-demo.js +33 -0
  43. package/test/hash-table-test.js +26 -0
  44. package/test/json-validation-test.js +164 -0
  45. package/test/rest-client-test.js +56 -0
  46. package/test/unit/calculator-full.test.js +191 -0
  47. package/test/unit/calculator-simple.test.js +96 -0
  48. package/test/unit/calculator.test.js +97 -0
  49. package/test/unit/cli_parameter_handler.test.js +116 -0
  50. package/test/weather-processor.test.js +104 -0
@@ -0,0 +1,1035 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System
5
+ * International Version - Pure English & ANSI Only
6
+ * Version: 1.0.94
7
+ */
8
+
9
+ console.log('[DEBUG] Stigmergy CLI script started...');
10
+
11
+ const { spawn, spawnSync } = require('child_process');
12
+ const path = require('path');
13
+ const fs = require('fs/promises');
14
+ const os = require('os');
15
+ const { Command } = require('commander');
16
+ const inquirer = require('inquirer');
17
+ const chalk = require('chalk');
18
+ const yaml = require('js-yaml');
19
+
20
+ // Import our custom modules
21
+ const SmartRouter = require('./core/smart_router');
22
+ const CLIHelpAnalyzer = require('./core/cli_help_analyzer');
23
+
24
+ // AI CLI Tools Configuration
25
+ const CLI_TOOLS = {
26
+ claude: {
27
+ name: 'Claude CLI',
28
+ version: 'claude --version',
29
+ install: 'npm install -g @anthropic-ai/claude-cli',
30
+ hooksDir: path.join(os.homedir(), '.claude', 'hooks'),
31
+ config: path.join(os.homedir(), '.claude', 'config.json')
32
+ },
33
+ gemini: {
34
+ name: 'Gemini CLI',
35
+ version: 'gemini --version',
36
+ install: 'npm install -g @google/generative-ai-cli',
37
+ hooksDir: path.join(os.homedir(), '.gemini', 'extensions'),
38
+ config: path.join(os.homedir(), '.gemini', 'config.json')
39
+ },
40
+ qwen: {
41
+ name: 'Qwen CLI',
42
+ version: 'qwen --version',
43
+ install: 'npm install -g @alibaba/qwen-cli',
44
+ hooksDir: path.join(os.homedir(), '.qwen', 'hooks'),
45
+ config: path.join(os.homedir(), '.qwen', 'config.json')
46
+ },
47
+ iflow: {
48
+ name: 'iFlow CLI',
49
+ version: 'iflow --version',
50
+ install: 'npm install -g iflow-cli',
51
+ hooksDir: path.join(os.homedir(), '.iflow', 'hooks'),
52
+ config: path.join(os.homedir(), '.iflow', 'config.json')
53
+ },
54
+ qodercli: {
55
+ name: 'Qoder CLI',
56
+ version: 'qodercli --version',
57
+ install: 'npm install -g @qoder-ai/qodercli',
58
+ hooksDir: path.join(os.homedir(), '.qoder', 'hooks'),
59
+ config: path.join(os.homedir(), '.qoder', 'config.json')
60
+ },
61
+ codebuddy: {
62
+ name: 'CodeBuddy CLI',
63
+ version: 'codebuddy --version',
64
+ install: 'npm install -g codebuddy-cli',
65
+ hooksDir: path.join(os.homedir(), '.codebuddy', 'hooks'),
66
+ config: path.join(os.homedir(), '.codebuddy', 'config.json')
67
+ },
68
+ copilot: {
69
+ name: 'GitHub Copilot CLI',
70
+ version: 'copilot --version',
71
+ install: 'npm install -g @github/copilot-cli',
72
+ hooksDir: path.join(os.homedir(), '.copilot', 'mcp'),
73
+ config: path.join(os.homedir(), '.copilot', 'config.json')
74
+ },
75
+ codex: {
76
+ name: 'OpenAI Codex CLI',
77
+ version: 'codex --version',
78
+ install: 'npm install -g openai-codex-cli',
79
+ hooksDir: path.join(os.homedir(), '.config', 'codex', 'slash_commands'),
80
+ config: path.join(os.homedir(), '.codex', 'config.json')
81
+ }
82
+ };
83
+
84
+ class SmartRouter {
85
+ constructor() {
86
+ this.tools = CLI_TOOLS;
87
+ this.routeKeywords = ['use', 'help', 'please', 'write', 'generate', 'explain', 'analyze', 'translate', 'code', 'article'];
88
+ this.defaultTool = 'claude';
89
+ }
90
+
91
+ shouldRoute(userInput) {
92
+ return this.routeKeywords.some(keyword =>
93
+ userInput.toLowerCase().includes(keyword.toLowerCase())
94
+ );
95
+ }
96
+
97
+ smartRoute(userInput) {
98
+ const input = userInput.trim();
99
+
100
+ // Detect tool-specific keywords
101
+ for (const [toolName, toolInfo] of Object.entries(this.tools)) {
102
+ for (const keyword of this.extractKeywords(toolName)) {
103
+ if (input.toLowerCase().includes(keyword.toLowerCase())) {
104
+ // Extract clean parameters
105
+ const cleanInput = input
106
+ .replace(new RegExp(`.*${keyword}\\s*`, 'gi'), '')
107
+ .replace(/^(use|please|help|using|with)\s*/i, '')
108
+ .trim();
109
+ return { tool: toolName, prompt: cleanInput };
110
+ }
111
+ }
112
+ }
113
+
114
+ // Default routing
115
+ const cleanInput = input.replace(/^(use|please|help|using|with)\s*/i, '').trim();
116
+ return { tool: this.defaultTool, prompt: cleanInput };
117
+ }
118
+
119
+ extractKeywords(toolName) {
120
+ const keywords = {
121
+ claude: ['claude', 'anthropic'],
122
+ gemini: ['gemini', 'google'],
123
+ qwen: ['qwen', 'alibaba', 'tongyi'],
124
+ iflow: ['iflow', 'workflow', 'intelligent'],
125
+ qodercli: ['qoder', 'code'],
126
+ codebuddy: ['codebuddy', 'buddy', 'assistant'],
127
+ copilot: ['copilot', 'github', 'gh'],
128
+ codex: ['codex', 'openai', 'gpt']
129
+ };
130
+
131
+ return keywords[toolName] || [toolName];
132
+ }
133
+ }
134
+
135
+ class MemoryManager {
136
+ constructor() {
137
+ this.globalMemoryFile = path.join(os.homedir(), '.stigmergy', 'memory.json');
138
+ this.projectMemoryFile = path.join(process.cwd(), 'STIGMERGY.md');
139
+ }
140
+
141
+ async addInteraction(tool, prompt, response) {
142
+ const interaction = {
143
+ timestamp: new Date().toISOString(),
144
+ tool,
145
+ prompt,
146
+ response,
147
+ duration: Date.now() - new Date().getTime()
148
+ };
149
+
150
+ // Add to global memory
151
+ await this.saveGlobalMemory(interaction);
152
+
153
+ // Add to project memory
154
+ await this.saveProjectMemory(interaction);
155
+ }
156
+
157
+ async saveGlobalMemory(interaction) {
158
+ try {
159
+ const memory = await this.loadGlobalMemory();
160
+ memory.interactions = memory.interactions.concat(interaction).slice(-100); // Keep last 100
161
+ memory.lastInteraction = interaction;
162
+
163
+ await fs.mkdir(path.dirname(this.globalMemoryFile), { recursive: true });
164
+ await fs.writeFile(this.globalMemoryFile, JSON.stringify(memory, null, 2));
165
+ } catch (error) {
166
+ console.error(`[MEMORY] Failed to save global memory: ${error.message}`);
167
+ }
168
+ }
169
+
170
+ async saveProjectMemory(interaction) {
171
+ try {
172
+ const memory = await this.loadProjectMemory();
173
+ memory.interactions = memory.interactions.concat(interaction).slice(-50); // Keep last 50
174
+ memory.lastInteraction = interaction;
175
+
176
+ await fs.writeFile(this.projectMemoryFile, this.formatProjectMemory(memory));
177
+ } catch (error) {
178
+ console.error(`[MEMORY] Failed to save project memory: ${error.message}`);
179
+ }
180
+ }
181
+
182
+ async loadGlobalMemory() {
183
+ try {
184
+ const data = await fs.readFile(this.globalMemoryFile, 'utf8');
185
+ return JSON.parse(data);
186
+ } catch {
187
+ return {
188
+ projectName: 'Global Stigmergy Memory',
189
+ interactions: [],
190
+ createdAt: new Date().toISOString()
191
+ };
192
+ }
193
+ }
194
+
195
+ async loadProjectMemory() {
196
+ try {
197
+ const data = await fs.readFile(this.projectMemoryFile, 'utf8');
198
+ return this.parseProjectMemory(data);
199
+ } catch {
200
+ return {
201
+ projectName: path.basename(process.cwd()),
202
+ interactions: [],
203
+ createdAt: new Date().toISOString()
204
+ };
205
+ }
206
+ }
207
+
208
+ formatProjectMemory(memory) {
209
+ let content = `# Stigmergy Project Memory\n\n`;
210
+ content += `**Project**: ${memory.projectName}\n`;
211
+ content += `**Created**: ${memory.createdAt}\n`;
212
+ content += `**Last Updated**: ${new Date().toISOString()}\n\n`;
213
+
214
+ if (memory.lastInteraction) {
215
+ content += `## Last Interaction\n\n`;
216
+ content += `- **Tool**: ${memory.lastInteraction.tool}\n`;
217
+ content += `- **Timestamp**: ${memory.lastInteraction.timestamp}\n`;
218
+ content += `- **Prompt**: ${memory.lastInteraction.prompt}\n`;
219
+ content += `- **Response**: ${memory.lastInteraction.response.substring(0, 200)}...\n\n`;
220
+ }
221
+
222
+ content += `## Recent Interactions (${memory.interactions.length})\n\n`;
223
+ memory.interactions.slice(-10).forEach((interaction, index) => {
224
+ content += `### ${index + 1}. ${interaction.tool} - ${interaction.timestamp}\n\n`;
225
+ content += `**Prompt**: ${interaction.prompt}\n\n`;
226
+ content += `**Response**: ${interaction.response.substring(0, 200)}...\n\n`;
227
+ });
228
+
229
+ return content;
230
+ }
231
+
232
+ parseProjectMemory(markdown) {
233
+ // Simple parser for project memory
234
+ return {
235
+ projectName: 'Project',
236
+ interactions: [],
237
+ createdAt: new Date().toISOString()
238
+ };
239
+ }
240
+ }
241
+
242
+ class StigmergyInstaller {
243
+ constructor() {
244
+ this.router = new SmartRouter();
245
+ this.memory = new MemoryManager();
246
+ this.configDir = path.join(os.homedir(), '.stigmergy');
247
+ }
248
+
249
+ async checkCLI(toolName) {
250
+ const tool = this.router.tools[toolName];
251
+ if (!tool) return false;
252
+
253
+ // Try multiple ways to check if CLI is available
254
+ const checks = [
255
+ // Method 1: Try version command
256
+ { args: ['--version'], expected: 0 },
257
+ // Method 2: Try help command
258
+ { args: ['--help'], expected: 0 },
259
+ // Method 3: Try help command with -h
260
+ { args: ['-h'], expected: 0 },
261
+ // Method 4: Try just the command (help case)
262
+ { args: [], expected: 0 },
263
+ ];
264
+
265
+ for (const check of checks) {
266
+ try {
267
+ const result = spawnSync(toolName, check.args, {
268
+ encoding: 'utf8',
269
+ timeout: 5000,
270
+ shell: true
271
+ });
272
+
273
+ // Check if command executed successfully or at least didn't fail with "command not found"
274
+ if (result.status === check.expected ||
275
+ (result.status !== 127 && result.status !== 9009)) { // 127 = command not found on Unix, 9009 = command not found on Windows
276
+ return true;
277
+ }
278
+ } catch (error) {
279
+ // Continue to next check method
280
+ continue;
281
+ }
282
+ }
283
+
284
+ return false;
285
+ }
286
+
287
+ async scanCLI() {
288
+ console.log('[SCAN] Scanning for AI CLI tools...');
289
+ const available = {};
290
+ const missing = {};
291
+
292
+ for (const [toolName, toolInfo] of Object.entries(this.router.tools)) {
293
+ try {
294
+ console.log(`[SCAN] Checking ${toolInfo.name}...`);
295
+ const isAvailable = await this.checkCLI(toolName);
296
+
297
+ if (isAvailable) {
298
+ console.log(`[OK] ${toolInfo.name} is available`);
299
+ available[toolName] = toolInfo;
300
+ } else {
301
+ console.log(`[MISSING] ${toolInfo.name} is not installed`);
302
+ missing[toolName] = toolInfo;
303
+ }
304
+ } catch (error) {
305
+ console.log(`[ERROR] Failed to check ${toolInfo.name}: ${error.message}`);
306
+ missing[toolName] = toolInfo;
307
+ }
308
+ }
309
+
310
+ return { available, missing };
311
+ }
312
+
313
+ async installTools(selectedTools, missingTools) {
314
+ console.log(`\n[INSTALL] Installing ${selectedTools.length} AI CLI tools...`);
315
+
316
+ for (const toolName of selectedTools) {
317
+ const toolInfo = missingTools[toolName];
318
+ if (!toolInfo) {
319
+ console.log(`[SKIP] Tool ${toolName} not found in missing tools list`);
320
+ continue;
321
+ }
322
+
323
+ try {
324
+ console.log(`\n[INSTALL] Installing ${toolInfo.name}...`);
325
+ console.log(`[CMD] ${toolInfo.install}`);
326
+
327
+ const result = spawnSync(toolInfo.install, {
328
+ shell: true,
329
+ stdio: 'inherit'
330
+ });
331
+
332
+ if (result.status === 0) {
333
+ console.log(`[OK] ${toolInfo.name} installed successfully`);
334
+ } else {
335
+ console.log(`[ERROR] Failed to install ${toolInfo.name} (exit code: ${result.status})`);
336
+ if (result.error) {
337
+ console.log(`[ERROR] Installation error: ${result.error.message}`);
338
+ }
339
+ console.log(`[INFO] Please run manually: ${toolInfo.install}`);
340
+ }
341
+ } catch (error) {
342
+ console.log(`[ERROR] Failed to install ${toolInfo.name}: ${error.message}`);
343
+ console.log(`[INFO] Please run manually: ${toolInfo.install}`);
344
+ }
345
+ }
346
+
347
+ return true;
348
+ }
349
+
350
+ async downloadRequiredAssets() {
351
+ console.log('\n[DOWNLOAD] Downloading required assets and plugins...');
352
+
353
+ // SAFETY CHECK: Verify no conflicting packages exist
354
+ await this.safetyCheck();
355
+
356
+ try {
357
+ // Create local assets directory
358
+ const assetsDir = path.join(os.homedir(), '.stigmergy', 'assets');
359
+ await fs.mkdir(assetsDir, { recursive: true });
360
+
361
+ // Copy template files from package
362
+ const packageTemplatesDir = path.join(__dirname, '..', 'templates', 'project-docs');
363
+ const localTemplatesDir = path.join(assetsDir, 'templates');
364
+
365
+ if (await this.fileExists(packageTemplatesDir)) {
366
+ await fs.mkdir(localTemplatesDir, { recursive: true });
367
+
368
+ // Copy all template files
369
+ const templateFiles = await fs.readdir(packageTemplatesDir);
370
+ for (const file of templateFiles) {
371
+ const srcPath = path.join(packageTemplatesDir, file);
372
+ const dstPath = path.join(localTemplatesDir, file);
373
+ await fs.copyFile(srcPath, dstPath);
374
+ console.log(`[OK] Copied template: ${file}`);
375
+ }
376
+ }
377
+
378
+ // Download/copy CLI adapters
379
+ const adaptersDir = path.join(__dirname, '..', 'src', 'adapters');
380
+ const localAdaptersDir = path.join(assetsDir, 'adapters');
381
+
382
+ if (await this.fileExists(adaptersDir)) {
383
+ await fs.mkdir(localAdaptersDir, { recursive: true });
384
+
385
+ // Copy all adapter directories
386
+ const adapterDirs = await fs.readdir(adaptersDir);
387
+ for (const dir of adapterDirs) {
388
+ // Skip non-directory items
389
+ const dirPath = path.join(adaptersDir, dir);
390
+ const stat = await fs.stat(dirPath);
391
+ if (!stat.isDirectory()) continue;
392
+
393
+ // Skip __pycache__ directories
394
+ if (dir === '__pycache__') continue;
395
+
396
+ const dstPath = path.join(localAdaptersDir, dir);
397
+ await this.copyDirectory(dirPath, dstPath);
398
+ console.log(`[OK] Copied adapter: ${dir}`);
399
+ }
400
+ }
401
+
402
+ console.log('[OK] All required assets downloaded successfully');
403
+ return true;
404
+
405
+ } catch (error) {
406
+ console.log(`[ERROR] Failed to download required assets: ${error.message}`);
407
+ return false;
408
+ }
409
+ }
410
+
411
+ async safetyCheck() {
412
+ console.log('\n[SAFETY] Performing safety check for conflicting packages...');
413
+
414
+ // List of potentially conflicting packages
415
+ const conflictingPackages = [
416
+ '@aws-amplify/cli',
417
+ 'firebase-tools',
418
+ 'heroku',
419
+ 'netlify-cli',
420
+ 'vercel',
421
+ 'surge',
422
+ 'now'
423
+ ];
424
+
425
+ // Check for globally installed conflicting packages
426
+ try {
427
+ const result = spawnSync('npm', ['list', '-g', '--depth=0'], {
428
+ encoding: 'utf8',
429
+ timeout: 10000
430
+ });
431
+
432
+ if (result.status === 0) {
433
+ const installedPackages = result.stdout;
434
+ const conflicts = [];
435
+
436
+ for (const pkg of conflictingPackages) {
437
+ if (installedPackages.includes(pkg)) {
438
+ conflicts.push(pkg);
439
+ }
440
+ }
441
+
442
+ if (conflicts.length > 0) {
443
+ console.log(`[WARN] Potential conflicting packages detected: ${conflicts.join(', ')}`);
444
+ console.log('[INFO] These packages may interfere with Stigmergy CLI functionality');
445
+ } else {
446
+ console.log('[OK] No conflicting packages detected');
447
+ }
448
+ }
449
+ } catch (error) {
450
+ console.log(`[WARN] Unable to perform safety check: ${error.message}`);
451
+ }
452
+ }
453
+
454
+ async copyDirectory(src, dest) {
455
+ try {
456
+ await fs.mkdir(dest, { recursive: true });
457
+ const entries = await fs.readdir(src, { withFileTypes: true });
458
+
459
+ for (const entry of entries) {
460
+ const srcPath = path.join(src, entry.name);
461
+ const destPath = path.join(dest, entry.name);
462
+
463
+ if (entry.isDirectory()) {
464
+ // Skip __pycache__ directories
465
+ if (entry.name === '__pycache__') continue;
466
+ await this.copyDirectory(srcPath, destPath);
467
+ } else {
468
+ await fs.copyFile(srcPath, destPath);
469
+ }
470
+ }
471
+ } catch (error) {
472
+ console.log(`[WARN] Failed to copy directory ${src} to ${dest}: ${error.message}`);
473
+ }
474
+ }
475
+
476
+ async fileExists(filePath) {
477
+ try {
478
+ await fs.access(filePath);
479
+ return true;
480
+ } catch {
481
+ return false;
482
+ }
483
+ }
484
+
485
+ async showInstallOptions(missingTools) {
486
+ if (Object.keys(missingTools).length === 0) {
487
+ console.log('[INFO] All required AI CLI tools are already installed!');
488
+ return [];
489
+ }
490
+
491
+ console.log('\n[INSTALL] Missing AI CLI tools detected:');
492
+ const choices = [];
493
+
494
+ for (const [toolName, toolInfo] of Object.entries(missingTools)) {
495
+ choices.push({
496
+ name: `${toolInfo.name} (${toolName}) - ${toolInfo.install}`,
497
+ value: toolName,
498
+ checked: true
499
+ });
500
+ }
501
+
502
+ const answers = await inquirer.prompt([
503
+ {
504
+ type: 'checkbox',
505
+ name: 'tools',
506
+ message: 'Select which tools to install (Space to select, Enter to confirm):',
507
+ choices: choices,
508
+ pageSize: 10
509
+ }
510
+ ]);
511
+
512
+ return answers.tools;
513
+ }
514
+
515
+ async getUserSelection(options, missingTools) {
516
+ if (options.length === 0) {
517
+ return [];
518
+ }
519
+
520
+ const answers = await inquirer.prompt([
521
+ {
522
+ type: 'confirm',
523
+ name: 'proceed',
524
+ message: `Install ${options.length} missing AI CLI tools?`,
525
+ default: true
526
+ }
527
+ ]);
528
+
529
+ if (answers.proceed) {
530
+ return options;
531
+ }
532
+
533
+ // If user doesn't want to install all, let them choose individually
534
+ const individualChoices = options.map(toolName => ({
535
+ name: missingTools[toolName].name,
536
+ value: toolName,
537
+ checked: true
538
+ }));
539
+
540
+ const individualAnswers = await inquirer.prompt([
541
+ {
542
+ type: 'checkbox',
543
+ name: 'selectedTools',
544
+ message: 'Select which tools to install:',
545
+ choices: individualChoices,
546
+ pageSize: 10
547
+ }
548
+ ]);
549
+
550
+ return individualAnswers.selectedTools;
551
+ }
552
+
553
+ async deployHooks(available) {
554
+ console.log('\n[DEPLOY] Deploying cross-CLI integration hooks...');
555
+
556
+ // Import the post-deployment configurer for executing installation scripts
557
+ const { PostDeploymentConfigurer } = require('./../scripts/post-deployment-config.js');
558
+ const configurer = new PostDeploymentConfigurer();
559
+
560
+ let successCount = 0;
561
+ let totalCount = Object.keys(available).length;
562
+
563
+ for (const [toolName, toolInfo] of Object.entries(available)) {
564
+ console.log(`\n[DEPLOY] Deploying hooks for ${toolInfo.name}...`);
565
+
566
+ try {
567
+ await fs.mkdir(toolInfo.hooksDir, { recursive: true });
568
+
569
+ // Create config directory (not the config file itself)
570
+ const configDir = path.dirname(toolInfo.config);
571
+ await fs.mkdir(configDir, { recursive: true });
572
+
573
+ // Copy adapter files from local assets
574
+ // Mapping for tool names that don't match their adapter directory names
575
+ const toolNameToAdapterDir = {
576
+ 'qodercli': 'qoder',
577
+ 'qwencode': 'qwen'
578
+ };
579
+ const adapterDirName = toolNameToAdapterDir[toolName] || toolName;
580
+ const assetsAdaptersDir = path.join(os.homedir(), '.stigmergy', 'assets', 'adapters', adapterDirName);
581
+ if (await this.fileExists(assetsAdaptersDir)) {
582
+ await this.copyDirectory(assetsAdaptersDir, toolInfo.hooksDir);
583
+ console.log(`[OK] Copied adapter files for ${toolInfo.name}`);
584
+ }
585
+
586
+ // Execute post-deployment configuration
587
+ try {
588
+ await configurer.configure(toolName, toolInfo);
589
+ console.log(`[OK] Post-deployment configuration completed for ${toolInfo.name}`);
590
+ successCount++;
591
+ } catch (configError) {
592
+ console.log(`[WARN] Post-deployment configuration failed for ${toolInfo.name}: ${configError.message}`);
593
+ // Continue with other tools even if one fails
594
+ }
595
+
596
+ } catch (error) {
597
+ console.log(`[ERROR] Failed to deploy hooks for ${toolInfo.name}: ${error.message}`);
598
+ console.log('[INFO] Continuing with other tools...');
599
+ }
600
+ }
601
+
602
+ console.log(`\n[SUMMARY] Hook deployment completed: ${successCount}/${totalCount} tools successful`);
603
+ }
604
+
605
+ async deployProjectDocumentation() {
606
+ console.log('\n[DEPLOY] Deploying project documentation...');
607
+
608
+ try {
609
+ // Create standard project documentation files
610
+ const docs = {
611
+ 'STIGMERGY.md': this.generateProjectMemoryTemplate(),
612
+ 'README.md': this.generateProjectReadme()
613
+ };
614
+
615
+ for (const [filename, content] of Object.entries(docs)) {
616
+ const filepath = path.join(process.cwd(), filename);
617
+ if (!(await this.fileExists(filepath))) {
618
+ await fs.writeFile(filepath, content);
619
+ console.log(`[OK] Created ${filename}`);
620
+ }
621
+ }
622
+
623
+ console.log('[OK] Project documentation deployed successfully');
624
+ } catch (error) {
625
+ console.log(`[ERROR] Failed to deploy project documentation: ${error.message}`);
626
+ }
627
+ }
628
+
629
+ generateProjectMemoryTemplate() {
630
+ return `# Stigmergy Project Memory
631
+
632
+ ## Project Information
633
+ - **Project Name**: ${path.basename(process.cwd())}
634
+ - **Created**: ${new Date().toISOString()}
635
+ - **Stigmergy Version**: 1.0.94
636
+
637
+ ## Usage Instructions
638
+ This file automatically tracks all interactions with AI CLI tools through the Stigmergy system.
639
+
640
+ ## Recent Interactions
641
+ No interactions recorded yet.
642
+
643
+ ## Collaboration History
644
+ No collaboration history yet.
645
+
646
+ ---
647
+ *This file is automatically managed by Stigmergy CLI*
648
+ *Last updated: ${new Date().toISOString()}*
649
+ `;
650
+ }
651
+
652
+ generateProjectReadme() {
653
+ return `# ${path.basename(process.cwd())}
654
+
655
+ This project uses Stigmergy CLI for AI-assisted development.
656
+
657
+ ## Getting Started
658
+ 1. Install Stigmergy CLI: \`npm install -g stigmergy\`
659
+ 2. Run \`stigmergy setup\` to configure the environment
660
+ 3. Use \`stigmergy call "<your prompt>"\` to interact with AI tools
661
+
662
+ ## Available AI Tools
663
+ - Claude (Anthropic)
664
+ - Qwen (Alibaba)
665
+ - Gemini (Google)
666
+ - And others configured in your environment
667
+
668
+ ## Project Memory
669
+ See [STIGMERGY.md](STIGMERGY.md) for interaction history and collaboration records.
670
+
671
+ ---
672
+ *Generated by Stigmergy CLI*
673
+ `;
674
+ }
675
+
676
+ async initializeConfig() {
677
+ console.log('\n[CONFIG] Initializing Stigmergy configuration...');
678
+
679
+ try {
680
+ // Create config directory
681
+ const configDir = path.join(os.homedir(), '.stigmergy');
682
+ await fs.mkdir(configDir, { recursive: true });
683
+
684
+ // Create initial configuration
685
+ const config = {
686
+ version: '1.0.94',
687
+ initialized: true,
688
+ createdAt: new Date().toISOString(),
689
+ lastUpdated: new Date().toISOString(),
690
+ defaultCLI: 'claude',
691
+ enableCrossCLI: true,
692
+ enableMemory: true,
693
+ tools: {}
694
+ };
695
+
696
+ // Save configuration
697
+ const configPath = path.join(configDir, 'config.json');
698
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2));
699
+
700
+ console.log('[OK] Configuration initialized successfully');
701
+ } catch (error) {
702
+ console.log(`[ERROR] Failed to initialize configuration: ${error.message}`);
703
+ }
704
+ }
705
+
706
+ showUsageInstructions() {
707
+ console.log('\n' + '='.repeat(60));
708
+ console.log('🎉 Stigmergy CLI Setup Complete!');
709
+ console.log('='.repeat(60));
710
+ console.log('');
711
+ console.log('Next steps:');
712
+ console.log(' 1. Run "stigmergy install" to scan and install AI CLI tools');
713
+ console.log(' 2. Run "stigmergy deploy" to set up cross-CLI integration');
714
+ console.log(' 3. Use "stigmergy call \\"<your prompt>\\"" to start collaborating');
715
+ console.log('');
716
+ console.log('Example usage:');
717
+ console.log(' stigmergy call "用claude分析项目架构"');
718
+ console.log(' stigmergy call "用qwen写一个hello world程序"');
719
+ console.log(' stigmergy call "用gemini设计数据库表结构"');
720
+ console.log('');
721
+ console.log('For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents');
722
+ console.log('[END] Happy collaborating with multiple AI CLI tools!');
723
+ }
724
+ }
725
+
726
+ // Main CLI functionality
727
+ async function main() {
728
+ console.log('[DEBUG] Main function called with args:', process.argv);
729
+ const args = process.argv.slice(2);
730
+ const installer = new StigmergyInstaller();
731
+
732
+ // Handle case when no arguments are provided
733
+ if (args.length === 0) {
734
+ console.log('Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System');
735
+ console.log('Version: 1.0.94');
736
+ console.log('');
737
+ console.log('[SYSTEM] Automated Installation and Deployment System');
738
+ console.log('');
739
+ console.log('Usage: stigmergy [command] [options]');
740
+ console.log('');
741
+ console.log('Commands:');
742
+ console.log(' help, --help Show this help message');
743
+ console.log(' version, --version Show version information');
744
+ console.log(' status Check CLI tools status');
745
+ console.log(' scan Scan for available AI CLI tools');
746
+ console.log(' install Auto-install missing CLI tools');
747
+ console.log(' deploy Deploy hooks and integration to installed tools');
748
+ console.log(' setup Complete setup and configuration');
749
+ console.log(' call "<prompt>" Execute prompt with auto-routed AI CLI');
750
+ console.log('');
751
+ console.log('[WORKFLOW] Automated Workflow:');
752
+ console.log(' 1. npm install -g stigmergy # Install Stigmergy');
753
+ console.log(' 2. stigmergy install # Auto-scan & install CLI tools');
754
+ console.log(' 3. stigmergy setup # Deploy hooks & config');
755
+ console.log(' 4. stigmergy call "<prompt>" # Start collaborating');
756
+ console.log('');
757
+ console.log('[INFO] For first-time setup, run: stigmergy setup');
758
+ console.log('[INFO] To scan and install AI tools, run: stigmergy install');
759
+ console.log('');
760
+ console.log('For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents');
761
+ return;
762
+ }
763
+
764
+ // Handle help commands
765
+ if (args.includes('--help') || args.includes('-h')) {
766
+ console.log('Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System');
767
+ console.log('Version: 1.0.94');
768
+ console.log('');
769
+ console.log('[SYSTEM] Automated Installation and Deployment System');
770
+ console.log('');
771
+ console.log('Usage: stigmergy [command] [options]');
772
+ console.log('');
773
+ console.log('Commands:');
774
+ console.log(' help, --help Show this help message');
775
+ console.log(' version, --version Show version information');
776
+ console.log(' status Check CLI tools status');
777
+ console.log(' scan Scan for available AI CLI tools');
778
+ console.log(' install Auto-install missing CLI tools');
779
+ console.log(' deploy Deploy hooks and integration to installed tools');
780
+ console.log(' setup Complete setup and configuration');
781
+ console.log(' call "<prompt>" Execute prompt with auto-routed AI CLI');
782
+ console.log('');
783
+ console.log('[WORKFLOW] Automated Workflow:');
784
+ console.log(' 1. npm install -g stigmergy # Install Stigmergy');
785
+ console.log(' 2. stigmergy install # Auto-scan & install CLI tools');
786
+ console.log(' 3. stigmergy setup # Deploy hooks & config');
787
+ console.log(' 4. stigmergy call "<prompt>" # Start collaborating');
788
+ console.log('');
789
+ console.log('For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents');
790
+ return;
791
+ }
792
+
793
+ const command = args[0];
794
+ switch (command) {
795
+ case 'version':
796
+ case '--version':
797
+ // Use the version from configuration instead of hardcoding
798
+ const config = {
799
+ version: '1.0.94',
800
+ initialized: true,
801
+ createdAt: new Date().toISOString(),
802
+ lastUpdated: new Date().toISOString(),
803
+ defaultCLI: 'claude',
804
+ enableCrossCLI: true,
805
+ enableMemory: true
806
+ };
807
+ console.log(`Stigmergy CLI v${config.version}`);
808
+ break;
809
+
810
+ case 'status':
811
+ const { available, missing } = await installer.scanCLI();
812
+ console.log('\n[STATUS] AI CLI Tools Status Report');
813
+ console.log('=====================================');
814
+
815
+ if (Object.keys(available).length > 0) {
816
+ console.log('\n✅ Available Tools:');
817
+ for (const [toolName, toolInfo] of Object.entries(available)) {
818
+ console.log(` - ${toolInfo.name} (${toolName})`);
819
+ }
820
+ }
821
+
822
+ if (Object.keys(missing).length > 0) {
823
+ console.log('\n❌ Missing Tools:');
824
+ for (const [toolName, toolInfo] of Object.entries(missing)) {
825
+ console.log(` - ${toolInfo.name} (${toolName})`);
826
+ console.log(` Install command: ${toolInfo.install}`);
827
+ }
828
+ }
829
+
830
+ console.log(`\n[SUMMARY] ${Object.keys(available).length} available, ${Object.keys(missing).length} missing`);
831
+ break;
832
+
833
+ case 'scan':
834
+ await installer.scanCLI();
835
+ break;
836
+
837
+ case 'install':
838
+ console.log('[INSTALL] Starting AI CLI tools installation...');
839
+ const { missing: missingTools } = await installer.scanCLI();
840
+ const options = await installer.showInstallOptions(missingTools);
841
+
842
+ if (options.length > 0) {
843
+ const selectedTools = await installer.getUserSelection(options, missingTools);
844
+ if (selectedTools.length > 0) {
845
+ console.log('\n[INFO] Installing selected tools (this may take several minutes for tools that download binaries)...');
846
+ await installer.installTools(selectedTools, missingTools);
847
+ }
848
+ } else {
849
+ console.log('\n[INFO] All required tools are already installed!');
850
+ }
851
+ break;
852
+
853
+ case 'deploy':
854
+ const { available: deployedTools } = await installer.scanCLI();
855
+ await installer.deployHooks(deployedTools);
856
+ break;
857
+
858
+ case 'setup':
859
+ console.log('[SETUP] Starting complete Stigmergy setup...\n');
860
+
861
+ // Step 1: Download required assets
862
+ await installer.downloadRequiredAssets();
863
+
864
+ // Step 2: Scan for CLI tools
865
+ const { available: setupAvailable, missing: setupMissing } = await installer.scanCLI();
866
+ const setupOptions = await installer.showInstallOptions(setupMissing);
867
+
868
+ // Step 3: Install missing CLI tools if user chooses
869
+ if (setupOptions.length > 0) {
870
+ const selectedTools = await installer.getUserSelection(setupOptions, setupMissing);
871
+ if (selectedTools.length > 0) {
872
+ console.log('\n[INFO] Installing selected tools (this may take several minutes for tools that download binaries)...');
873
+ await installer.installTools(selectedTools, setupMissing);
874
+ }
875
+ } else {
876
+ console.log('\n[INFO] All required tools are already installed!');
877
+ }
878
+
879
+ // Step 4: Deploy hooks to available CLI tools
880
+ await installer.deployHooks(setupAvailable);
881
+
882
+ // Step 5: Deploy project documentation
883
+ await installer.deployProjectDocumentation();
884
+
885
+ // Step 6: Initialize configuration
886
+ await installer.initializeConfig();
887
+
888
+ // Step 7: Show usage instructions
889
+ installer.showUsageInstructions();
890
+ break;
891
+
892
+ case 'call':
893
+ if (args.length < 2) {
894
+ console.log('[ERROR] Usage: stigmergy call "<prompt>"');
895
+ process.exit(1);
896
+ }
897
+
898
+ // Get the prompt (everything after the command)
899
+ const prompt = args.slice(1).join(' ');
900
+
901
+ // Use smart router to determine which tool to use
902
+ const router = new SmartRouter();
903
+ const route = router.smartRoute(prompt);
904
+
905
+ console.log(`[CALL] Routing to ${route.tool}: ${route.prompt}`);
906
+
907
+ // Execute the routed command
908
+ try {
909
+ const toolPath = route.tool;
910
+ const child = spawn(toolPath, [route.prompt], { stdio: 'inherit', shell: true });
911
+
912
+ child.on('close', (code) => {
913
+ if (code !== 0) {
914
+ console.log(`[WARN] ${route.tool} exited with code ${code}`);
915
+ }
916
+ process.exit(code);
917
+ });
918
+
919
+ child.on('error', (error) => {
920
+ console.log(`[ERROR] Failed to execute ${route.tool}:`, error.message);
921
+ process.exit(1);
922
+ });
923
+ } catch (error) {
924
+ console.log(`[ERROR] Failed to execute ${route.tool}:`, error.message);
925
+ process.exit(1);
926
+ }
927
+ break;
928
+
929
+ case 'auto-install':
930
+ // Auto-install mode for npm postinstall - NON-INTERACTIVE
931
+ console.log('[AUTO-INSTALL] Stigmergy CLI automated setup');
932
+ console.log('='.repeat(60));
933
+
934
+ try {
935
+ // Step 1: Download required assets
936
+ try {
937
+ console.log('[STEP] Downloading required assets...');
938
+ await installer.downloadRequiredAssets();
939
+ console.log('[OK] Assets downloaded successfully');
940
+ } catch (error) {
941
+ console.log(`[WARN] Failed to download assets: ${error.message}`);
942
+ console.log('[INFO] Continuing with installation...');
943
+ }
944
+
945
+ // Step 2: Scan for CLI tools
946
+ let autoAvailable = {}, autoMissing = {};
947
+ try {
948
+ console.log('[STEP] Scanning for CLI tools...');
949
+ const scanResult = await installer.scanCLI();
950
+ autoAvailable = scanResult.available;
951
+ autoMissing = scanResult.missing;
952
+ console.log('[OK] CLI tools scanned successfully');
953
+ } catch (error) {
954
+ console.log(`[WARN] Failed to scan CLI tools: ${error.message}`);
955
+ console.log('[INFO] Continuing with installation...');
956
+ }
957
+
958
+ // Step 3: Show summary to user after installation
959
+ try {
960
+ if (Object.keys(autoMissing).length > 0) {
961
+ console.log('\n[INFO] Found ' + Object.keys(autoMissing).length + ' missing AI CLI tools:');
962
+ for (const [toolName, toolInfo] of Object.entries(autoMissing)) {
963
+ console.log(` - ${toolInfo.name} (${toolName})`);
964
+ }
965
+ console.log('\n[INFO] Auto-install mode detected. Skipping automatic installation of missing tools.');
966
+ console.log('[INFO] For full functionality, please run "stigmergy install" after installation completes.');
967
+ } else {
968
+ console.log('\n[INFO] All AI CLI tools are already installed! No additional tools required.');
969
+ }
970
+ } catch (error) {
971
+ console.log(`[WARN] Failed to show tool summary: ${error.message}`);
972
+ }
973
+
974
+ // Step 4: Deploy hooks to available CLI tools
975
+ try {
976
+ console.log('[STEP] Deploying hooks to available CLI tools...');
977
+ await installer.deployHooks(autoAvailable);
978
+ console.log('[OK] Hooks deployed successfully');
979
+ } catch (error) {
980
+ console.log(`[ERROR] Failed to deploy hooks: ${error.message}`);
981
+ console.log('[INFO] You can manually deploy hooks later by running: stigmergy deploy');
982
+ }
983
+
984
+ // Step 5: Deploy project documentation
985
+ try {
986
+ console.log('[STEP] Deploying project documentation...');
987
+ await installer.deployProjectDocumentation();
988
+ console.log('[OK] Documentation deployed successfully');
989
+ } catch (error) {
990
+ console.log(`[WARN] Failed to deploy documentation: ${error.message}`);
991
+ console.log('[INFO] Continuing with installation...');
992
+ }
993
+
994
+ // Step 6: Initialize configuration
995
+ try {
996
+ console.log('[STEP] Initializing configuration...');
997
+ await installer.initializeConfig();
998
+ console.log('[OK] Configuration initialized successfully');
999
+ } catch (error) {
1000
+ console.log(`[ERROR] Failed to initialize configuration: ${error.message}`);
1001
+ console.log('[INFO] You can manually initialize configuration later by running: stigmergy setup');
1002
+ }
1003
+
1004
+ // Step 7: Show final message to guide users
1005
+ console.log('\n[SUCCESS] Stigmergy CLI installed successfully!');
1006
+ console.log('[USAGE] Run "stigmergy setup" to complete full configuration and install missing AI CLI tools.');
1007
+ console.log('[USAGE] Run "stigmergy install" to install only missing AI CLI tools.');
1008
+ console.log('[USAGE] Run "stigmergy --help" to see all available commands.');
1009
+ } catch (fatalError) {
1010
+ console.error('[FATAL] Auto-install process failed:', fatalError.message);
1011
+ console.log('\n[TROUBLESHOOTING] To manually complete installation:');
1012
+ console.log('1. Run: stigmergy setup # Complete setup');
1013
+ console.log('2. Run: stigmergy install # Install missing tools');
1014
+ console.log('3. Run: stigmergy deploy # Deploy hooks manually');
1015
+ process.exit(1);
1016
+ }
1017
+ break;
1018
+
1019
+ default:
1020
+ console.log(`[ERROR] Unknown command: ${command}`);
1021
+ console.log('[INFO] Run "stigmergy --help" for usage information');
1022
+ process.exit(1);
1023
+ }
1024
+ }
1025
+
1026
+ // Export for testing
1027
+ module.exports = { StigmergyInstaller, SmartRouter, MemoryManager, CLI_TOOLS };
1028
+
1029
+ // Run main function
1030
+ if (require.main === module) {
1031
+ main().catch(error => {
1032
+ console.error('[FATAL] Stigmergy CLI encountered an error:', error);
1033
+ process.exit(1);
1034
+ });
1035
+ }