@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,1474 @@
1
+ /**
2
+ * AgentPool - Manages the lifecycle, state, and communication of all active agents
3
+ *
4
+ * Purpose:
5
+ * - Agent creation and destruction
6
+ * - Agent notification and routing
7
+ * - Multi-agent conversation coordination
8
+ * - Agent state persistence and recovery
9
+ * - Agent activity management
10
+ */
11
+
12
+ import {
13
+ AGENT_TYPES,
14
+ AGENT_STATUS,
15
+ AGENT_MODES,
16
+ AGENT_MODE_STATES,
17
+ MESSAGE_ROLES,
18
+ MESSAGE_TYPES,
19
+ INTER_AGENT_MESSAGE,
20
+ MODEL_FORMAT_VERSIONS,
21
+ SYSTEM_DEFAULTS
22
+ } from '../utilities/constants.js';
23
+ import DirectoryAccessManager from '../utilities/directoryAccessManager.js';
24
+
25
+ class AgentPool {
26
+ constructor(config, logger, stateManager, contextManager, toolsRegistry = null) {
27
+ this.config = config;
28
+ this.logger = logger;
29
+ this.stateManager = stateManager;
30
+ this.contextManager = contextManager;
31
+ this.toolsRegistry = toolsRegistry;
32
+
33
+ // Agent registry - maps agent ID to agent object
34
+ this.agents = new Map();
35
+
36
+ // Agent directory for discovery
37
+ this.agentDirectory = new Map();
38
+
39
+ // Paused agents tracking
40
+ this.pausedAgents = new Map();
41
+
42
+ // Agent notification queue
43
+ this.notificationQueue = new Map();
44
+
45
+ this.maxAgentsPerProject = config.system?.maxAgentsPerProject || SYSTEM_DEFAULTS.MAX_AGENTS_PER_PROJECT;
46
+
47
+ // MessageProcessor reference for triggering responses (set via setMessageProcessor)
48
+ this.messageProcessor = null;
49
+
50
+ // Initialize directory access manager
51
+ this.directoryAccessManager = new DirectoryAccessManager(config, logger);
52
+ }
53
+
54
+ /**
55
+ * Create a new agent with specified configuration
56
+ * @param {Object} config - Agent configuration
57
+ * @param {string} config.name - Agent name
58
+ * @param {string} config.type - Agent type ('user-created', 'system-agent', 'agent-engineer')
59
+ * @param {string} config.systemPrompt - Agent's system prompt
60
+ * @param {string} config.preferredModel - Preferred LLM model
61
+ * @param {Array} config.capabilities - Available tools/capabilities
62
+ * @param {Object} config.directoryAccess - Directory access configuration
63
+ * @param {string} config.projectDir - Project directory for default access setup
64
+ * @returns {Promise<Object>} Created agent object
65
+ */
66
+ async createAgent(config) {
67
+ // Check agent limit
68
+ if (this.agents.size >= this.maxAgentsPerProject) {
69
+ throw new Error(`Maximum agents per project exceeded (${this.maxAgentsPerProject})`);
70
+ }
71
+
72
+ const agentId = this._generateAgentId(config.name);
73
+ const now = new Date().toISOString();
74
+
75
+ // Enhance system prompt with tool descriptions if available
76
+ let enhancedSystemPrompt = config.systemPrompt;
77
+ if (this.toolsRegistry && config.capabilities && config.capabilities.length > 0) {
78
+ try {
79
+ enhancedSystemPrompt = this.toolsRegistry.enhanceSystemPrompt(
80
+ config.systemPrompt,
81
+ config.capabilities,
82
+ {
83
+ compact: config.compactToolDescriptions || false,
84
+ includeExamples: config.includeToolExamples !== false,
85
+ includeUsageGuidelines: config.includeUsageGuidelines !== false,
86
+ includeSecurityNotes: config.includeSecurityNotes !== false
87
+ }
88
+ );
89
+
90
+ this.logger?.info(`System prompt enhanced with tool descriptions`, {
91
+ agentId,
92
+ capabilities: config.capabilities,
93
+ originalLength: config.systemPrompt?.length || 0,
94
+ enhancedLength: enhancedSystemPrompt?.length || 0
95
+ });
96
+ } catch (error) {
97
+ this.logger?.error(`Failed to enhance system prompt with tools`, {
98
+ agentId,
99
+ error: error.message,
100
+ capabilities: config.capabilities
101
+ });
102
+ // Fall back to original prompt
103
+ enhancedSystemPrompt = config.systemPrompt;
104
+ }
105
+ }
106
+
107
+ // Setup directory access configuration
108
+ let directoryAccess;
109
+
110
+ console.log('AgentPool DEBUG: createAgent - config.directoryAccess:', config.directoryAccess ? 'EXISTS' : 'NULL/UNDEFINED');
111
+ if (config.directoryAccess) {
112
+ console.log('AgentPool DEBUG: createAgent - directoryAccess from config:', JSON.stringify(config.directoryAccess, null, 2));
113
+ }
114
+ console.log('AgentPool DEBUG: createAgent - config.projectDir:', config.projectDir);
115
+
116
+ if (config.directoryAccess) {
117
+ // Validate provided directory access configuration
118
+ const validation = this.directoryAccessManager.validateAccessConfiguration(config.directoryAccess);
119
+ console.log('AgentPool DEBUG: createAgent - validation result:', validation);
120
+ if (!validation.valid) {
121
+ throw new Error(`Invalid directory access configuration: ${validation.errors.join(', ')}`);
122
+ }
123
+ directoryAccess = config.directoryAccess;
124
+ console.log('AgentPool DEBUG: createAgent - Using provided directoryAccess');
125
+ } else {
126
+ // Create default directory access based on project directory
127
+ const projectDir = config.projectDir || process.cwd();
128
+ directoryAccess = DirectoryAccessManager.createProjectDefaults(projectDir);
129
+ console.log('AgentPool DEBUG: createAgent - Created default directoryAccess for projectDir:', projectDir);
130
+ console.log('AgentPool DEBUG: createAgent - Default directoryAccess:', JSON.stringify(directoryAccess, null, 2));
131
+ }
132
+
133
+ const agent = {
134
+ id: agentId,
135
+ type: config.type || AGENT_TYPES.USER_CREATED,
136
+ name: config.name || `Agent-${Date.now()}`,
137
+ systemPrompt: enhancedSystemPrompt,
138
+ originalSystemPrompt: config.systemPrompt, // Store original for reference
139
+ preferredModel: config.preferredModel,
140
+ status: AGENT_STATUS.ACTIVE,
141
+ capabilities: config.capabilities || [],
142
+ directoryAccess: directoryAccess, // Directory access configuration
143
+ conversations: {
144
+ full: {
145
+ messages: [],
146
+ lastUpdated: now
147
+ }
148
+ },
149
+ currentModel: config.preferredModel,
150
+ dynamicModelRouting: config.dynamicModelRouting || false, // New field for routing
151
+ platformProvided: config.platformProvided || false, // Platform vs direct access
152
+
153
+ // Agent Mode Configuration
154
+ mode: config.mode || AGENT_MODES.CHAT,
155
+ modeState: AGENT_MODE_STATES.IDLE,
156
+ currentTask: null, // Current autonomous task being executed
157
+ taskStartTime: null,
158
+ maxIterations: config.maxIterations || 10, // Safety limit for autonomous loops
159
+ iterationCount: 0,
160
+ stopRequested: false,
161
+ delayEndTime: null, // When agent delay expires (for agentDelay tool)
162
+
163
+ // Message Queues for scheduler processing
164
+ messageQueues: {
165
+ toolResults: [], // Tool execution results waiting to be processed
166
+ interAgentMessages: [], // Messages from other agents
167
+ userMessages: [] // Messages from users
168
+ },
169
+
170
+ createdAt: now,
171
+ lastActivity: now,
172
+ pausedUntil: null,
173
+ metadata: config.metadata || {},
174
+
175
+ // CRITICAL: Store sessionId for API key resolution
176
+ sessionId: config.sessionId,
177
+
178
+ // Inter-agent conversation tracking to prevent spam
179
+ interAgentTracking: new Map(), // recipientId -> { lastSent, lastReceived, lastType }
180
+
181
+ // Task Management System for agent-mode autonomous operation
182
+ taskList: {
183
+ tasks: [], // Array of task objects
184
+ lastUpdated: now
185
+ },
186
+
187
+ // Incoming messages tracking (for unprocessed messages)
188
+ incomingMessages: []
189
+ };
190
+
191
+ this.logger.info(`Agent created with routing config`, {
192
+ agentId,
193
+ dynamicModelRouting: agent.dynamicModelRouting,
194
+ platformProvided: agent.platformProvided,
195
+ preferredModel: agent.preferredModel
196
+ });
197
+
198
+ // Initialize model-specific conversation with dual storage structure
199
+ if (config.preferredModel) {
200
+ agent.conversations[config.preferredModel] = {
201
+ // Dual storage for compactization support
202
+ messages: [], // Original messages - never modified
203
+ compactizedMessages: null, // Working copy - null until first compaction
204
+
205
+ // Compactization metadata
206
+ lastCompactization: null, // Timestamp of last compaction
207
+ compactizationCount: 0, // Number of times compacted
208
+ compactizationStrategy: null, // 'summarization', 'truncation', 'aggressive'
209
+ originalTokenCount: 0, // Token count before last compaction
210
+ compactedTokenCount: 0, // Token count after last compaction
211
+
212
+ // Backward compatibility
213
+ tokenCount: 0, // Current effective token count
214
+ lastUpdated: now,
215
+ formatVersion: this._getModelFormatVersion(config.preferredModel)
216
+ };
217
+ }
218
+
219
+ // Add to registry and directory
220
+ this.agents.set(agentId, agent);
221
+ this._updateAgentDirectory(agent);
222
+
223
+ // Persist agent state
224
+ await this.stateManager.persistAgentState(agentId);
225
+
226
+ this.logger.info(`Agent created: ${agentId}`, {
227
+ agentId,
228
+ name: agent.name,
229
+ type: agent.type,
230
+ model: agent.preferredModel
231
+ });
232
+
233
+ return agent;
234
+ }
235
+
236
+ /**
237
+ * Retrieve agent instance by ID
238
+ * @param {string} agentId - Agent identifier
239
+ * @returns {Promise<Object|null>} Agent object or null if not found
240
+ */
241
+ async getAgent(agentId, enrichWithSchedulerStatus = false) {
242
+ const agent = this.agents.get(agentId);
243
+ if (!agent) return null;
244
+
245
+ // Optionally enrich with scheduler status for UI
246
+ if (enrichWithSchedulerStatus && this.scheduler) {
247
+ agent.inScheduler = this.scheduler.isAgentInScheduler(agentId);
248
+ }
249
+
250
+ return agent;
251
+ }
252
+
253
+ /**
254
+ * Update an existing agent's configuration
255
+ * @param {string} agentId - Agent identifier
256
+ * @param {Object} updates - Updates to apply to the agent
257
+ * @returns {Promise<Object>} Updated agent object
258
+ */
259
+ async updateAgent(agentId, updates) {
260
+ const agent = await this.getAgent(agentId);
261
+ if (!agent) {
262
+ throw new Error(`Agent not found: ${agentId}`);
263
+ }
264
+
265
+ this.logger.info(`Updating agent: ${agentId}`, {
266
+ updates,
267
+ currentName: agent.name
268
+ });
269
+
270
+ // Validate directory access configuration if being updated
271
+ if (updates.directoryAccess) {
272
+ const validation = this.directoryAccessManager.validateAccessConfiguration(updates.directoryAccess);
273
+ if (!validation.valid) {
274
+ throw new Error(`Invalid directory access configuration: ${validation.errors.join(', ')}`);
275
+ }
276
+
277
+ this.logger.info(`Directory access validation passed for agent: ${agentId}`, {
278
+ workingDirectory: updates.directoryAccess.workingDirectory,
279
+ readOnlyDirs: updates.directoryAccess.readOnlyDirectories?.length || 0,
280
+ writeEnabledDirs: updates.directoryAccess.writeEnabledDirectories?.length || 0
281
+ });
282
+ }
283
+
284
+ // If capabilities are being updated, regenerate the enhanced system prompt
285
+ if (updates.capabilities && this.toolsRegistry) {
286
+ try {
287
+ const baseSystemPrompt = agent.originalSystemPrompt || agent.systemPrompt;
288
+ const enhancedSystemPrompt = this.toolsRegistry.enhanceSystemPrompt(
289
+ baseSystemPrompt,
290
+ updates.capabilities,
291
+ {
292
+ compact: agent.compactToolDescriptions || false,
293
+ includeExamples: agent.includeToolExamples !== false,
294
+ includeUsageGuidelines: agent.includeUsageGuidelines !== false,
295
+ includeSecurityNotes: agent.includeSecurityNotes !== false
296
+ }
297
+ );
298
+
299
+ updates.systemPrompt = enhancedSystemPrompt;
300
+
301
+ this.logger.info(`System prompt regenerated with updated capabilities`, {
302
+ agentId,
303
+ oldCapabilities: agent.capabilities,
304
+ newCapabilities: updates.capabilities,
305
+ originalLength: baseSystemPrompt?.length || 0,
306
+ enhancedLength: enhancedSystemPrompt?.length || 0
307
+ });
308
+ } catch (error) {
309
+ this.logger.error(`Failed to regenerate system prompt with updated capabilities`, {
310
+ agentId,
311
+ error: error.message,
312
+ capabilities: updates.capabilities
313
+ });
314
+ // Continue with update even if enhancement fails
315
+ }
316
+ }
317
+
318
+ // Create updated agent object with new values
319
+ const updatedAgent = {
320
+ ...agent,
321
+ ...updates,
322
+ id: agentId, // Ensure ID cannot be changed
323
+ lastModified: new Date().toISOString(),
324
+ lastActivity: new Date().toISOString()
325
+ };
326
+
327
+ // CRITICAL FIX: When preferredModel changes, also update currentModel
328
+ // This ensures the UI immediately reflects the model change
329
+ if (updates.preferredModel && updates.preferredModel !== agent.preferredModel) {
330
+ const oldModel = agent.preferredModel;
331
+ const newModel = updates.preferredModel;
332
+
333
+ updatedAgent.currentModel = newModel;
334
+
335
+ // CRITICAL FIX: Initialize conversation for new model if it doesn't exist
336
+ if (!updatedAgent.conversations[newModel]) {
337
+ updatedAgent.conversations[newModel] = this._createEmptyConversation(newModel);
338
+ this.logger.info(`Created conversation for new model: ${newModel}`, { agentId });
339
+ }
340
+
341
+ // Copy conversation history from old model to new model
342
+ // This preserves context when switching models
343
+ if (oldModel && updatedAgent.conversations[oldModel]) {
344
+ const oldConversation = updatedAgent.conversations[oldModel];
345
+ const newConversation = updatedAgent.conversations[newModel];
346
+
347
+ // Copy messages if new conversation is empty
348
+ if (newConversation.messages.length === 0 && oldConversation.messages.length > 0) {
349
+ // Copy original messages
350
+ newConversation.messages = [...oldConversation.messages];
351
+
352
+ // Copy compacted messages if they exist
353
+ if (oldConversation.compactizedMessages) {
354
+ newConversation.compactizedMessages = [...oldConversation.compactizedMessages];
355
+ newConversation.lastCompactization = oldConversation.lastCompactization;
356
+ newConversation.compactizationCount = oldConversation.compactizationCount;
357
+ newConversation.compactizationStrategy = oldConversation.compactizationStrategy;
358
+ newConversation.originalTokenCount = oldConversation.originalTokenCount;
359
+ newConversation.compactedTokenCount = oldConversation.compactedTokenCount;
360
+ }
361
+
362
+ newConversation.lastUpdated = new Date().toISOString();
363
+
364
+ this.logger.info(`Copied conversation history from ${oldModel} to ${newModel}`, {
365
+ agentId,
366
+ messageCount: newConversation.messages.length,
367
+ hasCompacted: !!newConversation.compactizedMessages
368
+ });
369
+ }
370
+ }
371
+
372
+ this.logger.info(`Model changed via UI - updating both preferredModel and currentModel`, {
373
+ agentId,
374
+ oldModel,
375
+ newModel,
376
+ conversationCopied: oldModel && updatedAgent.conversations[oldModel]?.messages.length > 0
377
+ });
378
+ }
379
+
380
+ // Update agent in registry
381
+ this.agents.set(agentId, updatedAgent);
382
+
383
+ // Log the actual update for debugging
384
+ this.logger.info(`Agent updated in registry with mode: ${updatedAgent.mode}`, {
385
+ agentId,
386
+ beforeMode: agent.mode,
387
+ afterMode: updatedAgent.mode,
388
+ allUpdates: Object.keys(updates)
389
+ });
390
+
391
+ // Update agent directory
392
+ this._updateAgentDirectory(updatedAgent);
393
+
394
+ // Persist the updated agent state
395
+ await this.stateManager.persistAgentState(updatedAgent);
396
+
397
+ // CRITICAL: If agent was switched to AGENT mode, add it to scheduler
398
+ if (updates.mode === AGENT_MODES.AGENT && this.scheduler) {
399
+ // CRITICAL FIX: Use the session ID from updates first, then agent's sessionId
400
+ const sessionId = updates.sessionId || updatedAgent.sessionId;
401
+
402
+ if (!sessionId) {
403
+ this.logger.warn(`Agent ${agentId} switching to AGENT mode but has no sessionId - this will cause API key resolution issues`);
404
+ }
405
+
406
+ this.logger.info(`Adding agent to scheduler (switched to AGENT mode): ${agentId}`, {
407
+ agentName: updatedAgent.name,
408
+ sessionId: sessionId,
409
+ hasSessionId: !!sessionId
410
+ });
411
+
412
+ await this.scheduler.addAgent(agentId, {
413
+ sessionId: sessionId, // NO FALLBACK - let scheduler handle missing session ID appropriately
414
+ triggeredBy: 'mode-change',
415
+ reason: 'Agent switched to AGENT mode'
416
+ });
417
+ }
418
+
419
+ // If agent was switched from AGENT to CHAT mode, remove from scheduler
420
+ if (agent.mode === AGENT_MODES.AGENT && updates.mode === AGENT_MODES.CHAT && this.scheduler) {
421
+ this.logger.info(`Removing agent from scheduler (switched to CHAT mode): ${agentId}`);
422
+ this.scheduler.removeAgent(agentId, 'mode-change-to-chat');
423
+ }
424
+
425
+ this.logger.info(`Agent updated successfully: ${agentId}`, {
426
+ newName: updatedAgent.name,
427
+ changes: Object.keys(updates)
428
+ });
429
+
430
+ return updatedAgent;
431
+ }
432
+
433
+ /**
434
+ * Agent notification from Message Processor for inter-agent communication
435
+ * @param {string} agentId - Target agent ID
436
+ * @param {Object} message - Message object with agent redirect
437
+ * @returns {Promise<boolean>} Success status
438
+ */
439
+ async notifyAgent(agentId, message) {
440
+ const agent = await this.getAgent(agentId);
441
+ if (!agent) {
442
+ this.logger.warn(`Agent notification failed - agent not found: ${agentId}`);
443
+ return false;
444
+ }
445
+
446
+ // Check if agent is paused
447
+ if (this._isAgentPaused(agent)) {
448
+ this.logger.info(`Agent notification queued - agent is paused: ${agentId}`);
449
+ this._queueNotification(agentId, message);
450
+ return true;
451
+ }
452
+
453
+ // Add notification to agent's conversation
454
+ const notificationMessage = {
455
+ id: `msg-${Date.now()}`,
456
+ conversationId: message.conversationId,
457
+ agentId: message.from, // sender agent ID
458
+ content: message.content,
459
+ role: MESSAGE_ROLES.SYSTEM,
460
+ timestamp: new Date().toISOString(),
461
+ type: MESSAGE_TYPES.AGENT_NOTIFICATION,
462
+ fromAgent: message.from,
463
+ context: message.context,
464
+ urgent: message.urgent || false,
465
+ requiresResponse: message.requiresResponse || false
466
+ };
467
+
468
+ // Add to full conversation
469
+ agent.conversations.full.messages.push(notificationMessage);
470
+ agent.conversations.full.lastUpdated = new Date().toISOString();
471
+
472
+ // Add to current model conversation
473
+ if (agent.currentModel && agent.conversations[agent.currentModel]) {
474
+ const formattedMessage = this._formatMessageForModel(notificationMessage, agent.currentModel);
475
+ agent.conversations[agent.currentModel].messages.push(formattedMessage);
476
+ agent.conversations[agent.currentModel].lastUpdated = new Date().toISOString();
477
+ }
478
+
479
+ // Update agent activity
480
+ agent.lastActivity = new Date().toISOString();
481
+ await this.persistAgentState(agentId);
482
+
483
+ this.logger.info(`Agent notified: ${agentId}`, {
484
+ fromAgent: message.from,
485
+ urgent: message.urgent,
486
+ requiresResponse: message.requiresResponse
487
+ });
488
+
489
+ return true;
490
+ }
491
+
492
+ /**
493
+ * Get all agents (returns full agent objects)
494
+ * @returns {Promise<Array>} List of all agent objects
495
+ */
496
+ async getAllAgents() {
497
+ const agents = Array.from(this.agents.values());
498
+
499
+ // Update pause status for all agents
500
+ for (const agent of agents) {
501
+ this._updateAgentPauseStatus(agent);
502
+ }
503
+
504
+ return agents;
505
+ }
506
+
507
+ /**
508
+ * List all active agents with their current status
509
+ * @returns {Promise<Array>} Array of agent objects
510
+ */
511
+ async listActiveAgents() {
512
+ const agents = Array.from(this.agents.values());
513
+
514
+ // Update pause status for all agents
515
+ for (const agent of agents) {
516
+ this._updateAgentPauseStatus(agent);
517
+ }
518
+
519
+ return agents.map(agent => ({
520
+ id: agent.id,
521
+ name: agent.name,
522
+ type: agent.type,
523
+ status: agent.status,
524
+ systemPrompt: agent.systemPrompt,
525
+ preferredModel: agent.preferredModel,
526
+ currentModel: agent.currentModel,
527
+ dynamicModelRouting: agent.dynamicModelRouting,
528
+ platformProvided: agent.platformProvided,
529
+ capabilities: agent.capabilities,
530
+ lastActivity: agent.lastActivity,
531
+ isPaused: this._isAgentPaused(agent),
532
+ pausedUntil: agent.pausedUntil,
533
+ messageCount: agent.conversations.full.messages.length,
534
+ createdAt: agent.createdAt
535
+ }));
536
+ }
537
+
538
+ /**
539
+ * Persist agent state to storage
540
+ * @param {string} agentId - Agent identifier
541
+ * @returns {Promise<void>}
542
+ */
543
+ async persistAgentState(agentId) {
544
+ const agent = await this.getAgent(agentId);
545
+ if (!agent) {
546
+ throw new Error(`Agent not found: ${agentId}`);
547
+ }
548
+
549
+ await this.stateManager.persistAgentState(agent);
550
+ }
551
+
552
+ /**
553
+ * Resume agent from persisted state
554
+ * @param {Object} agentData - Persisted agent data
555
+ * @returns {Promise<Object>} Restored agent object
556
+ */
557
+ async resumeAgent(agentData) {
558
+ const agent = {
559
+ ...agentData,
560
+ status: agentData.status === 'paused' && this._isPauseExpired(agentData) ? 'active' : agentData.status
561
+ };
562
+
563
+ // Validate conversations structure
564
+ if (!agent.conversations || !agent.conversations.full) {
565
+ agent.conversations = {
566
+ full: {
567
+ messages: [],
568
+ lastUpdated: new Date().toISOString()
569
+ }
570
+ };
571
+ }
572
+
573
+ // Add to registry and directory
574
+ this.agents.set(agent.id, agent);
575
+ this._updateAgentDirectory(agent);
576
+
577
+ // Process any queued notifications
578
+ await this._processQueuedNotifications(agent.id);
579
+
580
+ this.logger.info(`Agent resumed: ${agent.id}`, {
581
+ name: agent.name,
582
+ status: agent.status,
583
+ messageCount: agent.conversations.full.messages.length
584
+ });
585
+
586
+ return agent;
587
+ }
588
+
589
+ /**
590
+ * Pause agent for specified duration
591
+ * @param {string} agentId - Agent identifier
592
+ * @param {number|Date} duration - Pause duration in seconds or Date object
593
+ * @param {string} reason - Reason for pause
594
+ * @returns {Promise<Object>} Pause confirmation
595
+ */
596
+ async pauseAgent(agentId, duration, reason = 'Agent pause requested') {
597
+ const agent = await this.getAgent(agentId);
598
+ if (!agent) {
599
+ throw new Error(`Agent not found: ${agentId}`);
600
+ }
601
+
602
+ let pauseUntil;
603
+ if (duration instanceof Date) {
604
+ pauseUntil = duration;
605
+ } else {
606
+ // Duration in seconds
607
+ const maxPauseDuration = this.config.system?.maxPauseDuration || 300;
608
+ const pauseSeconds = Math.min(duration, maxPauseDuration);
609
+ pauseUntil = new Date(Date.now() + pauseSeconds * 1000);
610
+ }
611
+
612
+ agent.status = AGENT_STATUS.PAUSED;
613
+ agent.pausedUntil = pauseUntil.toISOString();
614
+ agent.lastActivity = new Date().toISOString();
615
+
616
+ // Add to paused agents tracking
617
+ this.pausedAgents.set(agentId, {
618
+ agentId,
619
+ pausedAt: new Date().toISOString(),
620
+ pausedUntil: pauseUntil.toISOString(),
621
+ reason,
622
+ originalStatus: AGENT_STATUS.ACTIVE
623
+ });
624
+
625
+ await this.persistAgentState(agentId);
626
+
627
+ this.logger.info(`Agent paused: ${agentId}`, {
628
+ pausedUntil: pauseUntil.toISOString(),
629
+ reason,
630
+ durationSeconds: Math.round((pauseUntil.getTime() - Date.now()) / 1000)
631
+ });
632
+
633
+ return {
634
+ success: true,
635
+ agentId,
636
+ pausedUntil: pauseUntil.toISOString(),
637
+ reason,
638
+ message: `Agent paused until ${pauseUntil.toISOString()}`
639
+ };
640
+ }
641
+
642
+ /**
643
+ * Resume paused agent
644
+ * @param {string} agentId - Agent identifier
645
+ * @returns {Promise<Object>} Resume confirmation
646
+ */
647
+ async resumeAgent(agentId) {
648
+ const agent = await this.getAgent(agentId);
649
+ if (!agent) {
650
+ throw new Error(`Agent not found: ${agentId}`);
651
+ }
652
+
653
+ if (agent.status !== AGENT_STATUS.PAUSED) {
654
+ return {
655
+ success: true,
656
+ message: `Agent ${agentId} is not paused`
657
+ };
658
+ }
659
+
660
+ agent.status = AGENT_STATUS.ACTIVE;
661
+ agent.pausedUntil = null;
662
+ agent.lastActivity = new Date().toISOString();
663
+
664
+ // Remove from paused agents tracking
665
+ this.pausedAgents.delete(agentId);
666
+
667
+ // Process any queued notifications
668
+ await this._processQueuedNotifications(agentId);
669
+
670
+ await this.persistAgentState(agentId);
671
+
672
+ this.logger.info(`Agent resumed: ${agentId}`);
673
+
674
+ return {
675
+ success: true,
676
+ agentId,
677
+ message: `Agent ${agentId} resumed successfully`
678
+ };
679
+ }
680
+
681
+ /**
682
+ * Restore agent from saved state
683
+ * @param {Object} agentState - Saved agent state
684
+ * @returns {Promise<Object>} Restored agent
685
+ */
686
+ async restoreAgent(agentState) {
687
+ return await this.resumeAgent(agentState);
688
+ }
689
+
690
+ /**
691
+ * Get agent discovery directory
692
+ * @returns {Array} Array of agent info for discovery
693
+ */
694
+ getAgentDirectory() {
695
+ return Array.from(this.agentDirectory.values());
696
+ }
697
+
698
+ /**
699
+ * List all active agents
700
+ * @returns {Array} Array of active agents
701
+ */
702
+
703
+ /**
704
+ * Delete an agent and clean up its resources
705
+ * @param {string} agentId - Agent identifier
706
+ * @returns {Promise<Object>} Deletion result
707
+ */
708
+ async deleteAgent(agentId) {
709
+ const agent = await this.getAgent(agentId);
710
+ if (!agent) {
711
+ throw new Error(`Agent not found: ${agentId}`);
712
+ }
713
+
714
+ // Clean up file attachments with reference counting
715
+ if (this.fileAttachmentService) {
716
+ try {
717
+ await this.fileAttachmentService.deleteAgentAttachments(agentId);
718
+ this.logger.info(`File attachments cleaned up for agent: ${agentId}`);
719
+ } catch (error) {
720
+ this.logger.warn(`Failed to clean up file attachments for agent: ${error.message}`, { agentId });
721
+ // Continue with agent deletion even if attachment cleanup fails
722
+ }
723
+ }
724
+
725
+ // Clean up agent resources
726
+ this.agents.delete(agentId);
727
+ this.agentDirectory.delete(agentId);
728
+ this.pausedAgents.delete(agentId);
729
+ this.notificationQueue.delete(agentId);
730
+
731
+ // Clean up persistent state
732
+ try {
733
+ await this.stateManager.deleteAgentState(agentId);
734
+ } catch (error) {
735
+ this.logger.warn(`Failed to delete agent persistent state: ${error.message}`, { agentId });
736
+ }
737
+
738
+ this.logger.info(`Agent deleted: ${agentId}`, {
739
+ agentName: agent.name,
740
+ totalAgents: this.agents.size
741
+ });
742
+
743
+ return {
744
+ success: true,
745
+ agentId,
746
+ remainingAgents: this.agents.size
747
+ };
748
+ }
749
+
750
+ /**
751
+ * Generate unique agent ID
752
+ * @private
753
+ */
754
+ _generateAgentId(name) {
755
+ const sanitizedName = name.toLowerCase().replace(/[^a-z0-9]/g, '-');
756
+ const timestamp = Date.now();
757
+ return `agent-${sanitizedName}-${timestamp}`;
758
+ }
759
+
760
+ /**
761
+ * Update agent directory for discovery
762
+ * @private
763
+ */
764
+ _updateAgentDirectory(agent) {
765
+ this.agentDirectory.set(agent.id, {
766
+ id: agent.id,
767
+ name: agent.name,
768
+ type: agent.type,
769
+ capabilities: agent.capabilities,
770
+ status: agent.status,
771
+ description: this._generateAgentDescription(agent)
772
+ });
773
+ }
774
+
775
+ /**
776
+ * Generate agent description for directory
777
+ * @private
778
+ */
779
+ _generateAgentDescription(agent) {
780
+ let description = `${agent.name} (${agent.type})`;
781
+
782
+ if (agent.capabilities.length > 0) {
783
+ description += ` - Capabilities: ${agent.capabilities.join(', ')}`;
784
+ }
785
+
786
+ return description;
787
+ }
788
+
789
+ /**
790
+ * Check if agent is currently paused
791
+ * @private
792
+ */
793
+ _isAgentPaused(agent) {
794
+ if (agent.status !== AGENT_STATUS.PAUSED || !agent.pausedUntil) {
795
+ return false;
796
+ }
797
+
798
+ return new Date() < new Date(agent.pausedUntil);
799
+ }
800
+
801
+ /**
802
+ * Check if pause duration has expired
803
+ * @private
804
+ */
805
+ _isPauseExpired(agent) {
806
+ if (!agent.pausedUntil) return true;
807
+ return new Date() >= new Date(agent.pausedUntil);
808
+ }
809
+
810
+ /**
811
+ * Update agent pause status
812
+ * @private
813
+ */
814
+ _updateAgentPauseStatus(agent) {
815
+ if (agent.status === AGENT_STATUS.PAUSED && this._isPauseExpired(agent)) {
816
+ agent.status = AGENT_STATUS.ACTIVE;
817
+ agent.pausedUntil = null;
818
+ this.pausedAgents.delete(agent.id);
819
+ }
820
+ }
821
+
822
+ /**
823
+ * Queue notification for paused agent
824
+ * @private
825
+ */
826
+ _queueNotification(agentId, message) {
827
+ if (!this.notificationQueue.has(agentId)) {
828
+ this.notificationQueue.set(agentId, []);
829
+ }
830
+
831
+ this.notificationQueue.get(agentId).push({
832
+ ...message,
833
+ queuedAt: new Date().toISOString()
834
+ });
835
+ }
836
+
837
+ /**
838
+ * Process queued notifications for agent
839
+ * @private
840
+ */
841
+ async _processQueuedNotifications(agentId) {
842
+ const notifications = this.notificationQueue.get(agentId);
843
+ if (!notifications || notifications.length === 0) {
844
+ return;
845
+ }
846
+
847
+ this.logger.info(`Processing ${notifications.length} queued notifications for agent: ${agentId}`);
848
+
849
+ for (const notification of notifications) {
850
+ await this.notifyAgent(agentId, notification);
851
+ }
852
+
853
+ // Clear queue
854
+ this.notificationQueue.delete(agentId);
855
+ }
856
+
857
+ /**
858
+ * Format message for specific model
859
+ * @private
860
+ */
861
+ _formatMessageForModel(message, targetModel) {
862
+ // This would be implemented with model-specific formatting logic
863
+ // For now, return the message as-is
864
+ return { ...message };
865
+ }
866
+
867
+ /**
868
+ * Get model format version
869
+ * @private
870
+ */
871
+ _getModelFormatVersion(model) {
872
+ return MODEL_FORMAT_VERSIONS[model] || MODEL_FORMAT_VERSIONS.DEFAULT;
873
+ }
874
+
875
+ /**
876
+ * Refresh tool descriptions for an existing agent
877
+ * @param {string} agentId - Agent identifier
878
+ * @param {Object} options - Refresh options
879
+ * @returns {Promise<boolean>} Success status
880
+ */
881
+ async refreshAgentToolDescriptions(agentId, options = {}) {
882
+ const agent = await this.getAgent(agentId);
883
+ if (!agent || !this.toolsRegistry) {
884
+ return false;
885
+ }
886
+
887
+ try {
888
+ // Use original prompt if available, otherwise current prompt
889
+ const basePrompt = agent.originalSystemPrompt || agent.systemPrompt;
890
+
891
+ // Enhance with current tool capabilities
892
+ const enhancedPrompt = this.toolsRegistry.enhanceSystemPrompt(
893
+ basePrompt,
894
+ agent.capabilities,
895
+ {
896
+ compact: options.compact || false,
897
+ includeExamples: options.includeExamples !== false,
898
+ includeUsageGuidelines: options.includeUsageGuidelines !== false,
899
+ includeSecurityNotes: options.includeSecurityNotes !== false
900
+ }
901
+ );
902
+
903
+ // Update agent's system prompt
904
+ agent.systemPrompt = enhancedPrompt;
905
+ agent.lastActivity = new Date().toISOString();
906
+
907
+ // Persist changes
908
+ await this.stateManager.persistAgentState(agentId);
909
+
910
+ this.logger?.info(`Agent tool descriptions refreshed: ${agentId}`, {
911
+ capabilities: agent.capabilities,
912
+ promptLength: enhancedPrompt.length
913
+ });
914
+
915
+ return true;
916
+
917
+ } catch (error) {
918
+ this.logger?.error(`Failed to refresh tool descriptions for agent: ${agentId}`, {
919
+ error: error.message
920
+ });
921
+ return false;
922
+ }
923
+ }
924
+
925
+ /**
926
+ * Set or update tools registry for the agent pool
927
+ * @param {ToolsRegistry} toolsRegistry - Tools registry instance
928
+ */
929
+ setToolsRegistry(toolsRegistry) {
930
+ this.toolsRegistry = toolsRegistry;
931
+
932
+ this.logger?.info('Tools registry updated for agent pool', {
933
+ hasRegistry: !!toolsRegistry
934
+ });
935
+ }
936
+
937
+ /**
938
+ * Bulk refresh tool descriptions for all agents
939
+ * @param {Object} options - Refresh options
940
+ * @returns {Promise<Object>} Results summary
941
+ */
942
+ async bulkRefreshToolDescriptions(options = {}) {
943
+ const results = {
944
+ total: this.agents.size,
945
+ successful: 0,
946
+ failed: 0,
947
+ skipped: 0
948
+ };
949
+
950
+ for (const [agentId, agent] of this.agents.entries()) {
951
+ if (!agent.capabilities || agent.capabilities.length === 0) {
952
+ results.skipped++;
953
+ continue;
954
+ }
955
+
956
+ const success = await this.refreshAgentToolDescriptions(agentId, options);
957
+ if (success) {
958
+ results.successful++;
959
+ } else {
960
+ results.failed++;
961
+ }
962
+ }
963
+
964
+ this.logger?.info('Bulk tool descriptions refresh completed', results);
965
+ return results;
966
+ }
967
+
968
+ /**
969
+ * Set MessageProcessor reference for triggering responses
970
+ * @param {MessageProcessor} messageProcessor - MessageProcessor instance
971
+ */
972
+ setMessageProcessor(messageProcessor) {
973
+ this.messageProcessor = messageProcessor;
974
+ }
975
+
976
+ /**
977
+ * Set AgentScheduler reference for managing agent modes
978
+ * @param {AgentScheduler} scheduler - AgentScheduler instance
979
+ */
980
+ setScheduler(scheduler) {
981
+ this.scheduler = scheduler;
982
+
983
+ this.logger?.info('AgentScheduler reference set for agent pool', {
984
+ hasScheduler: !!scheduler
985
+ });
986
+ }
987
+
988
+ /**
989
+ * Set FileAttachmentService reference for cleaning up attachments
990
+ * @param {FileAttachmentService} fileAttachmentService - FileAttachmentService instance
991
+ */
992
+ setFileAttachmentService(fileAttachmentService) {
993
+ this.fileAttachmentService = fileAttachmentService;
994
+
995
+ this.logger?.info('FileAttachmentService reference set for agent pool', {
996
+ hasService: !!fileAttachmentService
997
+ });
998
+ }
999
+
1000
+ // OLD INTER-AGENT MESSAGE QUEUE SYSTEM REMOVED
1001
+ // Now using the new messageQueues system with AgentScheduler
1002
+ // Inter-agent messages are queued via addInterAgentMessage() method
1003
+
1004
+ /**
1005
+ * Add message to agent's user message queue
1006
+ * @param {string} agentId - Agent ID
1007
+ * @param {Object} message - User message to queue
1008
+ * @returns {Promise<void>}
1009
+ */
1010
+ async addUserMessage(agentId, message) {
1011
+ const agent = await this.getAgent(agentId);
1012
+ if (!agent) {
1013
+ throw new Error(`Agent not found: ${agentId}`);
1014
+ }
1015
+
1016
+ const queuedMessage = {
1017
+ ...message,
1018
+ id: message.id || `user-msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1019
+ queuedAt: new Date().toISOString(),
1020
+ timestamp: message.timestamp || new Date().toISOString()
1021
+ };
1022
+
1023
+ agent.messageQueues.userMessages.push(queuedMessage);
1024
+ await this.persistAgentState(agentId);
1025
+
1026
+ this.logger.info(`User message queued for agent: ${agentId}`, {
1027
+ messageId: queuedMessage.id,
1028
+ queueSize: agent.messageQueues.userMessages.length
1029
+ });
1030
+ }
1031
+
1032
+ /**
1033
+ * Add message to agent's inter-agent message queue
1034
+ * @param {string} agentId - Agent ID
1035
+ * @param {Object} message - Inter-agent message to queue
1036
+ * @returns {Promise<void>}
1037
+ */
1038
+ async addInterAgentMessage(agentId, message) {
1039
+ const agent = await this.getAgent(agentId);
1040
+ if (!agent) {
1041
+ throw new Error(`Agent not found: ${agentId}`);
1042
+ }
1043
+
1044
+ const queuedMessage = {
1045
+ ...message,
1046
+ id: message.id || message.messageId || `inter-agent-msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1047
+ queuedAt: new Date().toISOString(),
1048
+ timestamp: message.timestamp || new Date().toISOString()
1049
+ };
1050
+
1051
+ agent.messageQueues.interAgentMessages.push(queuedMessage);
1052
+ await this.persistAgentState(agentId);
1053
+
1054
+ this.logger.info(`Inter-agent message queued for agent: ${agentId}`, {
1055
+ messageId: queuedMessage.id,
1056
+ sender: message.sender || message.senderName,
1057
+ queueSize: agent.messageQueues.interAgentMessages.length
1058
+ });
1059
+ }
1060
+
1061
+ /**
1062
+ * Add tool result to agent's tool results queue
1063
+ * @param {string} agentId - Agent ID
1064
+ * @param {Object} toolResult - Tool result to queue
1065
+ * @returns {Promise<void>}
1066
+ */
1067
+ async addToolResult(agentId, toolResult) {
1068
+ const agent = await this.getAgent(agentId);
1069
+ if (!agent) {
1070
+ throw new Error(`Agent not found: ${agentId}`);
1071
+ }
1072
+
1073
+ const queuedResult = {
1074
+ ...toolResult,
1075
+ id: toolResult.id || `tool-result-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1076
+ queuedAt: new Date().toISOString(),
1077
+ timestamp: toolResult.timestamp || new Date().toISOString()
1078
+ };
1079
+
1080
+ agent.messageQueues.toolResults.push(queuedResult);
1081
+ await this.persistAgentState(agentId);
1082
+
1083
+ this.logger.debug(`Tool result queued for agent: ${agentId}`, {
1084
+ toolId: toolResult.toolId,
1085
+ status: toolResult.status,
1086
+ queueSize: agent.messageQueues.toolResults.length
1087
+ });
1088
+ }
1089
+
1090
+ /**
1091
+ * Clear all message queues for an agent
1092
+ * @param {string} agentId - Agent ID
1093
+ * @returns {Promise<void>}
1094
+ */
1095
+ async clearAgentQueues(agentId) {
1096
+ const agent = await this.getAgent(agentId);
1097
+ if (!agent) {
1098
+ throw new Error(`Agent not found: ${agentId}`);
1099
+ }
1100
+
1101
+ agent.messageQueues.toolResults = [];
1102
+ agent.messageQueues.interAgentMessages = [];
1103
+ agent.messageQueues.userMessages = [];
1104
+
1105
+ await this.persistAgentState(agentId);
1106
+
1107
+ this.logger.info(`Message queues cleared for agent: ${agentId}`);
1108
+ }
1109
+
1110
+ /**
1111
+ * Get total queued messages count for an agent
1112
+ * @param {string} agentId - Agent ID
1113
+ * @returns {Promise<Object>} Queue counts by type
1114
+ */
1115
+ async getQueueCounts(agentId) {
1116
+ const agent = await this.getAgent(agentId);
1117
+ if (!agent) {
1118
+ return { toolResults: 0, interAgentMessages: 0, userMessages: 0, total: 0 };
1119
+ }
1120
+
1121
+ const counts = {
1122
+ toolResults: agent.messageQueues.toolResults.length,
1123
+ interAgentMessages: agent.messageQueues.interAgentMessages.length,
1124
+ userMessages: agent.messageQueues.userMessages.length
1125
+ };
1126
+
1127
+ counts.total = counts.toolResults + counts.interAgentMessages + counts.userMessages;
1128
+
1129
+ return counts;
1130
+ }
1131
+
1132
+ /**
1133
+ * Get messages for AI request - returns compacted if available, otherwise original
1134
+ * CRITICAL FIX: Ensures compacted messages stay in sync with new messages after compaction
1135
+ * This is the primary method that should be used when preparing messages for AI service
1136
+ * @param {string} agentId - Agent ID
1137
+ * @param {string} modelId - Model ID
1138
+ * @returns {Promise<Array>} Messages array to send to AI
1139
+ */
1140
+ async getMessagesForAI(agentId, modelId) {
1141
+ const ENABLE_COMPACT_DEBUG = process.env.COMPACT_DEBUG === 'true';
1142
+
1143
+ const agent = await this.getAgent(agentId);
1144
+ if (!agent) {
1145
+ throw new Error(`Agent not found: ${agentId}`);
1146
+ }
1147
+
1148
+ const conversation = agent.conversations[modelId];
1149
+ if (!conversation) {
1150
+ this.logger.warn(`No conversation found for model: ${modelId}`, { agentId });
1151
+ return [];
1152
+ }
1153
+
1154
+ // If no compacted messages exist, return original
1155
+ if (!conversation.compactizedMessages) {
1156
+ this.logger.debug('Retrieved messages for AI (no compaction)', {
1157
+ agentId,
1158
+ modelId,
1159
+ messageCount: conversation.messages.length
1160
+ });
1161
+
1162
+ if (ENABLE_COMPACT_DEBUG) {
1163
+ console.log('[GET-MESSAGES-FOR-AI]', {
1164
+ agentId,
1165
+ modelId,
1166
+ returnedArray: 'originalMessages',
1167
+ messageCount: conversation.messages.length,
1168
+ reason: 'No compacted messages exist'
1169
+ });
1170
+ }
1171
+
1172
+ return conversation.messages;
1173
+ }
1174
+
1175
+ // CRITICAL FIX: Check if new messages were added after compaction
1176
+ // This fixes the bug where user input was ignored after compaction
1177
+ const compactedLength = conversation.compactizedMessages.length;
1178
+ const originalLength = conversation.messages.length;
1179
+
1180
+ if (originalLength > compactedLength) {
1181
+ // New messages exist in original that aren't in compacted
1182
+ const missingMessages = conversation.messages.slice(compactedLength);
1183
+
1184
+ this.logger.info('Syncing compacted messages with new messages', {
1185
+ agentId,
1186
+ modelId,
1187
+ compactedLength,
1188
+ originalLength,
1189
+ missingCount: missingMessages.length
1190
+ });
1191
+
1192
+ // Append missing messages to compacted array
1193
+ conversation.compactizedMessages.push(...missingMessages);
1194
+
1195
+ // Persist the update
1196
+ await this.persistAgentState(agentId);
1197
+ }
1198
+
1199
+ this.logger.debug('Retrieved messages for AI (compacted + synced)', {
1200
+ agentId,
1201
+ modelId,
1202
+ messageCount: conversation.compactizedMessages.length,
1203
+ wasResynced: originalLength > compactedLength
1204
+ });
1205
+
1206
+ if (ENABLE_COMPACT_DEBUG) {
1207
+ console.log('[GET-MESSAGES-FOR-AI]', {
1208
+ agentId,
1209
+ modelId,
1210
+ returnedArray: 'compactizedMessages',
1211
+ messageCount: conversation.compactizedMessages.length,
1212
+ originalMessageCount: conversation.messages.length,
1213
+ wasSynced: originalLength > compactedLength,
1214
+ syncedMessageCount: originalLength > compactedLength ? originalLength - compactedLength : 0,
1215
+ reason: 'Compacted messages exist, returning compacted version'
1216
+ });
1217
+ }
1218
+
1219
+ return conversation.compactizedMessages;
1220
+ }
1221
+
1222
+ /**
1223
+ * Add message to conversation (stores in original messages array)
1224
+ * @param {string} agentId - Agent ID
1225
+ * @param {string} modelId - Model ID
1226
+ * @param {Object} message - Message object to add
1227
+ * @returns {Promise<void>}
1228
+ */
1229
+ async addMessageToConversation(agentId, modelId, message) {
1230
+ const ENABLE_COMPACT_DEBUG = process.env.COMPACT_DEBUG === 'true';
1231
+
1232
+ const agent = await this.getAgent(agentId);
1233
+ if (!agent) {
1234
+ throw new Error(`Agent not found: ${agentId}`);
1235
+ }
1236
+
1237
+ // Ensure model conversation exists
1238
+ if (!agent.conversations[modelId]) {
1239
+ agent.conversations[modelId] = this._createEmptyConversation(modelId);
1240
+ }
1241
+
1242
+ const conversation = agent.conversations[modelId];
1243
+
1244
+ const originalLengthBefore = conversation.messages.length;
1245
+ const compactedLengthBefore = conversation.compactizedMessages?.length || 0;
1246
+
1247
+ // Always add to original messages (never modify original)
1248
+ conversation.messages.push({
1249
+ ...message,
1250
+ timestamp: message.timestamp || new Date().toISOString()
1251
+ });
1252
+
1253
+ // If compacted version exists, also add to it (append new messages after compaction)
1254
+ if (conversation.compactizedMessages) {
1255
+ conversation.compactizedMessages.push({
1256
+ ...message,
1257
+ timestamp: message.timestamp || new Date().toISOString()
1258
+ });
1259
+ }
1260
+
1261
+ conversation.lastUpdated = new Date().toISOString();
1262
+
1263
+ if (ENABLE_COMPACT_DEBUG) {
1264
+ console.log('[ADD-MESSAGE-TO-CONVERSATION]', {
1265
+ agentId,
1266
+ modelId,
1267
+ role: message.role,
1268
+ hasCompactedVersion: !!conversation.compactizedMessages,
1269
+ originalMessages: {
1270
+ before: originalLengthBefore,
1271
+ after: conversation.messages.length,
1272
+ added: 1
1273
+ },
1274
+ compactizedMessages: conversation.compactizedMessages ? {
1275
+ before: compactedLengthBefore,
1276
+ after: conversation.compactizedMessages.length,
1277
+ added: 1
1278
+ } : null,
1279
+ behavior: conversation.compactizedMessages ? 'Added to BOTH arrays' : 'Added to original only'
1280
+ });
1281
+ }
1282
+
1283
+ await this.persistAgentState(agentId);
1284
+
1285
+ this.logger.debug('Message added to conversation', {
1286
+ agentId,
1287
+ modelId,
1288
+ role: message.role,
1289
+ hasCompacted: !!conversation.compactizedMessages
1290
+ });
1291
+ }
1292
+
1293
+ /**
1294
+ * Update compacted messages after compactization
1295
+ * @param {string} agentId - Agent ID
1296
+ * @param {string} modelId - Model ID
1297
+ * @param {Object} compactionResult - Compaction result with messages and metadata
1298
+ * @returns {Promise<void>}
1299
+ */
1300
+ async updateCompactedMessages(agentId, modelId, compactionResult) {
1301
+ const agent = await this.getAgent(agentId);
1302
+ if (!agent) {
1303
+ throw new Error(`Agent not found: ${agentId}`);
1304
+ }
1305
+
1306
+ // Ensure model conversation exists (important for model switching scenarios)
1307
+ if (!agent.conversations[modelId]) {
1308
+ agent.conversations[modelId] = this._createEmptyConversation(modelId);
1309
+ this.logger.debug(`Created conversation for model switching: ${modelId}`);
1310
+ }
1311
+
1312
+ const conversation = agent.conversations[modelId];
1313
+
1314
+ // Update compacted messages
1315
+ conversation.compactizedMessages = compactionResult.compactedMessages;
1316
+
1317
+ // Update metadata
1318
+ conversation.lastCompactization = new Date().toISOString();
1319
+ conversation.compactizationCount += 1;
1320
+ conversation.compactizationStrategy = compactionResult.strategy;
1321
+ conversation.originalTokenCount = compactionResult.originalTokenCount;
1322
+ conversation.compactedTokenCount = compactionResult.compactedTokenCount;
1323
+ conversation.tokenCount = compactionResult.compactedTokenCount;
1324
+ conversation.lastUpdated = new Date().toISOString();
1325
+
1326
+ await this.persistAgentState(agentId);
1327
+
1328
+ this.logger.info('Compacted messages updated', {
1329
+ agentId,
1330
+ modelId,
1331
+ strategy: compactionResult.strategy,
1332
+ originalTokens: compactionResult.originalTokenCount,
1333
+ compactedTokens: compactionResult.compactedTokenCount,
1334
+ reductionPercent: compactionResult.reductionPercent,
1335
+ compactizationCount: conversation.compactizationCount
1336
+ });
1337
+ }
1338
+
1339
+ /**
1340
+ * Clear compacted messages and revert to original
1341
+ * Useful for debugging or if compaction needs to be redone
1342
+ * @param {string} agentId - Agent ID
1343
+ * @param {string} modelId - Model ID
1344
+ * @returns {Promise<void>}
1345
+ */
1346
+ async clearCompactedMessages(agentId, modelId) {
1347
+ const agent = await this.getAgent(agentId);
1348
+ if (!agent) {
1349
+ throw new Error(`Agent not found: ${agentId}`);
1350
+ }
1351
+
1352
+ const conversation = agent.conversations[modelId];
1353
+ if (!conversation) {
1354
+ return;
1355
+ }
1356
+
1357
+ conversation.compactizedMessages = null;
1358
+ conversation.lastCompactization = null;
1359
+ conversation.compactizationCount = 0;
1360
+ conversation.compactizationStrategy = null;
1361
+ conversation.originalTokenCount = 0;
1362
+ conversation.compactedTokenCount = 0;
1363
+ conversation.tokenCount = 0;
1364
+
1365
+ await this.persistAgentState(agentId);
1366
+
1367
+ this.logger.info('Compacted messages cleared', { agentId, modelId });
1368
+ }
1369
+
1370
+ /**
1371
+ * Get compaction metadata for a conversation
1372
+ * @param {string} agentId - Agent ID
1373
+ * @param {string} modelId - Model ID
1374
+ * @returns {Promise<Object|null>} Compaction metadata or null if no compaction
1375
+ */
1376
+ async getCompactionMetadata(agentId, modelId) {
1377
+ const agent = await this.getAgent(agentId);
1378
+ if (!agent) {
1379
+ return null;
1380
+ }
1381
+
1382
+ const conversation = agent.conversations[modelId];
1383
+ if (!conversation) {
1384
+ return null;
1385
+ }
1386
+
1387
+ // Return metadata whether compacted or not
1388
+ const isCompacted = !!conversation.compactizedMessages;
1389
+
1390
+ return {
1391
+ isCompacted,
1392
+ lastCompactization: conversation.lastCompactization || null,
1393
+ compactizationCount: conversation.compactizationCount || 0,
1394
+ strategy: conversation.compactizationStrategy || null,
1395
+ originalTokenCount: conversation.originalTokenCount || 0,
1396
+ compactedTokenCount: conversation.compactedTokenCount || 0,
1397
+ reductionPercent: conversation.originalTokenCount > 0
1398
+ ? ((conversation.originalTokenCount - conversation.compactedTokenCount) / conversation.originalTokenCount) * 100
1399
+ : 0,
1400
+ originalMessages: conversation.messages || [],
1401
+ compactedMessages: conversation.compactizedMessages || null,
1402
+ originalMessageCount: conversation.messages?.length || 0,
1403
+ compactedMessageCount: conversation.compactizedMessages?.length || 0
1404
+ };
1405
+ }
1406
+
1407
+ /**
1408
+ * Migrate existing agent conversations to dual storage structure
1409
+ * Ensures backward compatibility with existing agents
1410
+ * @param {string} agentId - Agent ID
1411
+ * @returns {Promise<boolean>} True if migration was needed and performed
1412
+ */
1413
+ async migrateConversationStructure(agentId) {
1414
+ const agent = await this.getAgent(agentId);
1415
+ if (!agent) {
1416
+ return false;
1417
+ }
1418
+
1419
+ let migrated = false;
1420
+
1421
+ // Check each conversation for migration needs
1422
+ for (const [modelId, conversation] of Object.entries(agent.conversations)) {
1423
+ if (modelId === 'full') continue; // Skip full conversation
1424
+
1425
+ // Check if conversation needs migration (missing new fields)
1426
+ if (conversation.compactizedMessages === undefined) {
1427
+ // Add new fields
1428
+ conversation.compactizedMessages = null;
1429
+ conversation.lastCompactization = null;
1430
+ conversation.compactizationCount = 0;
1431
+ conversation.compactizationStrategy = null;
1432
+ conversation.originalTokenCount = 0;
1433
+ conversation.compactedTokenCount = 0;
1434
+
1435
+ migrated = true;
1436
+
1437
+ this.logger.info('Migrated conversation structure', {
1438
+ agentId,
1439
+ modelId,
1440
+ messageCount: conversation.messages?.length || 0
1441
+ });
1442
+ }
1443
+ }
1444
+
1445
+ if (migrated) {
1446
+ await this.persistAgentState(agentId);
1447
+ }
1448
+
1449
+ return migrated;
1450
+ }
1451
+
1452
+ /**
1453
+ * Create empty conversation structure with all required fields
1454
+ * @private
1455
+ * @param {string} modelId - Model ID
1456
+ * @returns {Object} Empty conversation structure
1457
+ */
1458
+ _createEmptyConversation(modelId) {
1459
+ return {
1460
+ messages: [],
1461
+ compactizedMessages: null,
1462
+ lastCompactization: null,
1463
+ compactizationCount: 0,
1464
+ compactizationStrategy: null,
1465
+ originalTokenCount: 0,
1466
+ compactedTokenCount: 0,
1467
+ tokenCount: 0,
1468
+ lastUpdated: new Date().toISOString(),
1469
+ formatVersion: this._getModelFormatVersion(modelId)
1470
+ };
1471
+ }
1472
+ }
1473
+
1474
+ export default AgentPool;