All files / src/managers ChatManager.ts

93.42% Statements 71/76
68.75% Branches 11/16
100% Functions 14/14
93.42% Lines 71/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 1901x 1x       1x   1x 17x 17x     17x 17x   17x 17x       17x 2x     17x 1x         16x 16x               16x 16x 16x   16x       4x       2x 1x   1x 1x       2x       1x 1x 1x 1x 1x         7x 1x     7x 7x         7x 1x 1x       7x               7x 7x     7x           7x     7x 7x   1x 1x         3x 3x       3x               3x 3x   3x 3x 6x 6x     3x 3x     3x         3x               4x 4x       2x 2x       2x                     2x 2x   2x       18x 18x 18x    
import { EventEmitter } from 'events';
import { v4 as uuidv4 } from 'uuid';
import { IChatManager } from '../interfaces/IChatManager';
import { IOrchestratorManager } from '../interfaces/IOrchestratorManager';
import { IMemoryManager } from '../interfaces/IMemoryManager';
import { ChatSession, Message, OperationMode } from '../types';
 
export class ChatManager extends EventEmitter implements IChatManager {
    private sessions: Map<string, ChatSession> = new Map();
    private activeSessionId: string | null = null;
 
    constructor(
        private orchestratorManager: IOrchestratorManager,
        private memoryManager: IMemoryManager
    ) {
        super();
        this.setupEventHandlers();
    }
 
    private setupEventHandlers(): void {
        this.orchestratorManager.on('agent-message', (event) => {
            this.handleAgentMessage(event);
        });
 
        this.orchestratorManager.on('error', (error) => {
            this.emit('error', error);
        });
    }
 
    createSession(): string {
        const sessionId = uuidv4();
        const session: ChatSession = {
            id: sessionId,
            createdAt: Date.now(),
            updatedAt: Date.now(),
            mode: OperationMode.Chat,
            messages: []
        };
 
        this.sessions.set(sessionId, session);
        this.activeSessionId = sessionId;
        this.emit('session-created', sessionId);
 
        return sessionId;
    }
 
    getActiveSession(): string | null {
        return this.activeSessionId;
    }
 
    setActiveSession(sessionId: string): void {
        if (!this.sessions.has(sessionId)) {
            throw new Error(`Session ${sessionId} not found`);
        }
        this.activeSessionId = sessionId;
        this.emit('session-changed', sessionId);
    }
 
    getSession(sessionId: string): ChatSession | undefined {
        return this.sessions.get(sessionId);
    }
 
    clearSession(sessionId: string): void {
        const session = this.sessions.get(sessionId);
        Eif (session) {
            session.messages = [];
            session.updatedAt = Date.now();
            this.emit('session-cleared', sessionId);
        }
    }
 
    async sendMessage(content: string, mode: OperationMode): Promise<void> {
        if (!this.activeSessionId) {
            this.createSession();
        }
 
        const session = this.sessions.get(this.activeSessionId!);
        Iif (!session) {
            throw new Error('No active session');
        }
 
        // Update session mode if different
        if (session.mode !== mode) {
            session.mode = mode;
            await this.orchestratorManager.switchMode(mode);
        }
 
        // Create user message
        const userMessage: Message = {
            id: uuidv4(),
            role: 'user',
            content,
            timestamp: Date.now()
        };
 
        // Add to session history
        session.messages.push(userMessage);
        session.updatedAt = Date.now();
 
        // Store in memory for context
        await this.memoryManager.store(
            `session:${session.id}:message:${userMessage.id}`,
            userMessage
        );
 
        // Emit user message event
        this.emit('user-message', userMessage);
 
        // Process with orchestrator
        try {
            await this.orchestratorManager.processMessage(content, mode);
        } catch (error) {
            this.emit('error', error);
            throw error;
        }
    }
 
    async streamResponse(response: AsyncIterable<string>): Promise<void> {
        const session = this.sessions.get(this.activeSessionId!);
        Iif (!session) {
            throw new Error('No active session');
        }
 
        const assistantMessage: Message = {
            id: uuidv4(),
            role: 'assistant',
            content: '',
            timestamp: Date.now(),
            metadata: { streaming: true }
        };
 
        session.messages.push(assistantMessage);
        this.emit('assistant-message-start', assistantMessage);
 
        try {
            for await (const chunk of response) {
                assistantMessage.content += chunk;
                this.emit('stream-chunk', chunk);
            }
 
            assistantMessage.metadata!.streaming = false;
            session.updatedAt = Date.now();
 
            // Store completed message
            await this.memoryManager.store(
                `session:${session.id}:message:${assistantMessage.id}`,
                assistantMessage
            );
 
            this.emit('assistant-message-complete', assistantMessage);
        } catch (error) {
            this.emit('stream-error', error);
            throw error;
        }
    }
 
    getHistory(sessionId: string): Message[] {
        const session = this.sessions.get(sessionId);
        return session ? [...session.messages] : [];
    }
 
    private handleAgentMessage(event: any): void {
        const session = this.sessions.get(this.activeSessionId!);
        Iif (!session) {
            return;
        }
 
        const agentMessage: Message = {
            id: uuidv4(),
            role: 'assistant',
            content: event.payload.message,
            timestamp: Date.now(),
            metadata: {
                agent: event.payload.agent,
                mode: session.mode
            }
        };
 
        session.messages.push(agentMessage);
        session.updatedAt = Date.now();
 
        this.emit('agent-message', agentMessage);
    }
 
    dispose(): void {
        this.removeAllListeners();
        this.sessions.clear();
        this.activeSessionId = null;
    }
}