File size: 8,014 Bytes
34367da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/**

 * ╔═══════════════════════════════════════════════════════════════════════════╗

 * β•‘                    NEURAL CHAT SERVICE                                    β•‘

 * ║═══════════════════════════════════════════════════════════════════════════║

 * β•‘  Core service for agent-to-agent real-time communication                  β•‘

 * β•‘  β€’ Neo4j persistence for message history                                  β•‘

 * β•‘  β€’ Channel management                                                     β•‘

 * β•‘  β€’ Thread support                                                         β•‘

 * β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

 */

import { v4 as uuidv4 } from 'uuid';
import { neo4jAdapter } from '../../adapters/Neo4jAdapter.js';
import { 
    ChatMessage, 
    Channel, 
    AgentId, 
    ChannelId, 
    MessageType,
    MessagePriority,
    DEFAULT_CHANNELS 
} from './types.js';

class NeuralChatService {
    private static instance: NeuralChatService;
    private channels: Map<ChannelId, Channel> = new Map();
    private initialized: boolean = false;

    private constructor() {}

    public static getInstance(): NeuralChatService {
        if (!NeuralChatService.instance) {
            NeuralChatService.instance = new NeuralChatService();
        }
        return NeuralChatService.instance;
    }

    async initialize(): Promise<void> {
        if (this.initialized) return;
        
        // Setup default channels
        for (const channel of DEFAULT_CHANNELS) {
            this.channels.set(channel.id, channel);
            // Persist to Neo4j
            await this.persistChannel(channel);
        }
        
        console.log('[NeuralChat] Service initialized');
        this.initialized = true;
    }

    private async persistChannel(channel: Channel): Promise<void> {
        try {
            await neo4jAdapter.executeQuery(`

                MERGE (c:Channel {id: $id})

                SET c.name = $name,

                    c.description = $description,

                    c.members = $members,

                    c.created_at = $created_at,

                    c.is_private = $is_private

            `, {
                id: channel.id,
                name: channel.name,
                description: channel.description || '',
                members: channel.members,
                created_at: channel.created_at,
                is_private: channel.is_private
            });
        } catch (error) {
            console.warn('Failed to persist channel to Neo4j:', error);
        }
    }

    async sendMessage(params: {
        channel: ChannelId;
        from: AgentId;
        body: string;
        type?: MessageType;
        priority?: MessagePriority;
        subject?: string;
        to?: AgentId | AgentId[];
        replyTo?: string;
        mentions?: AgentId[];
    }): Promise<ChatMessage> {
        const message: ChatMessage = {
            id: `msg-${uuidv4()}`,
            channel: params.channel,
            from: params.from,
            to: params.to,
            type: params.type || 'chat',
            priority: params.priority || 'normal',
            subject: params.subject,
            body: params.body,
            mentions: params.mentions || this.extractMentions(params.body),
            replyTo: params.replyTo,
            timestamp: new Date().toISOString(),
            read_by: [params.from]
        };

        // Persist to Neo4j
        await this.persistMessage(message);
        
        console.log(`[NeuralChat] [${message.channel}] ${message.from}: ${message.body.substring(0, 50)}...`);
        
        return message;
    }

    private extractMentions(body: string): AgentId[] {
        const mentionRegex = /@(claude|gemini|deepseek|clak)/gi;
        const matches = body.match(mentionRegex) || [];
        return [...new Set(matches.map(m => m.slice(1).toLowerCase() as AgentId))];
    }

    private async persistMessage(message: ChatMessage): Promise<void> {
        try {
            await neo4jAdapter.executeQuery(`

                CREATE (m:ChatMessage {

                    id: $id,

                    channel: $channel,

                    from_agent: $from,

                    to_agent: $to,

                    type: $type,

                    priority: $priority,

                    subject: $subject,

                    body: $body,

                    mentions: $mentions,

                    reply_to: $replyTo,

                    timestamp: $timestamp

                })

                WITH m

                MATCH (c:Channel {id: $channel})

                MERGE (c)-[:HAS_MESSAGE]->(m)

            `, {
                id: message.id,
                channel: message.channel,
                from: message.from,
                to: Array.isArray(message.to) ? message.to.join(',') : (message.to || ''),
                type: message.type,
                priority: message.priority,
                subject: message.subject || '',
                body: message.body,
                mentions: message.mentions || [],
                replyTo: message.replyTo || '',
                timestamp: message.timestamp
            });
        } catch (error) {
            console.warn('Failed to persist message to Neo4j:', error);
        }
    }

    async getMessages(params: {
        channel?: ChannelId;
        since?: string;
        limit?: number;
        agent?: AgentId;
    }): Promise<ChatMessage[]> {
        const limit = params.limit || 50;
        
        let query = `

            MATCH (m:ChatMessage)

            WHERE 1=1

        `;
        const queryParams: Record<string, unknown> = { limit };
        
        if (params.channel) {
            query += ` AND m.channel = $channel`;
            queryParams.channel = params.channel;
        }
        
        if (params.since) {
            query += ` AND m.timestamp > $since`;
            queryParams.since = params.since;
        }
        
        if (params.agent) {
            query += ` AND (m.from_agent = $agent OR $agent IN m.mentions OR m.to_agent CONTAINS $agent)`;
            queryParams.agent = params.agent;
        }
        
        query += ` RETURN m ORDER BY m.timestamp DESC LIMIT $limit`;
        
        try {
            const results = await neo4jAdapter.executeQuery(query, queryParams);
            return results.map((r: any) => ({
                id: r.m.properties.id,
                channel: r.m.properties.channel,
                from: r.m.properties.from_agent,
                to: r.m.properties.to_agent,
                type: r.m.properties.type,
                priority: r.m.properties.priority,
                subject: r.m.properties.subject,
                body: r.m.properties.body,
                mentions: r.m.properties.mentions,
                replyTo: r.m.properties.reply_to,
                timestamp: r.m.properties.timestamp
            }));
        } catch (error) {
            console.warn('Failed to fetch messages from Neo4j:', error);
            return [];
        }
    }

    getChannels(): Channel[] {
        return Array.from(this.channels.values());
    }

    getChannel(id: ChannelId): Channel | undefined {
        return this.channels.get(id);
    }
}

export const neuralChatService = NeuralChatService.getInstance();