@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,732 @@
1
+ /**
2
+ * MessageProcessor - Processes messages from agents, extracts tool commands, executes tools
3
+ *
4
+ * NEW ARCHITECTURE:
5
+ * - Only handles message queuing and tool execution
6
+ * - No scheduling or autonomous loops (handled by AgentScheduler)
7
+ * - Clean separation of concerns
8
+ */
9
+
10
+ import { AGENT_MODES, AGENT_MODE_STATES } from '../utilities/constants.js';
11
+ import TagParser from '../utilities/tagParser.js';
12
+ import { TOOL_IDS, COMMAND_FORMATS } from '../utilities/toolConstants.js';
13
+
14
+ class MessageProcessor {
15
+ constructor(config, logger, toolsRegistry, agentPool, contextManager, aiService, modelRouterService = null, modelsService = null) {
16
+ this.config = config;
17
+ this.logger = logger;
18
+ this.toolsRegistry = toolsRegistry;
19
+ this.agentPool = agentPool;
20
+ this.contextManager = contextManager;
21
+ this.aiService = aiService;
22
+ this.modelRouterService = modelRouterService;
23
+ this.modelsService = modelsService;
24
+
25
+ // Active async operations tracking
26
+ this.asyncOperations = new Map();
27
+
28
+ // Tool execution history
29
+ this.executionHistory = new Map();
30
+
31
+ // Operation ID counter
32
+ this.operationCounter = 0;
33
+
34
+ // WebSocket manager for real-time updates
35
+ this.webSocketManager = null;
36
+
37
+ // AgentScheduler reference
38
+ this.scheduler = null;
39
+
40
+ // Orchestrator reference (for backward compatibility)
41
+ this.orchestrator = null;
42
+
43
+ // Initialize TagParser for comprehensive tool command extraction
44
+ this.tagParser = new TagParser();
45
+ }
46
+
47
+ /**
48
+ * Set WebSocket manager for real-time UI updates
49
+ * @param {Object} webSocketManager - WebSocket manager instance
50
+ */
51
+ setWebSocketManager(webSocketManager) {
52
+ this.webSocketManager = webSocketManager;
53
+ this.logger?.info('WebSocket manager set for MessageProcessor', {
54
+ hasManager: !!webSocketManager
55
+ });
56
+ }
57
+
58
+ /**
59
+ * Set AgentScheduler reference
60
+ * @param {AgentScheduler} scheduler - AgentScheduler instance
61
+ */
62
+ setScheduler(scheduler) {
63
+ this.scheduler = scheduler;
64
+ this.logger?.info('AgentScheduler set for MessageProcessor', {
65
+ hasScheduler: !!scheduler
66
+ });
67
+ }
68
+
69
+ /**
70
+ * Main message processing entry point - NEW ARCHITECTURE
71
+ * Simply queues messages for scheduler processing
72
+ * @param {string} agentId - Target agent ID
73
+ * @param {string} message - Message content
74
+ * @param {Object} context - Message context
75
+ * @returns {Promise<Object>} Queuing result
76
+ */
77
+ async processMessage(agentId, message, context = {}) {
78
+ const agent = await this.agentPool.getAgent(agentId);
79
+ if (!agent) {
80
+ throw new Error(`Agent not found: ${agentId}`);
81
+ }
82
+
83
+ const messageString = typeof message === 'string' ? message : (message ? JSON.stringify(message) : '');
84
+ this.logger.info(`Queueing message for agent: ${agentId}`, {
85
+ messageLength: messageString.length,
86
+ messageType: typeof message,
87
+ isInterAgentMessage: context.isInterAgentMessage,
88
+ contextMessageType: context.messageType || 'user'
89
+ });
90
+
91
+ // Determine message type and queue appropriately
92
+ if (context.isInterAgentMessage) {
93
+ // Inter-agent message
94
+ await this.agentPool.addInterAgentMessage(agentId, {
95
+ content: message,
96
+ sender: context.originalSender,
97
+ senderName: context.senderName,
98
+ subject: context.subject || 'Inter-agent message',
99
+ timestamp: new Date().toISOString(),
100
+ sessionId: context.sessionId,
101
+ requiresReply: context.requiresReply || false
102
+ });
103
+ } else {
104
+ // User message
105
+ await this.agentPool.addUserMessage(agentId, {
106
+ content: message,
107
+ role: 'user',
108
+ timestamp: new Date().toISOString(),
109
+ contextReferences: context.contextReferences || [],
110
+ sessionId: context.sessionId
111
+ });
112
+ }
113
+
114
+ // Add agent to scheduler if not already active
115
+ if (this.scheduler) {
116
+ await this.scheduler.addAgent(agentId, {
117
+ triggeredBy: context.isInterAgentMessage ? 'inter-agent-message' : 'user-message',
118
+ sessionId: context.sessionId
119
+ });
120
+ }
121
+
122
+ return {
123
+ success: true,
124
+ message: 'Message queued for processing',
125
+ agentId: agentId,
126
+ queuedAt: new Date().toISOString()
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Unwrap TagParser format parameters
132
+ * TagParser wraps XML parameters in {value, attributes} objects
133
+ * This method unwraps them to direct values for tool consumption
134
+ * @param {Object} params - Parameters to unwrap
135
+ * @returns {Object} Unwrapped parameters
136
+ */
137
+ unwrapParameters(params) {
138
+ if (!params || typeof params !== 'object') {
139
+ return params;
140
+ }
141
+
142
+ const unwrapped = {};
143
+ for (const [key, value] of Object.entries(params)) {
144
+ if (value && typeof value === 'object' && 'value' in value && 'attributes' in value) {
145
+ // TagParser wrapped format: {value: "...", attributes: {}}
146
+ unwrapped[key] = value.value;
147
+
148
+ // Also preserve attributes if tool needs them
149
+ if (value.attributes && Object.keys(value.attributes).length > 0) {
150
+ unwrapped[`${key}_attributes`] = value.attributes;
151
+ }
152
+ } else {
153
+ // Already unwrapped or direct value
154
+ unwrapped[key] = value;
155
+ }
156
+ }
157
+
158
+ return unwrapped;
159
+ }
160
+
161
+ /**
162
+ * Extract tool commands from message content
163
+ * Supports multiple formats: XML, JSON, and simple bracket notation
164
+ * @param {string} message - Message containing tool commands
165
+ * @returns {Promise<Array>} Array of tool commands
166
+ */
167
+ async extractToolCommands(message) {
168
+ const commands = [];
169
+
170
+ // Use TagParser to extract XML and JSON format commands
171
+ const tagParserCommands = this.tagParser.extractToolCommands(message);
172
+
173
+ // Process TagParser commands and normalize them
174
+ for (const cmd of tagParserCommands) {
175
+ const normalized = this.tagParser.normalizeToolCommand(cmd);
176
+ commands.push({
177
+ toolId: normalized.toolId,
178
+ content: JSON.stringify(normalized.parameters), // Convert parameters to JSON string for tool execution
179
+ parameters: normalized.parameters,
180
+ type: normalized.type,
181
+ isAsync: normalized.parameters?.async === true,
182
+ raw: normalized.rawContent,
183
+ position: cmd.position || {}
184
+ });
185
+ }
186
+
187
+ // Also check for simple bracket notation [tool id="..."] for backward compatibility
188
+ const toolPattern = /\[tool\s+id="([^"]+)"(?:\s+async="(true|false)")?\]([\s\S]*?)\[\/tool\]/gi;
189
+
190
+ console.log('MessageProcessor DEBUG: checking bracket pattern on message length:', message.length);
191
+
192
+ let match;
193
+ while ((match = toolPattern.exec(message)) !== null) {
194
+ const [fullMatch, toolId, isAsync, content] = match;
195
+
196
+ console.log('MessageProcessor DEBUG: bracket pattern matched:', {
197
+ toolId: toolId.trim(),
198
+ contentLength: content.trim().length,
199
+ contentPreview: content.trim().substring(0, 100)
200
+ });
201
+
202
+ // Check if this command was already extracted by TagParser
203
+ const alreadyExtracted = commands.some(cmd =>
204
+ cmd.raw === fullMatch || (cmd.position.start === match.index && cmd.position.end === match.index + fullMatch.length)
205
+ );
206
+
207
+ if (!alreadyExtracted) {
208
+ console.log('MessageProcessor DEBUG: adding bracket command (not already extracted by TagParser)');
209
+
210
+ const trimmedContent = content.trim();
211
+
212
+ // Check if the content inside brackets contains XML tags
213
+ const hasXmlTags = /<[^>]+>/g.test(trimmedContent);
214
+
215
+ if (hasXmlTags) {
216
+ console.log('MessageProcessor DEBUG: detected XML content inside brackets, parsing with TagParser');
217
+
218
+ // Decode HTML entities before parsing XML
219
+ const decodedXmlContent = this.tagParser.decodeHtmlEntities(trimmedContent);
220
+ console.log('MessageProcessor DEBUG: HTML decoding changed content:', trimmedContent !== decodedXmlContent);
221
+
222
+ // Parse the XML content using TagParser
223
+ try {
224
+ const xmlParameters = this.tagParser.parseXMLParameters(decodedXmlContent);
225
+
226
+ console.log('MessageProcessor DEBUG: XML parameters extracted:', Object.keys(xmlParameters));
227
+
228
+ // Check if we got valid parameters
229
+ if (!xmlParameters || typeof xmlParameters !== 'object') {
230
+ throw new Error('Invalid XML parameters returned');
231
+ }
232
+
233
+ // Create a temporary XML command structure for normalization
234
+ const xmlCommand = {
235
+ type: COMMAND_FORMATS.XML,
236
+ toolId: toolId.trim(),
237
+ parameters: xmlParameters,
238
+ rawContent: decodedXmlContent
239
+ };
240
+
241
+ // Normalize it to get the actions array
242
+ const normalized = this.tagParser.normalizeToolCommand(xmlCommand);
243
+
244
+ console.log('MessageProcessor DEBUG: normalized XML command:', {
245
+ toolId: normalized.toolId,
246
+ hasActions: !!normalized.parameters.actions,
247
+ actionsLength: normalized.parameters.actions?.length || 0
248
+ });
249
+
250
+ // Add the properly parsed command
251
+ commands.push({
252
+ toolId: normalized.toolId,
253
+ content: JSON.stringify(normalized.parameters),
254
+ parameters: normalized.parameters,
255
+ type: COMMAND_FORMATS.XML, // Mark as XML since we parsed it
256
+ isAsync: isAsync === 'true',
257
+ raw: fullMatch,
258
+ position: {
259
+ start: match.index,
260
+ end: match.index + fullMatch.length
261
+ }
262
+ });
263
+
264
+ } catch (error) {
265
+ console.log('MessageProcessor DEBUG: XML parsing failed:', error.message);
266
+ console.log('MessageProcessor DEBUG: falling back to raw bracket format');
267
+
268
+ // Fall back to treating it as a simple bracket command
269
+ commands.push({
270
+ toolId: toolId.trim(),
271
+ content: trimmedContent,
272
+ type: COMMAND_FORMATS.BRACKET,
273
+ isAsync: isAsync === 'true',
274
+ raw: fullMatch,
275
+ position: {
276
+ start: match.index,
277
+ end: match.index + fullMatch.length
278
+ }
279
+ });
280
+ }
281
+ } else {
282
+ console.log('MessageProcessor DEBUG: no XML detected, treating as simple bracket command');
283
+
284
+ // Simple bracket command without XML content
285
+ commands.push({
286
+ toolId: toolId.trim(),
287
+ content: trimmedContent,
288
+ type: COMMAND_FORMATS.BRACKET,
289
+ isAsync: isAsync === 'true',
290
+ raw: fullMatch,
291
+ position: {
292
+ start: match.index,
293
+ end: match.index + fullMatch.length
294
+ }
295
+ });
296
+ }
297
+ } else {
298
+ console.log('MessageProcessor DEBUG: bracket command already extracted by TagParser, skipping');
299
+ }
300
+ }
301
+
302
+ // Extract agent redirects as well (for inter-agent communication)
303
+ const redirects = this.tagParser.extractAgentRedirects(message);
304
+ for (const redirect of redirects) {
305
+ commands.push({
306
+ toolId: TOOL_IDS.AGENT_COMMUNICATION,
307
+ content: JSON.stringify({
308
+ to: redirect.to,
309
+ message: redirect.content,
310
+ urgent: redirect.urgent,
311
+ requiresResponse: redirect.requiresResponse,
312
+ context: redirect.context
313
+ }),
314
+ type: COMMAND_FORMATS.REDIRECT,
315
+ isAsync: false,
316
+ raw: redirect.rawMatch,
317
+ position: {}
318
+ });
319
+ }
320
+
321
+ this.logger.debug(`Extracted ${commands.length} tool commands from message`, {
322
+ formats: commands.map(c => c.type),
323
+ tools: commands.map(c => c.toolId)
324
+ });
325
+
326
+ return commands;
327
+ }
328
+
329
+ /**
330
+ * Execute tool commands
331
+ * @param {Array} commands - Array of tool commands
332
+ * @param {Object} context - Execution context
333
+ * @returns {Promise<Array>} Array of execution results
334
+ */
335
+ async executeTools(commands, context) {
336
+ const results = [];
337
+
338
+ for (const command of commands) {
339
+ try {
340
+ const tool = this.toolsRegistry.getTool(command.toolId);
341
+
342
+ if (!tool) {
343
+ results.push({
344
+ toolId: command.toolId,
345
+ status: 'failed',
346
+ error: `Tool not found: ${command.toolId}`,
347
+ timestamp: new Date().toISOString()
348
+ });
349
+ continue;
350
+ }
351
+
352
+ this.logger.info(`Executing tool: ${command.toolId}`, {
353
+ agentId: context.agentId,
354
+ isAsync: command.isAsync
355
+ });
356
+
357
+ let result;
358
+ if (command.isAsync) {
359
+ result = await this.executeAsyncTool(command, tool, context);
360
+ } else {
361
+ // Synchronous tool execution
362
+ // If we have parameters object, use it. Otherwise parse the content.
363
+ let toolInput = command.parameters;
364
+
365
+ if (!toolInput && command.content) {
366
+ // Content is a string, need to parse it using tool's parseParameters method
367
+ if (typeof tool.parseParameters === 'function') {
368
+ try {
369
+ toolInput = tool.parseParameters(command.content);
370
+ this.logger?.debug(`Parsed parameters for tool: ${command.toolId}`, {
371
+ parsedKeys: Object.keys(toolInput)
372
+ });
373
+ } catch (error) {
374
+ this.logger?.warn(`Failed to parse parameters for tool: ${command.toolId}`, {
375
+ error: error.message
376
+ });
377
+ // Fall back to raw content
378
+ toolInput = command.content;
379
+ }
380
+ } else {
381
+ // Tool doesn't have parseParameters, use raw content
382
+ toolInput = command.content;
383
+ }
384
+ }
385
+
386
+ // CRITICAL FIX: Unwrap TagParser format before tool execution
387
+ // TagParser wraps XML parameters in {value, attributes} objects
388
+ // This unwrapping makes all tools work consistently
389
+ if (toolInput && typeof toolInput === 'object') {
390
+ toolInput = this.unwrapParameters(toolInput);
391
+ }
392
+
393
+ const toolResult = await tool.execute(toolInput, context);
394
+ result = {
395
+ toolId: command.toolId,
396
+ status: 'completed',
397
+ result: toolResult,
398
+ timestamp: new Date().toISOString()
399
+ };
400
+ }
401
+
402
+ results.push(result);
403
+
404
+ // Store in execution history
405
+ const historyKey = `${context.agentId}-${Date.now()}`;
406
+ this.executionHistory.set(historyKey, {
407
+ ...result,
408
+ agentId: context.agentId,
409
+ sessionId: context.sessionId
410
+ });
411
+
412
+ } catch (error) {
413
+ this.logger.error(`Tool execution failed: ${command.toolId}`, {
414
+ error: error.message,
415
+ agentId: context.agentId
416
+ });
417
+
418
+ results.push({
419
+ toolId: command.toolId,
420
+ status: 'failed',
421
+ error: error.message,
422
+ timestamp: new Date().toISOString()
423
+ });
424
+ }
425
+ }
426
+
427
+ return results;
428
+ }
429
+
430
+ /**
431
+ * Execute async tool
432
+ * @param {Object} command - Tool command
433
+ * @param {Object} tool - Tool instance
434
+ * @param {Object} context - Execution context
435
+ * @returns {Promise<Object>} Async operation reference
436
+ */
437
+ async executeAsyncTool(command, tool, context) {
438
+ const operationId = `async-${Date.now()}-${this.operationCounter++}`;
439
+
440
+ // Create async operation entry
441
+ const operation = {
442
+ id: operationId,
443
+ toolId: command.toolId,
444
+ agentId: context.agentId,
445
+ status: 'pending',
446
+ startTime: new Date().toISOString(),
447
+ context: context
448
+ };
449
+
450
+ this.asyncOperations.set(operationId, operation);
451
+
452
+ // Start async execution
453
+ // If we have parameters object, use it. Otherwise parse the content.
454
+ let toolInput = command.parameters;
455
+
456
+ if (!toolInput && command.content) {
457
+ // Content is a string, need to parse it using tool's parseParameters method
458
+ if (typeof tool.parseParameters === 'function') {
459
+ try {
460
+ toolInput = tool.parseParameters(command.content);
461
+ } catch (error) {
462
+ this.logger?.warn(`Failed to parse parameters for async tool: ${command.toolId}`, {
463
+ error: error.message
464
+ });
465
+ // Fall back to raw content
466
+ toolInput = command.content;
467
+ }
468
+ } else {
469
+ // Tool doesn't have parseParameters, use raw content
470
+ toolInput = command.content;
471
+ }
472
+ }
473
+
474
+ // CRITICAL FIX: Unwrap TagParser format before tool execution
475
+ // TagParser wraps XML parameters in {value, attributes} objects
476
+ // This unwrapping makes all tools work consistently
477
+ if (toolInput && typeof toolInput === 'object') {
478
+ toolInput = this.unwrapParameters(toolInput);
479
+ }
480
+
481
+ tool.execute(toolInput, context)
482
+ .then(result => {
483
+ operation.status = 'completed';
484
+ operation.result = result;
485
+ operation.endTime = new Date().toISOString();
486
+ this.notifyAgentOfToolCompletion(operation);
487
+ })
488
+ .catch(error => {
489
+ operation.status = 'failed';
490
+ operation.error = error.message;
491
+ operation.endTime = new Date().toISOString();
492
+ this.notifyAgentOfToolCompletion(operation);
493
+ });
494
+
495
+ // Start monitoring
496
+ this.monitorAsyncOperation(operationId);
497
+
498
+ return {
499
+ toolId: command.toolId,
500
+ status: 'async-pending',
501
+ operationId: operationId,
502
+ message: `Async tool started with operation ID: ${operationId}`,
503
+ timestamp: new Date().toISOString()
504
+ };
505
+ }
506
+
507
+ /**
508
+ * Monitor async operation
509
+ * @param {string} operationId - Operation ID to monitor
510
+ */
511
+ async monitorAsyncOperation(operationId) {
512
+ const checkInterval = 5000; // 5 seconds
513
+ const maxChecks = 120; // 10 minutes max
514
+ let checks = 0;
515
+
516
+ const monitor = setInterval(() => {
517
+ const operation = this.asyncOperations.get(operationId);
518
+
519
+ if (!operation) {
520
+ clearInterval(monitor);
521
+ return;
522
+ }
523
+
524
+ checks++;
525
+
526
+ if (operation.status !== 'pending' || checks >= maxChecks) {
527
+ clearInterval(monitor);
528
+
529
+ if (checks >= maxChecks) {
530
+ operation.status = 'timeout';
531
+ operation.error = 'Operation timed out';
532
+ operation.endTime = new Date().toISOString();
533
+ this.notifyAgentOfToolCompletion(operation);
534
+ }
535
+ }
536
+ }, checkInterval);
537
+ }
538
+
539
+ /**
540
+ * Notify agent of tool completion
541
+ * @param {Object} operation - Completed operation
542
+ */
543
+ async notifyAgentOfToolCompletion(operation) {
544
+ if (!operation.agentId) return;
545
+
546
+ try {
547
+ // Queue tool result for the agent
548
+ await this.agentPool.addToolResult(operation.agentId, {
549
+ toolId: operation.toolId,
550
+ status: operation.status,
551
+ result: operation.result,
552
+ error: operation.error,
553
+ executionTime: operation.endTime ?
554
+ new Date(operation.endTime) - new Date(operation.startTime) : null,
555
+ timestamp: operation.endTime || new Date().toISOString()
556
+ });
557
+
558
+ // Add agent back to scheduler if needed
559
+ if (this.scheduler) {
560
+ await this.scheduler.addAgent(operation.agentId, {
561
+ triggeredBy: 'tool-completion',
562
+ sessionId: operation.context?.sessionId
563
+ });
564
+ }
565
+
566
+ this.logger.info(`Agent notified of tool completion: ${operation.agentId}`, {
567
+ toolId: operation.toolId,
568
+ status: operation.status
569
+ });
570
+
571
+ } catch (error) {
572
+ this.logger.error(`Failed to notify agent of tool completion`, {
573
+ agentId: operation.agentId,
574
+ toolId: operation.toolId,
575
+ error: error.message
576
+ });
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Get tool status
582
+ * @param {string} operationId - Operation ID
583
+ * @returns {Promise<Object>} Operation status
584
+ */
585
+ async getToolStatus(operationId) {
586
+ const operation = this.asyncOperations.get(operationId);
587
+
588
+ if (!operation) {
589
+ return {
590
+ status: 'not-found',
591
+ error: `Operation not found: ${operationId}`
592
+ };
593
+ }
594
+
595
+ return {
596
+ id: operation.id,
597
+ toolId: operation.toolId,
598
+ status: operation.status,
599
+ result: operation.result,
600
+ error: operation.error,
601
+ startTime: operation.startTime,
602
+ endTime: operation.endTime
603
+ };
604
+ }
605
+
606
+ /**
607
+ * Extract and execute tools from content
608
+ * Called by AgentScheduler after getting AI response
609
+ * @param {string} content - Content containing tool commands
610
+ * @param {string} agentId - Agent ID
611
+ * @param {Object} context - Execution context
612
+ * @returns {Promise<Array>} Tool execution results
613
+ */
614
+ async extractAndExecuteTools(content, agentId, context) {
615
+ try {
616
+ // Extract tool commands
617
+ const commands = await this.extractToolCommands(content);
618
+
619
+ if (commands.length === 0) {
620
+ return [];
621
+ }
622
+
623
+ // Get agent to include its directoryAccess configuration
624
+ const agent = await this.agentPool.getAgent(agentId);
625
+
626
+ // Execute tools with agent context including sessionId and directoryAccess
627
+ const toolContext = {
628
+ ...context,
629
+ agentId,
630
+ sessionId: context.sessionId, // Ensure sessionId is explicitly available for tools
631
+ directoryAccess: agent?.directoryAccess, // Include agent's directory access configuration
632
+ projectDir: agent?.directoryAccess?.workingDirectory || agent?.projectDir || context.projectDir, // Extract project directory from directoryAccess
633
+ agentPool: this.agentPool,
634
+ contextManager: this.contextManager,
635
+ aiService: this.aiService,
636
+ messageProcessor: this,
637
+ orchestrator: this.orchestrator
638
+ };
639
+
640
+ const results = await this.executeTools(commands, toolContext);
641
+
642
+ this.logger.info(`Executed ${results.length} tools for agent: ${agentId}`, {
643
+ tools: results.map(r => ({ toolId: r.toolId, status: r.status }))
644
+ });
645
+
646
+ return results;
647
+
648
+ } catch (error) {
649
+ this.logger.error(`Tool extraction/execution failed for agent: ${agentId}`, {
650
+ error: error.message
651
+ });
652
+ return [];
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Stop autonomous execution for an agent
658
+ * Proxy method to AgentScheduler
659
+ * @param {string} agentId - Agent ID to stop
660
+ * @returns {Promise<Object>} Result with agent state
661
+ */
662
+ async stopAutonomousExecution(agentId) {
663
+ if (!this.scheduler) {
664
+ return {
665
+ success: false,
666
+ error: 'Scheduler not available'
667
+ };
668
+ }
669
+
670
+ return await this.scheduler.stopAgentExecution(agentId);
671
+ }
672
+
673
+ /**
674
+ * Inject tool results into conversation
675
+ * @param {string} agentId - Agent ID
676
+ * @param {Array} toolResults - Tool execution results
677
+ * @returns {Promise<void>}
678
+ */
679
+ async injectToolResultsIntoConversation(agentId, toolResults) {
680
+ const agent = await this.agentPool.getAgent(agentId);
681
+ if (!agent) return;
682
+
683
+ for (const result of toolResults) {
684
+ const toolMessage = {
685
+ id: `tool-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
686
+ role: 'system',
687
+ content: this.formatToolResultForAgent(result),
688
+ timestamp: new Date().toISOString(),
689
+ type: 'tool-result',
690
+ toolId: result.toolId,
691
+ status: result.status
692
+ };
693
+
694
+ // Add to conversation history
695
+ agent.conversations.full.messages.push(toolMessage);
696
+
697
+ // Also add to current model conversation if exists
698
+ if (agent.currentModel && agent.conversations[agent.currentModel]) {
699
+ agent.conversations[agent.currentModel].messages.push(toolMessage);
700
+ }
701
+ }
702
+
703
+ // Update last activity
704
+ agent.conversations.full.lastUpdated = new Date().toISOString();
705
+ if (agent.currentModel && agent.conversations[agent.currentModel]) {
706
+ agent.conversations[agent.currentModel].lastUpdated = new Date().toISOString();
707
+ }
708
+
709
+ await this.agentPool.persistAgentState(agentId);
710
+ }
711
+
712
+ /**
713
+ * Format tool result for agent consumption
714
+ * @param {Object} result - Tool execution result
715
+ * @returns {string} Formatted result
716
+ */
717
+ formatToolResultForAgent(result) {
718
+ if (result.status === 'completed') {
719
+ if (typeof result.result === 'object') {
720
+ return `Tool ${result.toolId} completed successfully:\n${JSON.stringify(result.result, null, 2)}`;
721
+ }
722
+ return `Tool ${result.toolId} completed successfully:\n${result.result}`;
723
+ } else if (result.status === 'failed') {
724
+ return `Tool ${result.toolId} failed: ${result.error || 'Unknown error'}`;
725
+ } else if (result.status === 'async-pending') {
726
+ return `Tool ${result.toolId} is running asynchronously (Operation ID: ${result.operationId})`;
727
+ }
728
+ return `Tool ${result.toolId} status: ${result.status}`;
729
+ }
730
+ }
731
+
732
+ export default MessageProcessor;