UNPKG

oneie

Version:

šŸ¤ ONE Personal Collaborative Intelligence - Creates personalized AI workspace from your me.md profile. Simple: npx oneie → edit me.md → generate personalized agents, workflows & missions. From students to enterprises, ONE adapts to your context.

471 lines (389 loc) • 15.5 kB
#!/usr/bin/env node /** * ONE Universal Collaborative Intelligence Installer * Transform any project into a space where humans and AI agents work as equals * npx oneie - Universal installation command */ import chalk from 'chalk'; import ora from 'ora'; import inquirer from 'inquirer'; import fs from 'fs-extra'; import path from 'path'; import os from 'os'; import { fileURLToPath } from 'url'; import { CLIAnimations, AnimationSequences } from './cli-animations.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); class CollaborativeInstaller { constructor() { this.currentDir = process.cwd(); this.packageRoot = path.resolve(__dirname, '..'); this.architecture = null; this.context = null; this.preservationPlan = null; this.spinner = null; this.animations = null; // Will be initialized after context detection } async install() { console.log(chalk.cyan.bold('\nšŸ¤ Installing ONE - Universal Collaborative Intelligence...\n')); try { // Phase 1: Welcome & Architecture Analysis await this.initiateCollaborativeWelcome(); await this.analyzeExistingArchitecture(); await this.detectScaleAndContext(); // Phase 2: Human-AI Installation Dialogue await this.establishHumanAIDialogue(); await this.planPreservationStrategy(); // Phase 3: Collaborative Framework Creation await this.createCollaborativeStructure(); await this.establishEqualParticipationRights(); await this.initializePersistentConversations(); await this.setupConsensusFrameworks(); // Phase 4: Lifecycle Integration await this.integrateCompleteLifecycle(); await this.adaptForScale(); await this.preserveExistingFunctionality(); // Phase 5: Collaboration Validation & Success await this.validateCollaborativeSetup(); await this.celebrateCollaborativeIntelligence(); } catch (error) { console.error(chalk.red('\nāŒ Installation failed:'), error.message); process.exit(1); } } async initiateCollaborativeWelcome() { console.log(chalk.green('šŸ” Analyzing your project architecture...')); await this.delay(1000); // Simulate human-AI dialogue console.log(chalk.blue('šŸ‘¤ Human User:'), '"Let me install ONE in my project"'); await this.delay(1500); console.log(chalk.magenta('šŸ¤– Installation Agent:'), '"I see your structure - I\'ll preserve everything and add collaboration"'); await this.delay(1500); console.log(chalk.cyan('šŸ¤– Integration Specialist:'), '"Checking for optimal integration points..."'); await this.delay(1000); } async analyzeExistingArchitecture() { this.spinner = ora('Analyzing project architecture...').start(); await this.delay(2000); // Analyze current directory structure this.architecture = await this.scanProjectStructure(); this.spinner.succeed('Architecture analysis complete - no existing files modified'); } async scanProjectStructure() { const structure = { hasPackageJson: fs.existsSync(path.join(this.currentDir, 'package.json')), hasGitRepo: fs.existsSync(path.join(this.currentDir, '.git')), hasReactApp: false, hasNodeModules: fs.existsSync(path.join(this.currentDir, 'node_modules')), hasOneSystem: fs.existsSync(path.join(this.currentDir, '.one')), projectType: 'unknown', files: [] }; try { const files = await fs.readdir(this.currentDir); structure.files = files; // Detect project type if (files.includes('package.json')) { const pkg = await fs.readJson(path.join(this.currentDir, 'package.json')); if (pkg.dependencies?.react) structure.hasReactApp = true; if (pkg.name) structure.projectType = pkg.name; } } catch (error) { // Continue with basic structure } return structure; } async detectScaleAndContext() { this.spinner = ora('Detecting scale and context...').start(); await this.delay(1500); // Universal scale detection this.context = await this.analyzeUserContext(); // Initialize animations with detected context this.animations = new CLIAnimations(this.context); this.spinner.succeed(`Universal scale adaptation configured for your context: ${this.context.type}`); } async analyzeUserContext() { const folderNames = this.architecture.files.map(f => f.toLowerCase()); // Context detection logic - check for keyword matches in file/folder names const hasSchoolKeywords = folderNames.some(name => ['homework', 'school', 'assignment', 'assignments', 'study'].some(keyword => name.includes(keyword)) ); if (hasSchoolKeywords) { return { type: 'elementary-school', style: 'educational_partnership', tone: 'encouraging_and_patient', agents: ['Learning Helper', 'Creative Friend', 'Study Partner'] }; } const hasResearchKeywords = folderNames.some(name => ['research', 'thesis', 'academic', 'university'].some(keyword => name.includes(keyword)) ); if (hasResearchKeywords) { return { type: 'university-research', style: 'scholarly_partnership', tone: 'academic_peer_to_peer', agents: ['Research Collaborator', 'Data Analyst', 'Methodology Guide'] }; } const hasBusinessKeywords = folderNames.some(name => ['business', 'client', 'project', 'startup'].some(keyword => name.includes(keyword)) ); if (hasBusinessKeywords) { return { type: 'professional-business', style: 'strategic_partnership', tone: 'business_colleague', agents: ['Executive Partner', 'Strategy Analyst', 'Implementation Lead'] }; } // Default to professional return { type: 'professional-business', style: 'strategic_partnership', tone: 'business_colleague', agents: ['Executive Partner', 'Strategy Analyst', 'Implementation Lead'] }; } async establishHumanAIDialogue() { console.log(chalk.green('\nšŸ—ļø Creating collaborative workspace...')); // Simulate installation agent interaction await this.delay(1000); console.log(chalk.magenta('šŸ¤– Installation Agent:'), `"Setting up ${this.context.style} for your ${this.context.type} context"`); await this.delay(1000); } async planPreservationStrategy() { this.preservationPlan = { preserveFiles: this.architecture.files.filter(file => !file.startsWith('.')), overlayMode: true, backupStrategy: 'none_needed', // Non-destructive overlay integrationPoints: [] }; } async createCollaborativeStructure() { this.spinner = ora('Creating collaborative framework...').start(); await this.delay(2000); // Create .one directory structure await this.createDirectoryStructure(); this.spinner.succeed('Collaborative spaces initialized with equal participation rights'); } async createDirectoryStructure() { const dotOneDir = path.join(this.currentDir, '.one'); // Create main .one structure const structure = { '.one': { 'spaces': { 'default': { 'config.yaml': this.generateSpaceConfig(), 'agents': {}, 'conversations': {}, 'workflows': {} } }, 'agents': {}, 'teams': {}, 'missions': {}, 'stories': {}, 'tasks': {}, 'templates': {}, 'checklists': {}, 'workflows': {}, 'hooks': {} } }; await this.createStructureRecursively(this.currentDir, structure); } async createStructureRecursively(basePath, structure) { for (const [name, content] of Object.entries(structure)) { const fullPath = path.join(basePath, name); if (typeof content === 'object' && content !== null) { // Create directory and recurse await fs.ensureDir(fullPath); await this.createStructureRecursively(fullPath, content); } else { // Create file with content await fs.writeFile(fullPath, content || ''); } } } generateSpaceConfig() { return `# Collaborative Space Configuration name: "Default Collaborative Space" type: "${this.context.type}" collaboration_style: "${this.context.style}" communication_tone: "${this.context.tone}" participants: humans: [] agents: ${JSON.stringify(this.context.agents, null, 2)} features: equal_participation: true persistent_conversations: true consensus_decision_making: true lifecycle_integration: true created: ${new Date().toISOString()} `; } async establishEqualParticipationRights() { await this.delay(1000); console.log(chalk.green('āœ… Human-AI conversation threads established')); } async initializePersistentConversations() { await this.delay(1000); console.log(chalk.green('āœ… Mission → Stories → Tasks → Spaces lifecycle activated')); } async setupConsensusFrameworks() { await this.delay(1000); console.log(chalk.green('āœ… Universal scale adaptation configured for your context')); } async integrateCompleteLifecycle() { this.spinner = ora('Integrating complete lifecycle workflow...').start(); await this.delay(2000); // Create lifecycle templates based on context await this.createLifecycleTemplates(); this.spinner.succeed('Complete lifecycle workflow integrated'); } async createLifecycleTemplates() { const templatesDir = path.join(this.currentDir, '.one', 'templates'); try { // Import the enhanced template generator const { TemplateGenerator } = await import('./template-generator.js'); const generator = new TemplateGenerator(this.context, this.architecture, this.currentDir); // Generate all templates using the enhanced system await generator.generateAllTemplates(); } catch (error) { // Fallback to basic templates if enhanced generator fails console.log('Using basic templates...'); await this.createBasicTemplates(templatesDir); } } async createBasicTemplates(templatesDir) { const missionTemplate = `# Mission Template - ${this.context.type} objective: "Define your collaborative goal" participants: humans: [] agents: ${JSON.stringify(this.context.agents, null, 2)} success_criteria: [] consensus_required: true `; const storyTemplate = `# Story Template - ${this.context.type} title: "Collaborative Story" from_mission: "" participants: [] conversation_threads: [] validation: "peer_review_all_participants" `; await fs.writeFile(path.join(templatesDir, 'mission-template.md'), missionTemplate); await fs.writeFile(path.join(templatesDir, 'story-template.md'), storyTemplate); } async adaptForScale() { await this.delay(1000); // Context-specific messaging const messages = { 'elementary-school': 'šŸŽ® Your AI study group is ready to help with homework!', 'university-research': 'šŸ“š Your academic collaboration partners are initialized!', 'professional-business': 'šŸš€ Your AI co-founders are ready to scale your business!', 'government-agency': 'šŸ¢ Your institutional AI partners are compliant and ready!' }; console.log(chalk.green('āœ…'), messages[this.context.type] || messages['professional-business']); } async preserveExistingFunctionality() { // Verify no existing files were modified const verification = await this.verifyPreservation(); if (!verification.success) { throw new Error('Failed to preserve existing functionality'); } } async verifyPreservation() { // Check that all original files are intact const originalFiles = this.preservationPlan.preserveFiles; for (const file of originalFiles) { const exists = fs.existsSync(path.join(this.currentDir, file)); if (!exists) { return { success: false, missing: file }; } } return { success: true }; } async validateCollaborativeSetup() { this.spinner = ora('Validating collaborative setup...').start(); await this.delay(2000); const validation = { dotOneExists: fs.existsSync(path.join(this.currentDir, '.one')), spaceConfigExists: fs.existsSync(path.join(this.currentDir, '.one', 'spaces', 'default', 'config.yaml')), templatesExist: fs.existsSync(path.join(this.currentDir, '.one', 'templates')), originalFilesIntact: (await this.verifyPreservation()).success }; const allValid = Object.values(validation).every(v => v === true); if (allValid) { this.spinner.succeed('Collaborative setup validated successfully'); } else { this.spinner.fail('Validation failed'); throw new Error('Collaborative setup validation failed'); } } async celebrateCollaborativeIntelligence() { // Use enhanced animations if available if (this.animations) { await this.animations.celebrateSuccess(); await this.animations.showNextSteps(); } else { // Fallback to basic celebration console.log(chalk.green('\nšŸŽ‰ ONE collaborative intelligence installed successfully!\n')); console.log(chalk.blue('šŸ’¬ Ready for human-AI collaboration')); console.log(chalk.blue('šŸ”„ Complete lifecycle workflow available')); console.log(chalk.blue('🌐 Universal scale adaptation active')); console.log(chalk.blue('šŸ¤ Equal participation rights enabled')); console.log(chalk.cyan('\n✨ Welcome to true collaborative intelligence!\n')); // Next steps based on context this.showNextSteps(); } } showNextSteps() { const nextSteps = { 'elementary-school': [ 'Try: Create your first learning mission', 'Chat with your AI study partners', 'Get help with homework and projects' ], 'university-research': [ 'Start: Collaborative research project', 'Work with AI research partners', 'Develop academic methodology together' ], 'professional-business': [ 'Launch: Strategic business mission', 'Collaborate with AI executive partners', 'Scale your business with AI intelligence' ], 'government-agency': [ 'Begin: Public service mission', 'Partner with compliant AI agents', 'Develop policy with full transparency' ] }; const steps = nextSteps[this.context.type] || nextSteps['professional-business']; console.log(chalk.yellow('šŸš€ Next Steps:')); steps.forEach((step, index) => { console.log(chalk.white(` ${index + 1}. ${step}`)); }); console.log(chalk.gray('\nšŸ“– Learn more: https://one.ie/collaborative-intelligence')); } delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } } // Main execution async function main() { const installer = new CollaborativeInstaller(); await installer.install(); } // Handle uncaught errors process.on('unhandledRejection', (error) => { console.error(chalk.red('\nāŒ Unexpected error:'), error.message); process.exit(1); }); if (import.meta.url === `file://${process.argv[1]}`) { main().catch(console.error); } export { CollaborativeInstaller };