stigmergy 1.0.97 → 1.0.98

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.
@@ -6,46 +6,46 @@
6
6
  * Version: 1.0.94
7
7
  */
8
8
 
9
- if (process.env.DEBUG === "true") {
10
- console.log("[DEBUG] Stigmergy CLI script started...");
9
+ if (process.env.DEBUG === 'true') {
10
+ console.log('[DEBUG] Stigmergy CLI script started...');
11
11
  }
12
12
 
13
- const { spawn, spawnSync } = require("child_process");
14
- const path = require("path");
15
- const fs = require("fs/promises");
16
- const os = require("os");
17
- const { Command } = require("commander");
18
- const inquirer = require("inquirer");
19
- const chalk = require("chalk");
20
- const yaml = require("js-yaml");
13
+ const { spawn, spawnSync } = require('child_process');
14
+ const path = require('path');
15
+ const fs = require('fs/promises');
16
+ const os = require('os');
17
+ const { Command } = require('commander');
18
+ const inquirer = require('inquirer');
19
+ const chalk = require('chalk');
20
+ const yaml = require('js-yaml');
21
21
 
22
22
  // Import our custom modules
23
- const SmartRouter = require("./core/smart_router");
24
- const CLIHelpAnalyzer = require("./core/cli_help_analyzer");
25
- const { CLI_TOOLS } = require("./core/cli_tools");
26
- const { errorHandler } = require("./core/error_handler");
27
- const { executeCommand, executeJSFile } = require("./utils");
23
+ const SmartRouter = require('./core/smart_router');
24
+ const CLIHelpAnalyzer = require('./core/cli_help_analyzer');
25
+ const { CLI_TOOLS } = require('./core/cli_tools');
26
+ const { errorHandler } = require('./core/error_handler');
27
+ const { executeCommand, executeJSFile } = require('./utils');
28
28
  const {
29
29
  handleRegister,
30
30
  handleLogin,
31
31
  handleLogout,
32
32
  handleStatus,
33
- } = require("./auth_command");
34
- const { UserAuthenticator } = require("./auth");
35
- const fsSync = require("fs");
33
+ } = require('./auth_command');
34
+ const { UserAuthenticator } = require('./auth');
35
+ const fsSync = require('fs');
36
36
 
37
37
  // Set up global error handlers using our error handler module
38
- const { setupGlobalErrorHandlers } = require("./core/error_handler");
38
+ const { setupGlobalErrorHandlers } = require('./core/error_handler');
39
39
  setupGlobalErrorHandlers();
40
40
 
41
41
  class MemoryManager {
42
42
  constructor() {
43
43
  this.globalMemoryFile = path.join(
44
44
  os.homedir(),
45
- ".stigmergy",
46
- "memory.json",
45
+ '.stigmergy',
46
+ 'memory.json',
47
47
  );
48
- this.projectMemoryFile = path.join(process.cwd(), "STIGMERGY.md");
48
+ this.projectMemoryFile = path.join(process.cwd(), 'STIGMERGY.md');
49
49
  }
50
50
 
51
51
  async addInteraction(tool, prompt, response) {
@@ -66,8 +66,8 @@ class MemoryManager {
66
66
  } catch (error) {
67
67
  await errorHandler.logError(
68
68
  error,
69
- "ERROR",
70
- "MemoryManager.addInteraction",
69
+ 'ERROR',
70
+ 'MemoryManager.addInteraction',
71
71
  );
72
72
  }
73
73
  }
@@ -86,8 +86,8 @@ class MemoryManager {
86
86
  } catch (error) {
87
87
  await errorHandler.logError(
88
88
  error,
89
- "ERROR",
90
- "MemoryManager.saveGlobalMemory",
89
+ 'ERROR',
90
+ 'MemoryManager.saveGlobalMemory',
91
91
  );
92
92
  console.error(`[MEMORY] Failed to save global memory: ${error.message}`);
93
93
  }
@@ -106,8 +106,8 @@ class MemoryManager {
106
106
  } catch (error) {
107
107
  await errorHandler.logError(
108
108
  error,
109
- "ERROR",
110
- "MemoryManager.saveProjectMemory",
109
+ 'ERROR',
110
+ 'MemoryManager.saveProjectMemory',
111
111
  );
112
112
  console.error(`[MEMORY] Failed to save project memory: ${error.message}`);
113
113
  }
@@ -115,11 +115,11 @@ class MemoryManager {
115
115
 
116
116
  async loadGlobalMemory() {
117
117
  try {
118
- const data = await fs.readFile(this.globalMemoryFile, "utf8");
118
+ const data = await fs.readFile(this.globalMemoryFile, 'utf8');
119
119
  return JSON.parse(data);
120
120
  } catch {
121
121
  return {
122
- projectName: "Global Stigmergy Memory",
122
+ projectName: 'Global Stigmergy Memory',
123
123
  interactions: [],
124
124
  createdAt: new Date().toISOString(),
125
125
  };
@@ -128,7 +128,7 @@ class MemoryManager {
128
128
 
129
129
  async loadProjectMemory() {
130
130
  try {
131
- const data = await fs.readFile(this.projectMemoryFile, "utf8");
131
+ const data = await fs.readFile(this.projectMemoryFile, 'utf8');
132
132
  return this.parseProjectMemory(data);
133
133
  } catch {
134
134
  return {
@@ -140,13 +140,13 @@ class MemoryManager {
140
140
  }
141
141
 
142
142
  formatProjectMemory(memory) {
143
- let content = `# Stigmergy Project Memory\n\n`;
143
+ let content = '# Stigmergy Project Memory\n\n';
144
144
  content += `**Project**: ${memory.projectName}\n`;
145
145
  content += `**Created**: ${memory.createdAt}\n`;
146
146
  content += `**Last Updated**: ${new Date().toISOString()}\n\n`;
147
147
 
148
148
  if (memory.lastInteraction) {
149
- content += `## Last Interaction\n\n`;
149
+ content += '## Last Interaction\n\n';
150
150
  content += `- **Tool**: ${memory.lastInteraction.tool}\n`;
151
151
  content += `- **Timestamp**: ${memory.lastInteraction.timestamp}\n`;
152
152
  content += `- **Prompt**: ${memory.lastInteraction.prompt}\n`;
@@ -166,7 +166,7 @@ class MemoryManager {
166
166
  parseProjectMemory(markdown) {
167
167
  // Simple parser for project memory
168
168
  return {
169
- projectName: "Project",
169
+ projectName: 'Project',
170
170
  interactions: [],
171
171
  createdAt: new Date().toISOString(),
172
172
  };
@@ -177,7 +177,7 @@ class StigmergyInstaller {
177
177
  constructor() {
178
178
  this.router = new SmartRouter();
179
179
  this.memory = new MemoryManager();
180
- this.configDir = path.join(os.homedir(), ".stigmergy");
180
+ this.configDir = path.join(os.homedir(), '.stigmergy');
181
181
  }
182
182
 
183
183
  async checkCLI(toolName) {
@@ -187,11 +187,11 @@ class StigmergyInstaller {
187
187
  // Try multiple ways to check if CLI is available
188
188
  const checks = [
189
189
  // Method 1: Try version command
190
- { args: ["--version"], expected: 0 },
190
+ { args: ['--version'], expected: 0 },
191
191
  // Method 2: Try help command
192
- { args: ["--help"], expected: 0 },
192
+ { args: ['--help'], expected: 0 },
193
193
  // Method 3: Try help command with -h
194
- { args: ["-h"], expected: 0 },
194
+ { args: ['-h'], expected: 0 },
195
195
  // Method 4: Try just the command (help case)
196
196
  { args: [], expected: 0 },
197
197
  ];
@@ -199,7 +199,7 @@ class StigmergyInstaller {
199
199
  for (const check of checks) {
200
200
  try {
201
201
  const result = spawnSync(toolName, check.args, {
202
- encoding: "utf8",
202
+ encoding: 'utf8',
203
203
  timeout: 5000,
204
204
  shell: true,
205
205
  });
@@ -222,7 +222,7 @@ class StigmergyInstaller {
222
222
  }
223
223
 
224
224
  async scanCLI() {
225
- console.log("[SCAN] Scanning for AI CLI tools...");
225
+ console.log('[SCAN] Scanning for AI CLI tools...');
226
226
  const available = {};
227
227
  const missing = {};
228
228
 
@@ -241,7 +241,7 @@ class StigmergyInstaller {
241
241
  } catch (error) {
242
242
  await errorHandler.logError(
243
243
  error,
244
- "WARN",
244
+ 'WARN',
245
245
  `StigmergyInstaller.scanCLI.${toolName}`,
246
246
  );
247
247
  console.log(
@@ -272,7 +272,7 @@ class StigmergyInstaller {
272
272
 
273
273
  const result = spawnSync(toolInfo.install, {
274
274
  shell: true,
275
- stdio: "inherit",
275
+ stdio: 'inherit',
276
276
  });
277
277
 
278
278
  if (result.status === 0) {
@@ -289,7 +289,7 @@ class StigmergyInstaller {
289
289
  } catch (error) {
290
290
  await errorHandler.logError(
291
291
  error,
292
- "ERROR",
292
+ 'ERROR',
293
293
  `StigmergyInstaller.installTools.${toolName}`,
294
294
  );
295
295
  console.log(
@@ -303,24 +303,24 @@ class StigmergyInstaller {
303
303
  }
304
304
 
305
305
  async downloadRequiredAssets() {
306
- console.log("\n[DOWNLOAD] Downloading required assets and plugins...");
306
+ console.log('\n[DOWNLOAD] Downloading required assets and plugins...');
307
307
 
308
308
  // SAFETY CHECK: Verify no conflicting packages exist
309
309
  await this.safetyCheck();
310
310
 
311
311
  try {
312
312
  // Create local assets directory
313
- const assetsDir = path.join(os.homedir(), ".stigmergy", "assets");
313
+ const assetsDir = path.join(os.homedir(), '.stigmergy', 'assets');
314
314
  await fs.mkdir(assetsDir, { recursive: true });
315
315
 
316
316
  // Copy template files from package
317
317
  const packageTemplatesDir = path.join(
318
318
  __dirname,
319
- "..",
320
- "templates",
321
- "project-docs",
319
+ '..',
320
+ 'templates',
321
+ 'project-docs',
322
322
  );
323
- const localTemplatesDir = path.join(assetsDir, "templates");
323
+ const localTemplatesDir = path.join(assetsDir, 'templates');
324
324
 
325
325
  if (await this.fileExists(packageTemplatesDir)) {
326
326
  await fs.mkdir(localTemplatesDir, { recursive: true });
@@ -336,8 +336,8 @@ class StigmergyInstaller {
336
336
  }
337
337
 
338
338
  // Download/copy CLI adapters
339
- const adaptersDir = path.join(__dirname, "..", "src", "adapters");
340
- const localAdaptersDir = path.join(assetsDir, "adapters");
339
+ const adaptersDir = path.join(__dirname, '..', 'src', 'adapters');
340
+ const localAdaptersDir = path.join(assetsDir, 'adapters');
341
341
 
342
342
  if (await this.fileExists(adaptersDir)) {
343
343
  await fs.mkdir(localAdaptersDir, { recursive: true });
@@ -351,7 +351,7 @@ class StigmergyInstaller {
351
351
  if (!stat.isDirectory()) continue;
352
352
 
353
353
  // Skip __pycache__ directories
354
- if (dir === "__pycache__") continue;
354
+ if (dir === '__pycache__') continue;
355
355
 
356
356
  const dstPath = path.join(localAdaptersDir, dir);
357
357
  await this.copyDirectory(dirPath, dstPath);
@@ -359,13 +359,13 @@ class StigmergyInstaller {
359
359
  }
360
360
  }
361
361
 
362
- console.log("[OK] All required assets downloaded successfully");
362
+ console.log('[OK] All required assets downloaded successfully');
363
363
  return true;
364
364
  } catch (error) {
365
365
  await errorHandler.logError(
366
366
  error,
367
- "ERROR",
368
- "StigmergyInstaller.downloadRequiredAssets",
367
+ 'ERROR',
368
+ 'StigmergyInstaller.downloadRequiredAssets',
369
369
  );
370
370
  console.log(
371
371
  `[ERROR] Failed to download required assets: ${error.message}`,
@@ -376,24 +376,24 @@ class StigmergyInstaller {
376
376
 
377
377
  async safetyCheck() {
378
378
  console.log(
379
- "\n[SAFETY] Performing safety check for conflicting packages...",
379
+ '\n[SAFETY] Performing safety check for conflicting packages...',
380
380
  );
381
381
 
382
382
  // List of potentially conflicting packages
383
383
  const conflictingPackages = [
384
- "@aws-amplify/cli",
385
- "firebase-tools",
386
- "heroku",
387
- "netlify-cli",
388
- "vercel",
389
- "surge",
390
- "now",
384
+ '@aws-amplify/cli',
385
+ 'firebase-tools',
386
+ 'heroku',
387
+ 'netlify-cli',
388
+ 'vercel',
389
+ 'surge',
390
+ 'now',
391
391
  ];
392
392
 
393
393
  // Check for globally installed conflicting packages
394
394
  try {
395
- const result = spawnSync("npm", ["list", "-g", "--depth=0"], {
396
- encoding: "utf8",
395
+ const result = spawnSync('npm', ['list', '-g', '--depth=0'], {
396
+ encoding: 'utf8',
397
397
  timeout: 10000,
398
398
  });
399
399
 
@@ -409,13 +409,13 @@ class StigmergyInstaller {
409
409
 
410
410
  if (conflicts.length > 0) {
411
411
  console.log(
412
- `[WARN] Potential conflicting packages detected: ${conflicts.join(", ")}`,
412
+ `[WARN] Potential conflicting packages detected: ${conflicts.join(', ')}`,
413
413
  );
414
414
  console.log(
415
- "[INFO] These packages may interfere with Stigmergy CLI functionality",
415
+ '[INFO] These packages may interfere with Stigmergy CLI functionality',
416
416
  );
417
417
  } else {
418
- console.log("[OK] No conflicting packages detected");
418
+ console.log('[OK] No conflicting packages detected');
419
419
  }
420
420
  }
421
421
  } catch (error) {
@@ -434,7 +434,7 @@ class StigmergyInstaller {
434
434
 
435
435
  if (entry.isDirectory()) {
436
436
  // Skip __pycache__ directories
437
- if (entry.name === "__pycache__") continue;
437
+ if (entry.name === '__pycache__') continue;
438
438
  await this.copyDirectory(srcPath, destPath);
439
439
  } else {
440
440
  await fs.copyFile(srcPath, destPath);
@@ -443,8 +443,8 @@ class StigmergyInstaller {
443
443
  } catch (error) {
444
444
  await errorHandler.logError(
445
445
  error,
446
- "WARN",
447
- "StigmergyInstaller.copyDirectory",
446
+ 'WARN',
447
+ 'StigmergyInstaller.copyDirectory',
448
448
  );
449
449
  console.log(
450
450
  `[WARN] Failed to copy directory ${src} to ${dest}: ${error.message}`,
@@ -463,11 +463,11 @@ class StigmergyInstaller {
463
463
 
464
464
  async showInstallOptions(missingTools) {
465
465
  if (Object.keys(missingTools).length === 0) {
466
- console.log("[INFO] All required AI CLI tools are already installed!");
466
+ console.log('[INFO] All required AI CLI tools are already installed!');
467
467
  return [];
468
468
  }
469
469
 
470
- console.log("\n[INSTALL] Missing AI CLI tools detected:");
470
+ console.log('\n[INSTALL] Missing AI CLI tools detected:');
471
471
  const choices = [];
472
472
 
473
473
  for (const [toolName, toolInfo] of Object.entries(missingTools)) {
@@ -480,10 +480,10 @@ class StigmergyInstaller {
480
480
 
481
481
  const answers = await inquirer.prompt([
482
482
  {
483
- type: "checkbox",
484
- name: "tools",
483
+ type: 'checkbox',
484
+ name: 'tools',
485
485
  message:
486
- "Select which tools to install (Space to select, Enter to confirm):",
486
+ 'Select which tools to install (Space to select, Enter to confirm):',
487
487
  choices: choices,
488
488
  pageSize: 10,
489
489
  },
@@ -499,8 +499,8 @@ class StigmergyInstaller {
499
499
 
500
500
  const answers = await inquirer.prompt([
501
501
  {
502
- type: "confirm",
503
- name: "proceed",
502
+ type: 'confirm',
503
+ name: 'proceed',
504
504
  message: `Install ${options.length} missing AI CLI tools?`,
505
505
  default: true,
506
506
  },
@@ -519,9 +519,9 @@ class StigmergyInstaller {
519
519
 
520
520
  const individualAnswers = await inquirer.prompt([
521
521
  {
522
- type: "checkbox",
523
- name: "selectedTools",
524
- message: "Select which tools to install:",
522
+ type: 'checkbox',
523
+ name: 'selectedTools',
524
+ message: 'Select which tools to install:',
525
525
  choices: individualChoices,
526
526
  pageSize: 10,
527
527
  },
@@ -531,12 +531,12 @@ class StigmergyInstaller {
531
531
  }
532
532
 
533
533
  async deployHooks(available) {
534
- console.log("\n[DEPLOY] Deploying cross-CLI integration hooks...");
534
+ console.log('\n[DEPLOY] Deploying cross-CLI integration hooks...');
535
535
 
536
536
  // Import the post-deployment configurer for executing installation scripts
537
537
  const {
538
538
  PostDeploymentConfigurer,
539
- } = require("./../scripts/post-deployment-config.js");
539
+ } = require('./../scripts/post-deployment-config.js');
540
540
  const configurer = new PostDeploymentConfigurer();
541
541
 
542
542
  let successCount = 0;
@@ -555,15 +555,15 @@ class StigmergyInstaller {
555
555
  // Copy adapter files from local assets
556
556
  // Mapping for tool names that don't match their adapter directory names
557
557
  const toolNameToAdapterDir = {
558
- qodercli: "qoder",
559
- qwencode: "qwen",
558
+ qodercli: 'qoder',
559
+ qwencode: 'qwen',
560
560
  };
561
561
  const adapterDirName = toolNameToAdapterDir[toolName] || toolName;
562
562
  const assetsAdaptersDir = path.join(
563
563
  os.homedir(),
564
- ".stigmergy",
565
- "assets",
566
- "adapters",
564
+ '.stigmergy',
565
+ 'assets',
566
+ 'adapters',
567
567
  adapterDirName,
568
568
  );
569
569
  if (await this.fileExists(assetsAdaptersDir)) {
@@ -581,7 +581,7 @@ class StigmergyInstaller {
581
581
  } catch (configError) {
582
582
  await errorHandler.logError(
583
583
  configError,
584
- "WARN",
584
+ 'WARN',
585
585
  `StigmergyInstaller.deployHooks.${toolName}.config`,
586
586
  );
587
587
  console.log(
@@ -592,13 +592,13 @@ class StigmergyInstaller {
592
592
  } catch (error) {
593
593
  await errorHandler.logError(
594
594
  error,
595
- "ERROR",
595
+ 'ERROR',
596
596
  `StigmergyInstaller.deployHooks.${toolName}`,
597
597
  );
598
598
  console.log(
599
599
  `[ERROR] Failed to deploy hooks for ${toolInfo.name}: ${error.message}`,
600
600
  );
601
- console.log("[INFO] Continuing with other tools...");
601
+ console.log('[INFO] Continuing with other tools...');
602
602
  }
603
603
  }
604
604
 
@@ -608,13 +608,13 @@ class StigmergyInstaller {
608
608
  }
609
609
 
610
610
  async deployProjectDocumentation() {
611
- console.log("\n[DEPLOY] Deploying project documentation...");
611
+ console.log('\n[DEPLOY] Deploying project documentation...');
612
612
 
613
613
  try {
614
614
  // Create standard project documentation files
615
615
  const docs = {
616
- "STIGMERGY.md": this.generateProjectMemoryTemplate(),
617
- "README.md": this.generateProjectReadme(),
616
+ 'STIGMERGY.md': this.generateProjectMemoryTemplate(),
617
+ 'README.md': this.generateProjectReadme(),
618
618
  };
619
619
 
620
620
  for (const [filename, content] of Object.entries(docs)) {
@@ -625,7 +625,7 @@ class StigmergyInstaller {
625
625
  }
626
626
  }
627
627
 
628
- console.log("[OK] Project documentation deployed successfully");
628
+ console.log('[OK] Project documentation deployed successfully');
629
629
  } catch (error) {
630
630
  console.log(
631
631
  `[ERROR] Failed to deploy project documentation: ${error.message}`,
@@ -681,30 +681,30 @@ See [STIGMERGY.md](STIGMERGY.md) for interaction history and collaboration recor
681
681
  }
682
682
 
683
683
  async initializeConfig() {
684
- console.log("\n[CONFIG] Initializing Stigmergy configuration...");
684
+ console.log('\n[CONFIG] Initializing Stigmergy configuration...');
685
685
 
686
686
  try {
687
687
  // Create config directory
688
- const configDir = path.join(os.homedir(), ".stigmergy");
688
+ const configDir = path.join(os.homedir(), '.stigmergy');
689
689
  await fs.mkdir(configDir, { recursive: true });
690
690
 
691
691
  // Create initial configuration
692
692
  const config = {
693
- version: "1.0.94",
693
+ version: '1.0.94',
694
694
  initialized: true,
695
695
  createdAt: new Date().toISOString(),
696
696
  lastUpdated: new Date().toISOString(),
697
- defaultCLI: "claude",
697
+ defaultCLI: 'claude',
698
698
  enableCrossCLI: true,
699
699
  enableMemory: true,
700
700
  tools: {},
701
701
  };
702
702
 
703
703
  // Save configuration
704
- const configPath = path.join(configDir, "config.json");
704
+ const configPath = path.join(configDir, 'config.json');
705
705
  await fs.writeFile(configPath, JSON.stringify(config, null, 2));
706
706
 
707
- console.log("[OK] Configuration initialized successfully");
707
+ console.log('[OK] Configuration initialized successfully');
708
708
  } catch (error) {
709
709
  console.log(
710
710
  `[ERROR] Failed to initialize configuration: ${error.message}`,
@@ -713,11 +713,11 @@ See [STIGMERGY.md](STIGMERGY.md) for interaction history and collaboration recor
713
713
  }
714
714
 
715
715
  showUsageInstructions() {
716
- console.log("\n" + "=".repeat(60));
717
- console.log("🎉 Stigmergy CLI Setup Complete!");
718
- console.log("=".repeat(60));
719
- console.log("");
720
- console.log("Next steps:");
716
+ console.log('\n' + '='.repeat(60));
717
+ console.log('🎉 Stigmergy CLI Setup Complete!');
718
+ console.log('='.repeat(60));
719
+ console.log('');
720
+ console.log('Next steps:');
721
721
  console.log(
722
722
  ' 1. Run "stigmergy install" to scan and install AI CLI tools',
723
723
  );
@@ -725,634 +725,629 @@ See [STIGMERGY.md](STIGMERGY.md) for interaction history and collaboration recor
725
725
  console.log(
726
726
  ' 3. Use "stigmergy call \\"<your prompt>\\"" to start collaborating',
727
727
  );
728
- console.log("");
729
- console.log("Example usage:");
728
+ console.log('');
729
+ console.log('Example usage:');
730
730
  console.log(' stigmergy call "用claude分析项目架构"');
731
731
  console.log(' stigmergy call "用qwen写一个hello world程序"');
732
732
  console.log(' stigmergy call "用gemini设计数据库表结构"');
733
- console.log("");
733
+ console.log('');
734
734
  console.log(
735
- "For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents",
735
+ 'For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents',
736
736
  );
737
- console.log("[END] Happy collaborating with multiple AI CLI tools!");
737
+ console.log('[END] Happy collaborating with multiple AI CLI tools!');
738
738
  }
739
739
  }
740
740
 
741
741
  // Main CLI functionality
742
742
  async function main() {
743
- if (process.env.DEBUG === "true") {
744
- console.log("[DEBUG] Main function called with args:", process.argv);
743
+ if (process.env.DEBUG === 'true') {
744
+ console.log('[DEBUG] Main function called with args:', process.argv);
745
745
  }
746
746
  const args = process.argv.slice(2);
747
747
  const installer = new StigmergyInstaller();
748
748
 
749
- try {
750
- // Handle case when no arguments are provided
751
- if (args.length === 0) {
752
- console.log(
753
- "Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System",
754
- );
755
- console.log("Version: 1.0.94");
756
- console.log("");
757
- console.log("[SYSTEM] Automated Installation and Deployment System");
758
- console.log("");
759
- console.log("Usage: stigmergy [command] [options]");
760
- console.log("");
761
- console.log("Commands:");
762
- console.log(" help, --help Show this help message");
763
- console.log(" version, --version Show version information");
764
- console.log(" status Check CLI tools status");
765
- console.log(" scan Scan for available AI CLI tools");
766
- console.log(" install Auto-install missing CLI tools");
767
- console.log(
768
- " deploy Deploy hooks and integration to installed tools",
769
- );
770
- console.log(" setup Complete setup and configuration");
771
- console.log(
772
- " init Initialize Stigmergy configuration (alias for setup)",
773
- );
774
- console.log(' call "<prompt>" Execute prompt with auto-routed AI CLI');
775
- console.log(" errors Display error report and statistics");
776
- console.log(
777
- " register <username> <password> Register a new user account",
778
- );
779
- console.log(" login <username> <password> Log in to your account");
780
- console.log(" logout Log out of your account");
781
- console.log(
782
- " auth-status Check authentication status",
783
- );
784
- console.log("");
785
- console.log("Authentication Commands:");
786
- console.log(
787
- " Register a new account: stigmergy register <username> <password>",
788
- );
789
- console.log(
790
- " Log in to your account: stigmergy login <username> <password>",
791
- );
792
- console.log(" Check auth status: stigmergy auth-status");
793
- console.log(" Log out of your account: stigmergy logout");
794
- console.log("");
795
- console.log("[WORKFLOW] Automated Workflow:");
796
- console.log(" 1. npm install -g stigmergy # Install Stigmergy");
797
- console.log(
798
- " 2. stigmergy install # Auto-scan & install CLI tools",
799
- );
800
- console.log(" 3. stigmergy setup # Deploy hooks & config");
801
- console.log(' 4. stigmergy call "<prompt>" # Start collaborating');
802
- console.log("");
803
- console.log("[INFO] For first-time setup, run: stigmergy setup");
804
- console.log(
805
- "[INFO] To scan and install AI tools, run: stigmergy install",
806
- );
807
- console.log("");
749
+ // Handle case when no arguments are provided
750
+ if (args.length === 0) {
751
+ console.log(
752
+ 'Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System',
753
+ );
754
+ console.log('Version: 1.0.94');
755
+ console.log('');
756
+ console.log('[SYSTEM] Automated Installation and Deployment System');
757
+ console.log('');
758
+ console.log('Usage: stigmergy [command] [options]');
759
+ console.log('');
760
+ console.log('Commands:');
761
+ console.log(' help, --help Show this help message');
762
+ console.log(' version, --version Show version information');
763
+ console.log(' status Check CLI tools status');
764
+ console.log(' scan Scan for available AI CLI tools');
765
+ console.log(' install Auto-install missing CLI tools');
766
+ console.log(
767
+ ' deploy Deploy hooks and integration to installed tools',
768
+ );
769
+ console.log(' setup Complete setup and configuration');
770
+ console.log(
771
+ ' init Initialize Stigmergy configuration (alias for setup)',
772
+ );
773
+ console.log(' call "<prompt>" Execute prompt with auto-routed AI CLI');
774
+ console.log(' errors Display error report and statistics');
775
+ console.log(
776
+ ' register <username> <password> Register a new user account',
777
+ );
778
+ console.log(' login <username> <password> Log in to your account');
779
+ console.log(' logout Log out of your account');
780
+ console.log(
781
+ ' auth-status Check authentication status',
782
+ );
783
+ console.log('');
784
+ console.log('Authentication Commands:');
785
+ console.log(
786
+ ' Register a new account: stigmergy register <username> <password>',
787
+ );
788
+ console.log(
789
+ ' Log in to your account: stigmergy login <username> <password>',
790
+ );
791
+ console.log(' Check auth status: stigmergy auth-status');
792
+ console.log(' Log out of your account: stigmergy logout');
793
+ console.log('');
794
+ console.log('[WORKFLOW] Automated Workflow:');
795
+ console.log(' 1. npm install -g stigmergy # Install Stigmergy');
796
+ console.log(
797
+ ' 2. stigmergy install # Auto-scan & install CLI tools',
798
+ );
799
+ console.log(' 3. stigmergy setup # Deploy hooks & config');
800
+ console.log(' 4. stigmergy call "<prompt>" # Start collaborating');
801
+ console.log('');
802
+ console.log('[INFO] For first-time setup, run: stigmergy setup');
803
+ console.log(
804
+ '[INFO] To scan and install AI tools, run: stigmergy install',
805
+ );
806
+ console.log('');
807
+ console.log(
808
+ 'For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents',
809
+ );
810
+ return;
811
+ }
812
+
813
+ // Handle help commands
814
+ if (args.includes('--help') || args.includes('-h')) {
815
+ console.log(
816
+ 'Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System',
817
+ );
818
+ console.log('Version: 1.0.94');
819
+ console.log('');
820
+ console.log('[SYSTEM] Automated Installation and Deployment System');
821
+ console.log('');
822
+ console.log('Usage: stigmergy [command] [options]');
823
+ console.log('');
824
+ console.log('Commands:');
825
+ console.log(' help, --help Show this help message');
826
+ console.log(' version, --version Show version information');
827
+ console.log(' status Check CLI tools status');
828
+ console.log(' scan Scan for available AI CLI tools');
829
+ console.log(' install Auto-install missing CLI tools');
830
+ console.log(
831
+ ' deploy Deploy hooks and integration to installed tools',
832
+ );
833
+ console.log(' setup Complete setup and configuration');
834
+ console.log(
835
+ ' init Initialize Stigmergy configuration (alias for setup)',
836
+ );
837
+ console.log(' call "<prompt>" Execute prompt with auto-routed AI CLI');
838
+ console.log(' errors Display error report and statistics');
839
+ console.log(
840
+ ' register <username> <password> Register a new user account',
841
+ );
842
+ console.log(' login <username> <password> Log in to your account');
843
+ console.log(' logout Log out of your account');
844
+ console.log(
845
+ ' auth-status Check authentication status',
846
+ );
847
+ console.log('');
848
+ console.log('Authentication Commands:');
849
+ console.log(
850
+ ' Register a new account: stigmergy register <username> <password>',
851
+ );
852
+ console.log(
853
+ ' Log in to your account: stigmergy login <username> <password>',
854
+ );
855
+ console.log(' Check auth status: stigmergy auth-status');
856
+ console.log(' Log out of your account: stigmergy logout');
857
+ console.log('');
858
+ console.log('[WORKFLOW] Automated Workflow:');
859
+ console.log(' 1. npm install -g stigmergy # Install Stigmergy');
860
+ console.log(
861
+ ' 2. stigmergy install # Auto-scan & install CLI tools',
862
+ );
863
+ console.log(' 3. stigmergy setup # Deploy hooks & config');
864
+ console.log(' 4. stigmergy call "<prompt>" # Start collaborating');
865
+ console.log('');
866
+ console.log(
867
+ 'For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents',
868
+ );
869
+ return;
870
+ }
871
+
872
+ const command = args[0];
873
+
874
+ // Define protected commands that require authentication
875
+ const protectedCommands = ['call', 'setup', 'deploy', 'install'];
876
+
877
+ // Check if command requires authentication
878
+ if (
879
+ protectedCommands.includes(command) &&
880
+ command !== 'version' &&
881
+ command !== '--version'
882
+ ) {
883
+ if (!isAuthenticated()) {
884
+ console.log('[ERROR] Authentication required. Please log in first.');
808
885
  console.log(
809
- "For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents",
886
+ '[INFO] Run "stigmergy login <username> <password>" to log in.',
810
887
  );
811
- return;
888
+ process.exit(1);
812
889
  }
890
+ }
813
891
 
814
- // Handle help commands
815
- if (args.includes("--help") || args.includes("-h")) {
816
- console.log(
817
- "Stigmergy CLI - Multi-Agents Cross-AI CLI Tools Collaboration System",
818
- );
819
- console.log("Version: 1.0.94");
820
- console.log("");
821
- console.log("[SYSTEM] Automated Installation and Deployment System");
822
- console.log("");
823
- console.log("Usage: stigmergy [command] [options]");
824
- console.log("");
825
- console.log("Commands:");
826
- console.log(" help, --help Show this help message");
827
- console.log(" version, --version Show version information");
828
- console.log(" status Check CLI tools status");
829
- console.log(" scan Scan for available AI CLI tools");
830
- console.log(" install Auto-install missing CLI tools");
831
- console.log(
832
- " deploy Deploy hooks and integration to installed tools",
833
- );
834
- console.log(" setup Complete setup and configuration");
835
- console.log(
836
- " init Initialize Stigmergy configuration (alias for setup)",
837
- );
838
- console.log(' call "<prompt>" Execute prompt with auto-routed AI CLI');
839
- console.log(" errors Display error report and statistics");
840
- console.log(
841
- " register <username> <password> Register a new user account",
842
- );
843
- console.log(" login <username> <password> Log in to your account");
844
- console.log(" logout Log out of your account");
845
- console.log(
846
- " auth-status Check authentication status",
847
- );
848
- console.log("");
849
- console.log("Authentication Commands:");
850
- console.log(
851
- " Register a new account: stigmergy register <username> <password>",
852
- );
853
- console.log(
854
- " Log in to your account: stigmergy login <username> <password>",
855
- );
856
- console.log(" Check auth status: stigmergy auth-status");
857
- console.log(" Log out of your account: stigmergy logout");
858
- console.log("");
859
- console.log("[WORKFLOW] Automated Workflow:");
860
- console.log(" 1. npm install -g stigmergy # Install Stigmergy");
861
- console.log(
862
- " 2. stigmergy install # Auto-scan & install CLI tools",
863
- );
864
- console.log(" 3. stigmergy setup # Deploy hooks & config");
865
- console.log(' 4. stigmergy call "<prompt>" # Start collaborating');
866
- console.log("");
867
- console.log(
868
- "For more information, visit: https://github.com/ptreezh/stigmergy-CLI-Multi-Agents",
892
+ switch (command) {
893
+ case 'version':
894
+ case '--version': {
895
+ // Use the version from configuration instead of hardcoding
896
+ const config = {
897
+ version: '1.0.94',
898
+ initialized: true,
899
+ createdAt: new Date().toISOString(),
900
+ lastUpdated: new Date().toISOString(),
901
+ defaultCLI: 'claude',
902
+ enableCrossCLI: true,
903
+ enableMemory: true,
904
+ };
905
+ console.log(`Stigmergy CLI v${config.version}`);
906
+ break;
907
+ }
908
+
909
+ case 'errors':
910
+ try {
911
+ console.log('[ERRORS] Generating Stigmergy CLI error report...\n');
912
+ await errorHandler.printErrorReport();
913
+ } catch (error) {
914
+ console.error(
915
+ '[ERROR] Failed to generate error report:',
916
+ error.message,
869
917
  );
870
- return;
918
+ process.exit(1);
871
919
  }
920
+ break;
872
921
 
873
- const command = args[0];
922
+ case 'init':
923
+ // Alias for setup command
924
+ console.log('[INIT] Initializing Stigmergy CLI...');
925
+ // Fall through to setup case
874
926
 
875
- // Define protected commands that require authentication
876
- const protectedCommands = ["call", "setup", "deploy", "install"];
927
+ case 'setup':
928
+ try {
929
+ console.log('[SETUP] Starting complete Stigmergy setup...\n');
877
930
 
878
- // Check if command requires authentication
879
- if (
880
- protectedCommands.includes(command) &&
881
- command !== "version" &&
882
- command !== "--version"
883
- ) {
884
- if (!isAuthenticated()) {
885
- console.log("[ERROR] Authentication required. Please log in first.");
886
- console.log(
887
- '[INFO] Run "stigmergy login <username> <password>" to log in.',
888
- );
889
- process.exit(1);
890
- }
891
- }
931
+ // Step 1: Download required assets
932
+ await installer.downloadRequiredAssets();
892
933
 
893
- switch (command) {
894
- case "version":
895
- case "--version":
896
- // Use the version from configuration instead of hardcoding
897
- const config = {
898
- version: "1.0.94",
899
- initialized: true,
900
- createdAt: new Date().toISOString(),
901
- lastUpdated: new Date().toISOString(),
902
- defaultCLI: "claude",
903
- enableCrossCLI: true,
904
- enableMemory: true,
905
- };
906
- console.log(`Stigmergy CLI v${config.version}`);
907
- break;
934
+ // Step 2: Scan for CLI tools
935
+ const { available: setupAvailable, missing: setupMissing } =
936
+ await installer.scanCLI();
937
+ const setupOptions = await installer.showInstallOptions(setupMissing);
908
938
 
909
- case "errors":
910
- try {
911
- console.log("[ERRORS] Generating Stigmergy CLI error report...\n");
912
- await errorHandler.printErrorReport();
913
- } catch (error) {
914
- console.error(
915
- "[ERROR] Failed to generate error report:",
916
- error.message,
939
+ // Step 3: Install missing CLI tools if user chooses
940
+ if (setupOptions.length > 0) {
941
+ const selectedTools = await installer.getUserSelection(
942
+ setupOptions,
943
+ setupMissing,
944
+ );
945
+ if (selectedTools.length > 0) {
946
+ console.log(
947
+ '\n[INFO] Installing selected tools (this may take several minutes for tools that download binaries)...',
917
948
  );
918
- process.exit(1);
949
+ await installer.installTools(selectedTools, setupMissing);
919
950
  }
920
- break;
921
-
922
- case "init":
923
- // Alias for setup command
924
- console.log("[INIT] Initializing Stigmergy CLI...");
925
- // Fall through to setup case
926
- case "setup":
927
- try {
928
- console.log("[SETUP] Starting complete Stigmergy setup...\n");
929
-
930
- // Step 1: Download required assets
931
- await installer.downloadRequiredAssets();
951
+ } else {
952
+ console.log('\n[INFO] All required tools are already installed!');
953
+ }
932
954
 
933
- // Step 2: Scan for CLI tools
934
- const { available: setupAvailable, missing: setupMissing } =
935
- await installer.scanCLI();
936
- const setupOptions = await installer.showInstallOptions(setupMissing);
955
+ // Step 4: Deploy hooks to available CLI tools
956
+ await installer.deployHooks(setupAvailable);
937
957
 
938
- // Step 3: Install missing CLI tools if user chooses
939
- if (setupOptions.length > 0) {
940
- const selectedTools = await installer.getUserSelection(
941
- setupOptions,
942
- setupMissing,
943
- );
944
- if (selectedTools.length > 0) {
945
- console.log(
946
- "\n[INFO] Installing selected tools (this may take several minutes for tools that download binaries)...",
947
- );
948
- await installer.installTools(selectedTools, setupMissing);
949
- }
950
- } else {
951
- console.log("\n[INFO] All required tools are already installed!");
952
- }
958
+ // Step 5: Deploy project documentation
959
+ await installer.deployProjectDocumentation();
953
960
 
954
- // Step 4: Deploy hooks to available CLI tools
955
- await installer.deployHooks(setupAvailable);
961
+ // Step 6: Initialize configuration
962
+ await installer.initializeConfig();
956
963
 
957
- // Step 5: Deploy project documentation
958
- await installer.deployProjectDocumentation();
964
+ // Step 7: Show usage instructions
965
+ installer.showUsageInstructions();
966
+ } catch (error) {
967
+ await errorHandler.logError(error, 'ERROR', 'main.setup');
968
+ console.log(`[ERROR] Setup failed: ${error.message}`);
969
+ console.log('\n[TROUBLESHOOTING] To manually complete setup:');
970
+ console.log('1. Run: stigmergy deploy # Deploy hooks manually');
971
+ console.log('2. Run: stigmergy setup # Try setup again');
972
+ process.exit(1);
973
+ }
974
+ break;
959
975
 
960
- // Step 6: Initialize configuration
961
- await installer.initializeConfig();
976
+ case 'status':
977
+ try {
978
+ const { available, missing } = await installer.scanCLI();
979
+ console.log('\n[STATUS] AI CLI Tools Status Report');
980
+ console.log('=====================================');
981
+
982
+ if (Object.keys(available).length > 0) {
983
+ console.log('\n✅ Available Tools:');
984
+ for (const [toolName, toolInfo] of Object.entries(available)) {
985
+ console.log(` - ${toolInfo.name} (${toolName})`);
986
+ }
987
+ }
962
988
 
963
- // Step 7: Show usage instructions
964
- installer.showUsageInstructions();
965
- } catch (error) {
966
- await errorHandler.logError(error, "ERROR", "main.setup");
967
- console.log(`[ERROR] Setup failed: ${error.message}`);
968
- console.log("\n[TROUBLESHOOTING] To manually complete setup:");
969
- console.log("1. Run: stigmergy deploy # Deploy hooks manually");
970
- console.log("2. Run: stigmergy setup # Try setup again");
971
- process.exit(1);
989
+ if (Object.keys(missing).length > 0) {
990
+ console.log('\n❌ Missing Tools:');
991
+ for (const [toolName, toolInfo] of Object.entries(missing)) {
992
+ console.log(` - ${toolInfo.name} (${toolName})`);
993
+ console.log(` Install command: ${toolInfo.install}`);
972
994
  }
973
- break;
974
- break;
995
+ }
975
996
 
976
- case "status":
977
- try {
978
- const { available, missing } = await installer.scanCLI();
979
- console.log("\n[STATUS] AI CLI Tools Status Report");
980
- console.log("=====================================");
981
-
982
- if (Object.keys(available).length > 0) {
983
- console.log("\n✅ Available Tools:");
984
- for (const [toolName, toolInfo] of Object.entries(available)) {
985
- console.log(` - ${toolInfo.name} (${toolName})`);
986
- }
987
- }
997
+ console.log(
998
+ `\n[SUMMARY] ${Object.keys(available).length} available, ${Object.keys(missing).length} missing`,
999
+ );
1000
+ } catch (error) {
1001
+ await errorHandler.logError(error, 'ERROR', 'main.status');
1002
+ console.log(`[ERROR] Failed to get status: ${error.message}`);
1003
+ process.exit(1);
1004
+ }
1005
+ break;
988
1006
 
989
- if (Object.keys(missing).length > 0) {
990
- console.log("\n❌ Missing Tools:");
991
- for (const [toolName, toolInfo] of Object.entries(missing)) {
992
- console.log(` - ${toolInfo.name} (${toolName})`);
993
- console.log(` Install command: ${toolInfo.install}`);
994
- }
995
- }
1007
+ case 'scan':
1008
+ try {
1009
+ await installer.scanCLI();
1010
+ } catch (error) {
1011
+ await errorHandler.logError(error, 'ERROR', 'main.scan');
1012
+ console.log(`[ERROR] Failed to scan CLI tools: ${error.message}`);
1013
+ process.exit(1);
1014
+ }
1015
+ break;
996
1016
 
1017
+ case 'install':
1018
+ try {
1019
+ console.log('[INSTALL] Starting AI CLI tools installation...');
1020
+ const { missing: missingTools } = await installer.scanCLI();
1021
+ const options = await installer.showInstallOptions(missingTools);
1022
+
1023
+ if (options.length > 0) {
1024
+ const selectedTools = await installer.getUserSelection(
1025
+ options,
1026
+ missingTools,
1027
+ );
1028
+ if (selectedTools.length > 0) {
997
1029
  console.log(
998
- `\n[SUMMARY] ${Object.keys(available).length} available, ${Object.keys(missing).length} missing`,
1030
+ '\n[INFO] Installing selected tools (this may take several minutes for tools that download binaries)...',
999
1031
  );
1000
- } catch (error) {
1001
- await errorHandler.logError(error, "ERROR", "main.status");
1002
- console.log(`[ERROR] Failed to get status: ${error.message}`);
1003
- process.exit(1);
1032
+ await installer.installTools(selectedTools, missingTools);
1004
1033
  }
1005
- break;
1006
-
1007
- case "scan":
1008
- try {
1009
- await installer.scanCLI();
1010
- } catch (error) {
1011
- await errorHandler.logError(error, "ERROR", "main.scan");
1012
- console.log(`[ERROR] Failed to scan CLI tools: ${error.message}`);
1013
- process.exit(1);
1014
- }
1015
- break;
1016
-
1017
- case "install":
1018
- try {
1019
- console.log("[INSTALL] Starting AI CLI tools installation...");
1020
- const { missing: missingTools } = await installer.scanCLI();
1021
- const options = await installer.showInstallOptions(missingTools);
1022
-
1023
- if (options.length > 0) {
1024
- const selectedTools = await installer.getUserSelection(
1025
- options,
1026
- missingTools,
1027
- );
1028
- if (selectedTools.length > 0) {
1029
- console.log(
1030
- "\n[INFO] Installing selected tools (this may take several minutes for tools that download binaries)...",
1031
- );
1032
- await installer.installTools(selectedTools, missingTools);
1033
- }
1034
- } else {
1035
- console.log("\n[INFO] All required tools are already installed!");
1036
- }
1037
- } catch (error) {
1038
- await errorHandler.logError(error, "ERROR", "main.install");
1039
- console.log(`[ERROR] Installation failed: ${error.message}`);
1040
- process.exit(1);
1041
- }
1042
- break;
1034
+ } else {
1035
+ console.log('\n[INFO] All required tools are already installed!');
1036
+ }
1037
+ } catch (error) {
1038
+ await errorHandler.logError(error, 'ERROR', 'main.install');
1039
+ console.log(`[ERROR] Installation failed: ${error.message}`);
1040
+ process.exit(1);
1041
+ }
1042
+ break;
1043
1043
 
1044
- case "deploy":
1045
- try {
1046
- const { available: deployedTools } = await installer.scanCLI();
1047
- await installer.deployHooks(deployedTools);
1048
- } catch (error) {
1049
- await errorHandler.logError(error, "ERROR", "main.deploy");
1050
- console.log(`[ERROR] Deployment failed: ${error.message}`);
1051
- process.exit(1);
1052
- }
1053
- break;
1044
+ case 'deploy':
1045
+ try {
1046
+ const { available: deployedTools } = await installer.scanCLI();
1047
+ await installer.deployHooks(deployedTools);
1048
+ } catch (error) {
1049
+ await errorHandler.logError(error, 'ERROR', 'main.deploy');
1050
+ console.log(`[ERROR] Deployment failed: ${error.message}`);
1051
+ process.exit(1);
1052
+ }
1053
+ break;
1054
1054
 
1055
- case "register":
1056
- if (args.length < 3) {
1057
- console.log(
1058
- "[ERROR] Usage: stigmergy register <username> <password>",
1059
- );
1060
- process.exit(1);
1061
- }
1062
- handleRegister(args[1], args[2]);
1063
- break;
1055
+ case 'register':
1056
+ if (args.length < 3) {
1057
+ console.log(
1058
+ '[ERROR] Usage: stigmergy register <username> <password>',
1059
+ );
1060
+ process.exit(1);
1061
+ }
1062
+ handleRegister(args[1], args[2]);
1063
+ break;
1064
1064
 
1065
- case "login":
1066
- if (args.length < 3) {
1067
- console.log("[ERROR] Usage: stigmergy login <username> <password>");
1068
- process.exit(1);
1069
- }
1070
- handleLogin(args[1], args[2]);
1071
- break;
1065
+ case 'login':
1066
+ if (args.length < 3) {
1067
+ console.log('[ERROR] Usage: stigmergy login <username> <password>');
1068
+ process.exit(1);
1069
+ }
1070
+ handleLogin(args[1], args[2]);
1071
+ break;
1072
1072
 
1073
- case "logout":
1074
- handleLogout();
1075
- break;
1073
+ case 'logout':
1074
+ handleLogout();
1075
+ break;
1076
1076
 
1077
- case "auth-status":
1078
- handleStatus();
1079
- break;
1077
+ case 'auth-status':
1078
+ handleStatus();
1079
+ break;
1080
1080
 
1081
- case "call":
1082
- if (args.length < 2) {
1083
- console.log('[ERROR] Usage: stigmergy call "<prompt>"');
1084
- process.exit(1);
1085
- }
1081
+ case 'call': {
1082
+ if (args.length < 2) {
1083
+ console.log('[ERROR] Usage: stigmergy call "<prompt>"');
1084
+ process.exit(1);
1085
+ }
1086
1086
 
1087
- // Get the prompt (everything after the command)
1088
- const prompt = args.slice(1).join(" ");
1087
+ // Get the prompt (everything after the command)
1088
+ const prompt = args.slice(1).join(' ');
1089
1089
 
1090
- // Use smart router to determine which tool to use
1091
- const router = new SmartRouter();
1092
- await router.initialize(); // Initialize the router first
1093
- const route = await router.smartRoute(prompt);
1090
+ // Use smart router to determine which tool to use
1091
+ const router = new SmartRouter();
1092
+ await router.initialize(); // Initialize the router first
1093
+ const route = await router.smartRoute(prompt);
1094
1094
 
1095
- console.log(`[CALL] Routing to ${route.tool}: ${route.prompt}`);
1095
+ console.log(`[CALL] Routing to ${route.tool}: ${route.prompt}`);
1096
1096
 
1097
- // Execute the routed command
1098
- try {
1099
- // Get the actual executable path for the tool
1100
- const toolPath = route.tool;
1097
+ // Execute the routed command
1098
+ try {
1099
+ // Get the actual executable path for the tool
1100
+ const toolPath = route.tool;
1101
1101
 
1102
- // SPECIAL TEST CASE: Simulate a non-existent tool for testing
1103
- // This is for demonstration purposes only
1104
- /*
1102
+ // SPECIAL TEST CASE: Simulate a non-existent tool for testing
1103
+ // This is for demonstration purposes only
1104
+ /*
1105
1105
  if (route.tool === "nonexistenttool") {
1106
1106
  toolPath = "this_tool_definitely_does_not_exist_12345";
1107
1107
  }
1108
1108
  */
1109
1109
 
1110
- console.log(
1111
- `[DEBUG] Tool path: ${toolPath}, Prompt: ${route.prompt}`,
1112
- );
1113
-
1114
- // For different tools, we need to pass the prompt differently
1115
- // Use unified parameter handler for better parameter handling
1116
- let toolArgs = [];
1110
+ console.log(
1111
+ `[DEBUG] Tool path: ${toolPath}, Prompt: ${route.prompt}`,
1112
+ );
1117
1113
 
1118
- try {
1119
- // Get CLI pattern for this tool
1120
- const cliPattern = await router.analyzer.getCLIPattern(route.tool);
1114
+ // For different tools, we need to pass the prompt differently
1115
+ // Use unified parameter handler for better parameter handling
1116
+ let toolArgs = [];
1121
1117
 
1122
- // Use the unified CLI parameter handler
1123
- const CLIParameterHandler = require("./core/cli_parameter_handler");
1124
- toolArgs = CLIParameterHandler.generateArguments(
1125
- route.tool,
1126
- route.prompt,
1127
- cliPattern,
1128
- );
1129
- } catch (patternError) {
1130
- // Fallback to original logic if pattern analysis fails
1131
- if (route.tool === "claude") {
1132
- // Claude CLI expects the prompt with -p flag for non-interactive mode
1133
- toolArgs = ["-p", `"${route.prompt}"`];
1134
- } else if (route.tool === "qodercli" || route.tool === "iflow") {
1135
- // Qoder CLI and iFlow expect the prompt with -p flag
1136
- toolArgs = ["-p", `"${route.prompt}"`];
1137
- } else if (route.tool === "codex") {
1138
- // Codex CLI needs 'exec' subcommand for non-interactive mode
1139
- toolArgs = ["exec", "-p", `"${route.prompt}"`];
1140
- } else {
1141
- // For other tools, pass the prompt with -p flag
1142
- toolArgs = ["-p", `"${route.prompt}"`];
1143
- }
1144
- }
1118
+ try {
1119
+ // Get CLI pattern for this tool
1120
+ const cliPattern = await router.analyzer.getCLIPattern(route.tool);
1121
+
1122
+ // Use the unified CLI parameter handler
1123
+ const CLIParameterHandler = require('./core/cli_parameter_handler');
1124
+ toolArgs = CLIParameterHandler.generateArguments(
1125
+ route.tool,
1126
+ route.prompt,
1127
+ cliPattern,
1128
+ );
1129
+ } catch (patternError) {
1130
+ // Fallback to original logic if pattern analysis fails
1131
+ if (route.tool === 'claude') {
1132
+ // Claude CLI expects the prompt with -p flag for non-interactive mode
1133
+ toolArgs = ['-p', `"${route.prompt}"`];
1134
+ } else if (route.tool === 'qodercli' || route.tool === 'iflow') {
1135
+ // Qoder CLI and iFlow expect the prompt with -p flag
1136
+ toolArgs = ['-p', `"${route.prompt}"`];
1137
+ } else if (route.tool === 'codex') {
1138
+ // Codex CLI needs 'exec' subcommand for non-interactive mode
1139
+ toolArgs = ['exec', '-p', `"${route.prompt}"`];
1140
+ } else {
1141
+ // For other tools, pass the prompt with -p flag
1142
+ toolArgs = ['-p', `"${route.prompt}"`];
1143
+ }
1144
+ }
1145
1145
 
1146
- // Use the reliable cross-platform execution function
1147
- try {
1148
- // Validate that the tool exists before attempting to execute
1149
- if (!toolPath || typeof toolPath !== "string") {
1150
- throw new Error(`Invalid tool path: ${toolPath}`);
1151
- }
1152
-
1153
- // Special handling for JS files to ensure proper execution
1154
- if (toolPath.endsWith(".js") || toolPath.endsWith(".cjs")) {
1155
- // Use safe JS file execution
1156
- console.log(
1157
- `[EXEC] Safely executing JS file: ${toolPath} ${toolArgs.join(" ")}`,
1158
- );
1159
- const result = await executeJSFile(toolPath, toolArgs, {
1160
- stdio: "inherit",
1161
- shell: true,
1162
- });
1163
-
1164
- if (!result.success) {
1165
- console.log(
1166
- `[WARN] ${route.tool} exited with code ${result.code}`,
1167
- );
1168
- }
1169
- process.exit(result.code || 0);
1170
- } else {
1171
- // Regular command execution
1172
- console.log(`[EXEC] Running: ${toolPath} ${toolArgs.join(" ")}`);
1173
- const result = await executeCommand(toolPath, toolArgs, {
1174
- stdio: "inherit",
1175
- shell: true,
1176
- });
1177
-
1178
- if (!result.success) {
1179
- console.log(
1180
- `[WARN] ${route.tool} exited with code ${result.code}`,
1181
- );
1182
- }
1183
- process.exit(result.code || 0);
1184
- }
1185
- } catch (executionError) {
1186
- const cliError = await errorHandler.handleCLIError(
1187
- route.tool,
1188
- executionError.error || executionError,
1189
- toolArgs.join(" "),
1190
- );
1146
+ // Use the reliable cross-platform execution function
1147
+ try {
1148
+ // Validate that the tool exists before attempting to execute
1149
+ if (!toolPath || typeof toolPath !== 'string') {
1150
+ throw new Error(`Invalid tool path: ${toolPath}`);
1151
+ }
1191
1152
 
1192
- // Provide clear ANSI English error message
1193
- console.log("==================================================");
1194
- console.log("ERROR: Failed to execute AI CLI tool");
1195
- console.log("==================================================");
1196
- console.log(`Tool: ${route.tool}`);
1197
- console.log(`Error: ${cliError.message}`);
1198
- if (executionError.stderr) {
1199
- console.log(`Stderr: ${executionError.stderr}`);
1200
- }
1201
- console.log("");
1202
- console.log("Possible solutions:");
1203
- console.log("1. Check if the AI CLI tool is properly installed");
1204
- console.log("2. Verify the tool is in your system PATH");
1205
- console.log("3. Try reinstalling the tool with: stigmergy install");
1206
- console.log("4. Run stigmergy status to check tool availability");
1207
- console.log("");
1208
- console.log("For manual execution, you can run:");
1209
- console.log(`${toolPath} ${toolArgs.join(" ")}`);
1210
- console.log("==================================================");
1211
-
1212
- process.exit(1);
1213
- }
1214
- } catch (error) {
1215
- const cliError = await errorHandler.handleCLIError(
1216
- route.tool,
1217
- error,
1218
- prompt,
1219
- );
1153
+ // Special handling for JS files to ensure proper execution
1154
+ if (toolPath.endsWith('.js') || toolPath.endsWith('.cjs')) {
1155
+ // Use safe JS file execution
1220
1156
  console.log(
1221
- `[ERROR] Failed to execute ${route.tool}:`,
1222
- cliError.message,
1157
+ `[EXEC] Safely executing JS file: ${toolPath} ${toolArgs.join(' ')}`,
1223
1158
  );
1224
- process.exit(1);
1225
- }
1226
- break;
1227
-
1228
- case "auto-install":
1229
- // Auto-install mode for npm postinstall - NON-INTERACTIVE
1230
- console.log("[AUTO-INSTALL] Stigmergy CLI automated setup");
1231
- console.log("=".repeat(60));
1159
+ const result = await executeJSFile(toolPath, toolArgs, {
1160
+ stdio: 'inherit',
1161
+ shell: true,
1162
+ });
1232
1163
 
1233
- try {
1234
- // Step 1: Download required assets
1235
- try {
1236
- console.log("[STEP] Downloading required assets...");
1237
- await installer.downloadRequiredAssets();
1238
- console.log("[OK] Assets downloaded successfully");
1239
- } catch (error) {
1240
- console.log(`[WARN] Failed to download assets: ${error.message}`);
1241
- console.log("[INFO] Continuing with installation...");
1242
- }
1243
-
1244
- // Step 2: Scan for CLI tools
1245
- let autoAvailable = {},
1246
- autoMissing = {};
1247
- try {
1248
- console.log("[STEP] Scanning for CLI tools...");
1249
- const scanResult = await installer.scanCLI();
1250
- autoAvailable = scanResult.available;
1251
- autoMissing = scanResult.missing;
1252
- console.log("[OK] CLI tools scanned successfully");
1253
- } catch (error) {
1254
- console.log(`[WARN] Failed to scan CLI tools: ${error.message}`);
1255
- console.log("[INFO] Continuing with installation...");
1256
- }
1257
-
1258
- // Step 3: Show summary to user after installation
1259
- try {
1260
- if (Object.keys(autoMissing).length > 0) {
1261
- console.log(
1262
- "\n[INFO] Found " +
1263
- Object.keys(autoMissing).length +
1264
- " missing AI CLI tools:",
1265
- );
1266
- for (const [toolName, toolInfo] of Object.entries(autoMissing)) {
1267
- console.log(` - ${toolInfo.name} (${toolName})`);
1268
- }
1269
- console.log(
1270
- "\n[INFO] Auto-install mode detected. Skipping automatic installation of missing tools.",
1271
- );
1272
- console.log(
1273
- '[INFO] For full functionality, please run "stigmergy install" after installation completes.',
1274
- );
1275
- } else {
1276
- console.log(
1277
- "\n[INFO] All AI CLI tools are already installed! No additional tools required.",
1278
- );
1279
- }
1280
- } catch (error) {
1281
- console.log(`[WARN] Failed to show tool summary: ${error.message}`);
1282
- }
1283
-
1284
- // Step 4: Deploy hooks to available CLI tools
1285
- try {
1286
- console.log("[STEP] Deploying hooks to available CLI tools...");
1287
- await installer.deployHooks(autoAvailable);
1288
- console.log("[OK] Hooks deployed successfully");
1289
- } catch (error) {
1290
- console.log(`[ERROR] Failed to deploy hooks: ${error.message}`);
1164
+ if (!result.success) {
1291
1165
  console.log(
1292
- "[INFO] You can manually deploy hooks later by running: stigmergy deploy",
1166
+ `[WARN] ${route.tool} exited with code ${result.code}`,
1293
1167
  );
1294
1168
  }
1295
-
1296
- // Step 5: Deploy project documentation
1297
- try {
1298
- console.log("[STEP] Deploying project documentation...");
1299
- await installer.deployProjectDocumentation();
1300
- console.log("[OK] Documentation deployed successfully");
1301
- } catch (error) {
1169
+ process.exit(result.code || 0);
1170
+ } else {
1171
+ // Regular command execution
1172
+ console.log(`[EXEC] Running: ${toolPath} ${toolArgs.join(' ')}`);
1173
+ const result = await executeCommand(toolPath, toolArgs, {
1174
+ stdio: 'inherit',
1175
+ shell: true,
1176
+ });
1177
+
1178
+ if (!result.success) {
1302
1179
  console.log(
1303
- `[WARN] Failed to deploy documentation: ${error.message}`,
1180
+ `[WARN] ${route.tool} exited with code ${result.code}`,
1304
1181
  );
1305
- console.log("[INFO] Continuing with installation...");
1306
1182
  }
1183
+ process.exit(result.code || 0);
1184
+ }
1185
+ } catch (executionError) {
1186
+ const cliError = await errorHandler.handleCLIError(
1187
+ route.tool,
1188
+ executionError.error || executionError,
1189
+ toolArgs.join(' '),
1190
+ );
1307
1191
 
1308
- // Step 6: Initialize configuration
1309
- try {
1310
- console.log("[STEP] Initializing configuration...");
1311
- await installer.initializeConfig();
1312
- console.log("[OK] Configuration initialized successfully");
1313
- } catch (error) {
1314
- console.log(
1315
- `[ERROR] Failed to initialize configuration: ${error.message}`,
1316
- );
1317
- console.log(
1318
- "[INFO] You can manually initialize configuration later by running: stigmergy setup",
1319
- );
1320
- }
1192
+ // Provide clear ANSI English error message
1193
+ console.log('==================================================');
1194
+ console.log('ERROR: Failed to execute AI CLI tool');
1195
+ console.log('==================================================');
1196
+ console.log(`Tool: ${route.tool}`);
1197
+ console.log(`Error: ${cliError.message}`);
1198
+ if (executionError.stderr) {
1199
+ console.log(`Stderr: ${executionError.stderr}`);
1200
+ }
1201
+ console.log('');
1202
+ console.log('Possible solutions:');
1203
+ console.log('1. Check if the AI CLI tool is properly installed');
1204
+ console.log('2. Verify the tool is in your system PATH');
1205
+ console.log('3. Try reinstalling the tool with: stigmergy install');
1206
+ console.log('4. Run stigmergy status to check tool availability');
1207
+ console.log('');
1208
+ console.log('For manual execution, you can run:');
1209
+ console.log(`${toolPath} ${toolArgs.join(' ')}`);
1210
+ console.log('==================================================');
1211
+
1212
+ process.exit(1);
1213
+ }
1214
+ } catch (error) {
1215
+ const cliError = await errorHandler.handleCLIError(
1216
+ route.tool,
1217
+ error,
1218
+ prompt,
1219
+ );
1220
+ console.log(
1221
+ `[ERROR] Failed to execute ${route.tool}:`,
1222
+ cliError.message,
1223
+ );
1224
+ process.exit(1);
1225
+ }
1226
+ break;
1227
+ }
1228
+
1229
+ case 'auto-install':
1230
+ // Auto-install mode for npm postinstall - NON-INTERACTIVE
1231
+ console.log('[AUTO-INSTALL] Stigmergy CLI automated setup');
1232
+ console.log('='.repeat(60));
1321
1233
 
1322
- // Step 7: Show final message to guide users
1323
- console.log("\n[SUCCESS] Stigmergy CLI installed successfully!");
1234
+ try {
1235
+ // Step 1: Download required assets
1236
+ try {
1237
+ console.log('[STEP] Downloading required assets...');
1238
+ await installer.downloadRequiredAssets();
1239
+ console.log('[OK] Assets downloaded successfully');
1240
+ } catch (error) {
1241
+ console.log(`[WARN] Failed to download assets: ${error.message}`);
1242
+ console.log('[INFO] Continuing with installation...');
1243
+ }
1244
+
1245
+ // Step 2: Scan for CLI tools
1246
+ let autoAvailable = {},
1247
+ autoMissing = {};
1248
+ try {
1249
+ console.log('[STEP] Scanning for CLI tools...');
1250
+ const scanResult = await installer.scanCLI();
1251
+ autoAvailable = scanResult.available;
1252
+ autoMissing = scanResult.missing;
1253
+ console.log('[OK] CLI tools scanned successfully');
1254
+ } catch (error) {
1255
+ console.log(`[WARN] Failed to scan CLI tools: ${error.message}`);
1256
+ console.log('[INFO] Continuing with installation...');
1257
+ }
1258
+
1259
+ // Step 3: Show summary to user after installation
1260
+ try {
1261
+ if (Object.keys(autoMissing).length > 0) {
1324
1262
  console.log(
1325
- '[USAGE] Run "stigmergy setup" to complete full configuration and install missing AI CLI tools.',
1263
+ '\n[INFO] Found ' +
1264
+ Object.keys(autoMissing).length +
1265
+ ' missing AI CLI tools:',
1326
1266
  );
1267
+ for (const [toolName, toolInfo] of Object.entries(autoMissing)) {
1268
+ console.log(` - ${toolInfo.name} (${toolName})`);
1269
+ }
1327
1270
  console.log(
1328
- '[USAGE] Run "stigmergy install" to install only missing AI CLI tools.',
1271
+ '\n[INFO] Auto-install mode detected. Skipping automatic installation of missing tools.',
1329
1272
  );
1330
1273
  console.log(
1331
- '[USAGE] Run "stigmergy --help" to see all available commands.',
1274
+ '[INFO] For full functionality, please run "stigmergy install" after installation completes.',
1332
1275
  );
1333
- } catch (fatalError) {
1334
- await errorHandler.logError(fatalError, "ERROR", "main.auto-install");
1335
- console.error(
1336
- "[FATAL] Auto-install process failed:",
1337
- fatalError.message,
1276
+ } else {
1277
+ console.log(
1278
+ '\n[INFO] All AI CLI tools are already installed! No additional tools required.',
1338
1279
  );
1339
- console.log("\n[TROUBLESHOOTING] To manually complete installation:");
1340
- console.log("1. Run: stigmergy setup # Complete setup");
1341
- console.log("2. Run: stigmergy install # Install missing tools");
1342
- console.log("3. Run: stigmergy deploy # Deploy hooks manually");
1343
- process.exit(1);
1344
1280
  }
1345
- break;
1346
- break;
1281
+ } catch (error) {
1282
+ console.log(`[WARN] Failed to show tool summary: ${error.message}`);
1283
+ }
1347
1284
 
1348
- default:
1349
- console.log(`[ERROR] Unknown command: ${command}`);
1350
- console.log('[INFO] Run "stigmergy --help" for usage information');
1351
- process.exit(1);
1285
+ // Step 4: Deploy hooks to available CLI tools
1286
+ try {
1287
+ console.log('[STEP] Deploying hooks to available CLI tools...');
1288
+ await installer.deployHooks(autoAvailable);
1289
+ console.log('[OK] Hooks deployed successfully');
1290
+ } catch (error) {
1291
+ console.log(`[ERROR] Failed to deploy hooks: ${error.message}`);
1292
+ console.log(
1293
+ '[INFO] You can manually deploy hooks later by running: stigmergy deploy',
1294
+ );
1295
+ }
1296
+
1297
+ // Step 5: Deploy project documentation
1298
+ try {
1299
+ console.log('[STEP] Deploying project documentation...');
1300
+ await installer.deployProjectDocumentation();
1301
+ console.log('[OK] Documentation deployed successfully');
1302
+ } catch (error) {
1303
+ console.log(
1304
+ `[WARN] Failed to deploy documentation: ${error.message}`,
1305
+ );
1306
+ console.log('[INFO] Continuing with installation...');
1307
+ }
1308
+
1309
+ // Step 6: Initialize configuration
1310
+ try {
1311
+ console.log('[STEP] Initializing configuration...');
1312
+ await installer.initializeConfig();
1313
+ console.log('[OK] Configuration initialized successfully');
1314
+ } catch (error) {
1315
+ console.log(
1316
+ `[ERROR] Failed to initialize configuration: ${error.message}`,
1317
+ );
1318
+ console.log(
1319
+ '[INFO] You can manually initialize configuration later by running: stigmergy setup',
1320
+ );
1321
+ }
1322
+
1323
+ // Step 7: Show final message to guide users
1324
+ console.log('\n[SUCCESS] Stigmergy CLI installed successfully!');
1325
+ console.log(
1326
+ '[USAGE] Run "stigmergy setup" to complete full configuration and install missing AI CLI tools.',
1327
+ );
1328
+ console.log(
1329
+ '[USAGE] Run "stigmergy install" to install only missing AI CLI tools.',
1330
+ );
1331
+ console.log(
1332
+ '[USAGE] Run "stigmergy --help" to see all available commands.',
1333
+ );
1334
+ } catch (fatalError) {
1335
+ await errorHandler.logError(fatalError, 'ERROR', 'main.auto-install');
1336
+ console.error(
1337
+ '[FATAL] Auto-install process failed:',
1338
+ fatalError.message,
1339
+ );
1340
+ console.log('\n[TROUBLESHOOTING] To manually complete installation:');
1341
+ console.log('1. Run: stigmergy setup # Complete setup');
1342
+ console.log('2. Run: stigmergy install # Install missing tools');
1343
+ console.log('3. Run: stigmergy deploy # Deploy hooks manually');
1344
+ process.exit(1);
1352
1345
  }
1353
- } catch (error) {
1354
- await errorHandler.logError(error, "ERROR", "main");
1355
- console.error("[FATAL] Stigmergy CLI encountered an error:", error.message);
1346
+ break;
1347
+
1348
+ default:
1349
+ console.log(`[ERROR] Unknown command: ${command}`);
1350
+ console.log('[INFO] Run "stigmergy --help" for usage information');
1356
1351
  process.exit(1);
1357
1352
  }
1358
1353
  }
@@ -1369,8 +1364,8 @@ function isAuthenticated() {
1369
1364
  // Load authentication data
1370
1365
  const authFile = path.join(
1371
1366
  process.env.HOME || process.env.USERPROFILE,
1372
- ".stigmergy",
1373
- "auth.json",
1367
+ '.stigmergy',
1368
+ 'auth.json',
1374
1369
  );
1375
1370
 
1376
1371
  if (!fsSync.existsSync(authFile)) {
@@ -1378,7 +1373,7 @@ function isAuthenticated() {
1378
1373
  }
1379
1374
 
1380
1375
  // Load the authentication data into the authenticator
1381
- const data = JSON.parse(fsSync.readFileSync(authFile, "utf8"));
1376
+ const data = JSON.parse(fsSync.readFileSync(authFile, 'utf8'));
1382
1377
  if (data.sessions) {
1383
1378
  for (const [token, sessionData] of Object.entries(data.sessions)) {
1384
1379
  authenticator._sessions.set(token, sessionData);
@@ -1388,15 +1383,15 @@ function isAuthenticated() {
1388
1383
  // Read the current session token
1389
1384
  const sessionFile = path.join(
1390
1385
  process.env.HOME || process.env.USERPROFILE,
1391
- ".stigmergy",
1392
- "session.token",
1386
+ '.stigmergy',
1387
+ 'session.token',
1393
1388
  );
1394
1389
 
1395
1390
  if (!fsSync.existsSync(sessionFile)) {
1396
1391
  return false;
1397
1392
  }
1398
1393
 
1399
- const token = fsSync.readFileSync(sessionFile, "utf8").trim();
1394
+ const token = fsSync.readFileSync(sessionFile, 'utf8').trim();
1400
1395
  const username = authenticator.validateSession(token);
1401
1396
 
1402
1397
  return !!username;
@@ -1418,9 +1413,9 @@ module.exports = {
1418
1413
  if (require.main === module) {
1419
1414
  main().catch((error) => {
1420
1415
  console.error(
1421
- "[FATAL] Stigmergy CLI encountered an unhandled error:",
1416
+ '[FATAL] Stigmergy CLI encountered an unhandled error:',
1422
1417
  error,
1423
1418
  );
1424
1419
  process.exit(1);
1425
1420
  });
1426
- }
1421
+ }