UNPKG

me-engine-one

Version:

The magic file system that regenerates entire AI universes from me.md

776 lines (647 loc) • 22.6 kB
import fs from 'fs-extra'; import path from 'path'; import chalk from 'chalk'; import Mustache from 'mustache'; import { meParser } from './me-parser.js'; /** * The magic regeneration engine that transforms entire AI universes * from a single me.md file - parallel processing for speed */ export class RegenerationEngine { constructor(options = {}) { this.rootPath = options.rootPath || process.cwd(); this.templatesPath = options.templatesPath || path.join(this.rootPath, 'templates'); this.outputPath = options.outputPath || this.rootPath; this.logger = options.logger || console; this.cache = new Map(); } /** * Main regeneration method - orchestrates complete universe update * @param {string} meFilePath - Path to me.md file * @returns {Object} Regeneration results */ async regenerateFromMe(meFilePath) { try { this.logger.log(chalk.cyan('🌟 Starting universe regeneration...')); const startTime = Date.now(); // Parse the magical me.md file const config = await meParser.parseMeFile(meFilePath); this.logger.log(chalk.green('āœ… Me.md parsed successfully')); // Parallel regeneration for maximum speed const results = await Promise.allSettled([ this.regenerateThemes(config.brand), this.regenerateAgents(config.top_agents, config.brand?.voice), this.regenerateSpaces(config.spaces, config.brand), this.regenerateMissions(config.goals, config.customers), this.regenerateWebsite(config), this.regenerateWorkflows(config), this.regenerateContent(config), this.regenerateAssets(config.brand) ]); // Process results and handle any failures const successful = results.filter(r => r.status === 'fulfilled').length; const failed = results.filter(r => r.status === 'rejected'); if (failed.length > 0) { this.logger.warn(chalk.yellow(`āš ļø ${failed.length} regeneration tasks failed:`)); failed.forEach((result, index) => { this.logger.error(chalk.red(` ${index + 1}. ${result.reason.message}`)); }); } const duration = Date.now() - startTime; this.logger.log(chalk.green(`✨ Universe regenerated! ${successful}/8 systems updated in ${duration}ms`)); return { success: true, duration, successful, failed: failed.length, config, timestamp: new Date().toISOString() }; } catch (error) { this.logger.error(chalk.red(`šŸ’„ Regeneration failed: ${error.message}`)); throw new RegenerationError('Universe regeneration failed', error); } } /** * Regenerate visual themes and styling * @param {Object} brand - Brand configuration */ async regenerateThemes(brand) { this.logger.log(chalk.blue('šŸŽØ Regenerating themes...')); const themeConfig = { name: brand.theme || 'professional', colors: brand.colors || ['#2563EB', '#64748B', '#FFFFFF'], font: brand.font || 'Inter', cursor: brand.cursor || 'default', animations: brand.animations || 'subtle' }; // Generate CSS variables const cssVars = this.generateCSSVariables(themeConfig); await this.writeFile('assets/themes/current.css', cssVars); // Update UI components with theme await this.updateComponentStyles(themeConfig); // Handle background assets if (brand.background) { await this.handleBackgroundAsset(brand.background); } // Handle music/audio themes if (brand.music) { await this.handleMusicAssets(brand.music); } this.logger.log(chalk.green('āœ… Themes regenerated')); } /** * Regenerate AI agent personalities and configurations * @param {Array} topAgents - Top 8 agent configurations * @param {string} voice - Overall voice/personality */ async regenerateAgents(topAgents, voice) { this.logger.log(chalk.blue('šŸ¤– Regenerating AI agents...')); for (const agent of topAgents || []) { // Generate agent configuration file const agentConfig = { name: agent.name, role: agent.role, personality: agent.personality || voice || 'Professional and helpful', catchphrase: agent.catchphrase || 'Ready to help!', base: agent.base || 'personal-assistant', slot: agent.slot, avatar: agent.avatar, voice_settings: { tone: this.extractTone(agent.personality), style: this.extractStyle(agent.personality), expertise: this.extractExpertise(agent.role) } }; // Write agent configuration const agentPath = `agents/${agent.name.toLowerCase()}.yaml`; await this.writeYAMLFile(agentPath, agentConfig); // Generate agent prompt template const promptTemplate = await this.generateAgentPrompt(agentConfig); await this.writeFile(`agents/prompts/${agent.name.toLowerCase()}.md`, promptTemplate); } this.logger.log(chalk.green('āœ… AI agents regenerated')); } /** * Regenerate spaces (AI universes/environments) * @param {Array} spaces - Space configurations * @param {Object} brand - Brand settings for styling */ async regenerateSpaces(spaces, brand) { this.logger.log(chalk.blue('🌌 Regenerating spaces...')); for (const space of spaces || []) { const spaceConfig = { id: space.id, title: space.title, vibe: space.vibe || 'Professional workspace', public: space.public || false, features: space.features || ['agents', 'missions'], branding: { colors: brand?.colors, theme: brand?.theme, font: brand?.font }, layout: this.generateSpaceLayout(space) }; // Generate space configuration await this.writeYAMLFile(`spaces/${space.id}.yaml`, spaceConfig); // Generate space HTML template const spaceHTML = await this.generateSpaceHTML(spaceConfig); await this.writeFile(`spaces/templates/${space.id}.html`, spaceHTML); } this.logger.log(chalk.green('āœ… Spaces regenerated')); } /** * Regenerate missions from goals * @param {Array} goals - User goals/objectives * @param {Object} customers - Customer information for context */ async regenerateMissions(goals, customers) { this.logger.log(chalk.blue('šŸŽÆ Regenerating missions...')); for (let i = 0; i < goals.length; i++) { const goal = goals[i]; const missionConfig = { id: `auto-mission-${i + 1}`, title: goal, objective: this.expandGoalToObjective(goal, customers), target_audience: customers?.primary || 'General users', success_metrics: this.generateSuccessMetrics(goal), stories: this.generateStoriesFromGoal(goal), timeline: this.estimateTimeline(goal), priority: i === 0 ? 'high' : 'medium' }; await this.writeYAMLFile(`missions/auto-mission-${i + 1}.yaml`, missionConfig); } this.logger.log(chalk.green('āœ… Missions regenerated')); } /** * Regenerate complete website from configuration * @param {Object} config - Complete me.md configuration */ async regenerateWebsite(config) { this.logger.log(chalk.blue('🌐 Regenerating website...')); const websiteData = { name: config.name || 'My AI Universe', tagline: config.tagline || 'Powered by ONE', story: config.story || 'Building the future with AI', brand: config.brand, agents: config.top_agents, spaces: config.spaces, goals: config.goals, style: config.style, generated: new Date().toISOString() }; // Generate main website files await Promise.all([ this.generateWebsiteHTML(websiteData), this.generateWebsiteCSS(websiteData), this.generateWebsiteJS(websiteData), this.generateWebsiteManifest(websiteData) ]); this.logger.log(chalk.green('āœ… Website regenerated')); } /** * Regenerate workflows and templates * @param {Object} config - Complete me.md configuration */ async regenerateWorkflows(config) { this.logger.log(chalk.blue('⚔ Regenerating workflows...')); // Generate mission workflow template const missionWorkflow = this.generateMissionWorkflow(config); await this.writeYAMLFile('workflows/mission-template.yaml', missionWorkflow); // Generate story workflow template const storyWorkflow = this.generateStoryWorkflow(config); await this.writeYAMLFile('workflows/story-template.yaml', storyWorkflow); // Generate agent coordination workflow const agentWorkflow = this.generateAgentWorkflow(config.top_agents); await this.writeYAMLFile('workflows/agent-coordination.yaml', agentWorkflow); this.logger.log(chalk.green('āœ… Workflows regenerated')); } /** * Regenerate content templates and examples * @param {Object} config - Complete me.md configuration */ async regenerateContent(config) { this.logger.log(chalk.blue('šŸ“ Regenerating content...')); // Generate personalized content templates const templates = { email: this.generateEmailTemplate(config), social: this.generateSocialTemplate(config), blog: this.generateBlogTemplate(config), mission: this.generateMissionTemplate(config) }; for (const [type, template] of Object.entries(templates)) { await this.writeFile(`content/templates/${type}.md`, template); } this.logger.log(chalk.green('āœ… Content regenerated')); } /** * Handle asset copying and optimization * @param {Object} brand - Brand configuration with asset paths */ async regenerateAssets(brand) { this.logger.log(chalk.blue('šŸ–¼ļø Regenerating assets...')); const assets = [ { src: brand?.logo, dest: 'assets/images/logo.png' }, { src: brand?.avatar, dest: 'assets/images/avatar.png' }, { src: brand?.background, dest: 'assets/images/background.png' }, { src: brand?.music?.theme_song, dest: 'assets/audio/theme.mp3' } ].filter(asset => asset.src); for (const asset of assets) { try { if (await fs.pathExists(asset.src)) { await fs.copy(asset.src, path.join(this.outputPath, asset.dest)); } } catch (error) { this.logger.warn(chalk.yellow(`āš ļø Asset not found: ${asset.src}`)); } } this.logger.log(chalk.green('āœ… Assets regenerated')); } // Helper methods for generation generateCSSVariables(theme) { return ` :root { --primary-color: ${theme.colors[0]}; --secondary-color: ${theme.colors[1]}; --background-color: ${theme.colors[2]}; --font-family: '${theme.font}', system-ui; --cursor: ${theme.cursor}; --animation-speed: ${theme.animations === 'full' ? '0.3s' : '0.1s'}; } body { font-family: var(--font-family); background-color: var(--background-color); color: var(--primary-color); cursor: var(--cursor); } .theme-${theme.name.toLowerCase()} { --theme-primary: ${theme.colors[0]}; --theme-secondary: ${theme.colors[1]}; --theme-background: ${theme.colors[2]}; } `; } async generateAgentPrompt(agent) { const template = `# ${agent.name} - ${agent.role} ## Personality ${agent.personality} ## Catchphrase "${agent.catchphrase}" ## Voice Settings - Tone: ${agent.voice_settings.tone} - Style: ${agent.voice_settings.style} - Expertise: ${agent.voice_settings.expertise} ## System Prompt You are ${agent.name}, ${agent.role}. ${agent.personality} Your catchphrase is "${agent.catchphrase}" - use it when appropriate. Always maintain your personality while being helpful and professional. `; return template; } generateSpaceLayout(space) { return { header: space.features?.includes('visiting') || false, sidebar: space.features?.includes('guestbook') || false, footer: space.features?.includes('template_store') || false, widgets: space.features || [] }; } async generateSpaceHTML(space) { return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>${space.title}</title> <link rel="stylesheet" href="/assets/themes/current.css"> </head> <body class="space-${space.id}"> <header class="space-header"> <h1>${space.title}</h1> <p class="space-vibe">${space.vibe}</p> </header> <main class="space-content"> <div class="agents-section"> <h2>My AI Team</h2> <div class="agents-grid" id="agents-grid"></div> </div> <div class="missions-section"> <h2>Active Missions</h2> <div class="missions-list" id="missions-list"></div> </div> </main> <script src="/assets/js/space.js"></script> </body> </html>`; } async generateWebsiteHTML(data) { const html = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>${data.name}</title> <meta name="description" content="${data.tagline}"> <link rel="stylesheet" href="assets/css/main.css"> </head> <body> <header class="hero"> <h1>${data.name}</h1> <p class="tagline">${data.tagline}</p> <div class="story">${data.story}</div> </header> <section class="agents"> <h2>Meet My AI Team</h2> <div class="agents-grid"> ${(data.agents || []).map(agent => ` <div class="agent-card" data-slot="${agent.slot}"> <img src="${agent.avatar || '/assets/images/default-avatar.png'}" alt="${agent.name}"> <h3>${agent.name}</h3> <p class="role">${agent.role}</p> <blockquote>"${agent.catchphrase}"</blockquote> </div> `).join('')} </div> </section> <footer> <p>Generated by ONE • ${data.generated}</p> </footer> <script src="assets/js/main.js"></script> </body> </html>`; await this.writeFile('website/index.html', html); } async generateWebsiteCSS(data) { const css = ` /* Generated CSS for ${data.name} */ ${this.generateCSSVariables(data.brand || {})} .hero { text-align: center; padding: 4rem 2rem; background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); color: white; } .agents-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 2rem; padding: 2rem; } .agent-card { background: white; border-radius: 1rem; padding: 1.5rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); text-align: center; } .agent-card img { width: 64px; height: 64px; border-radius: 50%; margin-bottom: 1rem; } `; await this.writeFile('website/assets/css/main.css', css); } async generateWebsiteJS(data) { const js = ` // Generated JavaScript for ${data.name} class AIUniverse { constructor() { this.agents = ${JSON.stringify(data.agents || [])}; this.init(); } init() { this.setupAgentInteractions(); this.setupThemeToggle(); this.setupAnimations(); } setupAgentInteractions() { document.querySelectorAll('.agent-card').forEach(card => { card.addEventListener('click', (e) => { const slot = e.currentTarget.dataset.slot; this.activateAgent(slot); }); }); } activateAgent(slot) { const agent = this.agents.find(a => a.slot == slot); if (agent) { console.log(\`Activating \${agent.name}: \${agent.catchphrase}\`); // TODO: Integrate with AI agent system } } setupThemeToggle() { // TODO: Dynamic theme switching } setupAnimations() { // TODO: Add ${data.brand?.animations || 'subtle'} animations } } // Initialize when DOM is ready document.addEventListener('DOMContentLoaded', () => { new AIUniverse(); }); `; await this.writeFile('website/assets/js/main.js', js); } async generateWebsiteManifest(data) { const manifest = { name: data.name, short_name: data.name.split(' ')[0], description: data.tagline, theme_color: data.brand?.colors?.[0] || '#2563EB', background_color: data.brand?.colors?.[2] || '#FFFFFF', display: 'standalone', icons: [ { src: 'assets/images/logo.png', sizes: '192x192', type: 'image/png' } ] }; await this.writeFile('website/manifest.json', JSON.stringify(manifest, null, 2)); } // Utility methods extractTone(personality) { const tones = { 'professional': 'professional', 'creative': 'creative', 'friendly': 'warm', 'rebel': 'edgy', 'encouraging': 'supportive' }; for (const [key, tone] of Object.entries(tones)) { if (personality?.toLowerCase().includes(key)) { return tone; } } return 'professional'; } extractStyle(personality) { if (personality?.toLowerCase().includes('unhinged')) return 'bold'; if (personality?.toLowerCase().includes('strategic')) return 'analytical'; if (personality?.toLowerCase().includes('encouraging')) return 'supportive'; return 'balanced'; } extractExpertise(role) { const expertise = { 'assistant': 'general productivity', 'creative': 'creative content', 'coordinator': 'project management', 'genius': 'strategic thinking' }; for (const [key, exp] of Object.entries(expertise)) { if (role?.toLowerCase().includes(key)) { return exp; } } return 'general assistance'; } expandGoalToObjective(goal, customers) { return `Achieve "${goal}" by serving ${customers?.primary || 'our target audience'} through strategic AI-powered initiatives`; } generateSuccessMetrics(goal) { return [ 'User engagement increase', 'Goal completion rate', 'User satisfaction score', 'System performance metrics' ]; } generateStoriesFromGoal(goal) { return [ `Story: Plan ${goal}`, `Story: Execute ${goal}`, `Story: Measure ${goal} success` ]; } estimateTimeline(goal) { // Simple heuristic based on goal complexity const words = goal.split(' ').length; return words > 5 ? '4-6 weeks' : '2-3 weeks'; } generateMissionWorkflow(config) { return { name: 'Custom Mission Workflow', trigger: 'user_goal', steps: [ { action: 'analyze_goal', agent: 'mission-commander' }, { action: 'create_stories', agent: 'story-teller' }, { action: 'assign_tasks', agent: 'task-master' }, { action: 'execute_with_agents', agents: config.top_agents?.slice(0, 3) } ] }; } generateStoryWorkflow(config) { return { name: 'Custom Story Workflow', voice: config.brand?.voice || 'professional', steps: [ 'story_creation', 'agent_assignment', 'execution', 'validation' ] }; } generateAgentWorkflow(agents) { return { name: 'Agent Coordination Workflow', agents: agents?.map(a => ({ name: a.name, role: a.role, slot: a.slot })) || [], coordination: 'parallel_with_handoffs' }; } generateEmailTemplate(config) { return `# Email Template for ${config.name || 'Your Business'} Subject: ${config.tagline || 'Powered by AI'} Hi there! ${config.story || 'We\'re building something amazing with AI.'} Best regards, The ${config.name || 'AI'} Team --- Powered by ONE • Your AI Universe `; } generateSocialTemplate(config) { return `# Social Media Template šŸš€ ${config.tagline || 'Building the future with AI'} ${config.story || 'Every day we\'re pushing the boundaries of what\'s possible.'} #AI #Innovation #Future --- Generated by ${config.name || 'ONE'} `; } generateBlogTemplate(config) { return `# Blog Post Template ## ${config.goals?.[0] || 'Our Mission'} ${config.story || 'We believe AI should amplify human potential.'} ### Our Approach ${config.brand?.voice || 'We combine innovation with practical solutions.'} ### The Team ${(config.top_agents || []).map(a => `- **${a.name}**: ${a.role}`).join('\n')} --- Published by ${config.name || 'ONE Team'} `; } generateMissionTemplate(config) { return `# Mission Template ## Objective Achieve one of our core goals: ${config.goals?.[0] || 'Drive success'} ## Target Audience ${config.customers?.primary || 'Our community'} ## Success Metrics - User engagement - Goal completion - Satisfaction scores ## Assigned Agents ${(config.top_agents || []).slice(0, 3).map(a => `- ${a.name} (${a.role})`).join('\n')} `; } // File operations async writeFile(relativePath, content) { const fullPath = path.join(this.outputPath, relativePath); await fs.ensureDir(path.dirname(fullPath)); await fs.writeFile(fullPath, content, 'utf8'); } async writeYAMLFile(relativePath, data) { const { stringify } = await import('yaml'); const content = stringify(data); await this.writeFile(relativePath, content); } async handleBackgroundAsset(backgroundPath) { // Copy background asset to assets directory if (await fs.pathExists(backgroundPath)) { const ext = path.extname(backgroundPath); await fs.copy(backgroundPath, path.join(this.outputPath, `assets/images/background${ext}`)); } } async handleMusicAssets(music) { if (music?.theme_song && await fs.pathExists(music.theme_song)) { const ext = path.extname(music.theme_song); await fs.copy(music.theme_song, path.join(this.outputPath, `assets/audio/theme${ext}`)); } } async updateComponentStyles(theme) { // Generate component-specific styles const componentCSS = ` /* Component styles for ${theme.name} theme */ .component { --theme-primary: ${theme.colors[0]}; --theme-secondary: ${theme.colors[1]}; --theme-background: ${theme.colors[2]}; } `; await this.writeFile('assets/css/components.css', componentCSS); } } /** * Custom regeneration error class */ export class RegenerationError extends Error { constructor(message, originalError = null) { super(message); this.name = 'RegenerationError'; this.originalError = originalError; } } // Export singleton instance export const regenerationEngine = new RegenerationEngine();