stigmergy 1.0.97 → 1.0.99

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