|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Qwen |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import type { Config } from '../config/config.js'; |
| 8 | +import { AgentSharedMemory } from './shared-memory.js'; |
| 9 | + |
| 10 | +export interface AgentMessage { |
| 11 | + id: string; |
| 12 | + from: string; |
| 13 | + to: string | 'broadcast'; |
| 14 | + type: 'request' | 'response' | 'notification' | 'data'; |
| 15 | + content: string | Record<string, unknown>; |
| 16 | + timestamp: string; |
| 17 | + correlationId?: string; // For matching requests with responses |
| 18 | + priority?: 'low' | 'medium' | 'high'; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Communication system for agents to send messages to each other |
| 23 | + */ |
| 24 | +export class AgentCommunicationSystem { |
| 25 | + private readonly memory: AgentSharedMemory; |
| 26 | + private config: Config; |
| 27 | + |
| 28 | + constructor(config: Config) { |
| 29 | + this.config = config; |
| 30 | + this.memory = new AgentSharedMemory(config); |
| 31 | + |
| 32 | + // Use config to log initialization if needed |
| 33 | + void this.config; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Send a message to another agent |
| 38 | + * @param from The sending agent |
| 39 | + * @param to The receiving agent, or 'broadcast' for all agents |
| 40 | + * @param type The type of message |
| 41 | + * @param content The content of the message |
| 42 | + * @param options Additional options like priority or correlation ID |
| 43 | + */ |
| 44 | + async sendMessage( |
| 45 | + from: string, |
| 46 | + to: string | 'broadcast', |
| 47 | + type: 'request' | 'response' | 'notification' | 'data', |
| 48 | + content: string | Record<string, unknown>, |
| 49 | + options?: { |
| 50 | + correlationId?: string; |
| 51 | + priority?: 'low' | 'medium' | 'high'; |
| 52 | + }, |
| 53 | + ): Promise<string> { |
| 54 | + const message: AgentMessage = { |
| 55 | + id: `msg-${Date.now()}-${Math.floor(Math.random() * 10000)}`, |
| 56 | + from, |
| 57 | + to, |
| 58 | + type, |
| 59 | + content, |
| 60 | + timestamp: new Date().toISOString(), |
| 61 | + correlationId: options?.correlationId, |
| 62 | + priority: options?.priority || 'medium', |
| 63 | + }; |
| 64 | + |
| 65 | + // Store in shared memory |
| 66 | + await this.memory.set(`message:${message.id}`, message); |
| 67 | + |
| 68 | + // Also store in the recipient's inbox if not broadcasting |
| 69 | + if (to !== 'broadcast') { |
| 70 | + const inboxKey = `inbox:${to}`; |
| 71 | + const inbox: AgentMessage[] = |
| 72 | + (await this.memory.get<AgentMessage[]>(inboxKey)) || []; |
| 73 | + inbox.push(message); |
| 74 | + await this.memory.set(inboxKey, inbox); |
| 75 | + } else { |
| 76 | + // For broadcast, add to all agents' inboxes |
| 77 | + const agentKeys = await this.memory.keys(); |
| 78 | + for (const key of agentKeys) { |
| 79 | + if (key.startsWith('inbox:')) { |
| 80 | + const inbox: AgentMessage[] = |
| 81 | + (await this.memory.get<AgentMessage[]>(key)) || []; |
| 82 | + inbox.push(message); |
| 83 | + await this.memory.set(key, inbox); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + return message.id; |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Get messages from an agent's inbox |
| 93 | + * @param agentId The agent to get messages for |
| 94 | + * @param count The maximum number of messages to return |
| 95 | + * @param priority Optional priority filter |
| 96 | + */ |
| 97 | + async getInbox( |
| 98 | + agentId: string, |
| 99 | + count?: number, |
| 100 | + priority?: 'low' | 'medium' | 'high', |
| 101 | + ): Promise<AgentMessage[]> { |
| 102 | + const inboxKey = `inbox:${agentId}`; |
| 103 | + const inbox: AgentMessage[] = |
| 104 | + (await this.memory.get<AgentMessage[]>(inboxKey)) || []; |
| 105 | + |
| 106 | + let filteredMessages = inbox; |
| 107 | + if (priority) { |
| 108 | + filteredMessages = inbox.filter((msg) => msg.priority === priority); |
| 109 | + } |
| 110 | + |
| 111 | + // Sort by timestamp (most recent first) |
| 112 | + filteredMessages.sort( |
| 113 | + (a, b) => |
| 114 | + new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(), |
| 115 | + ); |
| 116 | + |
| 117 | + return count ? filteredMessages.slice(0, count) : filteredMessages; |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Get all messages (for broadcast or admin purposes) |
| 122 | + */ |
| 123 | + async getAllMessages(): Promise<AgentMessage[]> { |
| 124 | + const allKeys = await this.memory.keys(); |
| 125 | + const messages: AgentMessage[] = []; |
| 126 | + |
| 127 | + for (const key of allKeys) { |
| 128 | + if (key.startsWith('message:')) { |
| 129 | + const message = await this.memory.get<AgentMessage>(key); |
| 130 | + if (message) { |
| 131 | + messages.push(message); |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + return messages; |
| 137 | + } |
| 138 | + |
| 139 | + /** |
| 140 | + * Clear an agent's inbox |
| 141 | + * @param agentId The agent whose inbox to clear |
| 142 | + */ |
| 143 | + async clearInbox(agentId: string): Promise<void> { |
| 144 | + const inboxKey = `inbox:${agentId}`; |
| 145 | + await this.memory.delete(inboxKey); |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Send a request and wait for a response |
| 150 | + * @param from The requesting agent |
| 151 | + * @param to The responding agent |
| 152 | + * @param request The request content |
| 153 | + * @param timeoutMs How long to wait for a response (in ms) |
| 154 | + */ |
| 155 | + async sendRequestAndWait( |
| 156 | + from: string, |
| 157 | + to: string, |
| 158 | + request: string | Record<string, unknown>, |
| 159 | + timeoutMs: number = 5000, |
| 160 | + ): Promise<AgentMessage | null> { |
| 161 | + const correlationId = `req-${Date.now()}`; |
| 162 | + |
| 163 | + // Send the request |
| 164 | + await this.sendMessage(from, to, 'request', request, { |
| 165 | + correlationId, |
| 166 | + priority: 'high', |
| 167 | + }); |
| 168 | + |
| 169 | + // Wait for a response with the matching correlation ID |
| 170 | + const startTime = Date.now(); |
| 171 | + while (Date.now() - startTime < timeoutMs) { |
| 172 | + const inbox = await this.getInbox(from); |
| 173 | + const response = inbox.find( |
| 174 | + (msg) => msg.correlationId === correlationId && msg.type === 'response', |
| 175 | + ); |
| 176 | + |
| 177 | + if (response) { |
| 178 | + // Remove the response from inbox if it's a direct request-response |
| 179 | + const inboxKey = `inbox:${from}`; |
| 180 | + const inbox: AgentMessage[] = |
| 181 | + (await this.memory.get<AgentMessage[]>(inboxKey)) || []; |
| 182 | + const updatedInbox = inbox.filter((msg) => msg.id !== response.id); |
| 183 | + await this.memory.set(inboxKey, updatedInbox); |
| 184 | + |
| 185 | + return response; |
| 186 | + } |
| 187 | + |
| 188 | + await new Promise((resolve) => setTimeout(resolve, 100)); // Wait 100ms before checking again |
| 189 | + } |
| 190 | + |
| 191 | + return null; // Timeout |
| 192 | + } |
| 193 | + |
| 194 | + /** |
| 195 | + * Get the shared memory instance for direct access |
| 196 | + */ |
| 197 | + getMemory(): AgentSharedMemory { |
| 198 | + return this.memory; |
| 199 | + } |
| 200 | +} |
0 commit comments