UNPKG

csvlod-ai-mcp-server

Version:

CSVLOD-AI MCP Server v3.0 with Quantum Context Intelligence - Revolutionary Context Intelligence Engine and Multimodal Processor for sovereign AI development

252 lines 10.5 kB
/** * CSVLOD-AI Agent Swarm Coordination System * * This module implements sovereign multi-agent coordination capabilities, * enabling developers to orchestrate specialized AI agents while maintaining * complete control over their development process. * * Core Principles: * - Sovereignty: All agents operate under developer control * - Structure: CSVLOD context provides coordination framework * - Emergence: Complex behaviors emerge from simple coordination rules */ import * as fs from 'fs/promises'; import * as path from 'path'; import * as yaml from 'js-yaml'; export class SwarmCoordinator { constructor(manifestPath) { this.activeTasks = new Map(); this.agentWorkloads = new Map(); this.contextCache = new Map(); this.loadManifest(manifestPath); } async loadManifest(manifestPath) { try { const manifestContent = await fs.readFile(manifestPath, 'utf-8'); this.manifest = yaml.load(manifestContent); // Initialize agent workloads if (this.manifest.agent_specializations) { for (const agentType of Object.keys(this.manifest.agent_specializations)) { this.agentWorkloads.set(agentType, 0); } } } catch (error) { throw new Error(`Failed to load agent manifest: ${error instanceof Error ? error.message : String(error)}`); } } /** * Decomposes a high-level task into agent-specific subtasks * based on agent specializations and context requirements */ async decomposeTask(description, projectPath, requiredContext = []) { if (!this.manifest.swarm_config?.enabled) { throw new Error('Swarm coordination is not enabled in agent manifest'); } const tasks = []; const taskId = this.generateTaskId(); // Analyze task requirements and map to agent specializations const taskMapping = await this.analyzeTaskRequirements(description, requiredContext); for (const [agentType, taskDetails] of Object.entries(taskMapping)) { const specialization = this.manifest.agent_specializations?.[agentType]; if (!specialization) continue; const task = { id: `${taskId}-${agentType}`, agent_type: agentType, description: taskDetails.description, context_requirements: taskDetails.context_requirements, dependencies: taskDetails.dependencies, priority: specialization.priority, status: 'pending', created_at: new Date(), updated_at: new Date() }; tasks.push(task); this.activeTasks.set(task.id, task); } return this.prioritizeTasks(tasks); } /** * Analyzes task requirements and maps them to appropriate agent specializations */ async analyzeTaskRequirements(description, requiredContext) { const taskMapping = {}; // Simple keyword-based mapping (can be enhanced with LLM analysis) const keywords = description.toLowerCase(); if (this.manifest.agent_specializations) { // Backend tasks if (keywords.includes('api') || keywords.includes('database') || keywords.includes('server')) { taskMapping.backend_specialist = { description: `Handle backend implementation for: ${description}`, context_requirements: ['standards', 'designs', 'considerations'], dependencies: [] }; } // Frontend tasks if (keywords.includes('ui') || keywords.includes('interface') || keywords.includes('frontend')) { taskMapping.frontend_specialist = { description: `Handle frontend implementation for: ${description}`, context_requirements: ['visions', 'outlines', 'designs'], dependencies: keywords.includes('api') ? ['backend_specialist'] : [] }; } // Security tasks if (keywords.includes('security') || keywords.includes('auth') || keywords.includes('permission')) { taskMapping.security_auditor = { description: `Security review and implementation for: ${description}`, context_requirements: ['considerations', 'standards'], dependencies: ['backend_specialist'] }; } // Documentation tasks taskMapping.documentation_agent = { description: `Generate documentation for: ${description}`, context_requirements: ['landscapes', 'outlines'], dependencies: Object.keys(taskMapping).filter(agent => agent !== 'documentation_agent') }; // Coordinator always oversees taskMapping.coordinator = { description: `Coordinate and integrate implementation of: ${description}`, context_requirements: ['considerations', 'visions', 'landscapes'], dependencies: [] }; } return taskMapping; } /** * Prioritizes tasks based on dependencies and agent priority levels */ prioritizeTasks(tasks) { return tasks.sort((a, b) => { // First by priority (lower number = higher priority) if (a.priority !== b.priority) { return a.priority - b.priority; } // Then by dependency count (fewer dependencies first) return a.dependencies.length - b.dependencies.length; }); } /** * Assigns tasks to available agents based on workload and specialization */ async assignTask(taskId) { const task = this.activeTasks.get(taskId); if (!task) { throw new Error(`Task ${taskId} not found`); } // Check if dependencies are completed const pendingDependencies = task.dependencies.filter(depId => { const depTask = Array.from(this.activeTasks.values()) .find(t => t.agent_type === depId); return depTask && depTask.status !== 'completed'; }); if (pendingDependencies.length > 0) { return null; // Cannot assign yet, dependencies not completed } // Find least loaded agent of the required type const currentWorkload = this.agentWorkloads.get(task.agent_type) || 0; const maxConcurrent = this.manifest.swarm_config?.max_concurrent_agents || 3; if (currentWorkload >= maxConcurrent) { return null; // Agent type at capacity } // Assign task const agentId = `${task.agent_type}-${Date.now()}`; task.assigned_agent = agentId; task.status = 'in_progress'; task.updated_at = new Date(); this.agentWorkloads.set(task.agent_type, currentWorkload + 1); return agentId; } /** * Completes a task and updates swarm state */ async completeTask(taskId, result) { const task = this.activeTasks.get(taskId); if (!task) { throw new Error(`Task ${taskId} not found`); } task.status = 'completed'; task.result = result; task.updated_at = new Date(); // Reduce agent workload const currentWorkload = this.agentWorkloads.get(task.agent_type) || 0; this.agentWorkloads.set(task.agent_type, Math.max(0, currentWorkload - 1)); // Update context cache with task results await this.updateContextCache(task); // Check if any dependent tasks can now be assigned await this.checkDependentTasks(task.agent_type); } /** * Updates the shared context cache with task results */ async updateContextCache(task) { const cacheKey = `${task.agent_type}-${task.id}`; this.contextCache.set(cacheKey, { agent_type: task.agent_type, task_description: task.description, result: task.result, completed_at: task.updated_at, context_contributions: task.context_requirements }); } /** * Checks if any pending tasks can now be assigned after a dependency completes */ async checkDependentTasks(completedAgentType) { const pendingTasks = Array.from(this.activeTasks.values()) .filter(task => task.status === 'pending' && task.dependencies.includes(completedAgentType)); for (const task of pendingTasks) { await this.assignTask(task.id); } } /** * Generates a unique task ID */ generateTaskId() { return `swarm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } /** * Gets current swarm status and active tasks */ getSwarmStatus() { const tasks = Array.from(this.activeTasks.values()); const tasksByStatus = { pending: tasks.filter(t => t.status === 'pending').length, in_progress: tasks.filter(t => t.status === 'in_progress').length, completed: tasks.filter(t => t.status === 'completed').length, failed: tasks.filter(t => t.status === 'failed').length }; return { swarm_enabled: this.manifest.swarm_config?.enabled || false, coordination_mode: this.manifest.swarm_config?.coordination_mode || 'hierarchical', active_agents: Object.fromEntries(this.agentWorkloads), task_counts: tasksByStatus, total_tasks: tasks.length, context_cache_size: this.contextCache.size }; } /** * Gets detailed information about a specific task */ getTaskDetails(taskId) { return this.activeTasks.get(taskId) || null; } /** * Gets all tasks for a specific agent type */ getTasksByAgent(agentType) { return Array.from(this.activeTasks.values()) .filter(task => task.agent_type === agentType); } } /** * Creates a new swarm coordinator instance */ export async function createSwarmCoordinator(projectPath) { const manifestPath = path.join(projectPath, '.csvlod', 'AGENT-MANIFEST.yaml'); return new SwarmCoordinator(manifestPath); } export default SwarmCoordinator; //# sourceMappingURL=swarm.js.map