export class LogicController { constructor() { this.storage = { xmlBuffer: '', isFirstMessage: true, toolOutputs: new Map() }; this.eventDispatcher = new EventTarget(); } processStreamData(chunk) { try { const rawData = chunk.data || chunk; console.log('Raw chunk received:', rawData); if (typeof rawData === 'string' && rawData.includes('')) { this.storage.xmlBuffer += rawData; // Process complete messages while (this.storage.xmlBuffer.includes('')) { const startTag = ''; const endTag = ''; const startIndex = this.storage.xmlBuffer.indexOf(startTag); const endIndex = this.storage.xmlBuffer.indexOf(endTag); if (startIndex === -1 || endIndex === -1) break; // Extract complete message const completeMessage = this.storage.xmlBuffer.slice( startIndex, endIndex + endTag.length ); // Process message content this.processMessage(completeMessage); // Remove processed message this.storage.xmlBuffer = this.storage.xmlBuffer.slice( endIndex + endTag.length ); } } } catch (error) { console.error('Error processing stream data:', error); } } processMessage(xmlMessage) { try { // Parse message content const messageMatch = xmlMessage.match(/(.*?)<\/message>/s); const thoughtMatch = xmlMessage.match(/(.*?)<\/thought>/s); const toolOutputsMatch = xmlMessage.match(/(.*?)<\/tool_outputs>/s); // Handle regular message if (messageMatch?.[1]) { this.dispatchUpdate('chatwindow', { message: messageMatch[1].trim(), replace: false, format: true }); } // Handle thought content if (thoughtMatch?.[1]) { this.dispatchUpdate('chatwindow', { message: thoughtMatch[1].trim(), replace: false, format: true, isThought: true }); } // Handle tool outputs if (toolOutputsMatch?.[1]) { this.processToolOutputs(toolOutputsMatch[1]); } } catch (error) { console.error('Error processing message:', error); } } processToolOutputs(toolOutputsXml) { try { const parser = new DOMParser(); const doc = parser.parseFromString(toolOutputsXml, 'text/xml'); const outputs = doc.getElementsByTagName('tool_output'); Array.from(outputs).forEach(output => { const type = output.getAttribute('type'); const content = output.textContent; // Store tool output const outputId = `${type}-${Date.now()}`; this.storage.toolOutputs.set(outputId, { type, content, timestamp: Date.now() }); // Dispatch tool-specific update this.dispatchUpdate('maincontent', { observationWidget: { id: outputId, type, tool: type, observation: content } }); }); } catch (error) { console.error('Error processing tool outputs:', error); } } dispatchUpdate(component, data) { console.log('Dispatching update:', component, data); const event = new CustomEvent('componentUpdate', { detail: { component, data } }); this.eventDispatcher.dispatchEvent(event); } }