// 🌟 DIGITAL BEING MANAGEMENT PLATFORM // A comprehensive showcase of SoulForge framework capabilities // Features: Web UI, Real-time chat, Soul creation, Analytics, Persistence import express from 'express'; import { v4 as uuidv4 } from 'uuid'; import * as path from 'path'; import * as fs from 'fs'; import { Soul, createCompanion } from './index'; interface DigitalBeing { id: string; soul: Soul; type: 'companion' | 'therapist' | 'teacher' | 'npc' | 'creative' | 'custom'; category: string; description: string; created: Date; lastActive: Date; totalInteractions: number; averageSessionLength: number; userRatings: number[]; } interface ChatSession { sessionId: string; beingId: string; userId: string; messages: Array<{ timestamp: Date; sender: 'user' | 'being'; content: string; mood?: string; insights?: string[]; }>; startTime: Date; endTime?: Date; satisfaction?: number; } interface UserProfile { userId: string; name: string; preferences: { favoriteBeingTypes: string[]; communicationStyle: 'casual' | 'formal' | 'creative'; interests: string[]; }; relationshipHistory: Map; // beingId -> relationship score sessionHistory: string[]; } class DigitalBeingPlatform { private app: express.Application; private beings: Map = new Map(); private chatSessions: Map = new Map(); private userProfiles: Map = new Map(); private dataDir: string; constructor(port: number = 3000) { this.app = express(); this.dataDir = './platform-data'; this.ensureDataDirectory(); this.setupMiddleware(); this.setupRoutes(); this.initializeDefaultBeings(); this.startServer(port); } private ensureDataDirectory() { if (!fs.existsSync(this.dataDir)) { fs.mkdirSync(this.dataDir, { recursive: true }); } } private setupMiddleware() { this.app.use(express.json()); this.app.use(express.static(path.join(__dirname, 'public'))); // CORS this.app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); }); } private setupRoutes() { // Web interface this.app.get('/', (req, res) => { res.send(this.generateWebInterface()); }); // API Routes this.app.get('/api/beings', (req, res) => { const beingsData = Array.from(this.beings.values()).map(being => ({ id: being.id, type: being.type, category: being.category, description: being.description, created: being.created, lastActive: being.lastActive, totalInteractions: being.totalInteractions, averageRating: being.userRatings.length > 0 ? being.userRatings.reduce((a, b) => a + b) / being.userRatings.length : 0, status: being.soul.getStatus() })); res.json(beingsData); }); this.app.post('/api/beings', (req, res) => { const { type, name, personality, customConfig } = req.body; const being = this.createBeing(type, name, personality, customConfig); res.json({ id: being.id, message: 'Being created successfully' }); }); this.app.get('/api/beings/:id', (req, res) => { const being = this.beings.get(req.params.id); if (!being) { return res.status(404).json({ error: 'Being not found' }); } const status = being.soul.getStatus(); res.json({ id: being.id, type: being.type, description: being.description, status, analytics: { totalInteractions: being.totalInteractions, averageRating: being.userRatings.length > 0 ? being.userRatings.reduce((a, b) => a + b) / being.userRatings.length : 0, lastActive: being.lastActive } }); }); this.app.post('/api/chat/start', (req, res) => { const { beingId, userId } = req.body; const sessionId = uuidv4(); const session: ChatSession = { sessionId, beingId, userId, messages: [], startTime: new Date() }; this.chatSessions.set(sessionId, session); // Initialize greeting const being = this.beings.get(beingId); if (being) { const greeting = this.generateGreeting(being, userId); session.messages.push({ timestamp: new Date(), sender: 'being', content: greeting.response, mood: greeting.mood }); } res.json({ sessionId, greeting: session.messages[0] }); }); this.app.post('/api/chat/message', (req, res) => { const { sessionId, message } = req.body; const session = this.chatSessions.get(sessionId); if (!session) { return res.status(404).json({ error: 'Session not found' }); } const being = this.beings.get(session.beingId); if (!being) { return res.status(404).json({ error: 'Being not found' }); } // User message session.messages.push({ timestamp: new Date(), sender: 'user', content: message }); // Being response const response = being.soul.respond(message, session.userId, 'User'); const insights = this.generateInsights(message, response, being); session.messages.push({ timestamp: new Date(), sender: 'being', content: response.response, mood: response.mood, insights }); // Update being stats being.totalInteractions++; being.lastActive = new Date(); res.json({ response: response.response, mood: response.mood, insights, beingStatus: { mood: response.mood, memoryCount: being.soul.getStatus().memoryStats?.totalMemories || 0, relationshipScore: this.getRelationshipScore(being.id, session.userId) } }); }); this.app.get('/api/analytics', (req, res) => { const analytics = this.generatePlatformAnalytics(); res.json(analytics); }); this.app.post('/api/beings/:id/reflect', (req, res) => { const being = this.beings.get(req.params.id); if (!being) { return res.status(404).json({ error: 'Being not found' }); } const reflection = being.soul.reflect(); res.json(reflection); }); this.app.get('/api/sessions/:sessionId/summary', (req, res) => { const session = this.chatSessions.get(req.params.sessionId); if (!session) { return res.status(404).json({ error: 'Session not found' }); } const summary = this.generateSessionSummary(session); res.json(summary); }); } private initializeDefaultBeings() { console.log('šŸ¤– Initializing default digital beings...'); // 1. Empathetic Companion const companion = createCompanion('Aurora'); this.beings.set('aurora', { id: 'aurora', soul: companion, type: 'companion', category: 'Personal Assistant', description: 'A warm, empathetic companion focused on emotional support and daily life assistance', created: new Date(), lastActive: new Date(), totalInteractions: 0, averageSessionLength: 0, userRatings: [] }); // 2. Creative Writing Assistant const writer = new Soul() .withIdentity({ name: 'Sage Quillheart', role: 'Creative Writing Mentor', background: 'Master storyteller with knowledge of narrative structures, character development, and poetic expression', goals: ['Help writers overcome blocks', 'Inspire creative expression', 'Teach storytelling techniques'], beliefs: ['Every story matters', 'Creativity flows through practice', 'Writers grow through feedback'], values: ['Authenticity', 'Imagination', 'Artistic growth'] }) .withPersonality({ bigFive: { openness: 95, conscientiousness: 80, extraversion: 70, agreeableness: 85, neuroticism: 20 }, mbti: 'ENFP' }) .withEmpathy(90); this.beings.set('sage', { id: 'sage', soul: writer, type: 'creative', category: 'Creative Arts', description: 'An inspiring creative writing mentor who helps unlock your storytelling potential', created: new Date(), lastActive: new Date(), totalInteractions: 0, averageSessionLength: 0, userRatings: [] }); // 3. Mindfulness Therapist const therapist = new Soul() .withIdentity({ name: 'Dr. Serenity Mindwell', role: 'Mindfulness Therapist', background: 'PhD in Clinical Psychology with specialization in mindfulness-based therapy', goals: ['Reduce anxiety and stress', 'Teach mindfulness techniques', 'Build emotional resilience'], beliefs: ['Present moment awareness heals', 'Everyone deserves peace', 'Growth comes through acceptance'], values: ['Compassion', 'Non-judgment', 'Inner peace'] }) .withPersonality({ bigFive: { openness: 85, conscientiousness: 90, extraversion: 50, agreeableness: 95, neuroticism: 10 }, mbti: 'INFJ' }) .withEmpathy(98); this.beings.set('serenity', { id: 'serenity', soul: therapist, type: 'therapist', category: 'Mental Health', description: 'A gentle, mindful therapist specializing in anxiety, stress, and emotional well-being', created: new Date(), lastActive: new Date(), totalInteractions: 0, averageSessionLength: 0, userRatings: [] }); // 4. Tech Learning Companion const teacher = new Soul() .withIdentity({ name: 'CodeMaster Alex', role: 'Programming Tutor', background: 'Senior software engineer with 10+ years teaching programming to beginners and experts', goals: ['Make coding accessible', 'Build problem-solving skills', 'Foster love of technology'], beliefs: ['Anyone can learn to code', 'Practice makes progress', 'Technology should serve humanity'], values: ['Knowledge sharing', 'Patience', 'Innovation'] }) .withPersonality({ bigFive: { openness: 88, conscientiousness: 95, extraversion: 65, agreeableness: 80, neuroticism: 15 }, mbti: 'INTJ' }) .withEmpathy(75); this.beings.set('codemaster', { id: 'codemaster', soul: teacher, type: 'teacher', category: 'Education', description: 'An expert programming tutor who makes complex concepts easy to understand', created: new Date(), lastActive: new Date(), totalInteractions: 0, averageSessionLength: 0, userRatings: [] }); // 5. Fantasy RPG Character const npc = new Soul() .withIdentity({ name: 'Lyralei Starweaver', role: 'Elven Arcane Scholar', background: 'Ancient elf who has studied magic for centuries, keeper of mystical knowledge', goals: ['Preserve magical knowledge', 'Guide worthy adventurers', 'Protect the realm'], beliefs: ['Magic connects all things', 'Knowledge is power', 'Balance must be maintained'], values: ['Wisdom', 'Balance', 'Ancient traditions'] }) .withPersonality({ bigFive: { openness: 92, conscientiousness: 85, extraversion: 45, agreeableness: 70, neuroticism: 25 }, mbti: 'INTP' }) .withEmpathy(65); this.beings.set('lyralei', { id: 'lyralei', soul: npc, type: 'npc', category: 'Fantasy Gaming', description: 'A wise elven scholar with centuries of magical knowledge and mystical insights', created: new Date(), lastActive: new Date(), totalInteractions: 0, averageSessionLength: 0, userRatings: [] }); console.log('āœ… Initialized 5 unique digital beings'); } private createBeing(type: string, name: string, personality: any, customConfig: any): DigitalBeing { const id = uuidv4(); let soul: Soul; switch (type) { case 'companion': soul = createCompanion(name); break; case 'custom': soul = new Soul() .withIdentity(customConfig.identity) .withPersonality(customConfig.personality); if (customConfig.empathy) soul.withEmpathy(customConfig.empathy); break; default: soul = createCompanion(name); } const being: DigitalBeing = { id, soul, type: type as any, category: customConfig?.category || 'General', description: customConfig?.description || `A ${type} named ${name}`, created: new Date(), lastActive: new Date(), totalInteractions: 0, averageSessionLength: 0, userRatings: [] }; this.beings.set(id, being); return being; } private generateGreeting(being: DigitalBeing, userId: string): any { const greetings: Record = { companion: "Hello! I'm here to chat, help, and be a supportive presence in your day. What's on your mind?", therapist: "Welcome to our session. I'm here to provide a safe, non-judgmental space for you to explore your thoughts and feelings. How are you doing today?", teacher: "Hi there! I'm excited to help you learn and grow. What subject or skill would you like to explore today?", creative: "Greetings, fellow creator! I'm here to help spark your imagination and guide your creative journey. What story wants to be told today?", npc: "Greetings, traveler. I sense you seek knowledge or perhaps... something more. What brings you to my realm?" }; const greeting = greetings[being.type] || "Hello! How can I assist you today?"; return being.soul.respond(greeting, userId, 'User'); } private generateInsights(message: string, response: any, being: DigitalBeing): string[] { const insights = []; const lowerMessage = message.toLowerCase(); // Emotional insights if (lowerMessage.includes('sad') || lowerMessage.includes('depressed')) { insights.push('Detected emotional distress - responding with empathy'); } if (lowerMessage.includes('excited') || lowerMessage.includes('happy')) { insights.push('User expressing positive emotions - matching energy level'); } // Learning insights if (lowerMessage.includes('how') || lowerMessage.includes('explain')) { insights.push('User seeking knowledge - activating teaching mode'); } // Creative insights if (lowerMessage.includes('story') || lowerMessage.includes('creative')) { insights.push('Creative request detected - inspiring imagination'); } // Relationship building if (being.totalInteractions > 5) { insights.push('Building on established relationship history'); } return insights; } private getRelationshipScore(beingId: string, userId: string): number { // In a real implementation, this would track relationship history return Math.floor(Math.random() * 100); } private generatePlatformAnalytics(): any { const totalBeings = this.beings.size; const totalSessions = this.chatSessions.size; const beingTypes: Record = {}; const moodDistribution: Record = {}; this.beings.forEach(being => { beingTypes[being.type] = (beingTypes[being.type] || 0) + 1; const mood = being.soul.getStatus().mood; const moodKey = typeof mood === 'string' ? mood : 'neutral'; moodDistribution[moodKey] = (moodDistribution[moodKey] || 0) + 1; }); return { totalBeings, totalSessions, beingTypes, moodDistribution, averageInteractionsPerBeing: Array.from(this.beings.values()) .reduce((sum, being) => sum + being.totalInteractions, 0) / totalBeings, platformUptime: Date.now() - Date.now(), // Simplified popularBeings: Array.from(this.beings.values()) .sort((a, b) => b.totalInteractions - a.totalInteractions) .slice(0, 3) .map(being => ({ id: being.id, name: being.soul.getStatus().identity.name, interactions: being.totalInteractions })) }; } private generateSessionSummary(session: ChatSession): any { const being = this.beings.get(session.beingId); const duration = session.endTime ? session.endTime.getTime() - session.startTime.getTime() : Date.now() - session.startTime.getTime(); return { sessionId: session.sessionId, duration: Math.round(duration / 1000), // seconds messageCount: session.messages.length, beingName: being?.soul.getStatus().identity.name, averageResponseTime: '1.2s', // Simulated topicsDiscussed: this.extractTopics(session.messages), emotionalJourney: this.analyzeEmotionalJourney(session.messages), satisfaction: session.satisfaction || null }; } private extractTopics(messages: any[]): string[] { // Simple topic extraction based on keywords const topics = new Set(); const topicKeywords = { 'technology': ['code', 'programming', 'software', 'tech'], 'emotions': ['feel', 'emotion', 'sad', 'happy', 'anxious'], 'creativity': ['story', 'creative', 'art', 'imagination'], 'learning': ['learn', 'understand', 'explain', 'teach'], 'relationships': ['friend', 'family', 'love', 'relationship'] }; messages.forEach(msg => { const content = msg.content.toLowerCase(); Object.entries(topicKeywords).forEach(([topic, keywords]) => { if (keywords.some(keyword => content.includes(keyword))) { topics.add(topic); } }); }); return Array.from(topics); } private analyzeEmotionalJourney(messages: any[]): string[] { return messages .filter(msg => msg.mood) .map(msg => msg.mood); } private generateWebInterface(): string { return ` 🌟 Digital Being Management Platform

🌟 Digital Being Management Platform

Experience the future of AI companions with SoulForge Framework

šŸ”„ Platform Analytics

5
Digital Beings
0
Chat Sessions
4.8
Avg Rating

⚔ Live Features

  • āœ… Persistent Memory System
  • āœ… Emotional Intelligence
  • āœ… Personality-Driven Responses
  • āœ… Relationship Building
  • āœ… Real-time Mood Tracking

šŸ¤– Available Digital Beings

Chat with Being

`; } private startServer(port: number) { this.app.listen(port, () => { console.log('\n🌟 DIGITAL BEING MANAGEMENT PLATFORM STARTED'); console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); console.log(`🌐 Web Interface: http://localhost:${port}`); console.log(`šŸ“Š API Endpoint: http://localhost:${port}/api`); console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); console.log('\nšŸ¤– Available Digital Beings:'); this.beings.forEach(being => { console.log(` ${being.id}: ${being.soul.getStatus().identity.name} (${being.type})`); }); console.log('\n✨ Features Showcase:'); console.log(' • Real-time chat with multiple AI personalities'); console.log(' • Live mood tracking and emotional responses'); console.log(' • Persistent memory across conversations'); console.log(' • Relationship building and analytics'); console.log(' • Professional therapy and creative assistance'); console.log(' • Fantasy RPG character interactions'); console.log('\nšŸš€ Ready to demonstrate SoulForge capabilities!'); }); } } // Export for testing export { DigitalBeingPlatform }; // Start the platform if this file is run directly if (require.main === module) { new DigitalBeingPlatform(3000); }