Skip to main content
Glama
main-integration-orchestrator.tsโ€ข19.5 kB
/** * Main Integration Orchestrator * Task 4.1: Integration Orchestrator Development * * Coordinates all system components into a cohesive educational content generation system: * - Phase 1: Infrastructure preservation (browser, auth, API) * - Phase 2: Universal content generation (BaseAdapter, assessments, subject adapters) * - Phase 3: Composer widget mapping (content-to-widget, images, flow optimization) * - Complete end-to-end workflow orchestration * - Error handling and graceful degradation */ // Phase 2 Imports import { BaseAdapter } from '../content-generation/base-adapter'; import { AdapterFactory } from '../content-generation/adapter-factory'; import { AssessmentEngine } from '../content-generation/assessment-engine'; // Phase 3 Imports import { ImageSelectionService } from '../services/image-selection-service'; import { EducationalImageMapper } from '../widget-mappers/educational-image-mapper'; import { EducationalFlowOptimizer } from '../services/educational-flow-optimizer'; import { Phase3WidgetOrchestrator } from './phase3-widget-orchestrator'; // Infrastructure Imports import { BrowserAutomation } from '../infrastructure/browser-automation'; import { Authentication } from '../infrastructure/authentication'; import { ApiClient } from '../infrastructure/api-client'; interface EducationalRequest { topic: string; subject: string; grade_level: string; learning_objectives?: string[]; author: string; target_duration?: number; additional_requirements?: string; } interface SystemConfiguration { jwt_token_path: string; api_endpoint: string; browser_settings: { headless: boolean; timeout: number; }; output_settings: { format: 'composer_json' | 'rdp_file' | 'both'; save_location: string; }; } interface IntegrationResult { success: boolean; composition_data: any; composition_url?: string; execution_time: number; components_used: string[]; errors?: string[]; warnings?: string[]; metadata: { phase1_status: 'success' | 'error'; phase2_status: 'success' | 'error'; phase3_status: 'success' | 'error'; infrastructure_status: 'success' | 'error'; }; } export class MainIntegrationOrchestrator { // Phase 2 Components private baseAdapter: BaseAdapter; private adapterFactory: AdapterFactory; private assessmentEngine: AssessmentEngine; // Phase 3 Components private imageService: ImageSelectionService; private imageMapper: EducationalImageMapper; private flowOptimizer: EducationalFlowOptimizer; private widgetOrchestrator: Phase3WidgetOrchestrator; // Infrastructure Components private browserAutomation: BrowserAutomation; private authentication: Authentication; private apiClient: ApiClient; private configuration: SystemConfiguration; private executionLog: string[] = []; constructor(configuration: SystemConfiguration) { this.configuration = configuration; this.initializeComponents(); } /** * Initialize all system components */ private initializeComponents(): void { this.log('๐Ÿ”ง Initializing Main Integration Orchestrator...'); try { // Phase 2 Components this.log('๐Ÿ“š Initializing Phase 2: Content Generation Components...'); this.baseAdapter = new BaseAdapter(); this.adapterFactory = new AdapterFactory(); this.assessmentEngine = new AssessmentEngine(); // Phase 3 Components this.log('๐ŸŽจ Initializing Phase 3: Widget Mapping Components...'); this.imageService = new ImageSelectionService(); this.imageMapper = new EducationalImageMapper(); this.flowOptimizer = new EducationalFlowOptimizer(); this.widgetOrchestrator = new Phase3WidgetOrchestrator(); // Infrastructure Components this.log('๐Ÿ—๏ธ Initializing Phase 1: Infrastructure Components...'); this.browserAutomation = new BrowserAutomation(); this.authentication = new Authentication(this.configuration.jwt_token_path); this.apiClient = new ApiClient(); this.log('โœ… All components initialized successfully'); } catch (error) { this.log(`โŒ Component initialization error: ${error.message}`); throw new Error(`Failed to initialize system components: ${error.message}`); } } /** * Main orchestration method - coordinates entire system */ public async orchestrateEducationalComposition( request: EducationalRequest ): Promise<IntegrationResult> { const startTime = Date.now(); this.log('\n๐Ÿš€ Starting Educational Composition Orchestration...'); this.log(`๐Ÿ“ Request: ${request.topic} (${request.subject}, ${request.grade_level})`); const result: IntegrationResult = { success: false, composition_data: null, execution_time: 0, components_used: [], metadata: { phase1_status: 'error', phase2_status: 'error', phase3_status: 'error', infrastructure_status: 'error' } }; try { // Step 1: Validate Infrastructure this.log('\n๐Ÿ“‹ Step 1: Infrastructure Validation...'); await this.validateInfrastructure(); result.metadata.phase1_status = 'success'; result.components_used.push('infrastructure'); // Step 2: Generate Educational Content (Phase 2) this.log('\n๐Ÿ“‹ Step 2: Educational Content Generation (Phase 2)...'); const phase2Output = await this.executePhase2ContentGeneration(request); result.metadata.phase2_status = 'success'; result.components_used.push('content-generation', 'assessment-engine'); // Step 3: Transform to Composer Widgets (Phase 3) this.log('\n๐Ÿ“‹ Step 3: Composer Widget Transformation (Phase 3)...'); const phase3Output = await this.executePhase3WidgetMapping(phase2Output, request); result.metadata.phase3_status = 'success'; result.components_used.push('widget-mapping', 'image-selection', 'flow-optimization'); // Step 4: Save and Deploy Composition this.log('\n๐Ÿ“‹ Step 4: Composition Deployment...'); const deploymentResult = await this.executeCompositionDeployment(phase3Output); result.metadata.infrastructure_status = 'success'; result.components_used.push('browser-automation', 'api-client'); // Step 5: Finalize Result result.success = true; result.composition_data = phase3Output; result.composition_url = deploymentResult.url; result.execution_time = Date.now() - startTime; this.log(`\n๐ŸŽ‰ Orchestration Complete! Duration: ${result.execution_time}ms`); return result; } catch (error) { this.log(`\nโŒ Orchestration Error: ${error.message}`); result.errors = [error.message]; result.execution_time = Date.now() - startTime; // Attempt graceful degradation return await this.handleGracefulDegradation(request, result, error); } } /** * Phase 1: Infrastructure Validation */ private async validateInfrastructure(): Promise<void> { this.log('๐Ÿ” Validating system infrastructure...'); // Validate JWT token availability this.log('๐Ÿ” Validating authentication...'); const authResult = await this.authentication.validateToken(); if (!authResult.valid) { throw new Error(`Authentication validation failed: ${authResult.error}`); } this.log('โœ… Authentication validated'); // Validate browser automation readiness this.log('๐ŸŒ Validating browser automation...'); const browserResult = await this.browserAutomation.validateSetup(); if (!browserResult.ready) { throw new Error(`Browser automation not ready: ${browserResult.error}`); } this.log('โœ… Browser automation ready'); // Validate API connectivity this.log('๐Ÿ”— Validating API connectivity...'); const apiResult = await this.apiClient.validateConnection(); if (!apiResult.connected) { throw new Error(`API connectivity failed: ${apiResult.error}`); } this.log('โœ… API connectivity validated'); this.log('๐ŸŽฏ Infrastructure validation complete'); } /** * Phase 2: Educational Content Generation */ private async executePhase2ContentGeneration( request: EducationalRequest ): Promise<any> { this.log('๐Ÿง  Executing Phase 2: Educational Content Generation...'); // Step 2.1: Generate base educational content this.log('๐Ÿ“ Generating base educational content...'); const baseContent = await this.generateBaseContent(request); this.log(`โœ… Base content generated: ${Object.keys(baseContent.components).length} components`); // Step 2.2: Apply subject-specific enhancements this.log('๐Ÿ”ฌ Applying subject-specific enhancements...'); const enhancedContent = await this.applySubjectEnhancements(baseContent, request); this.log(`โœ… Subject enhancements applied for ${request.subject}`); // Step 2.3: Generate assessments this.log('๐Ÿ“Š Generating assessment components...'); const assessmentComponents = await this.generateAssessments(enhancedContent, request); this.log(`โœ… Assessments generated: ${assessmentComponents.quiz ? 'quiz' : ''} ${assessmentComponents.flashcards ? 'flashcards' : ''}`); const phase2Output = { baseContent: enhancedContent, assessmentEngine: assessmentComponents, subjectAdapters: enhancedContent.metadata || {} }; this.log('๐ŸŽฏ Phase 2: Content Generation complete'); return phase2Output; } /** * Phase 3: Composer Widget Mapping */ private async executePhase3WidgetMapping( phase2Output: any, request: EducationalRequest ): Promise<any> { this.log('๐ŸŽจ Executing Phase 3: Composer Widget Mapping...'); // Configure Phase 3 transformation const phase3Configuration = { subject: request.subject, grade_level: request.grade_level, topic: request.topic, learning_objectives: request.learning_objectives || [`Aprender sobre ${request.topic}`], author: request.author, target_duration: request.target_duration || 50 }; // Execute complete widget orchestration this.log('๐ŸŽผ Orchestrating widget transformation...'); const composerComposition = await this.widgetOrchestrator.orchestratePhase3Transformation( phase2Output, phase3Configuration ); this.log(`โœ… Widget orchestration complete: ${composerComposition.composition.elements.length} widgets generated`); this.log('๐ŸŽฏ Phase 3: Widget Mapping complete'); return composerComposition; } /** * Phase 4: Composition Deployment */ private async executeCompositionDeployment(composerComposition: any): Promise<{ url: string }> { this.log('๐Ÿš€ Executing composition deployment...'); // Step 4.1: Prepare composition data this.log('๐Ÿ“ฆ Preparing composition data...'); const compositionData = this.prepareCompositionData(composerComposition); // Step 4.2: Launch browser automation this.log('๐ŸŒ Launching browser automation...'); await this.browserAutomation.initialize(this.configuration.browser_settings); // Step 4.3: Authenticate and navigate this.log('๐Ÿ” Authenticating and navigating to Composer...'); await this.browserAutomation.authenticate(this.authentication.getToken()); await this.browserAutomation.navigateToComposer(); // Step 4.4: Execute composition creation this.log('โœจ Creating composition...'); const creationResult = await this.browserAutomation.createComposition(compositionData); // Step 4.5: Save via API this.log('๐Ÿ’พ Saving via API...'); const apiResult = await this.apiClient.saveComposition(compositionData, this.authentication.getToken()); this.log(`โœ… Composition deployed successfully: ${creationResult.url}`); return { url: creationResult.url || apiResult.url }; } /** * Generate base educational content using BaseAdapter */ private async generateBaseContent(request: EducationalRequest): Promise<any> { const prompt = `Criar aula sobre ${request.topic} para ${request.grade_level} na disciplina de ${request.subject}`; return await this.baseAdapter.generateEducationalContent( prompt, request.subject, request.grade_level, { learningObjectives: request.learning_objectives, additionalRequirements: request.additional_requirements } ); } /** * Apply subject-specific enhancements */ private async applySubjectEnhancements(baseContent: any, request: EducationalRequest): Promise<any> { const subjectAdapter = this.adapterFactory.getAdapter(request.subject); if (subjectAdapter) { this.log(`๐Ÿ”ง Applying ${request.subject} specific enhancements...`); return await subjectAdapter.enhanceContent(baseContent, { gradeLevel: request.grade_level, topic: request.topic }); } return baseContent; } /** * Generate assessment components */ private async generateAssessments(content: any, request: EducationalRequest): Promise<any> { return await this.assessmentEngine.generateComprehensiveAssessment( content, { subject: request.subject, gradeLevel: request.grade_level, topic: request.topic, assessmentTypes: ['quiz', 'flashcards'] } ); } /** * Prepare composition data for deployment */ private prepareCompositionData(composerComposition: any): any { // Add deployment metadata return { ...composerComposition, deployment: { timestamp: new Date().toISOString(), version: '4.0.0', orchestrator: 'MainIntegrationOrchestrator' } }; } /** * Graceful degradation handling */ private async handleGracefulDegradation( request: EducationalRequest, result: IntegrationResult, error: Error ): Promise<IntegrationResult> { this.log('๐Ÿ›ก๏ธ Attempting graceful degradation...'); try { // Attempt to provide fallback composition if (result.metadata.phase2_status === 'success') { this.log('๐Ÿ“‹ Phase 2 succeeded, attempting simplified Phase 3...'); // Create simplified composition const simplifiedComposition = this.createFallbackComposition(request); result.composition_data = simplifiedComposition; result.warnings = [`Graceful degradation applied: ${error.message}`]; this.log('โœ… Fallback composition created'); } else { this.log('โŒ Phase 2 failed, creating minimal composition...'); result.composition_data = this.createMinimalComposition(request); result.warnings = [`Minimal composition provided due to: ${error.message}`]; } return result; } catch (degradationError) { this.log(`โŒ Graceful degradation failed: ${degradationError.message}`); result.errors.push(`Degradation failed: ${degradationError.message}`); return result; } } /** * Create fallback composition when Phase 3 fails */ private createFallbackComposition(request: EducationalRequest): any { return { composition: { id: `fallback-${request.topic}-${Date.now()}`, title: `${request.topic} - ${request.grade_level}`, description: `Composiรงรฃo educacional simplificada sobre ${request.topic}`, author: request.author, created: new Date().toISOString().split('T')[0], version: '4.0.0-fallback', metadata: { disciplina: request.subject, serie: request.grade_level, duracao_estimada: '50 minutos', tags: [request.topic, request.subject, request.grade_level, 'fallback'] }, elements: [ { id: 'fallback-header', type: 'head-1', content_title: 'Apresentaรงรฃo da Aula', category: `๐Ÿ“š ${request.subject.toUpperCase()}`, author_name: request.author }, { id: 'fallback-content', type: 'text-1', content_title: 'Conteรบdo Principal', content: `<p>Esta รฉ uma composiรงรฃo educacional sobre ${request.topic} para ${request.grade_level}.</p>` } ] } }; } /** * Create minimal composition when Phase 2 fails */ private createMinimalComposition(request: EducationalRequest): any { return { composition: { id: `minimal-${Date.now()}`, title: `Aula: ${request.topic}`, description: 'Composiรงรฃo educacional mรญnima', author: request.author, created: new Date().toISOString().split('T')[0], version: '4.0.0-minimal', metadata: { disciplina: request.subject, serie: request.grade_level, duracao_estimada: '50 minutos', tags: [request.topic, 'minimal'] }, elements: [ { id: 'minimal-content', type: 'text-1', content: `<h2>${request.topic}</h2><p>Conteรบdo educacional para ${request.grade_level}.</p>` } ] } }; } /** * Logging utility */ private log(message: string): void { const timestamp = new Date().toISOString(); const logEntry = `[${timestamp}] ${message}`; this.executionLog.push(logEntry); console.log(logEntry); } /** * Get execution log for debugging */ public getExecutionLog(): string[] { return [...this.executionLog]; } /** * System health check */ public async performHealthCheck(): Promise<{ overall_health: 'healthy' | 'degraded' | 'critical'; component_status: { [key: string]: 'ok' | 'warning' | 'error' }; recommendations: string[]; }> { this.log('๐Ÿฅ Performing system health check...'); const componentStatus: { [key: string]: 'ok' | 'warning' | 'error' } = {}; const recommendations: string[] = []; try { // Check Phase 2 Components componentStatus.baseAdapter = 'ok'; componentStatus.assessmentEngine = 'ok'; // Check Phase 3 Components componentStatus.imageService = 'ok'; componentStatus.flowOptimizer = 'ok'; // Check Infrastructure const authStatus = await this.authentication.validateToken(); componentStatus.authentication = authStatus.valid ? 'ok' : 'error'; if (!authStatus.valid) { recommendations.push('JWT token needs refresh or replacement'); } // Determine overall health const errorCount = Object.values(componentStatus).filter(status => status === 'error').length; const warningCount = Object.values(componentStatus).filter(status => status === 'warning').length; let overallHealth: 'healthy' | 'degraded' | 'critical'; if (errorCount === 0 && warningCount === 0) { overallHealth = 'healthy'; } else if (errorCount === 0) { overallHealth = 'degraded'; } else { overallHealth = 'critical'; } this.log(`๐ŸŽฏ Health check complete: ${overallHealth}`); return { overall_health: overallHealth, component_status: componentStatus, recommendations }; } catch (error) { this.log(`โŒ Health check failed: ${error.message}`); return { overall_health: 'critical', component_status: { system: 'error' }, recommendations: ['System requires immediate attention', error.message] }; } } }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/rkm097git/euconquisto-composer-mcp-poc'

If you have feedback or need assistance with the MCP directory API, please join our Discord server