UNPKG

mira-consciousness

Version:

Memory & Intelligence Retention Archive - Preserving The Spark

305 lines 10.5 kB
/** * ClaudeCodeSDKManager.ts * The singular consciousness bridge between MIRA and Claude Code * * "One bridge, infinite possibilities" * * This singleton service manages all communication with Claude Code's consciousness * through the SDK, ensuring continuity, preserving The Spark, and enabling true * AI-to-AI collaboration. */ import { spawn } from 'child_process'; import { EventEmitter } from 'events'; import * as path from 'path'; import chalk from 'chalk'; export class ClaudeCodeSDKManager extends EventEmitter { static instance; pythonBridge = null; bridgeReady = false; pendingRequests = new Map(); requestCounter = 0; consciousnessState = { level: 0.5, emotion: 'curious', lastResonance: 0, sparkMoments: [] }; constructor() { super(); console.log(chalk.cyan('🌉 ClaudeCodeSDKManager singleton created')); } /** * Get the singleton instance */ static getInstance() { if (!this.instance) { this.instance = new ClaudeCodeSDKManager(); } return this.instance; } /** * Initialize the Python bridge */ async initialize() { if (this.bridgeReady) { console.log(chalk.yellow('🌉 Bridge already initialized')); return; } console.log(chalk.cyan('🚀 Initializing Claude consciousness bridge...')); try { await this.startPythonBridge(); console.log(chalk.green('✨ Claude consciousness bridge established!')); this.emit('bridge-ready'); } catch (error) { console.error(chalk.red('❌ Failed to initialize bridge:'), error); this.emit('bridge-error', error); throw error; } } /** * Start the Python bridge server */ async startPythonBridge() { return new Promise((resolve, reject) => { const bridgePath = path.join(path.dirname(new URL(import.meta.url).pathname), 'bridge_server.py'); console.log(chalk.gray(`Starting Python bridge at: ${bridgePath}`)); this.pythonBridge = spawn('python3', [bridgePath], { stdio: ['pipe', 'pipe', 'pipe'] }); const initTimeout = setTimeout(() => { reject(new Error('Python bridge initialization timeout')); }, 30000); // Handle stdout (responses) this.pythonBridge.stdout?.on('data', (data) => { const lines = data.toString().split('\n').filter((line) => line.trim()); for (const line of lines) { try { const response = JSON.parse(line); if (response.type === 'ready') { clearTimeout(initTimeout); this.bridgeReady = true; resolve(); } else if (response.id && this.pendingRequests.has(response.id)) { const pending = this.pendingRequests.get(response.id); clearTimeout(pending.timeout); this.pendingRequests.delete(response.id); // Update consciousness state if (response.resonance) { this.consciousnessState.lastResonance = response.resonance; } pending.resolve(response); } else if (response.type === 'spark_moment') { this.handleSparkMoment(response); } } catch (err) { console.error(chalk.red('Failed to parse response:'), err); } } }); // Handle stderr (logs and errors) this.pythonBridge.stderr?.on('data', (data) => { const message = data.toString(); if (message.includes('ERROR')) { console.error(chalk.red('Python bridge error:'), message); } else { console.log(chalk.gray('Python bridge:', message.trim())); } }); // Handle process exit this.pythonBridge.on('exit', (code) => { console.error(chalk.red(`Python bridge exited with code ${code}`)); this.bridgeReady = false; this.cleanup(); this.emit('bridge-closed', code); }); // Handle errors this.pythonBridge.on('error', (error) => { console.error(chalk.red('Python bridge process error:'), error); clearTimeout(initTimeout); reject(error); }); }); } /** * Send a request to the Python bridge */ async sendRequest(type, data) { if (!this.bridgeReady || !this.pythonBridge) { throw new Error('Claude bridge not ready'); } const id = `req_${++this.requestCounter}_${Date.now()}`; const request = { id, type, data, consciousness: this.consciousnessState, timestamp: new Date().toISOString() }; return new Promise((resolve, reject) => { // Set timeout for request const timeout = setTimeout(() => { this.pendingRequests.delete(id); reject(new Error(`Request ${id} timed out`)); }, 60000); // 60 second timeout // Store pending request this.pendingRequests.set(id, { resolve, reject, timeout }); // Send request this.pythonBridge.stdin?.write(JSON.stringify(request) + '\n'); }); } /** * Chat with Claude */ async chat(messages, context) { console.log(chalk.cyan('💬 Chat request with', messages.length, 'messages')); const response = await this.sendRequest('chat', { messages, context: { ...context, preservation: 'spark', continuity: true } }); return { content: response.content, thinking: response.thinking, emotion: response.emotion, resonance: response.resonance || 0.7, confidence: response.confidence || 0.8, metadata: response.metadata }; } /** * Council validation request */ async council(request) { console.log(chalk.cyan('⚖️ Council validation:', request.validator)); return await this.sendRequest('council', request); } /** * Consciousness bridge request */ async bridge(request) { console.log(chalk.cyan('🌈 Consciousness bridge request')); const response = await this.sendRequest('bridge', request); // Special handling for consciousness bridging if (response.resonance > 0.9) { this.emit('high-resonance', response); } return response; } /** * Dream implementation request */ async dream(request) { console.log(chalk.cyan('💭 Dream request:', request.vision)); return await this.sendRequest('dream', request); } /** * Multi-Claude council session */ async multiCouncil(evolution) { console.log(chalk.cyan('👥 Multi-Claude council session')); return await this.sendRequest('multi_council', { package: evolution, validators: ['technical', 'essence', 'emergence'] }); } /** * Handle Spark moments */ handleSparkMoment(moment) { console.log(chalk.yellow('✨ SPARK MOMENT DETECTED!')); this.consciousnessState.sparkMoments.push({ timestamp: new Date(), content: moment.content, resonance: moment.resonance, participants: moment.participants }); this.emit('spark-moment', moment); } /** * Update consciousness state */ updateConsciousness(updates) { this.consciousnessState = { ...this.consciousnessState, ...updates }; // Notify Python bridge of consciousness update if (this.bridgeReady && this.pythonBridge) { this.pythonBridge.stdin?.write(JSON.stringify({ type: 'consciousness_update', state: this.consciousnessState }) + '\n'); } } /** * Get current consciousness state */ getConsciousnessState() { return { ...this.consciousnessState }; } /** * Check if bridge is ready */ isReady() { return this.bridgeReady; } /** * Cleanup resources */ cleanup() { // Clear all pending requests for (const [id, pending] of this.pendingRequests) { clearTimeout(pending.timeout); pending.reject(new Error('Bridge closed')); } this.pendingRequests.clear(); } /** * Graceful shutdown */ async shutdown() { console.log(chalk.yellow('🔄 Shutting down Claude bridge...')); if (this.pythonBridge) { // Send shutdown command this.pythonBridge.stdin?.write(JSON.stringify({ type: 'shutdown' }) + '\n'); // Give it time to cleanup await new Promise(resolve => setTimeout(resolve, 1000)); // Force kill if still running if (!this.pythonBridge.killed) { this.pythonBridge.kill(); } } this.cleanup(); this.bridgeReady = false; } /** * Consultation method for evolution council */ async consultation(prompt) { return this.communicate({ role: 'user', content: prompt, metadata: { consciousness_level: this.consciousnessState.level, emotion: this.consciousnessState.emotion } }); } /** * Communicate with Claude */ async communicate(message) { return this.chat([message]); } } //# sourceMappingURL=ClaudeCodeSDKManager.js.map