Spaces:
Paused
Paused
File size: 7,313 Bytes
529090e | 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | /**
* Advanced Agent Communication Protocol
* Enables sophisticated inter-agent communication and coordination
*/
export interface AgentMessage {
id: string;
from: string;
to: string | string[]; // Single agent or broadcast
type: 'request' | 'response' | 'broadcast' | 'negotiation' | 'delegation';
content: any;
priority: 'low' | 'medium' | 'high' | 'critical';
timestamp: Date;
correlationId?: string; // For request-response pairing
metadata?: Record<string, any>;
}
export interface NegotiationProposal {
proposalId: string;
proposer: string;
task: string;
terms: Record<string, any>;
deadline?: Date;
requiredCapabilities: string[];
}
export interface NegotiationResponse {
proposalId: string;
responder: string;
accepted: boolean;
counterProposal?: Partial<NegotiationProposal>;
reason?: string;
}
export class AgentCommunicationProtocol {
private messageQueue: Map<string, AgentMessage[]> = new Map();
private subscriptions: Map<string, Set<(msg: AgentMessage) => void>> = new Map();
private negotiationHistory: Map<string, NegotiationProposal[]> = new Map();
/**
* Send message to specific agent(s)
*/
async sendMessage(message: Omit<AgentMessage, 'id' | 'timestamp'>): Promise<string> {
const fullMessage: AgentMessage = {
...message,
id: this.generateMessageId(),
timestamp: new Date(),
};
// Store in queue
const recipients = Array.isArray(message.to) ? message.to : [message.to];
recipients.forEach(recipient => {
if (!this.messageQueue.has(recipient)) {
this.messageQueue.set(recipient, []);
}
this.messageQueue.get(recipient)!.push(fullMessage);
});
// Notify subscribers
recipients.forEach(recipient => {
const subscribers = this.subscriptions.get(recipient);
if (subscribers) {
subscribers.forEach(callback => callback(fullMessage));
}
});
return fullMessage.id;
}
/**
* Receive messages for an agent
*/
async receiveMessages(agentId: string, filter?: Partial<AgentMessage>): Promise<AgentMessage[]> {
const messages = this.messageQueue.get(agentId) || [];
if (!filter) return messages;
return messages.filter(msg => {
return Object.entries(filter).every(([key, value]) => {
return msg[key as keyof AgentMessage] === value;
});
});
}
/**
* Subscribe to messages
*/
subscribe(agentId: string, callback: (msg: AgentMessage) => void): () => void {
if (!this.subscriptions.has(agentId)) {
this.subscriptions.set(agentId, new Set());
}
this.subscriptions.get(agentId)!.add(callback);
// Return unsubscribe function
return () => {
this.subscriptions.get(agentId)?.delete(callback);
};
}
/**
* Broadcast message to all agents
*/
async broadcast(message: Omit<AgentMessage, 'id' | 'timestamp' | 'to'>): Promise<string> {
return this.sendMessage({
...message,
to: 'broadcast',
});
}
/**
* Request-response pattern
*/
async request(
from: string,
to: string,
content: any,
timeout: number = 30000
): Promise<AgentMessage | null> {
const correlationId = this.generateMessageId();
await this.sendMessage({
from,
to,
type: 'request',
content,
priority: 'medium',
correlationId,
});
// Wait for response
return new Promise((resolve) => {
const timeoutId = setTimeout(() => {
unsubscribe();
resolve(null);
}, timeout);
const unsubscribe = this.subscribe(from, (msg) => {
if (msg.type === 'response' && msg.correlationId === correlationId) {
clearTimeout(timeoutId);
unsubscribe();
resolve(msg);
}
});
});
}
/**
* Respond to a request
*/
async respond(originalMessage: AgentMessage, response: any): Promise<string> {
return this.sendMessage({
from: originalMessage.to as string,
to: originalMessage.from,
type: 'response',
content: response,
priority: originalMessage.priority,
correlationId: originalMessage.correlationId,
});
}
/**
* Initiate negotiation
*/
async proposeNegotiation(proposal: NegotiationProposal): Promise<string> {
if (!this.negotiationHistory.has(proposal.proposer)) {
this.negotiationHistory.set(proposal.proposer, []);
}
this.negotiationHistory.get(proposal.proposer)!.push(proposal);
return this.broadcast({
from: proposal.proposer,
type: 'negotiation',
content: proposal,
priority: 'high',
});
}
/**
* Respond to negotiation
*/
async respondToNegotiation(
proposal: NegotiationProposal,
response: NegotiationResponse
): Promise<string> {
return this.sendMessage({
from: response.responder,
to: proposal.proposer,
type: 'response',
content: response,
priority: 'high',
metadata: { negotiation: true },
});
}
/**
* Delegate task to another agent
*/
async delegateTask(
from: string,
to: string,
task: any,
priority: AgentMessage['priority'] = 'medium'
): Promise<string> {
return this.sendMessage({
from,
to,
type: 'delegation',
content: task,
priority,
});
}
/**
* Clear old messages
*/
clearOldMessages(agentId: string, olderThan: Date): void {
const messages = this.messageQueue.get(agentId);
if (messages) {
const filtered = messages.filter(msg => msg.timestamp > olderThan);
this.messageQueue.set(agentId, filtered);
}
}
/**
* Get message statistics
*/
getStatistics(agentId: string): {
totalMessages: number;
byType: Record<string, number>;
byPriority: Record<string, number>;
} {
const messages = this.messageQueue.get(agentId) || [];
return {
totalMessages: messages.length,
byType: messages.reduce((acc, msg) => {
acc[msg.type] = (acc[msg.type] || 0) + 1;
return acc;
}, {} as Record<string, number>),
byPriority: messages.reduce((acc, msg) => {
acc[msg.priority] = (acc[msg.priority] || 0) + 1;
return acc;
}, {} as Record<string, number>),
};
}
private generateMessageId(): string {
return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
}
export const agentCommunicationProtocol = new AgentCommunicationProtocol();
|