@mmlotfy/intellicodemcp
Version:
IntelliCodeMCP - Advanced AI Model Context Protocol System for intelligent code management and orchestration
437 lines • 17.6 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MCPPerformanceOrchestrator = void 0;
exports.executePerformanceOrchestrator = executePerformanceOrchestrator;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const yaml = __importStar(require("js-yaml"));
const code_trace_1 = require("./code-trace");
const smartthink_weaver_1 = require("./smartthink-weaver");
const memory_bank_1 = require("./memory-bank");
const perf_hooks_1 = require("perf_hooks");
const fuse_js_1 = __importDefault(require("fuse.js"));
class MCPPerformanceOrchestrator {
constructor(configPath = '.roo/code-intelligence.yaml') {
this.modelProfiles = [];
this.taskClassifier = 'GrokMini';
// Initialize synchronously - init() will be called separately
}
async init(configPath) {
try {
await this.loadConfiguration(configPath);
await this.loadProfiles();
await this.initializeSearch();
}
catch (error) {
console.error('Failed to initialize Performance Orchestrator:', error.message);
throw new Error(`Performance Orchestrator initialization failed: ${error.message}`);
}
}
async loadConfiguration(configPath) {
try {
const file = await fs_1.promises.readFile(path_1.default.join(process.cwd(), configPath), 'utf8');
this.config = yaml.load(file);
}
catch (err) {
console.warn(`Configuration file not found at ${configPath}, using default configuration`);
// Use default configuration
this.config = this.getDefaultConfiguration();
}
}
getDefaultConfiguration() {
return {
performance: {
model_selection: {
default: "Gemini-2.5-Pro",
simple: "Gemini-2.5-Pro",
code_writing: "Claude",
analytical: "Grok",
complex: "DeepSeek"
},
quality_threshold: 0.95,
max_processing_time_ms: 3000,
max_tokens_per_task: 2000,
phases: {
inspection: {
enabled: true,
priority: "critical",
model_preference: "Gemini-2.5-Pro"
},
diagnosis: {
enabled: true,
priority: "high",
model_preference: ["DeepSeek", "Claude"]
},
execution_plan: {
enabled: true,
priority: "medium",
confirmation_required: true,
model_preference: ["Claude", "Grok"]
}
}
},
integrations: {
search: {
enabled: true,
search_path: "intelliMemoryHub/",
result_directory: "intelliMemoryHub/docs/search_results/",
max_results: 50
}
}
};
}
async loadProfiles() {
const profilePath = 'intelliMemoryHub/model_profiles/profiles.json';
try {
const data = await fs_1.promises.readFile(path_1.default.join(process.cwd(), profilePath), 'utf8');
this.modelProfiles = JSON.parse(data);
}
catch (err) {
console.warn(`Failed to load profiles from ${profilePath}, using default profiles`);
this.modelProfiles = this.getDefaultProfiles();
}
}
getDefaultProfiles() {
return [
{
model: "Gemini-2.5-Pro",
strengths: ["natural_conversation", "balanced_speed_quality", "context_understanding"],
weaknesses: ["higher_token_cost", "needs_precise_prompts"],
optimal_tasks: ["quick_code_fixes", "document_analysis", "strategic_planning"],
token_cost_per_request: 25,
response_time_ms: 500,
max_context_tokens: 128000
},
{
model: "Claude",
strengths: ["high_code_quality", "long_context_memory", "deep_system_design"],
weaknesses: ["slower_response", "high_token_cost"],
optimal_tasks: ["complex_coding", "code_reviews", "system_architecture"],
token_cost_per_request: 0.3,
response_time_ms: 1000,
max_context_tokens: 200000
},
{
model: "Grok",
strengths: ["logical_reasoning", "scientific_analysis", "think_mode"],
weaknesses: ["weaker_code_formatting", "slower_simple_tasks"],
optimal_tasks: ["algorithm_design", "data_analysis", "scientific_computing"],
token_cost_per_request: 0.15,
response_time_ms: 700,
max_context_tokens: 128000
},
{
model: "DeepSeek",
strengths: ["chain_of_thought", "high_transparency", "mathematical_precision"],
weaknesses: ["less_natural_conversation", "limited_non_analytical_tasks"],
optimal_tasks: ["algorithm_explanation", "step_by_step_analysis", "mathematical_computing"],
token_cost_per_request: 0.18,
response_time_ms: 800,
max_context_tokens: 128000
}
];
}
async initializeSearch() {
try {
const searchPath = this.config?.integrations?.search?.search_path || 'intelliMemoryHub';
const files = await this.getFiles(searchPath);
const documents = await Promise.all(files.map(async (file) => ({
file,
content: await fs_1.promises.readFile(file, 'utf8'),
})));
this.fuse = new fuse_js_1.default(documents, {
keys: ['content'],
includeScore: true,
threshold: 0.3,
});
}
catch (error) {
console.warn('Failed to initialize search, using empty index');
this.fuse = new fuse_js_1.default([], {
keys: ['content'],
includeScore: true,
threshold: 0.3,
});
}
}
async searchProject(query) {
const results = this.fuse.search(query);
const searchResults = results.map((result) => ({
file: result.item.file,
content: result.item.content.slice(0, 200) + '...',
score: result.score || 0,
}));
await this.saveSearchResults(query, searchResults);
return searchResults.slice(0, this.config.integrations.search.max_results);
}
async saveSearchResults(query, results) {
const timestamp = new Date().toISOString().replace(/[-:.]/g, '');
const logEntry = {
query,
results,
timestamp: new Date().toISOString(),
};
await (0, memory_bank_1.executeMemoryFile)({
action: 'write',
category: 'search',
file_name: `search_result_${timestamp}.json`,
content: JSON.stringify(logEntry, null, 2),
});
}
async getFiles(dir) {
const entries = await fs_1.promises.readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const fullPath = path_1.default.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...await this.getFiles(fullPath));
}
else if (fullPath.match(/\.(ts|tsx|js|jsx|txt|md|json|yaml)$/)) {
files.push(fullPath);
}
}
return files;
}
async processTask(task) {
const taskType = await this.classifyTask(task);
task.type = taskType;
// Enhance context with search results
if (task.input) {
const searchResults = await this.searchProject(task.input);
task.context = (task.context || '') + `\nSearch Results:\n${searchResults.map(r => `File: ${r.file}, Preview: ${r.content}`).join('\n')}`;
}
const model = this.selectModel(taskType);
const phases = this.config.performance.phases;
const results = [];
const startTime = perf_hooks_1.performance.now();
try {
if (phases.inspection.enabled) {
const phaseStart = perf_hooks_1.performance.now();
const inspection = await this.inspectTask(task, model);
const timeTaken = perf_hooks_1.performance.now() - phaseStart;
const tokenUsage = this.estimateTokens(inspection, model);
results.push({
phase: 'Inspection',
output: inspection,
model: model.model,
execution_time_ms: timeTaken,
token_usage: tokenUsage,
});
}
if (phases.diagnosis.enabled) {
const phaseStart = perf_hooks_1.performance.now();
const diagnosis = await this.diagnoseTask(task, model);
const timeTaken = perf_hooks_1.performance.now() - phaseStart;
const tokenUsage = this.estimateTokens(diagnosis, model);
results.push({
phase: 'Diagnosis',
output: diagnosis,
model: model.model,
execution_time_ms: timeTaken,
token_usage: tokenUsage,
});
}
if (phases.execution_plan.enabled) {
const phaseStart = perf_hooks_1.performance.now();
const plan = await this.planExecution(task, model);
const timeTaken = perf_hooks_1.performance.now() - phaseStart;
const tokenUsage = this.estimateTokens(plan, model);
if (phases.execution_plan.confirmation_required) {
const approved = await this.requestConfirmation(plan);
if (!approved) {
throw new Error(`Execution plan for task ${task.id} not approved`);
}
}
results.push({
phase: 'Execution',
output: plan,
model: model.model,
execution_time_ms: timeTaken,
token_usage: tokenUsage,
});
}
await this.logPerformance(task, model, results, perf_hooks_1.performance.now() - startTime);
return results;
}
catch (error) {
await this.logPerformance(task, model, results, perf_hooks_1.performance.now() - startTime, error);
throw error;
}
}
async classifyTask(task) {
if (task.input.includes('fix') || task.input.includes('error')) {
return 'simple';
}
if (task.input.includes('write') || task.input.includes('code')) {
return 'code_writing';
}
if (task.input.includes('algorithm') || task.input.includes('analyze')) {
return 'analytical';
}
return 'complex';
}
selectModel(taskType) {
const preferences = this.config.performance.model_selection;
const modelName = preferences[taskType] || preferences.default;
const model = this.modelProfiles.find(p => p.model === modelName);
if (!model) {
throw new Error(`Model ${modelName} not found`);
}
return model;
}
async inspectTask(task, model) {
if (model.model === 'Gemini-2.5-Pro') {
const traceResult = await (0, code_trace_1.executeCodeTrace)({
project_path: task.context || process.cwd(),
check_type: 'all',
});
return {
source: 'CodeTraceMCP',
output: traceResult,
context: 'Inspected with Gemini for rapid analysis',
};
}
return {
source: 'Skipped',
message: `Inspection not implemented for ${model.model}`,
};
}
async diagnoseTask(task, model) {
if (['Claude', 'DeepSeek'].includes(model.model)) {
const thinkResult = await (0, smartthink_weaver_1.executeSmartThink)({
problem: task.input,
context: task.context,
});
return {
source: 'SmartThink',
output: thinkResult,
context: `Diagnosed with ${model.model}`,
};
}
return {
source: 'Basic',
message: 'No issues detected',
};
}
async planExecution(task, model) {
if (model.model === 'Grok') {
return {
source: 'Grok',
steps: [
{
action: 'Analyze requirements',
details: `Logical breakdown for ${task.input}`,
task_type: task.type,
},
{
action: 'Propose solution',
details: 'Step-by-step reasoning',
},
],
};
}
if (model.model === 'Claude') {
return {
source: 'Claude',
steps: [
{
action: 'Generate code',
file: task.context ? path_1.default.basename(task.context) : 'solution.ts',
content: '// Claude-generated TypeScript code\ninterface User {\n id: string;\n email: string;\n}\nfunction authenticate(email: string): User {\n return { id: "123", email };\n}',
},
{
action: 'Review code',
details: 'Ensure TypeScript best practices',
},
],
};
}
return {
source: 'Generic',
steps: [],
};
}
async requestConfirmation(plan) {
console.log('=== Approval Required ===');
console.log(JSON.stringify(plan, null, 2));
return true; // Simulated approval for now
}
estimateTokens(output, model) {
const outputSize = JSON.stringify(output).length;
return Math.round(outputSize * model.token_cost_per_request);
}
async logPerformance(task, model, results, totalTimeMs, error) {
const logEntry = {
task_id: task.id,
task_input: task.input,
task_type: task.type,
priority: task.priority,
model: model.model,
executions: results,
total_time_ms: totalTimeMs,
error: error ? error.message : null,
timestamp: new Date().toISOString(),
};
const timestamp = new Date().toISOString().replace(/[-:.]/g, '');
const logFile = `log_${timestamp}.json`;
await (0, memory_bank_1.executeMemoryFile)({
action: 'write',
category: 'technical',
file_name: logFile,
content: JSON.stringify(logEntry, null, 2),
});
}
}
exports.MCPPerformanceOrchestrator = MCPPerformanceOrchestrator;
async function executePerformanceOrchestrator(args) {
try {
const orchestrator = new MCPPerformanceOrchestrator();
await orchestrator.init('.roo/code-intelligence.yaml');
return await orchestrator.processTask(args.task);
}
catch (error) {
console.error('Performance Orchestrator execution failed:', error.message);
return {
status: 'error',
message: error.message,
timestamp: new Date().toISOString()
};
}
}
//# sourceMappingURL=performance-orchestrator.js.map