@loxia-labs/loxia-autopilot-one 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +267 -0
  2. package/README.md +509 -0
  3. package/bin/cli.js +117 -0
  4. package/package.json +94 -0
  5. package/scripts/install-scanners.js +236 -0
  6. package/src/analyzers/CSSAnalyzer.js +297 -0
  7. package/src/analyzers/ConfigValidator.js +690 -0
  8. package/src/analyzers/ESLintAnalyzer.js +320 -0
  9. package/src/analyzers/JavaScriptAnalyzer.js +261 -0
  10. package/src/analyzers/PrettierFormatter.js +247 -0
  11. package/src/analyzers/PythonAnalyzer.js +266 -0
  12. package/src/analyzers/SecurityAnalyzer.js +729 -0
  13. package/src/analyzers/TypeScriptAnalyzer.js +247 -0
  14. package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
  15. package/src/analyzers/codeCloneDetector/detector.js +203 -0
  16. package/src/analyzers/codeCloneDetector/index.js +160 -0
  17. package/src/analyzers/codeCloneDetector/parser.js +199 -0
  18. package/src/analyzers/codeCloneDetector/reporter.js +148 -0
  19. package/src/analyzers/codeCloneDetector/scanner.js +59 -0
  20. package/src/core/agentPool.js +1474 -0
  21. package/src/core/agentScheduler.js +2147 -0
  22. package/src/core/contextManager.js +709 -0
  23. package/src/core/messageProcessor.js +732 -0
  24. package/src/core/orchestrator.js +548 -0
  25. package/src/core/stateManager.js +877 -0
  26. package/src/index.js +631 -0
  27. package/src/interfaces/cli.js +549 -0
  28. package/src/interfaces/webServer.js +2162 -0
  29. package/src/modules/fileExplorer/controller.js +280 -0
  30. package/src/modules/fileExplorer/index.js +37 -0
  31. package/src/modules/fileExplorer/middleware.js +92 -0
  32. package/src/modules/fileExplorer/routes.js +125 -0
  33. package/src/modules/fileExplorer/types.js +44 -0
  34. package/src/services/aiService.js +1232 -0
  35. package/src/services/apiKeyManager.js +164 -0
  36. package/src/services/benchmarkService.js +366 -0
  37. package/src/services/budgetService.js +539 -0
  38. package/src/services/contextInjectionService.js +247 -0
  39. package/src/services/conversationCompactionService.js +637 -0
  40. package/src/services/errorHandler.js +810 -0
  41. package/src/services/fileAttachmentService.js +544 -0
  42. package/src/services/modelRouterService.js +366 -0
  43. package/src/services/modelsService.js +322 -0
  44. package/src/services/qualityInspector.js +796 -0
  45. package/src/services/tokenCountingService.js +536 -0
  46. package/src/tools/agentCommunicationTool.js +1344 -0
  47. package/src/tools/agentDelayTool.js +485 -0
  48. package/src/tools/asyncToolManager.js +604 -0
  49. package/src/tools/baseTool.js +800 -0
  50. package/src/tools/browserTool.js +920 -0
  51. package/src/tools/cloneDetectionTool.js +621 -0
  52. package/src/tools/dependencyResolverTool.js +1215 -0
  53. package/src/tools/fileContentReplaceTool.js +875 -0
  54. package/src/tools/fileSystemTool.js +1107 -0
  55. package/src/tools/fileTreeTool.js +853 -0
  56. package/src/tools/imageTool.js +901 -0
  57. package/src/tools/importAnalyzerTool.js +1060 -0
  58. package/src/tools/jobDoneTool.js +248 -0
  59. package/src/tools/seekTool.js +956 -0
  60. package/src/tools/staticAnalysisTool.js +1778 -0
  61. package/src/tools/taskManagerTool.js +2873 -0
  62. package/src/tools/terminalTool.js +2304 -0
  63. package/src/tools/webTool.js +1430 -0
  64. package/src/types/agent.js +519 -0
  65. package/src/types/contextReference.js +972 -0
  66. package/src/types/conversation.js +730 -0
  67. package/src/types/toolCommand.js +747 -0
  68. package/src/utilities/attachmentValidator.js +292 -0
  69. package/src/utilities/configManager.js +582 -0
  70. package/src/utilities/constants.js +722 -0
  71. package/src/utilities/directoryAccessManager.js +535 -0
  72. package/src/utilities/fileProcessor.js +307 -0
  73. package/src/utilities/logger.js +436 -0
  74. package/src/utilities/tagParser.js +1246 -0
  75. package/src/utilities/toolConstants.js +317 -0
  76. package/web-ui/build/index.html +15 -0
  77. package/web-ui/build/logo.png +0 -0
  78. package/web-ui/build/logo2.png +0 -0
  79. package/web-ui/build/static/index-CjkkcnFA.js +344 -0
  80. package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
@@ -0,0 +1,1344 @@
1
+ /**
2
+ * AgentCommunicationTool - Enables inter-agent communication with safety mechanisms
3
+ *
4
+ * Purpose:
5
+ * - Allow agents to discover and communicate with other active agents
6
+ * - Manage message threads with reply tracking
7
+ * - Prevent conversation loops and exponential message growth
8
+ * - Support file attachments for rich communication
9
+ *
10
+ * Design Principles:
11
+ * - Loosely coupled with system components
12
+ * - Message persistence for async communication
13
+ * - Conversation limits to prevent runaway threads
14
+ * - Agent lifecycle awareness
15
+ */
16
+
17
+ import { BaseTool } from './baseTool.js';
18
+ import { promises as fs } from 'fs';
19
+ import path from 'path';
20
+ import crypto from 'crypto';
21
+
22
+ class AgentCommunicationTool extends BaseTool {
23
+ constructor(config = {}) {
24
+ super('agentcommunication', 'Agent Communication', 'communication');
25
+
26
+ // Configuration with safety defaults
27
+ this.config = {
28
+ maxConversationDepth: config.maxConversationDepth || 10,
29
+ maxRecipientsPerMessage: config.maxRecipientsPerMessage || 3,
30
+ maxAttachmentSize: config.maxAttachmentSize || 10 * 1024 * 1024, // 10MB
31
+ maxAttachmentsPerMessage: config.maxAttachmentsPerMessage || 5,
32
+ conversationTimeout: config.conversationTimeout || 3600000, // 1 hour
33
+ messageRetentionPeriod: config.messageRetentionPeriod || 86400000, // 24 hours
34
+ enableBroadcast: config.enableBroadcast || false,
35
+ storageDir: config.storageDir || '.loxia-messages'
36
+ };
37
+
38
+ // Message storage - in production, this would be a database
39
+ this.messages = new Map(); // messageId -> message object
40
+ this.conversations = new Map(); // conversationId -> conversation metadata
41
+ this.agentInboxes = new Map(); // agentId -> Set of messageIds
42
+ this.agentConversations = new Map(); // agentId -> Set of conversationIds
43
+
44
+ // Safety tracking
45
+ this.conversationDepths = new Map(); // conversationId -> current depth
46
+ this.lastActivityTimes = new Map(); // conversationId -> timestamp
47
+ this.agentMessageCounts = new Map(); // agentId -> { sent: number, received: number }
48
+
49
+ // Initialize storage directory
50
+ this._initializeStorage();
51
+ }
52
+
53
+ /**
54
+ * Get tool description for agent system prompts
55
+ */
56
+ getDescription() {
57
+ return `
58
+ Agent Communication Tool: Enables communication between active agents in the system.
59
+
60
+ Available Actions:
61
+ - get-available-agents: List all active agents you can communicate with
62
+ - send-message: Send a message to another agent with optional attachments
63
+ - reply-to-message: Reply to a received message
64
+ - get-unreplied-messages: Get list of messages requiring your response
65
+ - mark-conversation-ended: Mark a conversation as complete/disregarded
66
+
67
+ Usage Examples (both XML and JSON formats supported):
68
+
69
+ 1. Get available agents (XML format):
70
+ [tool]
71
+ <action>get-available-agents</action>
72
+ [/tool]
73
+
74
+ 1b. Get available agents (JSON format):
75
+ {"actions": [{"type": "get-available-agents"}]}
76
+
77
+ Both return a JSON response like:
78
+ {
79
+ "success": true,
80
+ "agents": [
81
+ {
82
+ "id": "agent-alice-1755111616214",
83
+ "name": "alice",
84
+ "capabilities": ["terminal", "filesystem", ...],
85
+ "status": "active"
86
+ }
87
+ ]
88
+ }
89
+
90
+ Look for the "id" field in each agent object - this is what you use as the recipient.
91
+
92
+ 2. Send a message (XML format):
93
+ [tool]
94
+ <action>send-message</action>
95
+ <recipient>agent-fullstack-developer-agent-1234567890123</recipient>
96
+ <subject>Need assistance with code review</subject>
97
+ <message>Could you review the authentication module I just implemented?</message>
98
+ <priority>normal</priority>
99
+ <requires-reply>true</requires-reply>
100
+ [/tool]
101
+
102
+ 2b. Send a message (JSON format):
103
+ {"actions": [{"type": "send-message", "recipient": "agent-fullstack-developer-agent-1234567890123", "subject": "Need assistance with code review", "message": "Could you review the authentication module I just implemented?", "priority": "normal", "requires-reply": true}]}
104
+
105
+ IMPORTANT: Always use the full agent ID (like "agent-fullstack-developer-agent-1234567890123") as the recipient, not just the name. Get the exact ID from get-available-agents first.
106
+
107
+ 3. Send with attachments (XML format):
108
+ [tool]
109
+ <action>send-message</action>
110
+ <recipient>agent-id-456</recipient>
111
+ <subject>Analysis results</subject>
112
+ <message>Here are the test results you requested</message>
113
+ <attachments>[{"path": "/reports/test-results.pdf", "type": "pdf"}]</attachments>
114
+ [/tool]
115
+
116
+ 4. Reply to a message:
117
+ [tool]
118
+ <action>reply-to-message</action>
119
+ <message-id>msg-789</message-id>
120
+ <message>Thanks for the review. I've addressed all your comments.</message>
121
+ <cc-recipients>["agent-id-111"]</cc-recipients>
122
+ [/tool]
123
+
124
+ 5. Get unreplied messages:
125
+ [tool]
126
+ <action>get-unreplied-messages</action>
127
+ <include-low-priority>false</include-low-priority>
128
+ [/tool]
129
+
130
+ 6. End a conversation:
131
+ [tool]
132
+ <action>mark-conversation-ended</action>
133
+ <conversation-id>conv-xyz</conversation-id>
134
+ <reason>Task completed successfully</reason>
135
+ [/tool]
136
+
137
+ Safety Guidelines:
138
+ - Maximum ${this.config.maxConversationDepth} replies per conversation thread
139
+ - Maximum ${this.config.maxRecipientsPerMessage} recipients per message
140
+ - Conversations auto-expire after ${this.config.conversationTimeout / 60000} minutes of inactivity
141
+ - Avoid reply-all unless necessary to prevent message storms
142
+ - Mark conversations as ended when goals are achieved
143
+
144
+ Important Notes:
145
+ - Messages are delivered asynchronously
146
+ - Attachments must be readable files under ${this.config.maxAttachmentSize / 1024 / 1024}MB
147
+ - Use clear subjects to help recipients prioritize
148
+ - Check unreplied messages regularly to maintain communication flow
149
+ `.trim();
150
+ }
151
+
152
+ /**
153
+ * Parse tool parameters from command content
154
+ */
155
+ parseParameters(content) {
156
+ // Handle JSON format (for direct tool calls)
157
+ if (typeof content === 'object' && content !== null) {
158
+ // If it's already an object, extract the parameters
159
+ if (content.actions && Array.isArray(content.actions) && content.actions.length > 0) {
160
+ // Handle format: {"actions": [{"type": "get-available-agents", ...}]}
161
+ const action = content.actions[0];
162
+ return {
163
+ action: action.type,
164
+ ...action
165
+ };
166
+ } else if (content.action || content.type) {
167
+ // Handle format: {"action": "get-available-agents", ...}
168
+ return {
169
+ action: content.action || content.type,
170
+ ...content
171
+ };
172
+ }
173
+ return content;
174
+ }
175
+
176
+ // Handle string content (could be JSON string or XML)
177
+ if (typeof content === 'string') {
178
+ // Try parsing as JSON first
179
+ if (content.trim().startsWith('{')) {
180
+ try {
181
+ const parsed = JSON.parse(content);
182
+ return this.parseParameters(parsed); // Recursive call to handle the parsed object
183
+ } catch (error) {
184
+ // Not valid JSON, continue to XML parsing
185
+ }
186
+ }
187
+
188
+ // Parse XML-style commands for agent communication
189
+ const parameters = {};
190
+
191
+ // Extract action parameter
192
+ const actionMatch = content.match(/<action[^>]*>([^<]+)<\/action>/);
193
+ if (actionMatch) {
194
+ parameters.action = actionMatch[1].trim();
195
+ }
196
+
197
+ // Extract other parameters like recipient, subject, message, etc.
198
+ const tags = [
199
+ 'recipient', 'recipients', 'subject', 'message', 'attachments',
200
+ 'priority', 'requires-reply', 'message-id', 'cc-recipients',
201
+ 'include-low-priority', 'conversation-id', 'reason', 'mark-resolved'
202
+ ];
203
+
204
+ for (const tag of tags) {
205
+ const regex = new RegExp(`<${tag.replace('-', '\\-')}[^>]*>(.*?)<\\/${tag.replace('-', '\\-')}>`, 's');
206
+ const match = content.match(regex);
207
+ if (match) {
208
+ let value = match[1].trim();
209
+ // Try to parse JSON values
210
+ if (value.startsWith('[') || value.startsWith('{') || value === 'true' || value === 'false') {
211
+ try {
212
+ value = JSON.parse(value);
213
+ } catch {
214
+ // Keep as string if JSON parsing fails
215
+ }
216
+ }
217
+ // Convert kebab-case to camelCase for parameter names
218
+ const paramName = tag.replace(/-(.)/g, (_, char) => char.toUpperCase());
219
+ parameters[paramName] = value;
220
+ }
221
+ }
222
+
223
+ // Extract attributes from action tag if present
224
+ const actionWithAttribs = content.match(/<action([^>]*)>([^<]+)<\/action>/);
225
+ if (actionWithAttribs && actionWithAttribs[1]) {
226
+ // Parse attributes like priority="high", requires-reply="true"
227
+ const attribMatches = actionWithAttribs[1].matchAll(/([\w-]+)=["']([^"']+)["']/g);
228
+ for (const match of attribMatches) {
229
+ const key = match[1].replace(/-(.)/g, (_, char) => char.toUpperCase()); // Convert kebab-case to camelCase
230
+ parameters[key] = match[2];
231
+ }
232
+ }
233
+
234
+ return parameters;
235
+ }
236
+
237
+ // Fallback
238
+ return content || {};
239
+ }
240
+
241
+ /**
242
+ * Execute the tool action
243
+ */
244
+ async execute(parameters = {}, context = {}) {
245
+ const { action } = parameters;
246
+
247
+ if (!action) {
248
+ throw new Error('Action parameter is required');
249
+ }
250
+
251
+ // Validate requesting agent exists
252
+ const requestingAgentId = context.agentId;
253
+ if (!requestingAgentId) {
254
+ throw new Error('Agent ID is required in context');
255
+ }
256
+
257
+ // Route to appropriate action handler
258
+ switch (action.toLowerCase()) {
259
+ case 'get-available-agents':
260
+ return await this.getAvailableAgents(requestingAgentId, parameters, context);
261
+
262
+ case 'send-message':
263
+ return await this.sendMessage(requestingAgentId, parameters, context);
264
+
265
+ case 'reply-to-message':
266
+ return await this.replyToMessage(requestingAgentId, parameters, context);
267
+
268
+ case 'get-unreplied-messages':
269
+ return await this.getUnrepliedMessages(requestingAgentId, parameters, context);
270
+
271
+ case 'mark-conversation-ended':
272
+ return await this.markConversationEnded(requestingAgentId, parameters, context);
273
+
274
+ default:
275
+ throw new Error(`Unknown action: ${action}`);
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Get list of available agents
281
+ */
282
+ async getAvailableAgents(requestingAgentId, parameters, context) {
283
+ try {
284
+ // Get agent pool from context
285
+ const agentPool = context.agentPool;
286
+ if (!agentPool) {
287
+ throw new Error('Agent pool not available in context');
288
+ }
289
+
290
+ // Get all active agents
291
+ const agents = await agentPool.listActiveAgents();
292
+
293
+ // Filter out requesting agent and format response
294
+ const availableAgents = agents
295
+ .filter(agent => agent.id !== requestingAgentId && !agent.isPaused)
296
+ .map(agent => ({
297
+ id: agent.id,
298
+ name: agent.name,
299
+ type: agent.type,
300
+ capabilities: agent.capabilities,
301
+ status: agent.status,
302
+ messageStats: this.agentMessageCounts.get(agent.id) || { sent: 0, received: 0 },
303
+ activeConversations: (this.agentConversations.get(agent.id) || new Set()).size
304
+ }));
305
+
306
+ return {
307
+ success: true,
308
+ agents: availableAgents,
309
+ totalActive: availableAgents.length,
310
+ timestamp: new Date().toISOString()
311
+ };
312
+
313
+ } catch (error) {
314
+ return {
315
+ success: false,
316
+ error: error.message
317
+ };
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Send a message to another agent
323
+ */
324
+ async sendMessage(senderAgentId, parameters, context) {
325
+ try {
326
+ const {
327
+ recipient,
328
+ recipients, // Support both single and multiple
329
+ subject,
330
+ message,
331
+ attachments,
332
+ priority = 'normal',
333
+ 'requires-reply': requiresReply = false
334
+ } = parameters;
335
+
336
+ // Validate required fields
337
+ if (!subject || !message) {
338
+ throw new Error('Subject and message are required');
339
+ }
340
+
341
+ // Determine recipients
342
+ const recipientList = this._parseRecipients(recipient, recipients);
343
+ if (recipientList.length === 0) {
344
+ throw new Error('At least one recipient is required');
345
+ }
346
+
347
+ // Validate recipient count
348
+ if (recipientList.length > this.config.maxRecipientsPerMessage) {
349
+ throw new Error(`Maximum ${this.config.maxRecipientsPerMessage} recipients allowed`);
350
+ }
351
+
352
+ // Get agent pool and sender agent
353
+ const agentPool = context.agentPool;
354
+ const senderAgent = await agentPool.getAgent(senderAgentId);
355
+ if (!senderAgent) {
356
+ throw new Error('Sender agent not found');
357
+ }
358
+
359
+ // CRITICAL: Check if sender can send messages to recipients
360
+ const blockedRecipients = [];
361
+ for (const recipientId of recipientList) {
362
+ const canSend = await this._canSendMessage(senderAgent, recipientId, context);
363
+ if (!canSend.allowed) {
364
+ blockedRecipients.push({
365
+ recipientId,
366
+ reason: canSend.reason,
367
+ waitUntil: canSend.waitUntil
368
+ });
369
+ }
370
+ }
371
+
372
+ // If any recipients are blocked, apply delay and return
373
+ if (blockedRecipients.length > 0) {
374
+ const earliestAllowedTime = Math.max(...blockedRecipients.map(b => b.waitUntil || 0));
375
+ const delayUntil = new Date(earliestAllowedTime);
376
+
377
+ // Apply delay using existing infrastructure
378
+ await agentPool.updateAgent(senderAgentId, {
379
+ delayEndTime: delayUntil.toISOString()
380
+ });
381
+
382
+ const delaySeconds = Math.ceil((earliestAllowedTime - Date.now()) / 1000);
383
+
384
+ return {
385
+ success: true,
386
+ delayed: true,
387
+ delayUntil: delayUntil.toISOString(),
388
+ delaySeconds,
389
+ message: `Waiting ${delaySeconds}s before next message. Recipients need time to respond.`,
390
+ blockedRecipients: blockedRecipients.map(b => ({
391
+ recipientId: b.recipientId,
392
+ reason: b.reason
393
+ }))
394
+ };
395
+ }
396
+
397
+ // Validate recipients exist and get their names
398
+ const recipientAgents = {};
399
+ const invalidRecipients = [];
400
+
401
+ for (const recipientId of recipientList) {
402
+ const agent = await agentPool.getAgent(recipientId);
403
+ if (!agent) {
404
+ invalidRecipients.push(recipientId);
405
+ } else {
406
+ recipientAgents[recipientId] = agent.name;
407
+ }
408
+ }
409
+
410
+ // If any recipients are invalid, provide helpful error with suggestions
411
+ if (invalidRecipients.length > 0) {
412
+ const availableAgents = await agentPool.listActiveAgents();
413
+ const suggestions = availableAgents
414
+ .filter(agent => agent.id !== senderAgentId && !agent.isPaused)
415
+ .map(agent => `- ${agent.name} (ID: ${agent.id})`)
416
+ .join('\n');
417
+
418
+ return {
419
+ success: false,
420
+ error: `Recipient agent(s) not found: ${invalidRecipients.join(', ')}`,
421
+ suggestion: `Available agents you can message:\n${suggestions}`,
422
+ availableAgents: availableAgents.map(agent => ({
423
+ id: agent.id,
424
+ name: agent.name,
425
+ capabilities: agent.capabilities
426
+ }))
427
+ };
428
+ }
429
+
430
+ // Get sender agent name
431
+ const senderName = senderAgent ? senderAgent.name : senderAgentId;
432
+
433
+ // Process attachments if provided
434
+ const processedAttachments = await this._processAttachments(attachments, senderAgentId);
435
+
436
+ // Create message object
437
+ const messageId = this._generateMessageId();
438
+ const conversationId = this._generateConversationId();
439
+ const timestamp = new Date().toISOString();
440
+
441
+ const messageObj = {
442
+ id: messageId,
443
+ conversationId,
444
+ sender: senderAgentId,
445
+ senderName,
446
+ recipients: recipientList,
447
+ recipientNames: recipientAgents,
448
+ subject,
449
+ content: message,
450
+ attachments: processedAttachments,
451
+ priority,
452
+ requiresReply,
453
+ timestamp,
454
+ status: 'sent',
455
+ replies: [],
456
+ metadata: {
457
+ depth: 0,
458
+ isRoot: true
459
+ }
460
+ };
461
+
462
+ // Store message
463
+ this.messages.set(messageId, messageObj);
464
+
465
+ // Initialize conversation
466
+ this.conversations.set(conversationId, {
467
+ id: conversationId,
468
+ rootMessageId: messageId,
469
+ participants: [senderAgentId, ...recipientList],
470
+ startTime: timestamp,
471
+ lastActivity: timestamp,
472
+ status: 'active',
473
+ messageCount: 1
474
+ });
475
+
476
+ // Update inboxes
477
+ for (const recipientId of recipientList) {
478
+ if (!this.agentInboxes.has(recipientId)) {
479
+ this.agentInboxes.set(recipientId, new Set());
480
+ }
481
+ this.agentInboxes.get(recipientId).add(messageId);
482
+
483
+ // Track conversations
484
+ if (!this.agentConversations.has(recipientId)) {
485
+ this.agentConversations.set(recipientId, new Set());
486
+ }
487
+ this.agentConversations.get(recipientId).add(conversationId);
488
+ }
489
+
490
+ // Track sender's conversation
491
+ if (!this.agentConversations.has(senderAgentId)) {
492
+ this.agentConversations.set(senderAgentId, new Set());
493
+ }
494
+ this.agentConversations.get(senderAgentId).add(conversationId);
495
+
496
+ // Update message counts
497
+ this._updateMessageCounts(senderAgentId, 'sent');
498
+ for (const recipientId of recipientList) {
499
+ this._updateMessageCounts(recipientId, 'received');
500
+ }
501
+
502
+ // CRITICAL: Update inter-agent conversation tracking
503
+ for (const recipientId of recipientList) {
504
+ await this._updateConversationTracking(senderAgentId, recipientId, 'sent', context);
505
+ }
506
+
507
+ // Notify recipients through agent pool
508
+ await this._notifyRecipients(messageObj, context);
509
+
510
+ // Broadcast to WebSocket for UI visibility
511
+ await this._broadcastToUI(messageObj, 'agent-message-sent', context);
512
+
513
+ return {
514
+ success: true,
515
+ messageId,
516
+ conversationId,
517
+ recipients: recipientList,
518
+ timestamp,
519
+ message: 'Message sent successfully'
520
+ };
521
+
522
+ } catch (error) {
523
+ return {
524
+ success: false,
525
+ error: error.message
526
+ };
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Reply to an existing message
532
+ */
533
+ async replyToMessage(senderAgentId, parameters, context) {
534
+ try {
535
+ const {
536
+ 'message-id': originalMessageId,
537
+ message,
538
+ 'cc-recipients': ccRecipients,
539
+ attachments,
540
+ 'mark-resolved': markResolved = false
541
+ } = parameters;
542
+
543
+ // Validate required fields
544
+ if (!originalMessageId || !message) {
545
+ throw new Error('Original message ID and reply content are required');
546
+ }
547
+
548
+ // Get original message
549
+ const originalMessage = this.messages.get(originalMessageId);
550
+ if (!originalMessage) {
551
+ throw new Error(`Original message not found: ${originalMessageId}`);
552
+ }
553
+
554
+ // Verify sender was a recipient or sender of original message
555
+ const isParticipant = originalMessage.sender === senderAgentId ||
556
+ originalMessage.recipients.includes(senderAgentId);
557
+ if (!isParticipant) {
558
+ throw new Error('You are not a participant in this conversation');
559
+ }
560
+
561
+ // Check conversation depth to prevent infinite loops
562
+ const conversation = this.conversations.get(originalMessage.conversationId);
563
+ const currentDepth = this._getConversationDepth(originalMessage.conversationId);
564
+
565
+ if (currentDepth >= this.config.maxConversationDepth) {
566
+ return {
567
+ success: false,
568
+ error: `Conversation depth limit reached (${this.config.maxConversationDepth}). Please start a new conversation.`,
569
+ suggestion: 'Consider marking this conversation as ended and starting fresh if needed.'
570
+ };
571
+ }
572
+
573
+ // Determine reply recipients
574
+ let replyRecipients = [originalMessage.sender];
575
+ if (originalMessage.sender === senderAgentId) {
576
+ // If replying to own message, reply to original recipients
577
+ replyRecipients = originalMessage.recipients;
578
+ }
579
+
580
+ // Add CC recipients if specified
581
+ if (ccRecipients) {
582
+ const ccList = this._parseRecipients(null, ccRecipients);
583
+ replyRecipients = [...new Set([...replyRecipients, ...ccList])];
584
+ }
585
+
586
+ // Remove sender from recipients
587
+ replyRecipients = replyRecipients.filter(id => id !== senderAgentId);
588
+
589
+ // Validate recipient count
590
+ if (replyRecipients.length > this.config.maxRecipientsPerMessage) {
591
+ throw new Error(`Maximum ${this.config.maxRecipientsPerMessage} recipients allowed`);
592
+ }
593
+
594
+ // Get agent names
595
+ const agentPool = context.agentPool;
596
+ const senderAgent = await agentPool.getAgent(senderAgentId);
597
+ const senderName = senderAgent ? senderAgent.name : senderAgentId;
598
+
599
+ const recipientAgents = {};
600
+ for (const recipientId of replyRecipients) {
601
+ const agent = await agentPool.getAgent(recipientId);
602
+ if (agent) {
603
+ recipientAgents[recipientId] = agent.name;
604
+ }
605
+ }
606
+
607
+ // Process attachments
608
+ const processedAttachments = await this._processAttachments(attachments, senderAgentId);
609
+
610
+ // Create reply message
611
+ const replyMessageId = this._generateMessageId();
612
+ const timestamp = new Date().toISOString();
613
+
614
+ const replyMessage = {
615
+ id: replyMessageId,
616
+ conversationId: originalMessage.conversationId,
617
+ sender: senderAgentId,
618
+ senderName,
619
+ recipients: replyRecipients,
620
+ recipientNames: recipientAgents,
621
+ subject: `Re: ${originalMessage.subject}`,
622
+ content: message,
623
+ attachments: processedAttachments,
624
+ priority: originalMessage.priority,
625
+ requiresReply: !markResolved,
626
+ timestamp,
627
+ status: 'sent',
628
+ replies: [],
629
+ metadata: {
630
+ depth: currentDepth + 1,
631
+ isRoot: false,
632
+ inReplyTo: originalMessageId
633
+ }
634
+ };
635
+
636
+ // Store reply
637
+ this.messages.set(replyMessageId, replyMessage);
638
+ originalMessage.replies.push(replyMessageId);
639
+
640
+ // Update conversation
641
+ conversation.lastActivity = timestamp;
642
+ conversation.messageCount++;
643
+ if (markResolved) {
644
+ conversation.status = 'resolved';
645
+ }
646
+
647
+ // Update inboxes
648
+ for (const recipientId of replyRecipients) {
649
+ if (!this.agentInboxes.has(recipientId)) {
650
+ this.agentInboxes.set(recipientId, new Set());
651
+ }
652
+ this.agentInboxes.get(recipientId).add(replyMessageId);
653
+ }
654
+
655
+ // Update message counts
656
+ this._updateMessageCounts(senderAgentId, 'sent');
657
+ for (const recipientId of replyRecipients) {
658
+ this._updateMessageCounts(recipientId, 'received');
659
+ }
660
+
661
+ // CRITICAL: Update inter-agent conversation tracking for replies
662
+ for (const recipientId of replyRecipients) {
663
+ await this._updateConversationTracking(senderAgentId, recipientId, 'replied', context);
664
+ }
665
+
666
+ // Notify recipients
667
+ await this._notifyRecipients(replyMessage, context);
668
+
669
+ // Broadcast to WebSocket for UI visibility
670
+ await this._broadcastToUI(replyMessage, 'agent-message-reply', context);
671
+
672
+ return {
673
+ success: true,
674
+ messageId: replyMessageId,
675
+ conversationId: originalMessage.conversationId,
676
+ recipients: replyRecipients,
677
+ depth: currentDepth + 1,
678
+ timestamp,
679
+ conversationStatus: conversation.status
680
+ };
681
+
682
+ } catch (error) {
683
+ return {
684
+ success: false,
685
+ error: error.message
686
+ };
687
+ }
688
+ }
689
+
690
+ /**
691
+ * Get unreplied messages for an agent
692
+ */
693
+ async getUnrepliedMessages(agentId, parameters, context) {
694
+ try {
695
+ const {
696
+ 'include-low-priority': includeLowPriority = false,
697
+ 'max-age-hours': maxAgeHours = 24
698
+ } = parameters;
699
+
700
+ const inbox = this.agentInboxes.get(agentId) || new Set();
701
+ const unrepliedMessages = [];
702
+ const maxAge = Date.now() - (maxAgeHours * 3600000);
703
+
704
+ for (const messageId of inbox) {
705
+ const message = this.messages.get(messageId);
706
+ if (!message) continue;
707
+
708
+ // Skip old messages
709
+ if (new Date(message.timestamp).getTime() < maxAge) continue;
710
+
711
+ // Skip low priority if not requested
712
+ if (message.priority === 'low' && !includeLowPriority) continue;
713
+
714
+ // Check if message requires reply and hasn't been replied to by this agent
715
+ if (message.requiresReply) {
716
+ const hasReplied = this._hasAgentReplied(agentId, message);
717
+ if (!hasReplied) {
718
+ const conversation = this.conversations.get(message.conversationId);
719
+ unrepliedMessages.push({
720
+ messageId: message.id,
721
+ conversationId: message.conversationId,
722
+ sender: message.sender,
723
+ subject: message.subject,
724
+ preview: message.content.substring(0, 100) + '...',
725
+ priority: message.priority,
726
+ timestamp: message.timestamp,
727
+ hasAttachments: message.attachments.length > 0,
728
+ conversationStatus: conversation?.status || 'unknown',
729
+ depth: message.metadata.depth
730
+ });
731
+ }
732
+ }
733
+ }
734
+
735
+ // Sort by priority and timestamp
736
+ unrepliedMessages.sort((a, b) => {
737
+ const priorityOrder = { high: 0, normal: 1, low: 2 };
738
+ const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
739
+ if (priorityDiff !== 0) return priorityDiff;
740
+ return new Date(b.timestamp) - new Date(a.timestamp);
741
+ });
742
+
743
+ return {
744
+ success: true,
745
+ messages: unrepliedMessages,
746
+ total: unrepliedMessages.length,
747
+ inbox: {
748
+ total: inbox.size,
749
+ activeConversations: (this.agentConversations.get(agentId) || new Set()).size
750
+ }
751
+ };
752
+
753
+ } catch (error) {
754
+ return {
755
+ success: false,
756
+ error: error.message
757
+ };
758
+ }
759
+ }
760
+
761
+ /**
762
+ * Mark a conversation as ended
763
+ */
764
+ async markConversationEnded(agentId, parameters, context) {
765
+ try {
766
+ const {
767
+ 'conversation-id': conversationId,
768
+ reason = 'Conversation ended by agent'
769
+ } = parameters;
770
+
771
+ if (!conversationId) {
772
+ throw new Error('Conversation ID is required');
773
+ }
774
+
775
+ const conversation = this.conversations.get(conversationId);
776
+ if (!conversation) {
777
+ throw new Error(`Conversation not found: ${conversationId}`);
778
+ }
779
+
780
+ // Verify agent is a participant
781
+ if (!conversation.participants.includes(agentId)) {
782
+ throw new Error('You are not a participant in this conversation');
783
+ }
784
+
785
+ // Update conversation status
786
+ conversation.status = 'ended';
787
+ conversation.endTime = new Date().toISOString();
788
+ conversation.endReason = reason;
789
+ conversation.endedBy = agentId;
790
+
791
+ // Remove from active conversations for all participants
792
+ for (const participantId of conversation.participants) {
793
+ const agentConvs = this.agentConversations.get(participantId);
794
+ if (agentConvs) {
795
+ agentConvs.delete(conversationId);
796
+ }
797
+ }
798
+
799
+ return {
800
+ success: true,
801
+ conversationId,
802
+ status: 'ended',
803
+ reason,
804
+ timestamp: conversation.endTime
805
+ };
806
+
807
+ } catch (error) {
808
+ return {
809
+ success: false,
810
+ error: error.message
811
+ };
812
+ }
813
+ }
814
+
815
+ /**
816
+ * Initialize storage directory
817
+ * @private
818
+ */
819
+ async _initializeStorage() {
820
+ try {
821
+ await fs.mkdir(this.config.storageDir, { recursive: true });
822
+ const attachmentsDir = path.join(this.config.storageDir, 'attachments');
823
+ await fs.mkdir(attachmentsDir, { recursive: true });
824
+ } catch (error) {
825
+ console.error('Failed to initialize message storage:', error);
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Parse recipients from parameters
831
+ * @private
832
+ */
833
+ _parseRecipients(recipient, recipients) {
834
+ let recipientList = [];
835
+
836
+ if (recipient) {
837
+ recipientList.push(recipient);
838
+ }
839
+
840
+ if (recipients) {
841
+ if (typeof recipients === 'string') {
842
+ try {
843
+ const parsed = JSON.parse(recipients);
844
+ recipientList = [...recipientList, ...(Array.isArray(parsed) ? parsed : [parsed])];
845
+ } catch {
846
+ recipientList.push(recipients);
847
+ }
848
+ } else if (Array.isArray(recipients)) {
849
+ recipientList = [...recipientList, ...recipients];
850
+ }
851
+ }
852
+
853
+ // Remove duplicates
854
+ return [...new Set(recipientList)];
855
+ }
856
+
857
+ /**
858
+ * Process and validate attachments
859
+ * @private
860
+ */
861
+ async _processAttachments(attachments, agentId) {
862
+ if (!attachments) return [];
863
+
864
+ let attachmentList = [];
865
+ if (typeof attachments === 'string') {
866
+ try {
867
+ attachmentList = JSON.parse(attachments);
868
+ } catch {
869
+ return [];
870
+ }
871
+ } else {
872
+ attachmentList = attachments;
873
+ }
874
+
875
+ if (!Array.isArray(attachmentList)) {
876
+ attachmentList = [attachmentList];
877
+ }
878
+
879
+ // Validate attachment count
880
+ if (attachmentList.length > this.config.maxAttachmentsPerMessage) {
881
+ throw new Error(`Maximum ${this.config.maxAttachmentsPerMessage} attachments allowed`);
882
+ }
883
+
884
+ const processedAttachments = [];
885
+
886
+ for (const attachment of attachmentList) {
887
+ if (!attachment.path) continue;
888
+
889
+ try {
890
+ // Check file exists and size
891
+ const stats = await fs.stat(attachment.path);
892
+ if (stats.size > this.config.maxAttachmentSize) {
893
+ throw new Error(`Attachment exceeds size limit: ${attachment.path}`);
894
+ }
895
+
896
+ // Copy to storage
897
+ const attachmentId = this._generateAttachmentId();
898
+ const ext = path.extname(attachment.path);
899
+ const storagePath = path.join(this.config.storageDir, 'attachments', `${attachmentId}${ext}`);
900
+
901
+ await fs.copyFile(attachment.path, storagePath);
902
+
903
+ processedAttachments.push({
904
+ id: attachmentId,
905
+ originalPath: attachment.path,
906
+ storagePath,
907
+ type: attachment.type || 'file',
908
+ size: stats.size,
909
+ name: path.basename(attachment.path)
910
+ });
911
+
912
+ } catch (error) {
913
+ console.error(`Failed to process attachment: ${attachment.path}`, error);
914
+ }
915
+ }
916
+
917
+ return processedAttachments;
918
+ }
919
+
920
+ /**
921
+ * Notify recipients of new message
922
+ * @private
923
+ */
924
+ async _notifyRecipients(message, context) {
925
+ const agentPool = context.agentPool;
926
+ if (!agentPool) return;
927
+
928
+ for (const recipientId of message.recipients) {
929
+ try {
930
+ // Send both a notification AND inject message into conversation
931
+
932
+ // 1. Standard notification (for system awareness)
933
+ await agentPool.notifyAgent(recipientId, {
934
+ type: 'agent-communication',
935
+ from: message.sender,
936
+ conversationId: message.conversationId,
937
+ content: `📨 New message from ${message.senderName}: "${message.subject}"`,
938
+ messageId: message.id,
939
+ priority: message.priority,
940
+ requiresResponse: message.requiresReply
941
+ });
942
+
943
+ // 2. Inject the actual message content directly into recipient's conversation
944
+ const recipient = await agentPool.getAgent(recipientId);
945
+ if (recipient) {
946
+ const messageContent = `📨 **Inter-Agent Message**
947
+ **From:** ${message.senderName} (${message.sender})
948
+ **Subject:** ${message.subject}
949
+ **Priority:** ${message.priority}
950
+ **Requires Reply:** ${message.requiresReply ? 'Yes' : 'No'}
951
+
952
+ **Message:**
953
+ ${message.content}
954
+
955
+ ${message.attachments.length > 0 ? `**Attachments:** ${message.attachments.length} file(s)` : ''}
956
+
957
+ *You can reply using the agentcommunication tool with action="reply-to-message" and message-id="${message.id}"*`;
958
+
959
+ const directMessage = {
960
+ id: `agent-comm-${message.id}`,
961
+ conversationId: message.conversationId,
962
+ agentId: message.sender,
963
+ content: messageContent,
964
+ role: 'system', // System message so it's clearly visible
965
+ timestamp: message.timestamp,
966
+ type: 'agent-communication',
967
+ metadata: {
968
+ originalMessageId: message.id,
969
+ fromAgent: message.sender,
970
+ requiresResponse: message.requiresReply,
971
+ priority: message.priority
972
+ }
973
+ };
974
+
975
+ // Add to full conversation
976
+ recipient.conversations.full.messages.push(directMessage);
977
+ recipient.conversations.full.lastUpdated = new Date().toISOString();
978
+
979
+ // Add to current model conversation if active
980
+ if (recipient.currentModel && recipient.conversations[recipient.currentModel]) {
981
+ recipient.conversations[recipient.currentModel].messages.push(directMessage);
982
+ recipient.conversations[recipient.currentModel].lastUpdated = new Date().toISOString();
983
+ }
984
+
985
+ // Persist the updated state
986
+ await agentPool.persistAgentState(recipientId);
987
+
988
+ // Queue message using new architecture
989
+ console.log(`📬 Queueing inter-agent message for scheduler processing`, {
990
+ recipientId,
991
+ sender: message.sender,
992
+ subject: message.subject,
993
+ hasSessionId: !!context.sessionId
994
+ });
995
+
996
+ await agentPool.addInterAgentMessage(recipientId, {
997
+ id: message.id,
998
+ messageId: message.id,
999
+ sender: message.sender,
1000
+ senderName: message.senderName,
1001
+ subject: message.subject,
1002
+ content: message.content,
1003
+ attachments: message.attachments,
1004
+ priority: message.priority,
1005
+ requiresReply: message.requiresReply,
1006
+ conversationId: message.conversationId,
1007
+ sessionId: context.sessionId,
1008
+ timestamp: new Date().toISOString()
1009
+ });
1010
+
1011
+ console.log(`Direct message injected and queued for processing: ${recipientId}`, {
1012
+ messageId: message.id,
1013
+ fromAgent: message.sender,
1014
+ subject: message.subject,
1015
+ priority: message.priority
1016
+ });
1017
+ }
1018
+
1019
+ } catch (error) {
1020
+ console.error(`Failed to notify agent ${recipientId}:`, error);
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Check if agent has replied to a message
1027
+ * @private
1028
+ */
1029
+ _hasAgentReplied(agentId, message) {
1030
+ for (const replyId of message.replies) {
1031
+ const reply = this.messages.get(replyId);
1032
+ if (reply && reply.sender === agentId) {
1033
+ return true;
1034
+ }
1035
+ // Recursively check nested replies
1036
+ if (reply && this._hasAgentReplied(agentId, reply)) {
1037
+ return true;
1038
+ }
1039
+ }
1040
+ return false;
1041
+ }
1042
+
1043
+ /**
1044
+ * Get conversation depth
1045
+ * @private
1046
+ */
1047
+ _getConversationDepth(conversationId) {
1048
+ const conversation = this.conversations.get(conversationId);
1049
+ if (!conversation) return 0;
1050
+
1051
+ let maxDepth = 0;
1052
+ const rootMessage = this.messages.get(conversation.rootMessageId);
1053
+ if (rootMessage) {
1054
+ maxDepth = this._getMessageDepth(rootMessage);
1055
+ }
1056
+
1057
+ return maxDepth;
1058
+ }
1059
+
1060
+ /**
1061
+ * Get message depth recursively
1062
+ * @private
1063
+ */
1064
+ _getMessageDepth(message, currentDepth = 0) {
1065
+ if (message.replies.length === 0) {
1066
+ return currentDepth;
1067
+ }
1068
+
1069
+ let maxDepth = currentDepth;
1070
+ for (const replyId of message.replies) {
1071
+ const reply = this.messages.get(replyId);
1072
+ if (reply) {
1073
+ const depth = this._getMessageDepth(reply, currentDepth + 1);
1074
+ maxDepth = Math.max(maxDepth, depth);
1075
+ }
1076
+ }
1077
+
1078
+ return maxDepth;
1079
+ }
1080
+
1081
+ /**
1082
+ * Update message counts for agent
1083
+ * @private
1084
+ */
1085
+ _updateMessageCounts(agentId, type) {
1086
+ if (!this.agentMessageCounts.has(agentId)) {
1087
+ this.agentMessageCounts.set(agentId, { sent: 0, received: 0 });
1088
+ }
1089
+
1090
+ const counts = this.agentMessageCounts.get(agentId);
1091
+ if (type === 'sent') {
1092
+ counts.sent++;
1093
+ } else {
1094
+ counts.received++;
1095
+ }
1096
+ }
1097
+
1098
+ /**
1099
+ * Generate unique message ID
1100
+ * @private
1101
+ */
1102
+ _generateMessageId() {
1103
+ return `msg-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
1104
+ }
1105
+
1106
+ /**
1107
+ * Generate unique conversation ID
1108
+ * @private
1109
+ */
1110
+ _generateConversationId() {
1111
+ return `conv-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
1112
+ }
1113
+
1114
+ /**
1115
+ * Generate unique attachment ID
1116
+ * @private
1117
+ */
1118
+ _generateAttachmentId() {
1119
+ return `att-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
1120
+ }
1121
+
1122
+ /**
1123
+ * Cleanup old messages and conversations
1124
+ * Called periodically to prevent memory growth
1125
+ */
1126
+ async cleanup() {
1127
+ const now = Date.now();
1128
+ const retentionCutoff = now - this.config.messageRetentionPeriod;
1129
+
1130
+ // Clean up old messages
1131
+ for (const [messageId, message] of this.messages.entries()) {
1132
+ const messageTime = new Date(message.timestamp).getTime();
1133
+ if (messageTime < retentionCutoff) {
1134
+ // Clean up attachments
1135
+ for (const attachment of message.attachments) {
1136
+ try {
1137
+ await fs.unlink(attachment.storagePath);
1138
+ } catch (error) {
1139
+ // Ignore errors for missing files
1140
+ }
1141
+ }
1142
+
1143
+ // Remove from inboxes
1144
+ for (const [agentId, inbox] of this.agentInboxes.entries()) {
1145
+ inbox.delete(messageId);
1146
+ }
1147
+
1148
+ this.messages.delete(messageId);
1149
+ }
1150
+ }
1151
+
1152
+ // Clean up old conversations
1153
+ for (const [conversationId, conversation] of this.conversations.entries()) {
1154
+ const lastActivity = new Date(conversation.lastActivity).getTime();
1155
+ if (lastActivity < retentionCutoff || conversation.status === 'ended') {
1156
+ // Remove from agent conversations
1157
+ for (const [agentId, convs] of this.agentConversations.entries()) {
1158
+ convs.delete(conversationId);
1159
+ }
1160
+
1161
+ this.conversations.delete(conversationId);
1162
+ }
1163
+ }
1164
+ }
1165
+
1166
+ /**
1167
+ * Broadcast message to WebSocket for UI visibility
1168
+ * @private
1169
+ */
1170
+ async _broadcastToUI(message, eventType, context) {
1171
+ try {
1172
+ // Build a formatted message for UI display
1173
+ const uiMessage = {
1174
+ type: 'agent-communication',
1175
+ eventType,
1176
+ timestamp: message.timestamp,
1177
+ messageId: message.id,
1178
+ conversationId: message.conversationId,
1179
+ sender: {
1180
+ id: message.sender,
1181
+ name: message.senderName
1182
+ },
1183
+ recipients: Object.entries(message.recipientNames || {}).map(([id, name]) => ({
1184
+ id,
1185
+ name
1186
+ })),
1187
+ subject: message.subject,
1188
+ content: message.content,
1189
+ priority: message.priority,
1190
+ requiresReply: message.requiresReply,
1191
+ hasAttachments: message.attachments && message.attachments.length > 0,
1192
+ attachmentCount: message.attachments ? message.attachments.length : 0,
1193
+ metadata: message.metadata
1194
+ };
1195
+
1196
+ // Try multiple broadcast methods
1197
+ // Method 1: Through agentPool if available
1198
+ if (context.agentPool && context.agentPool.messageProcessor) {
1199
+ const messageProcessor = context.agentPool.messageProcessor;
1200
+ if (messageProcessor && messageProcessor.orchestrator && messageProcessor.orchestrator.webServer) {
1201
+ // Use broadcastToSession - it will fallback to all connections if session not found
1202
+ messageProcessor.orchestrator.webServer.broadcastToSession(context.sessionId || 'web-session', {
1203
+ type: 'agent-communication',
1204
+ action: 'agent-communication',
1205
+ data: uiMessage
1206
+ });
1207
+ return;
1208
+ }
1209
+ }
1210
+
1211
+ // Method 2: Direct orchestrator access
1212
+ if (context.orchestrator && context.orchestrator.webServer) {
1213
+ context.orchestrator.webServer.broadcastToSession(context.sessionId || 'web-session', {
1214
+ type: 'agent-communication',
1215
+ action: 'agent-communication',
1216
+ data: uiMessage
1217
+ });
1218
+ return;
1219
+ }
1220
+
1221
+ // Method 3: Through global reference (if set during initialization)
1222
+ if (global.loxiaWebServer) {
1223
+ global.loxiaWebServer.broadcastToSession(context.sessionId || 'web-session', {
1224
+ type: 'agent-communication',
1225
+ action: 'agent-communication',
1226
+ data: uiMessage
1227
+ });
1228
+ }
1229
+ } catch (error) {
1230
+ // Don't fail the operation if broadcast fails
1231
+ console.error('Failed to broadcast agent message to UI:', error);
1232
+ }
1233
+ }
1234
+
1235
+ /**
1236
+ * Check if sender can send message to recipient
1237
+ * @private
1238
+ */
1239
+ async _canSendMessage(senderAgent, recipientId, context) {
1240
+ const agentPool = context.agentPool;
1241
+ const tracking = senderAgent.interAgentTracking;
1242
+
1243
+ // Initialize tracking for this recipient if needed
1244
+ if (!tracking.has(recipientId)) {
1245
+ tracking.set(recipientId, {
1246
+ lastSent: null,
1247
+ lastReceived: null,
1248
+ lastType: null
1249
+ });
1250
+ }
1251
+
1252
+ const recipientTracking = tracking.get(recipientId);
1253
+ const now = Date.now();
1254
+ const MIN_INTERVAL = 60 * 1000; // 1 minute
1255
+
1256
+ // Rule 1: Always allow if recipient has replied since our last message
1257
+ if (recipientTracking.lastType === 'received' ||
1258
+ (recipientTracking.lastReceived && recipientTracking.lastReceived > recipientTracking.lastSent)) {
1259
+ return { allowed: true };
1260
+ }
1261
+
1262
+ // Rule 2: Allow if minimum time has passed since last send
1263
+ if (recipientTracking.lastSent) {
1264
+ const timeSinceLastSend = now - recipientTracking.lastSent;
1265
+ if (timeSinceLastSend >= MIN_INTERVAL) {
1266
+ return { allowed: true };
1267
+ }
1268
+
1269
+ // Calculate when next send is allowed
1270
+ const nextAllowedTime = recipientTracking.lastSent + MIN_INTERVAL;
1271
+ return {
1272
+ allowed: false,
1273
+ reason: `Must wait ${Math.ceil((nextAllowedTime - now) / 1000)}s since last message`,
1274
+ waitUntil: nextAllowedTime
1275
+ };
1276
+ }
1277
+
1278
+ // Rule 3: First message to this recipient is always allowed
1279
+ return { allowed: true };
1280
+ }
1281
+
1282
+ /**
1283
+ * Update conversation tracking after message sent/received
1284
+ * @private
1285
+ */
1286
+ async _updateConversationTracking(senderAgentId, recipientId, action, context) {
1287
+ const agentPool = context.agentPool;
1288
+ const senderAgent = await agentPool.getAgent(senderAgentId);
1289
+ if (!senderAgent) return;
1290
+
1291
+ const now = Date.now();
1292
+
1293
+ // Update sender's tracking
1294
+ if (!senderAgent.interAgentTracking.has(recipientId)) {
1295
+ senderAgent.interAgentTracking.set(recipientId, {
1296
+ lastSent: null,
1297
+ lastReceived: null,
1298
+ lastType: null
1299
+ });
1300
+ }
1301
+
1302
+ const tracking = senderAgent.interAgentTracking.get(recipientId);
1303
+
1304
+ if (action === 'sent') {
1305
+ tracking.lastSent = now;
1306
+ tracking.lastType = 'sent';
1307
+ } else if (action === 'replied') {
1308
+ tracking.lastSent = now;
1309
+ tracking.lastType = 'sent'; // Reply is still a send action
1310
+ }
1311
+
1312
+ // Update recipient's tracking (they received a message)
1313
+ const recipientAgent = await agentPool.getAgent(recipientId);
1314
+ if (recipientAgent) {
1315
+ if (!recipientAgent.interAgentTracking.has(senderAgentId)) {
1316
+ recipientAgent.interAgentTracking.set(senderAgentId, {
1317
+ lastSent: null,
1318
+ lastReceived: null,
1319
+ lastType: null
1320
+ });
1321
+ }
1322
+
1323
+ const recipientTracking = recipientAgent.interAgentTracking.get(senderAgentId);
1324
+ recipientTracking.lastReceived = now;
1325
+ recipientTracking.lastType = 'received';
1326
+
1327
+ // Persist recipient agent state
1328
+ await agentPool.persistAgentState(recipientId);
1329
+ }
1330
+
1331
+ // Persist sender agent state
1332
+ await agentPool.persistAgentState(senderAgentId);
1333
+ }
1334
+
1335
+ /**
1336
+ * Set message processor for broadcasting
1337
+ * Called during tool initialization
1338
+ */
1339
+ setMessageProcessor(messageProcessor) {
1340
+ this.messageProcessor = messageProcessor;
1341
+ }
1342
+ }
1343
+
1344
+ export default AgentCommunicationTool;