/** * GLYTCH AI Tool Router for Cloud Connect * Intelligent command routing to appropriate tools and services * Integrates with Code Converter, ARC File Manager, and all Cloud Connect tools */ class GLYTCHToolRouter { constructor() { this.tools = { codeConverter: { url: '/tools/cc-code-converter.html', commands: [ 'format', 'beautify', 'minify', 'compress', 'validate', 'lint', 'convert', 'transform', 'encode', 'decode', 'obfuscate', 'analyze' ], fileTypes: ['html', 'css', 'js', 'json', 'xml', 'sql', 'php', 'py', 'java', 'cpp'] }, arcManager: { url: '/tools/cc-arc-file-manager.html', commands: [ 'backup', 'sync', 'restore', 'duplicate', 'manage', 'organize', 'cloud', 'storage', 'files', 'folders', 'move', 'copy' ], contexts: ['file', 'folder', 'directory', 'storage', 'cloud', 'backup'] }, legendaryLeads: { url: '/tools/cc-legendary-leads.html', commands: ['lead', 'contact', 'email', 'instagram', 'social', 'database', 'search'], contexts: ['marketing', 'outreach', 'prospects'] }, imageGenerator: { url: '/tools/cc-ai-image-generator.html', commands: ['generate', 'create', 'image', 'photo', 'picture', 'art', 'design'], contexts: ['visual', 'creative', 'graphics'] }, pricingCalculator: { url: '/tools/cc-pricing-calculator.html', commands: ['price', 'cost', 'calculate', 'quote', 'estimate', 'billing'], contexts: ['pricing', 'sales', 'revenue'] }, documentGenerator: { url: '/tools/cc-document-generator.html', commands: ['document', 'generate', 'create', 'template', 'invoice', 'proposal'], contexts: ['business', 'paperwork', 'documentation'] } }; this.contextHistory = []; this.userPreferences = this.loadUserPreferences(); this.initializeRouter(); } /** * Main command processing function * Analyzes user input and routes to appropriate tool */ async processCommand(userInput, context = {}) { try { const analysis = await this.analyzeCommand(userInput, context); const route = this.determineRoute(analysis); const action = this.buildAction(route, analysis); // Log command for learning this.logCommand(userInput, route, action); return await this.executeAction(action); } catch (error) { console.error('GLYTCH Router Error:', error); return { success: false, error: error.message, suggestion: this.getSuggestion(userInput) }; } } /** * Advanced NLP analysis of user commands */ async analyzeCommand(input, context) { const tokens = this.tokenize(input.toLowerCase()); const intent = this.detectIntent(tokens); const entities = this.extractEntities(tokens, context); const confidence = this.calculateConfidence(intent, entities, tokens); return { originalInput: input, tokens, intent, entities, confidence, context: { ...context, history: this.contextHistory } }; } /** * Tokenization with smart preprocessing */ tokenize(input) { return input .replace(/[^\w\s.-]/g, ' ') .split(/\s+/) .filter(token => token.length > 0) .map(token => this.stemWord(token)); } /** * Intent detection using keyword matching and context */ detectIntent(tokens) { const intents = { // Code Converter intents CODE_FORMAT: ['format', 'beautify', 'clean', 'organize', 'structure'], CODE_MINIFY: ['minify', 'compress', 'optimize', 'shrink', 'reduce'], CODE_CONVERT: ['convert', 'transform', 'change', 'translate'], CODE_VALIDATE: ['validate', 'check', 'verify', 'lint', 'test'], CODE_SECURITY: ['security', 'scan', 'vulnerable', 'safe', 'protect'], CODE_OBFUSCATE: ['obfuscate', 'hide', 'protect', 'scramble'], // ARC File Manager intents FILE_BACKUP: ['backup', 'save', 'protect', 'archive', 'store'], FILE_SYNC: ['sync', 'synchronize', 'match', 'update', 'mirror'], FILE_RESTORE: ['restore', 'recover', 'retrieve', 'get back'], FILE_DUPLICATE: ['duplicate', 'copy', 'clone', 'same', 'identical'], FILE_ORGANIZE: ['organize', 'sort', 'arrange', 'manage', 'clean'], FILE_MOVE: ['move', 'transfer', 'relocate', 'shift'], // Other tool intents GENERATE_IMAGE: ['generate', 'create', 'make', 'produce', 'image', 'picture'], CALCULATE_PRICE: ['price', 'cost', 'calculate', 'quote', 'estimate'], CREATE_DOCUMENT: ['document', 'create', 'generate', 'template'], FIND_LEADS: ['lead', 'contact', 'find', 'search', 'prospect'] }; let bestIntent = null; let maxScore = 0; Object.entries(intents).forEach(([intent, keywords]) => { const score = keywords.reduce((sum, keyword) => { return sum + (tokens.includes(keyword) ? 1 : 0); }, 0); if (score > maxScore) { maxScore = score; bestIntent = intent; } }); return { name: bestIntent, confidence: maxScore / Math.max(tokens.length, 1) }; } /** * Entity extraction (files, formats, services, etc.) */ extractEntities(tokens, context) { const entities = { files: [], formats: [], services: [], numbers: [], paths: [] }; const formatPatterns = { code: ['html', 'css', 'js', 'javascript', 'json', 'xml', 'sql', 'php', 'python', 'java'], cloud: ['google', 'drive', 'dropbox', 'onedrive', 'icloud', 'aws', 's3'], document: ['pdf', 'docx', 'xlsx', 'pptx', 'txt'] }; tokens.forEach(token => { // File formats Object.entries(formatPatterns).forEach(([category, formats]) => { if (formats.includes(token)) { entities.formats.push({ type: category, value: token }); } }); // Numbers if (/^\d+(\.\d+)?$/.test(token)) { entities.numbers.push(parseFloat(token)); } // File paths if (token.includes('/') || token.includes('\\')) { entities.paths.push(token); } }); // Context-based entity extraction if (context.files) { entities.files = context.files; } return entities; } /** * Confidence calculation based on multiple factors */ calculateConfidence(intent, entities, tokens) { let confidence = intent.confidence; // Boost confidence if entities match intent if (intent.name?.includes('CODE') && entities.formats.some(f => f.type === 'code')) { confidence += 0.2; } if (intent.name?.includes('FILE') && (entities.files.length > 0 || entities.paths.length > 0)) { confidence += 0.2; } // Consider user history const recentCommands = this.contextHistory.slice(-5); const contextBoost = recentCommands.some(cmd => cmd.intent === intent.name) ? 0.1 : 0; return Math.min(confidence + contextBoost, 1.0); } /** * Route determination based on analysis */ determineRoute(analysis) { const { intent, entities, confidence } = analysis; // Confidence threshold if (confidence < 0.3) { return { tool: 'clarification', confidence, reason: 'Low confidence in intent detection' }; } // Intent to tool mapping const intentMapping = { CODE_FORMAT: 'codeConverter', CODE_MINIFY: 'codeConverter', CODE_CONVERT: 'codeConverter', CODE_VALIDATE: 'codeConverter', CODE_SECURITY: 'codeConverter', CODE_OBFUSCATE: 'codeConverter', FILE_BACKUP: 'arcManager', FILE_SYNC: 'arcManager', FILE_RESTORE: 'arcManager', FILE_DUPLICATE: 'arcManager', FILE_ORGANIZE: 'arcManager', FILE_MOVE: 'arcManager', GENERATE_IMAGE: 'imageGenerator', CALCULATE_PRICE: 'pricingCalculator', CREATE_DOCUMENT: 'documentGenerator', FIND_LEADS: 'legendaryLeads' }; const tool = intentMapping[intent.name] || 'clarification'; return { tool, intent: intent.name, confidence, entities, parameters: this.extractParameters(analysis) }; } /** * Extract specific parameters for tool execution */ extractParameters(analysis) { const { intent, entities, tokens } = analysis; const params = {}; switch (intent.name) { case 'CODE_FORMAT': case 'CODE_MINIFY': case 'CODE_CONVERT': params.operation = intent.name.split('_')[1].toLowerCase(); if (entities.formats.length > 0) { params.inputFormat = entities.formats[0].value; params.outputFormat = entities.formats[1]?.value || entities.formats[0].value; } break; case 'FILE_BACKUP': case 'FILE_SYNC': params.operation = intent.name.split('_')[1].toLowerCase(); params.files = entities.files; params.services = entities.formats .filter(f => f.type === 'cloud') .map(f => f.value); break; case 'GENERATE_IMAGE': params.prompt = tokens.filter(t => !['generate', 'create', 'make', 'image', 'picture'].includes(t) ).join(' '); break; case 'CALCULATE_PRICE': params.services = this.extractServices(tokens); params.quantity = entities.numbers[0] || 1; break; } return params; } /** * Build executable action from route */ buildAction(route, analysis) { return { tool: route.tool, url: this.tools[route.tool]?.url, method: 'navigate', // or 'api', 'iframe', etc. parameters: { ...route.parameters, autoExecute: route.confidence > 0.8, userInput: analysis.originalInput }, metadata: { timestamp: new Date().toISOString(), confidence: route.confidence, intent: route.intent } }; } /** * Execute the determined action */ async executeAction(action) { try { switch (action.method) { case 'navigate': return await this.navigateToTool(action); case 'api': return await this.callToolAPI(action); case 'iframe': return await this.embedTool(action); case 'clarification': return this.requestClarification(action); default: throw new Error(`Unknown action method: ${action.method}`); } } catch (error) { return { success: false, error: error.message, action }; } } /** * Navigate to appropriate tool with parameters */ async navigateToTool(action) { const { tool, url, parameters } = action; // Build URL with parameters const urlParams = new URLSearchParams(); Object.entries(parameters).forEach(([key, value]) => { if (value !== undefined && value !== null) { urlParams.append(key, typeof value === 'object' ? JSON.stringify(value) : value); } }); const fullUrl = `${url}?${urlParams.toString()}`; // For Cloud Connect dashboard integration if (typeof window !== 'undefined') { // Client-side navigation if (parameters.autoExecute) { // Auto-execute the operation window.postMessage({ type: 'GLYTCH_AUTO_EXECUTE', tool, parameters }, '*'); } window.location.href = fullUrl; } return { success: true, action: 'navigate', tool, url: fullUrl, message: `Opening ${this.getToolDisplayName(tool)}...`, autoExecute: parameters.autoExecute }; } /** * Call tool API directly (for headless operations) */ async callToolAPI(action) { // Implementation for direct API calls to tools // This would be used for background operations return { success: true, action: 'api_call', result: 'API call completed' }; } /** * Request clarification from user */ requestClarification(action) { const suggestions = this.generateSuggestions(action.parameters?.userInput || ''); return { success: false, needsClarification: true, message: "I'm not sure exactly what you want to do. Here are some suggestions:", suggestions, originalInput: action.parameters?.userInput }; } /** * Generate helpful suggestions based on input */ generateSuggestions(input) { const suggestions = [ { text: "Format my JavaScript code", action: { tool: 'codeConverter', operation: 'format', format: 'javascript' } }, { text: "Backup my project files", action: { tool: 'arcManager', operation: 'backup' } }, { text: "Find duplicate files", action: { tool: 'arcManager', operation: 'duplicates' } }, { text: "Generate a logo image", action: { tool: 'imageGenerator', prompt: 'professional logo' } }, { text: "Calculate service pricing", action: { tool: 'pricingCalculator' } } ]; // Filter suggestions based on input similarity return suggestions.filter(suggestion => { const similarity = this.calculateSimilarity(input, suggestion.text); return similarity > 0.2; }); } /** * Simple similarity calculation */ calculateSimilarity(str1, str2) { const tokens1 = this.tokenize(str1); const tokens2 = this.tokenize(str2); const commonTokens = tokens1.filter(token => tokens2.includes(token)); return commonTokens.length / Math.max(tokens1.length, tokens2.length, 1); } /** * Extract service names from command */ extractServices(tokens) { const services = ['leads', 'storage', 'backup', 'ai', 'automation', 'support']; return tokens.filter(token => services.includes(token)); } /** * Get display name for tool */ getToolDisplayName(tool) { const displayNames = { codeConverter: 'Code Converter Pro', arcManager: 'ARC File Manager', legendaryLeads: 'Legendary Leads', imageGenerator: 'AI Image Generator', pricingCalculator: 'Pricing Calculator', documentGenerator: 'Document Generator' }; return displayNames[tool] || tool; } /** * Simple word stemming */ stemWord(word) { // Basic stemming rules const rules = [ [/ing$/, ''], [/ed$/, ''], [/s$/, ''], [/er$/, ''], [/est$/, ''] ]; for (const [pattern, replacement] of rules) { if (pattern.test(word) && word.length > 4) { return word.replace(pattern, replacement); } } return word; } /** * Log command for machine learning */ logCommand(input, route, action) { const logEntry = { timestamp: new Date().toISOString(), input, route, action, userId: this.getUserId() }; this.contextHistory.push(logEntry); // Keep only recent history if (this.contextHistory.length > 50) { this.contextHistory = this.contextHistory.slice(-25); } // Save to localStorage for persistence this.saveCommandHistory(); } /** * Load user preferences */ loadUserPreferences() { try { const prefs = localStorage.getItem('glytch_user_preferences'); return prefs ? JSON.parse(prefs) : { preferredTools: [], confidenceThreshold: 0.3, autoExecute: true }; } catch (error) { return { preferredTools: [], confidenceThreshold: 0.3, autoExecute: true }; } } /** * Save command history for learning */ saveCommandHistory() { try { localStorage.setItem('glytch_command_history', JSON.stringify(this.contextHistory)); } catch (error) { console.warn('Could not save command history:', error); } } /** * Get or generate user ID */ getUserId() { let userId = localStorage.getItem('cc_user_id'); if (!userId) { userId = 'cc_user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9); localStorage.setItem('cc_user_id', userId); } return userId; } /** * Get suggestion for unrecognized commands */ getSuggestion(input) { const commonMistakes = { 'code': 'Try: "format my JavaScript code" or "minify this CSS"', 'file': 'Try: "backup my files" or "find duplicates"', 'image': 'Try: "generate a logo" or "create a banner image"', 'price': 'Try: "calculate pricing for 10 users" or "show me pricing options"' }; for (const [keyword, suggestion] of Object.entries(commonMistakes)) { if (input.toLowerCase().includes(keyword)) { return suggestion; } } return 'Try being more specific about what you want to do, like "format my code" or "backup my files"'; } /** * Initialize router with event listeners */ initializeRouter() { // Listen for GLYTCH commands if (typeof window !== 'undefined') { window.addEventListener('message', (event) => { if (event.data.type === 'GLYTCH_COMMAND') { this.processCommand(event.data.command, event.data.context); } }); } console.log('GLYTCH AI Tool Router initialized successfully'); } } // Usage Examples and Integration const glytchRouter = new GLYTCHToolRouter(); /** * Example GLYTCH AI Integration Commands */ const exampleCommands = { // Code Converter Examples codeFormatting: [ "Format my JavaScript code", "Beautify this CSS file", "Clean up my HTML", "Organize this JSON data" ], codeOptimization: [ "Minify my JavaScript", "Compress this CSS", "Optimize my code for production", "Make this file smaller" ], codeConversion: [ "Convert JSON to XML", "Transform this YAML to JSON", "Change XML to CSV", "Convert this data format" ], codeValidation: [ "Check my code for errors", "Validate this JSON", "Scan for security issues", "Test my JavaScript syntax" ], // ARC File Manager Examples fileManagement: [ "Backup my project files", "Sync all my cloud storage", "Find duplicate files", "Organize my documents" ], cloudOperations: [ "Upload to Google Drive", "Sync with Dropbox", "Backup to all clouds", "Restore from yesterday" ], // Other Tools imageGeneration: [ "Generate a logo for my company", "Create a banner image", "Make a professional headshot", "Design a social media post" ], businessTools: [ "Calculate pricing for 50 users", "Create an invoice template", "Find leads in tech industry", "Generate a proposal document" ] }; /** * Integration with Cloud Connect Dashboard */ function integrateWithDashboard() { // Add GLYTCH command interface to dashboard const glytchInterface = `
`; // Process commands from dashboard window.processGLYTCHCommand = async function() { const input = document.getElementById('glytch-input').value; const result = await glytchRouter.processCommand(input); if (result.success) { console.log('GLYTCH executed successfully:', result); } else if (result.needsClarification) { showClarificationDialog(result); } else { console.error('GLYTCH error:', result.error); } }; } /** * Export for Cloud Connect integration */ if (typeof module !== 'undefined' && module.exports) { module.exports = { GLYTCHToolRouter, exampleCommands }; } else if (typeof window !== 'undefined') { window.GLYTCHToolRouter = GLYTCHToolRouter; window.glytchRouter = glytchRouter; }