@loxia-labs/loxia-autopilot-one 1.0.1 → 1.0.3

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 (120) hide show
  1. package/README.md +44 -54
  2. package/bin/cli.js +1 -115
  3. package/bin/loxia-terminal-v2.js +3 -0
  4. package/bin/loxia-terminal.js +3 -0
  5. package/bin/start-with-terminal.js +3 -0
  6. package/package.json +14 -15
  7. package/scripts/install-scanners.js +1 -235
  8. package/src/analyzers/CSSAnalyzer.js +1 -297
  9. package/src/analyzers/ConfigValidator.js +1 -690
  10. package/src/analyzers/ESLintAnalyzer.js +1 -320
  11. package/src/analyzers/JavaScriptAnalyzer.js +1 -261
  12. package/src/analyzers/PrettierFormatter.js +1 -247
  13. package/src/analyzers/PythonAnalyzer.js +1 -266
  14. package/src/analyzers/SecurityAnalyzer.js +1 -729
  15. package/src/analyzers/TypeScriptAnalyzer.js +1 -247
  16. package/src/analyzers/codeCloneDetector/analyzer.js +1 -344
  17. package/src/analyzers/codeCloneDetector/detector.js +1 -203
  18. package/src/analyzers/codeCloneDetector/index.js +1 -160
  19. package/src/analyzers/codeCloneDetector/parser.js +1 -199
  20. package/src/analyzers/codeCloneDetector/reporter.js +1 -148
  21. package/src/analyzers/codeCloneDetector/scanner.js +1 -59
  22. package/src/core/agentPool.js +1 -1474
  23. package/src/core/agentScheduler.js +1 -2147
  24. package/src/core/contextManager.js +1 -709
  25. package/src/core/messageProcessor.js +1 -732
  26. package/src/core/orchestrator.js +1 -548
  27. package/src/core/stateManager.js +1 -877
  28. package/src/index.js +1 -631
  29. package/src/interfaces/cli.js +1 -549
  30. package/src/interfaces/terminal/__tests__/smoke/advancedFeatures.test.js +1 -0
  31. package/src/interfaces/terminal/__tests__/smoke/agentControl.test.js +1 -0
  32. package/src/interfaces/terminal/__tests__/smoke/agents.test.js +1 -0
  33. package/src/interfaces/terminal/__tests__/smoke/components.test.js +1 -0
  34. package/src/interfaces/terminal/__tests__/smoke/connection.test.js +1 -0
  35. package/src/interfaces/terminal/__tests__/smoke/enhancements.test.js +1 -0
  36. package/src/interfaces/terminal/__tests__/smoke/imports.test.js +1 -0
  37. package/src/interfaces/terminal/__tests__/smoke/messages.test.js +1 -0
  38. package/src/interfaces/terminal/__tests__/smoke/tools.test.js +1 -0
  39. package/src/interfaces/terminal/api/apiClient.js +1 -0
  40. package/src/interfaces/terminal/api/messageRouter.js +1 -0
  41. package/src/interfaces/terminal/api/session.js +1 -0
  42. package/src/interfaces/terminal/api/websocket.js +1 -0
  43. package/src/interfaces/terminal/components/AgentCreator.js +1 -0
  44. package/src/interfaces/terminal/components/AgentEditor.js +1 -0
  45. package/src/interfaces/terminal/components/AgentSwitcher.js +1 -0
  46. package/src/interfaces/terminal/components/ErrorBoundary.js +1 -0
  47. package/src/interfaces/terminal/components/ErrorPanel.js +1 -0
  48. package/src/interfaces/terminal/components/Header.js +1 -0
  49. package/src/interfaces/terminal/components/HelpPanel.js +1 -0
  50. package/src/interfaces/terminal/components/InputBox.js +1 -0
  51. package/src/interfaces/terminal/components/Layout.js +1 -0
  52. package/src/interfaces/terminal/components/LoadingSpinner.js +1 -0
  53. package/src/interfaces/terminal/components/MessageList.js +1 -0
  54. package/src/interfaces/terminal/components/MultilineTextInput.js +1 -0
  55. package/src/interfaces/terminal/components/SearchPanel.js +1 -0
  56. package/src/interfaces/terminal/components/SettingsPanel.js +1 -0
  57. package/src/interfaces/terminal/components/StatusBar.js +1 -0
  58. package/src/interfaces/terminal/components/TextInput.js +1 -0
  59. package/src/interfaces/terminal/config/agentEditorConstants.js +1 -0
  60. package/src/interfaces/terminal/config/constants.js +1 -0
  61. package/src/interfaces/terminal/index.js +1 -0
  62. package/src/interfaces/terminal/state/useAgentControl.js +1 -0
  63. package/src/interfaces/terminal/state/useAgents.js +1 -0
  64. package/src/interfaces/terminal/state/useConnection.js +1 -0
  65. package/src/interfaces/terminal/state/useMessages.js +1 -0
  66. package/src/interfaces/terminal/state/useTools.js +1 -0
  67. package/src/interfaces/terminal/utils/debugLogger.js +1 -0
  68. package/src/interfaces/terminal/utils/settingsStorage.js +1 -0
  69. package/src/interfaces/terminal/utils/theme.js +1 -0
  70. package/src/interfaces/webServer.js +1 -2162
  71. package/src/modules/fileExplorer/controller.js +1 -280
  72. package/src/modules/fileExplorer/index.js +1 -37
  73. package/src/modules/fileExplorer/middleware.js +1 -92
  74. package/src/modules/fileExplorer/routes.js +1 -125
  75. package/src/modules/fileExplorer/types.js +1 -44
  76. package/src/services/aiService.js +1 -1232
  77. package/src/services/apiKeyManager.js +1 -164
  78. package/src/services/benchmarkService.js +1 -366
  79. package/src/services/budgetService.js +1 -539
  80. package/src/services/contextInjectionService.js +1 -247
  81. package/src/services/conversationCompactionService.js +1 -637
  82. package/src/services/errorHandler.js +1 -810
  83. package/src/services/fileAttachmentService.js +1 -544
  84. package/src/services/modelRouterService.js +1 -366
  85. package/src/services/modelsService.js +1 -322
  86. package/src/services/qualityInspector.js +1 -796
  87. package/src/services/tokenCountingService.js +1 -536
  88. package/src/tools/agentCommunicationTool.js +1 -1344
  89. package/src/tools/agentDelayTool.js +1 -485
  90. package/src/tools/asyncToolManager.js +1 -604
  91. package/src/tools/baseTool.js +1 -800
  92. package/src/tools/browserTool.js +1 -920
  93. package/src/tools/cloneDetectionTool.js +1 -621
  94. package/src/tools/dependencyResolverTool.js +1 -1215
  95. package/src/tools/fileContentReplaceTool.js +1 -875
  96. package/src/tools/fileSystemTool.js +1 -1107
  97. package/src/tools/fileTreeTool.js +1 -853
  98. package/src/tools/imageTool.js +1 -901
  99. package/src/tools/importAnalyzerTool.js +1 -1060
  100. package/src/tools/jobDoneTool.js +1 -248
  101. package/src/tools/seekTool.js +1 -956
  102. package/src/tools/staticAnalysisTool.js +1 -1778
  103. package/src/tools/taskManagerTool.js +1 -2873
  104. package/src/tools/terminalTool.js +1 -2304
  105. package/src/tools/webTool.js +1 -1430
  106. package/src/types/agent.js +1 -519
  107. package/src/types/contextReference.js +1 -972
  108. package/src/types/conversation.js +1 -730
  109. package/src/types/toolCommand.js +1 -747
  110. package/src/utilities/attachmentValidator.js +1 -292
  111. package/src/utilities/configManager.js +1 -582
  112. package/src/utilities/constants.js +1 -722
  113. package/src/utilities/directoryAccessManager.js +1 -535
  114. package/src/utilities/fileProcessor.js +1 -307
  115. package/src/utilities/logger.js +1 -436
  116. package/src/utilities/tagParser.js +1 -1246
  117. package/src/utilities/toolConstants.js +1 -317
  118. package/web-ui/build/index.html +2 -2
  119. package/web-ui/build/static/{index-Dy2bYbOa.css → index-CClD1090.css} +1 -1
  120. package/web-ui/build/static/{index-CjkkcnFA.js → index-lCBai6dX.js} +66 -67
@@ -1,1474 +1 @@
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;
1
+ function a0_0xc205(_0x121e4e,_0x51c543){_0x121e4e=_0x121e4e-0x15b;const _0x201366=a0_0x2013();let _0xc2055f=_0x201366[_0x121e4e];if(a0_0xc205['dhFZcX']===undefined){var _0x79c81a=function(_0x2fc5ca){const _0x27b692='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x1417a5='',_0x12b524='';for(let _0x22f0a2=0x0,_0x9212a9,_0x17475e,_0x2762f4=0x0;_0x17475e=_0x2fc5ca['charAt'](_0x2762f4++);~_0x17475e&&(_0x9212a9=_0x22f0a2%0x4?_0x9212a9*0x40+_0x17475e:_0x17475e,_0x22f0a2++%0x4)?_0x1417a5+=String['fromCharCode'](0xff&_0x9212a9>>(-0x2*_0x22f0a2&0x6)):0x0){_0x17475e=_0x27b692['indexOf'](_0x17475e);}for(let _0x1895f1=0x0,_0xca1f25=_0x1417a5['length'];_0x1895f1<_0xca1f25;_0x1895f1++){_0x12b524+='%'+('00'+_0x1417a5['charCodeAt'](_0x1895f1)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x12b524);};a0_0xc205['NEOqwF']=_0x79c81a,a0_0xc205['NcRMgg']={},a0_0xc205['dhFZcX']=!![];}const _0x31d316=_0x201366[0x0],_0x4d09fe=_0x121e4e+_0x31d316,_0x189f73=a0_0xc205['NcRMgg'][_0x4d09fe];return!_0x189f73?(_0xc2055f=a0_0xc205['NEOqwF'](_0xc2055f),a0_0xc205['NcRMgg'][_0x4d09fe]=_0xc2055f):_0xc2055f=_0x189f73,_0xc2055f;}const a0_0x1eaa50=a0_0xc205;(function(_0x214cbb,_0x2d0641){const _0x2a2695=a0_0xc205,_0x2cdcf1=_0x214cbb();while(!![]){try{const _0x33e09a=-parseInt(_0x2a2695(0x1fc))/0x1+-parseInt(_0x2a2695(0x16d))/0x2+-parseInt(_0x2a2695(0x1cf))/0x3+parseInt(_0x2a2695(0x188))/0x4+-parseInt(_0x2a2695(0x19f))/0x5*(parseInt(_0x2a2695(0x1c1))/0x6)+parseInt(_0x2a2695(0x1d9))/0x7+parseInt(_0x2a2695(0x15f))/0x8;if(_0x33e09a===_0x2d0641)break;else _0x2cdcf1['push'](_0x2cdcf1['shift']());}catch(_0x1bc18d){_0x2cdcf1['push'](_0x2cdcf1['shift']());}}}(a0_0x2013,0xe7fa8));function a0_0x2013(){const _0x4c4bd1=['u3LZDgvTihbYB21WDcbYzwDLBMvYyxrLzcb3AxrOihvWzgf0zwqGy2fWywjPBgL0AwvZ','CM9Szq','C3LZDgvT','rMLSzsbHDhrHy2HTzw50CYbJBgvHBMvKihvWigzVCIbHz2vUDdOG','y29TCgfJDgL6zwrnzxnZywDLCW','mtaZognzB1rdvG','qwDLBNqG','qwDLBNrqB29SierfqLvhoIbJCMvHDgvbz2vUDcaTifvZAw5NihbYB3zPzgvKigrPCMvJDg9YEufJy2vZCW','ihn3AxrJAgLUzYb0BYbbr0vovcbTB2rLigj1DcbOyxmGBM8GC2vZC2LVBKLKic0GDgHPCYb3AwXSignHDxnLiefqssbRzxKGCMvZB2X1DgLVBIbPC3n1zxm','vg9VBcbYzxn1BhqGCxvLDwvKigzVCIbHz2vUDdOG','zhLUyw1Py01VzgvSuM91DgLUzW','zw52','Dg90ywW','x2nYzwf0zuvTChr5q29UDMvYC2f0Aw9U','twLNCMf0zwqGy29UDMvYC2f0Aw9Uihn0CNvJDhvYzq','C2v0','rMfPBgvKihrVignSzwfUihvWigzPBguGyxr0ywnOBwvUDhmGzM9YigfNzw50oIa','BwvZC2fNzxm','BwvZC2fNzvbYB2nLC3nVCG','nti3mte1owDUsvPbCa','BgfZDenVBxbHy3rPEMf0Aw9U','q29TCgfJDgvKig1LC3nHz2vZigv4Axn0lcbYzxr1CM5PBMCGy29TCgfJDgvKihzLCNnPB24','Bwf4ugf1C2veDxjHDgLVBG','C2vZC2LVBKLK','B3jPz2LUywXuB2TLBKnVDw50','ywDLBNreAxjLy3rVCNK','Aw50zxjbz2vUDe1LC3nHz2vZ','twf4Aw11BsbHz2vUDhmGCgvYihbYB2PLy3qGzxHJzwvKzwqGka','BwLNCMf0zunVBNzLCNnHDgLVBLn0CNvJDhvYzq','mteXnZC1ndrdELDnANK','q0Hbva','x3vWzgf0zufNzw50rgLYzwn0B3j5','rvHju1rt','y3vYCMvUDe1VzgvS','rMfPBgvKihrVigvUAgfUy2uGC3LZDgvTihbYB21WDcb3AxrOihrVB2XZ','CMvHze9UBhLeAxjLy3rVCMLLCW','BgLZDefJDgL2zufNzw50CW','ic0Gq2fWywjPBgL0AwvZoIa','uMvTB3zPBMCGywDLBNqGzNjVBsbZy2HLzhvSzxiGkhn3AxrJAgvKihrVieniqvqGBw9KzsK6ia','Bwf4qwDLBNrZugvYuhjVAMvJDa','ywrKvg9VBfjLC3vSDa','uefvu0ve','BM90AwzPy2f0Aw9UuxvLDwu','zw5Oyw5Jzvn5C3rLBvbYB21WDa','BMfTzq','uMv0CMLLDMvKig1LC3nHz2vZigzVCIbbssaOBM8Gy29TCgfJDgLVBIK','DhLWzq','ihjLC3vTzwqGC3vJy2vZC2z1BgX5','C3vIC3rY','vxbKyxrPBMCGywDLBNq6ia','A2v5CW','y29UDMvYC2f0Aw9Uswq','yNvSA1jLzNjLC2HuB29SrgvZy3jPChrPB25Z','revgqvvmva','CMvXDwLYzxnszxnWB25Zzq','CMvZDw1LqwDLBNq','y29UDMvYC2f0Aw9UCW','y2XLyxjdB21Wywn0zwrnzxnZywDLCW','vg9VBhmGCMvNAxn0CNKGDxbKyxrLzcbMB3iGywDLBNqGCg9VBa','y29TCgfJDgL6yxrPB25dB3vUDa','qwDLBNrqB29SierfqLvhoIbJCMvHDgvbz2vUDcaTignVBMzPzY5KAxjLy3rVCNLby2nLC3m6','vvnfuL9duKvbveve','ChjLzMvYCMvKtw9KzwW','BwfW','mti2ntKWnwvArgrzsa','BwvZC2fNzvf1zxvLCW','Dg9VBeLK','CgvYC2LZDefNzw50u3rHDgu','BM90Awz5qwDLBNq','zxjYB3i','Cgf1C2vKqwDLBNrZ','q09nuefdvf9erujvrW','Bw9Kzq','Cgf1C2vK','AM9PBG','DgLTzxn0yw1W','zNvSBa','DxbKyxrLqwDLBNq','ywn0AxzL','BM93','Dg9VBhnszwDPC3rYEq','CMvKDwn0Aw9UugvYy2vUDa','z2v0','CMvZDg9YzufNzw50','z2v0vgLTzq','CMfUzg9T','y2fWywjPBgL0AwvZ','qwDLBNrqB29SierfqLvhoIbJCMvHDgvbz2vUDcaTierLzMf1BhqGzgLYzwn0B3j5qwnJzxnZoG','z2v0qwDLBNq','tufyx0fhru5uu19qrvjFufjpsKvdva','u3LZDgvTihbYB21WDcbLBMHHBMnLzcb3AxrOihrVB2WGzgvZy3jPChrPB25Z','DxbKyxrLq29TCgfJDgvKtwvZC2fNzxm','Aw5MBW','qwDLBNqGBM90igzVDw5KoIa','mJK1oty3nJb5uvjYrw0','w0ferc1nrvntquDflvrplunptLzfuLnbveLptL0','DxnLCK1LC3nHz2vZ','C3rYyxrLz3K','zMfPBgvK','D2fYBG','CgXHDgzVCM1qCM92AwrLza','CMvWBgfJzq','tM8Gy29UDMvYC2f0Aw9UigzVDw5KigzVCIbTB2rLBdOG','z2v0twvZC2fNzxngB3jbsq','zgvIDwC','qwDLBNqGzgvSzxrLzdOG','Dg9Rzw5dB3vUDa','qwDLBNqGy3jLyxrLzcb3AxrOihjVDxrPBMCGy29UzMLN','mti4nZi3mKD6vMnKuq','C3rYAw5NAwz5','Aw5JBhvKzvrVB2XfEgfTCgXLCW','CMvMCMvZAefNzw50vg9VBerLC2nYAxb0Aw9UCW','C3LZDgvTuhjVBxb0','CM91BMq','C2XPy2u','zxjYB3jZ','zgLYzwn0B3j5qwnJzxnZ','x2zVCM1HDe1LC3nHz2vgB3jnB2rLBa','ywrKsw50zxjbz2vUDe1LC3nHz2u','rgLYzwn0B3j5igfJy2vZCYb2ywXPzgf0Aw9UihbHC3nLzcbMB3iGywDLBNq6ia','qunusvzf','qNvSAYb0B29SigrLC2nYAxb0Aw9UCYbYzwzYzxnOignVBxbSzxrLza','y29TCgfJDfrVB2XezxnJCMLWDgLVBNm','ihf1zxvLzcbUB3rPzMLJyxrPB25ZigzVCIbHz2vUDdOG','qwDLBNqGCgf1C2uGCMvXDwvZDgvK','BgfZDefJDgL2Axr5','Bg9Nz2vY','ywDLBNrZ','ywrKvxnLCK1LC3nHz2u','Dg9ju09tDhjPBMC','x3vWzgf0zufNzw50ugf1C2vtDgf0Dxm','zgLYzwn0B3j5qwnJzxnZtwfUywDLCG','rMLSzuf0DgfJAg1LBNrtzxj2AwnLihjLzMvYzw5JzsbZzxqGzM9YigfNzw50ihbVB2W','x2DLBMvYyxrLqwDLBNrezxnJCMLWDgLVBG','zgvSzxrL','mZe2mtq4ogrftLviwG','C3rHDgvnyw5Hz2vY','qwDLBNrqB29SierfqLvhoIbJCMvHDgvbz2vUDcaTignVBMzPzY5WCM9Qzwn0rgLYoG','zw50CMLLCW','BgfZDfvWzgf0zwq','q29TCgfJDgvKig1LC3nHz2vZihvWzgf0zwq','ChjVAMvJDerPCG','qwDLBNqGC3DPDgnOzwqGDg8GquDftLqGBw9Kzq','AgfZ','Cgf1C2vKvw50AwW','tLvmtc9vtKrfrKLoruq','DxjNzw50','Bg9N','qwrKAw5NigfNzw50ihrVihnJAgvKDwXLCIaOC3DPDgnOzwqGDg8GquDftLqGBw9KzsK6ia','y29TCgfJDgvKtwvZC2fNzxm','zMLSzuf0DgfJAg1LBNrtzxj2AwnL','qwDLBNqGBM90AwzPzwq6ia','qwDLBNrqB29SierfqLvhoIbJCMvHDgvbz2vUDcaTihzHBgLKyxrPB24GCMvZDwX0oG','y29TCgfJDgvKvg9Rzw5dB3vUDa','qwDLBNqT','ChvZAa','rMfPBgvKihrVihjLz2vUzxjHDguGC3LZDgvTihbYB21WDcb3AxrOihvWzgf0zwqGy2fWywjPBgL0AwvZ','y2XLyxjbz2vUDff1zxvLCW','ndi0odvRAKfluLG','C2vUzgvYtMfTzq','BxnNlq','BwvZC2fNzq','Dg9VBfjLC3vSDhm','y29TCgfJDgL6yxrPB25tDhjHDgvNEq','C2L6zq','w0Dfvc1nrvntquDfuY1gt1iTquLD','Bw9Kzs1JAgfUz2uTDg8Ty2HHDa','Axnbz2vUDeLUu2nOzwr1BgvY','x2DLBMvYyxrLqwDLBNrjza','igLZig5VDcbWyxvZzwq','Dg9tDhjPBMC','qwDLBNqGCgf1C2vKoIa','C2nOzwr1BgvY','quDftLrFtK9usuzjq0fusu9o','x2LZugf1C2vfEhbPCMvK','C2v0u2nOzwr1BgvY','y29UDgvUDa','x3f1zxvLtM90AwzPy2f0Aw9U','x2DLDe1VzgvSrM9YBwf0vMvYC2LVBG','BgvUz3rO','x3bYB2nLC3nrDwv1zwroB3rPzMLJyxrPB25Z','quDftLq','y3jLyxrLuhjVAMvJDerLzMf1BhrZ','C2v0vg9VBhnszwDPC3rYEq','zNjVBq','C3rHDhvZ','twvZC2fNzsbHzgrLzcb0BYbJB252zxjZyxrPB24'];a0_0x2013=function(){return _0x4c4bd1;};return a0_0x2013();}import{AGENT_TYPES,AGENT_STATUS,AGENT_MODES,AGENT_MODE_STATES,MESSAGE_ROLES,MESSAGE_TYPES,INTER_AGENT_MESSAGE,MODEL_FORMAT_VERSIONS,SYSTEM_DEFAULTS}from'../utilities/constants.js';import a0_0x1417a5 from'../utilities/directoryAccessManager.js';class AgentPool{constructor(_0x12b524,_0x22f0a2,_0x9212a9,_0x17475e,_0x2762f4=null){const _0x594f2e=a0_0xc205;this['config']=_0x12b524,this['logger']=_0x22f0a2,this[_0x594f2e(0x189)]=_0x9212a9,this['contextManager']=_0x17475e,this['toolsRegistry']=_0x2762f4,this['agents']=new Map(),this['agentDirectory']=new Map(),this['pausedAgents']=new Map(),this['notificationQueue']=new Map(),this['maxAgentsPerProject']=_0x12b524['system']?.[_0x594f2e(0x1e3)]||SYSTEM_DEFAULTS[_0x594f2e(0x215)],this[_0x594f2e(0x1ce)]=null,this[_0x594f2e(0x184)]=new a0_0x1417a5(_0x12b524,_0x22f0a2);}async['createAgent'](_0x1895f1){const _0x445a0e=a0_0xc205;if(this['agents'][_0x445a0e(0x1a5)]>=this['maxAgentsPerProject'])throw new Error(_0x445a0e(0x1d7)+this['maxAgentsPerProject']+')');const _0xca1f25=this[_0x445a0e(0x1a9)](_0x1895f1[_0x445a0e(0x1e8)]),_0x561aba=new Date()['toISOString']();let _0x21807c=_0x1895f1['systemPrompt'];if(this[_0x445a0e(0x20c)]&&_0x1895f1[_0x445a0e(0x212)]&&_0x1895f1[_0x445a0e(0x212)]['length']>0x0)try{_0x21807c=this[_0x445a0e(0x20c)]['enhanceSystemPrompt'](_0x1895f1['systemPrompt'],_0x1895f1[_0x445a0e(0x212)],{'compact':_0x1895f1['compactToolDescriptions']||![],'includeExamples':_0x1895f1[_0x445a0e(0x16f)]!==![],'includeUsageGuidelines':_0x1895f1['includeUsageGuidelines']!==![],'includeSecurityNotes':_0x1895f1['includeSecurityNotes']!==![]}),this[_0x445a0e(0x17f)]?.['info'](_0x445a0e(0x15b),{'agentId':_0xca1f25,'capabilities':_0x1895f1[_0x445a0e(0x212)],'originalLength':_0x1895f1['systemPrompt']?.[_0x445a0e(0x1b4)]||0x0,'enhancedLength':_0x21807c?.['length']||0x0});}catch(_0x466d08){this['logger']?.[_0x445a0e(0x201)](_0x445a0e(0x1de),{'agentId':_0xca1f25,'error':_0x466d08[_0x445a0e(0x1a2)],'capabilities':_0x1895f1['capabilities']}),_0x21807c=_0x1895f1[_0x445a0e(0x171)];}let _0x127491;console['log'](_0x445a0e(0x1f8),_0x1895f1['directoryAccess']?_0x445a0e(0x1dc):_0x445a0e(0x192));_0x1895f1['directoryAccess']&&console['log']('AgentPool DEBUG: createAgent - directoryAccess from config:',JSON[_0x445a0e(0x16e)](_0x1895f1['directoryAccess'],null,0x2));console['log'](_0x445a0e(0x18a),_0x1895f1['projectDir']);if(_0x1895f1[_0x445a0e(0x175)]){const _0x1f84da=this['directoryAccessManager']['validateAccessConfiguration'](_0x1895f1['directoryAccess']);console[_0x445a0e(0x194)](_0x445a0e(0x199),_0x1f84da);if(!_0x1f84da['valid'])throw new Error('Invalid\x20directory\x20access\x20configuration:\x20'+_0x1f84da[_0x445a0e(0x174)]['join'](',\x20'));_0x127491=_0x1895f1[_0x445a0e(0x175)],console[_0x445a0e(0x194)](_0x445a0e(0x1c3));}else{const _0x1d613c=_0x1895f1[_0x445a0e(0x18e)]||process['cwd']();_0x127491=a0_0x1417a5[_0x445a0e(0x1b7)](_0x1d613c),console[_0x445a0e(0x194)]('AgentPool DEBUG: createAgent - Created default directoryAccess for projectDir:',_0x1d613c),console[_0x445a0e(0x194)](_0x445a0e(0x213),JSON[_0x445a0e(0x16e)](_0x127491,null,0x2));}const _0x27a5df={'id':_0xca1f25,'type':_0x1895f1['type']||AGENT_TYPES[_0x445a0e(0x1f9)],'name':_0x1895f1['name']||_0x445a0e(0x19b)+Date[_0x445a0e(0x20b)](),'systemPrompt':_0x21807c,'originalSystemPrompt':_0x1895f1[_0x445a0e(0x171)],'preferredModel':_0x1895f1['preferredModel'],'status':AGENT_STATUS['ACTIVE'],'capabilities':_0x1895f1[_0x445a0e(0x212)]||[],'directoryAccess':_0x127491,'conversations':{'full':{'messages':[],'lastUpdated':_0x561aba}},'currentModel':_0x1895f1['preferredModel'],'dynamicModelRouting':_0x1895f1[_0x445a0e(0x1c6)]||![],'platformProvided':_0x1895f1[_0x445a0e(0x165)]||![],'mode':_0x1895f1['mode']||AGENT_MODES[_0x445a0e(0x1da)],'modeState':AGENT_MODE_STATES['IDLE'],'currentTask':null,'taskStartTime':null,'maxIterations':_0x1895f1['maxIterations']||0xa,'iterationCount':0x0,'stopRequested':![],'delayEndTime':null,'messageQueues':{'toolResults':[],'interAgentMessages':[],'userMessages':[]},'createdAt':_0x561aba,'lastActivity':_0x561aba,'pausedUntil':null,'metadata':_0x1895f1['metadata']||{},'sessionId':_0x1895f1[_0x445a0e(0x1d3)],'interAgentTracking':new Map(),'taskList':{'tasks':[],'lastUpdated':_0x561aba},'incomingMessages':[]};return this['logger'][_0x445a0e(0x15d)](_0x445a0e(0x16c),{'agentId':_0xca1f25,'dynamicModelRouting':_0x27a5df[_0x445a0e(0x1c6)],'platformProvided':_0x27a5df['platformProvided'],'preferredModel':_0x27a5df[_0x445a0e(0x1fa)]}),_0x1895f1['preferredModel']&&(_0x27a5df['conversations'][_0x1895f1[_0x445a0e(0x1fa)]]={'messages':[],'compactizedMessages':null,'lastCompactization':null,'compactizationCount':0x0,'compactizationStrategy':null,'originalTokenCount':0x0,'compactedTokenCount':0x0,'tokenCount':0x0,'lastUpdated':_0x561aba,'formatVersion':this[_0x445a0e(0x1b3)](_0x1895f1['preferredModel'])}),this[_0x445a0e(0x180)]['set'](_0xca1f25,_0x27a5df),this['_updateAgentDirectory'](_0x27a5df),await this[_0x445a0e(0x189)]['persistAgentState'](_0xca1f25),this[_0x445a0e(0x17f)]['info']('Agent\x20created:\x20'+_0xca1f25,{'agentId':_0xca1f25,'name':_0x27a5df['name'],'type':_0x27a5df[_0x445a0e(0x1ea)],'model':_0x27a5df[_0x445a0e(0x1fa)]}),_0x27a5df;}async['getAgent'](_0x360b1b,_0x313cf0=![]){const _0xcfa7fa=a0_0xc205,_0x24d638=this['agents'][_0xcfa7fa(0x20e)](_0x360b1b);if(!_0x24d638)return null;return _0x313cf0&&this[_0xcfa7fa(0x1ad)]&&(_0x24d638['inScheduler']=this[_0xcfa7fa(0x1ad)][_0xcfa7fa(0x1a8)](_0x360b1b)),_0x24d638;}async[a0_0x1eaa50(0x209)](_0x2b78fe,_0x53cc2a){const _0x10e763=a0_0x1eaa50,_0x173296=await this[_0x10e763(0x214)](_0x2b78fe);if(!_0x173296)throw new Error(_0x10e763(0x15e)+_0x2b78fe);this['logger']['info'](_0x10e763(0x1ed)+_0x2b78fe,{'updates':_0x53cc2a,'currentName':_0x173296['name']});if(_0x53cc2a[_0x10e763(0x175)]){const _0x3805c7=this['directoryAccessManager']['validateAccessConfiguration'](_0x53cc2a['directoryAccess']);if(!_0x3805c7['valid'])throw new Error('Invalid\x20directory\x20access\x20configuration:\x20'+_0x3805c7['errors']['join'](',\x20'));this[_0x10e763(0x17f)]['info'](_0x10e763(0x178)+_0x2b78fe,{'workingDirectory':_0x53cc2a['directoryAccess']['workingDirectory'],'readOnlyDirs':_0x53cc2a[_0x10e763(0x175)][_0x10e763(0x1df)]?.[_0x10e763(0x1b4)]||0x0,'writeEnabledDirs':_0x53cc2a[_0x10e763(0x175)]['writeEnabledDirectories']?.['length']||0x0});}if(_0x53cc2a['capabilities']&&this['toolsRegistry'])try{const _0x2cb1c9=_0x173296['originalSystemPrompt']||_0x173296['systemPrompt'],_0x2c0023=this['toolsRegistry'][_0x10e763(0x1e7)](_0x2cb1c9,_0x53cc2a[_0x10e763(0x212)],{'compact':_0x173296[_0x10e763(0x17b)]||![],'includeExamples':_0x173296[_0x10e763(0x16f)]!==![],'includeUsageGuidelines':_0x173296['includeUsageGuidelines']!==![],'includeSecurityNotes':_0x173296['includeSecurityNotes']!==![]});_0x53cc2a['systemPrompt']=_0x2c0023,this['logger'][_0x10e763(0x15d)](_0x10e763(0x1bc),{'agentId':_0x2b78fe,'oldCapabilities':_0x173296['capabilities'],'newCapabilities':_0x53cc2a['capabilities'],'originalLength':_0x2cb1c9?.[_0x10e763(0x1b4)]||0x0,'enhancedLength':_0x2c0023?.['length']||0x0});}catch(_0x337b32){this['logger'][_0x10e763(0x201)](_0x10e763(0x19d),{'agentId':_0x2b78fe,'error':_0x337b32['message'],'capabilities':_0x53cc2a['capabilities']});}const _0xb930c3={..._0x173296,..._0x53cc2a,'id':_0x2b78fe,'lastModified':new Date()[_0x10e763(0x182)](),'lastActivity':new Date()[_0x10e763(0x182)]()};if(_0x53cc2a[_0x10e763(0x1fa)]&&_0x53cc2a[_0x10e763(0x1fa)]!==_0x173296[_0x10e763(0x1fa)]){const _0x10a108=_0x173296[_0x10e763(0x1fa)],_0x22561d=_0x53cc2a['preferredModel'];_0xb930c3[_0x10e763(0x1dd)]=_0x22561d;!_0xb930c3[_0x10e763(0x1f4)][_0x22561d]&&(_0xb930c3['conversations'][_0x22561d]=this['_createEmptyConversation'](_0x22561d),this['logger'][_0x10e763(0x15d)]('Created\x20conversation\x20for\x20new\x20model:\x20'+_0x22561d,{'agentId':_0x2b78fe}));if(_0x10a108&&_0xb930c3['conversations'][_0x10a108]){const _0x1fb002=_0xb930c3['conversations'][_0x10a108],_0x4d843c=_0xb930c3['conversations'][_0x22561d];_0x4d843c[_0x10e763(0x1cd)][_0x10e763(0x1b4)]===0x0&&_0x1fb002[_0x10e763(0x1cd)]['length']>0x0&&(_0x4d843c[_0x10e763(0x1cd)]=[..._0x1fb002['messages']],_0x1fb002['compactizedMessages']&&(_0x4d843c['compactizedMessages']=[..._0x1fb002[_0x10e763(0x1c0)]],_0x4d843c[_0x10e763(0x1d0)]=_0x1fb002['lastCompactization'],_0x4d843c['compactizationCount']=_0x1fb002['compactizationCount'],_0x4d843c['compactizationStrategy']=_0x1fb002['compactizationStrategy'],_0x4d843c['originalTokenCount']=_0x1fb002[_0x10e763(0x1d4)],_0x4d843c['compactedTokenCount']=_0x1fb002['compactedTokenCount']),_0x4d843c[_0x10e763(0x18c)]=new Date()['toISOString'](),this[_0x10e763(0x17f)]['info']('Copied\x20conversation\x20history\x20from\x20'+_0x10a108+'\x20to\x20'+_0x22561d,{'agentId':_0x2b78fe,'messageCount':_0x4d843c[_0x10e763(0x1cd)]['length'],'hasCompacted':!!_0x4d843c['compactizedMessages']}));}this[_0x10e763(0x17f)][_0x10e763(0x15d)]('Model\x20changed\x20via\x20UI\x20-\x20updating\x20both\x20preferredModel\x20and\x20currentModel',{'agentId':_0x2b78fe,'oldModel':_0x10a108,'newModel':_0x22561d,'conversationCopied':_0x10a108&&_0xb930c3[_0x10e763(0x1f4)][_0x10a108]?.['messages'][_0x10e763(0x1b4)]>0x0});}this[_0x10e763(0x180)]['set'](_0x2b78fe,_0xb930c3),this['logger'][_0x10e763(0x15d)]('Agent\x20updated\x20in\x20registry\x20with\x20mode:\x20'+_0xb930c3[_0x10e763(0x204)],{'agentId':_0x2b78fe,'beforeMode':_0x173296['mode'],'afterMode':_0xb930c3['mode'],'allUpdates':Object['keys'](_0x53cc2a)}),this['_updateAgentDirectory'](_0xb930c3),await this[_0x10e763(0x189)][_0x10e763(0x1ff)](_0xb930c3);if(_0x53cc2a['mode']===AGENT_MODES['AGENT']&&this[_0x10e763(0x1ad)]){const _0x4a972d=_0x53cc2a['sessionId']||_0xb930c3[_0x10e763(0x1d3)];!_0x4a972d&&this[_0x10e763(0x17f)][_0x10e763(0x164)]('Agent\x20'+_0x2b78fe+_0x10e763(0x1c4)),this['logger']['info'](_0x10e763(0x195)+_0x2b78fe,{'agentName':_0xb930c3[_0x10e763(0x1e8)],'sessionId':_0x4a972d,'hasSessionId':!!_0x4a972d}),await this[_0x10e763(0x1ad)]['addAgent'](_0x2b78fe,{'sessionId':_0x4a972d,'triggeredBy':'mode-change','reason':_0x10e763(0x18f)});}return _0x173296[_0x10e763(0x204)]===AGENT_MODES[_0x10e763(0x1b6)]&&_0x53cc2a[_0x10e763(0x204)]===AGENT_MODES['CHAT']&&this['scheduler']&&(this['logger'][_0x10e763(0x15d)](_0x10e763(0x1e2)+_0x2b78fe),this[_0x10e763(0x1ad)]['removeAgent'](_0x2b78fe,_0x10e763(0x1a7))),this[_0x10e763(0x17f)]['info']('Agent\x20updated\x20successfully:\x20'+_0x2b78fe,{'newName':_0xb930c3[_0x10e763(0x1e8)],'changes':Object[_0x10e763(0x1ee)](_0x53cc2a)}),_0xb930c3;}async[a0_0x1eaa50(0x200)](_0x541118,_0x5067e8){const _0x13fd4b=a0_0x1eaa50,_0x580c55=await this['getAgent'](_0x541118);if(!_0x580c55)return this['logger']['warn']('Agent\x20notification\x20failed\x20-\x20agent\x20not\x20found:\x20'+_0x541118),![];if(this['_isAgentPaused'](_0x580c55))return this['logger'][_0x13fd4b(0x15d)]('Agent\x20notification\x20queued\x20-\x20agent\x20is\x20paused:\x20'+_0x541118),this['_queueNotification'](_0x541118,_0x5067e8),!![];const _0x3c5d91={'id':_0x13fd4b(0x1a1)+Date[_0x13fd4b(0x20b)](),'conversationId':_0x5067e8[_0x13fd4b(0x1ef)],'agentId':_0x5067e8[_0x13fd4b(0x1b9)],'content':_0x5067e8[_0x13fd4b(0x1b1)],'role':MESSAGE_ROLES['SYSTEM'],'timestamp':new Date()[_0x13fd4b(0x182)](),'type':MESSAGE_TYPES[_0x13fd4b(0x1ae)],'fromAgent':_0x5067e8['from'],'context':_0x5067e8['context'],'urgent':_0x5067e8[_0x13fd4b(0x193)]||![],'requiresResponse':_0x5067e8[_0x13fd4b(0x1f2)]||![]};_0x580c55[_0x13fd4b(0x1f4)][_0x13fd4b(0x208)]['messages'][_0x13fd4b(0x19c)](_0x3c5d91),_0x580c55[_0x13fd4b(0x1f4)]['full'][_0x13fd4b(0x18c)]=new Date()[_0x13fd4b(0x182)]();if(_0x580c55[_0x13fd4b(0x1dd)]&&_0x580c55[_0x13fd4b(0x1f4)][_0x580c55[_0x13fd4b(0x1dd)]]){const _0x21d318=this['_formatMessageForModel'](_0x3c5d91,_0x580c55[_0x13fd4b(0x1dd)]);_0x580c55[_0x13fd4b(0x1f4)][_0x580c55[_0x13fd4b(0x1dd)]]['messages'][_0x13fd4b(0x19c)](_0x21d318),_0x580c55[_0x13fd4b(0x1f4)][_0x580c55[_0x13fd4b(0x1dd)]]['lastUpdated']=new Date()['toISOString']();}return _0x580c55[_0x13fd4b(0x17e)]=new Date()[_0x13fd4b(0x182)](),await this[_0x13fd4b(0x1ff)](_0x541118),this[_0x13fd4b(0x17f)][_0x13fd4b(0x15d)](_0x13fd4b(0x198)+_0x541118,{'fromAgent':_0x5067e8[_0x13fd4b(0x1b9)],'urgent':_0x5067e8['urgent'],'requiresResponse':_0x5067e8[_0x13fd4b(0x1f2)]}),!![];}async['getAllAgents'](){const _0x10cd42=a0_0x1eaa50,_0x2f3317=Array['from'](this['agents']['values']());for(const _0x5c10b0 of _0x2f3317){this[_0x10cd42(0x183)](_0x5c10b0);}return _0x2f3317;}async[a0_0x1eaa50(0x1e0)](){const _0x57e14f=a0_0x1eaa50,_0x1aa811=Array['from'](this['agents']['values']());for(const _0xdf8240 of _0x1aa811){this['_updateAgentPauseStatus'](_0xdf8240);}return _0x1aa811[_0x57e14f(0x1fb)](_0x5be963=>({'id':_0x5be963['id'],'name':_0x5be963['name'],'type':_0x5be963[_0x57e14f(0x1ea)],'status':_0x5be963['status'],'systemPrompt':_0x5be963['systemPrompt'],'preferredModel':_0x5be963['preferredModel'],'currentModel':_0x5be963['currentModel'],'dynamicModelRouting':_0x5be963['dynamicModelRouting'],'platformProvided':_0x5be963['platformProvided'],'capabilities':_0x5be963['capabilities'],'lastActivity':_0x5be963['lastActivity'],'isPaused':this['_isAgentPaused'](_0x5be963),'pausedUntil':_0x5be963[_0x57e14f(0x191)],'messageCount':_0x5be963[_0x57e14f(0x1f4)]['full'][_0x57e14f(0x1cd)]['length'],'createdAt':_0x5be963['createdAt']}));}async[a0_0x1eaa50(0x1ff)](_0x361f26){const _0x331537=a0_0x1eaa50,_0x1bc458=await this[_0x331537(0x214)](_0x361f26);if(!_0x1bc458)throw new Error(_0x331537(0x15e)+_0x361f26);await this['stateManager'][_0x331537(0x1ff)](_0x1bc458);}async[a0_0x1eaa50(0x1f3)](_0xaf0069){const _0x236501=a0_0x1eaa50,_0x1768d2={..._0xaf0069,'status':_0xaf0069['status']===_0x236501(0x205)&&this['_isPauseExpired'](_0xaf0069)?_0x236501(0x20a):_0xaf0069[_0x236501(0x1ba)]};return(!_0x1768d2[_0x236501(0x1f4)]||!_0x1768d2['conversations']['full'])&&(_0x1768d2['conversations']={'full':{'messages':[],'lastUpdated':new Date()[_0x236501(0x182)]()}}),this['agents']['set'](_0x1768d2['id'],_0x1768d2),this['_updateAgentDirectory'](_0x1768d2),await this[_0x236501(0x1b5)](_0x1768d2['id']),this['logger']['info']('Agent\x20resumed:\x20'+_0x1768d2['id'],{'name':_0x1768d2['name'],'status':_0x1768d2[_0x236501(0x1ba)],'messageCount':_0x1768d2['conversations']['full'][_0x236501(0x1cd)][_0x236501(0x1b4)]}),_0x1768d2;}async['pauseAgent'](_0x5f361b,_0x31ef67,_0x57879f=a0_0x1eaa50(0x17d)){const _0x4bdad7=a0_0x1eaa50,_0x57dc4e=await this[_0x4bdad7(0x214)](_0x5f361b);if(!_0x57dc4e)throw new Error(_0x4bdad7(0x15e)+_0x5f361b);let _0x407dd3;if(_0x31ef67 instanceof Date)_0x407dd3=_0x31ef67;else{const _0x1d97ea=this['config'][_0x4bdad7(0x1be)]?.[_0x4bdad7(0x1d2)]||0x12c,_0x3b35f1=Math['min'](_0x31ef67,_0x1d97ea);_0x407dd3=new Date(Date['now']()+_0x3b35f1*0x3e8);}return _0x57dc4e['status']=AGENT_STATUS['PAUSED'],_0x57dc4e['pausedUntil']=_0x407dd3['toISOString'](),_0x57dc4e[_0x4bdad7(0x17e)]=new Date()['toISOString'](),this[_0x4bdad7(0x202)][_0x4bdad7(0x1cb)](_0x5f361b,{'agentId':_0x5f361b,'pausedAt':new Date()[_0x4bdad7(0x182)](),'pausedUntil':_0x407dd3[_0x4bdad7(0x182)](),'reason':_0x57879f,'originalStatus':AGENT_STATUS['ACTIVE']}),await this['persistAgentState'](_0x5f361b),this['logger']['info'](_0x4bdad7(0x1ac)+_0x5f361b,{'pausedUntil':_0x407dd3['toISOString'](),'reason':_0x57879f,'durationSeconds':Math[_0x4bdad7(0x172)]((_0x407dd3[_0x4bdad7(0x210)]()-Date[_0x4bdad7(0x20b)]())/0x3e8)}),{'success':!![],'agentId':_0x5f361b,'pausedUntil':_0x407dd3[_0x4bdad7(0x182)](),'reason':_0x57879f,'message':'Agent\x20paused\x20until\x20'+_0x407dd3['toISOString']()};}async[a0_0x1eaa50(0x1f3)](_0x6c1727){const _0x31044d=a0_0x1eaa50,_0x38edd6=await this['getAgent'](_0x6c1727);if(!_0x38edd6)throw new Error('Agent\x20not\x20found:\x20'+_0x6c1727);if(_0x38edd6['status']!==AGENT_STATUS['PAUSED'])return{'success':!![],'message':_0x31044d(0x1c2)+_0x6c1727+_0x31044d(0x1aa)};return _0x38edd6[_0x31044d(0x1ba)]=AGENT_STATUS[_0x31044d(0x179)],_0x38edd6['pausedUntil']=null,_0x38edd6[_0x31044d(0x17e)]=new Date()[_0x31044d(0x182)](),this[_0x31044d(0x202)][_0x31044d(0x187)](_0x6c1727),await this[_0x31044d(0x1b5)](_0x6c1727),await this[_0x31044d(0x1ff)](_0x6c1727),this['logger'][_0x31044d(0x15d)]('Agent\x20resumed:\x20'+_0x6c1727),{'success':!![],'agentId':_0x6c1727,'message':_0x31044d(0x1c2)+_0x6c1727+_0x31044d(0x1eb)};}async[a0_0x1eaa50(0x20f)](_0x4f8228){const _0x2e5736=a0_0x1eaa50;return await this[_0x2e5736(0x1f3)](_0x4f8228);}['getAgentDirectory'](){const _0x4ea3f3=a0_0x1eaa50;return Array[_0x4ea3f3(0x1b9)](this['agentDirectory']['values']());}async['deleteAgent'](_0x325010){const _0x209f11=a0_0x1eaa50,_0x1b8a1b=await this[_0x209f11(0x214)](_0x325010);if(!_0x1b8a1b)throw new Error('Agent\x20not\x20found:\x20'+_0x325010);if(this[_0x209f11(0x197)])try{await this[_0x209f11(0x197)]['deleteAgentAttachments'](_0x325010),this[_0x209f11(0x17f)]['info'](_0x209f11(0x1bf)+_0x325010);}catch(_0x7041f6){this['logger'][_0x209f11(0x164)](_0x209f11(0x1cc)+_0x7041f6['message'],{'agentId':_0x325010});}this[_0x209f11(0x180)]['delete'](_0x325010),this[_0x209f11(0x1d5)][_0x209f11(0x187)](_0x325010),this[_0x209f11(0x202)]['delete'](_0x325010),this['notificationQueue']['delete'](_0x325010);try{await this['stateManager']['deleteAgentState'](_0x325010);}catch(_0x433b27){this[_0x209f11(0x17f)][_0x209f11(0x164)]('Failed\x20to\x20delete\x20agent\x20persistent\x20state:\x20'+_0x433b27[_0x209f11(0x1a2)],{'agentId':_0x325010});}return this['logger']['info'](_0x209f11(0x16a)+_0x325010,{'agentName':_0x1b8a1b['name'],'totalAgents':this['agents'][_0x209f11(0x1a5)]}),{'success':!![],'agentId':_0x325010,'remainingAgents':this[_0x209f11(0x180)][_0x209f11(0x1a5)]};}['_generateAgentId'](_0x3d1117){const _0x184c34=a0_0x1eaa50,_0x5141bc=_0x3d1117['toLowerCase']()[_0x184c34(0x166)](/[^a-z0-9]/g,'-'),_0x3d6f93=Date['now']();return'agent-'+_0x5141bc+'-'+_0x3d6f93;}[a0_0x1eaa50(0x1db)](_0x3759a0){const _0x3e23b5=a0_0x1eaa50;this[_0x3e23b5(0x1d5)][_0x3e23b5(0x1cb)](_0x3759a0['id'],{'id':_0x3759a0['id'],'name':_0x3759a0['name'],'type':_0x3759a0['type'],'capabilities':_0x3759a0['capabilities'],'status':_0x3759a0[_0x3e23b5(0x1ba)],'description':this[_0x3e23b5(0x186)](_0x3759a0)});}[a0_0x1eaa50(0x186)](_0x6c0622){const _0x67bab=a0_0x1eaa50;let _0x2cee26=_0x6c0622['name']+'\x20('+_0x6c0622['type']+')';return _0x6c0622[_0x67bab(0x212)]['length']>0x0&&(_0x2cee26+=_0x67bab(0x1e1)+_0x6c0622['capabilities'][_0x67bab(0x206)](',\x20')),_0x2cee26;}['_isAgentPaused'](_0x286b1e){const _0x5bab07=a0_0x1eaa50;if(_0x286b1e['status']!==AGENT_STATUS['PAUSED']||!_0x286b1e[_0x5bab07(0x191)])return![];return new Date()<new Date(_0x286b1e[_0x5bab07(0x191)]);}[a0_0x1eaa50(0x1af)](_0x33458b){const _0x40fbde=a0_0x1eaa50;if(!_0x33458b[_0x40fbde(0x191)])return!![];return new Date()>=new Date(_0x33458b[_0x40fbde(0x191)]);}['_updateAgentPauseStatus'](_0x3fd487){const _0x527c75=a0_0x1eaa50;_0x3fd487[_0x527c75(0x1ba)]===AGENT_STATUS[_0x527c75(0x1e5)]&&this['_isPauseExpired'](_0x3fd487)&&(_0x3fd487['status']=AGENT_STATUS[_0x527c75(0x179)],_0x3fd487[_0x527c75(0x191)]=null,this[_0x527c75(0x202)]['delete'](_0x3fd487['id']));}[a0_0x1eaa50(0x1b2)](_0x26cc22,_0x11bd00){const _0x442d50=a0_0x1eaa50;!this['notificationQueue'][_0x442d50(0x190)](_0x26cc22)&&this['notificationQueue'][_0x442d50(0x1cb)](_0x26cc22,[]),this[_0x442d50(0x1e6)]['get'](_0x26cc22)['push']({..._0x11bd00,'queuedAt':new Date()[_0x442d50(0x182)]()});}async[a0_0x1eaa50(0x1b5)](_0x2d505a){const _0x415e33=a0_0x1eaa50,_0x9279a5=this['notificationQueue'][_0x415e33(0x20e)](_0x2d505a);if(!_0x9279a5||_0x9279a5[_0x415e33(0x1b4)]===0x0)return;this[_0x415e33(0x17f)][_0x415e33(0x15d)]('Processing\x20'+_0x9279a5['length']+_0x415e33(0x17c)+_0x2d505a);for(const _0x438ad2 of _0x9279a5){await this['notifyAgent'](_0x2d505a,_0x438ad2);}this['notificationQueue'][_0x415e33(0x187)](_0x2d505a);}[a0_0x1eaa50(0x176)](_0x9fec8c,_0x1638e1){return{..._0x9fec8c};}['_getModelFormatVersion'](_0x5f5dd7){const _0x1ed20c=a0_0x1eaa50;return MODEL_FORMAT_VERSIONS[_0x5f5dd7]||MODEL_FORMAT_VERSIONS[_0x1ed20c(0x1f1)];}async['refreshAgentToolDescriptions'](_0x1773b1,_0x94155e={}){const _0x8e63c1=a0_0x1eaa50,_0x36eda9=await this['getAgent'](_0x1773b1);if(!_0x36eda9||!this['toolsRegistry'])return![];try{const _0x122d11=_0x36eda9['originalSystemPrompt']||_0x36eda9[_0x8e63c1(0x171)],_0x4b3aa1=this[_0x8e63c1(0x20c)]['enhanceSystemPrompt'](_0x122d11,_0x36eda9['capabilities'],{'compact':_0x94155e['compact']||![],'includeExamples':_0x94155e['includeExamples']!==![],'includeUsageGuidelines':_0x94155e['includeUsageGuidelines']!==![],'includeSecurityNotes':_0x94155e['includeSecurityNotes']!==![]});return _0x36eda9['systemPrompt']=_0x4b3aa1,_0x36eda9['lastActivity']=new Date()[_0x8e63c1(0x182)](),await this['stateManager']['persistAgentState'](_0x1773b1),this[_0x8e63c1(0x17f)]?.[_0x8e63c1(0x15d)]('Agent\x20tool\x20descriptions\x20refreshed:\x20'+_0x1773b1,{'capabilities':_0x36eda9[_0x8e63c1(0x212)],'promptLength':_0x4b3aa1[_0x8e63c1(0x1b4)]}),!![];}catch(_0x53150d){return this['logger']?.[_0x8e63c1(0x201)]('Failed\x20to\x20refresh\x20tool\x20descriptions\x20for\x20agent:\x20'+_0x1773b1,{'error':_0x53150d[_0x8e63c1(0x1a2)]}),![];}}[a0_0x1eaa50(0x1b8)](_0x190aba){const _0x31ad77=a0_0x1eaa50;this[_0x31ad77(0x20c)]=_0x190aba,this[_0x31ad77(0x17f)]?.[_0x31ad77(0x15d)](_0x31ad77(0x1f6),{'hasRegistry':!!_0x190aba});}async[a0_0x1eaa50(0x1f0)](_0xf0aad7={}){const _0x100387=a0_0x1eaa50,_0x3b0c2d={'total':this[_0x100387(0x180)]['size'],'successful':0x0,'failed':0x0,'skipped':0x0};for(const [_0x2f8699,_0x318926]of this['agents']['entries']()){if(!_0x318926[_0x100387(0x212)]||_0x318926[_0x100387(0x212)]['length']===0x0){_0x3b0c2d['skipped']++;continue;}const _0x1d46de=await this[_0x100387(0x170)](_0x2f8699,_0xf0aad7);_0x1d46de?_0x3b0c2d['successful']++:_0x3b0c2d[_0x100387(0x163)]++;}return this['logger']?.[_0x100387(0x15d)](_0x100387(0x17a),_0x3b0c2d),_0x3b0c2d;}['setMessageProcessor'](_0x538ec9){const _0x1c33d4=a0_0x1eaa50;this[_0x1c33d4(0x1ce)]=_0x538ec9;}[a0_0x1eaa50(0x1b0)](_0x1b3bf8){const _0x528af8=a0_0x1eaa50;this[_0x528af8(0x1ad)]=_0x1b3bf8,this['logger']?.[_0x528af8(0x15d)]('AgentScheduler\x20reference\x20set\x20for\x20agent\x20pool',{'hasScheduler':!!_0x1b3bf8});}['setFileAttachmentService'](_0x27a167){const _0x57de87=a0_0x1eaa50;this[_0x57de87(0x197)]=_0x27a167,this['logger']?.['info'](_0x57de87(0x185),{'hasService':!!_0x27a167});}async[a0_0x1eaa50(0x181)](_0x5e8ead,_0x40da23){const _0x5bee9f=a0_0x1eaa50,_0x4352d5=await this['getAgent'](_0x5e8ead);if(!_0x4352d5)throw new Error('Agent\x20not\x20found:\x20'+_0x5e8ead);const _0x2ef3d2={..._0x40da23,'id':_0x40da23['id']||'user-msg-'+Date['now']()+'-'+Math[_0x5bee9f(0x211)]()[_0x5bee9f(0x1ab)](0x24)[_0x5bee9f(0x1ec)](0x2,0x9),'queuedAt':new Date()['toISOString'](),'timestamp':_0x40da23[_0x5bee9f(0x207)]||new Date()['toISOString']()};_0x4352d5['messageQueues'][_0x5bee9f(0x161)][_0x5bee9f(0x19c)](_0x2ef3d2),await this[_0x5bee9f(0x1ff)](_0x5e8ead),this['logger']['info']('User\x20message\x20queued\x20for\x20agent:\x20'+_0x5e8ead,{'messageId':_0x2ef3d2['id'],'queueSize':_0x4352d5[_0x5bee9f(0x1fd)][_0x5bee9f(0x161)][_0x5bee9f(0x1b4)]});}async[a0_0x1eaa50(0x177)](_0x43ada5,_0x32bc50){const _0x157584=a0_0x1eaa50,_0x857339=await this['getAgent'](_0x43ada5);if(!_0x857339)throw new Error('Agent\x20not\x20found:\x20'+_0x43ada5);const _0x44770a={..._0x32bc50,'id':_0x32bc50['id']||_0x32bc50['messageId']||'inter-agent-msg-'+Date['now']()+'-'+Math[_0x157584(0x211)]()[_0x157584(0x1ab)](0x24)['substr'](0x2,0x9),'queuedAt':new Date()['toISOString'](),'timestamp':_0x32bc50[_0x157584(0x207)]||new Date()['toISOString']()};_0x857339['messageQueues']['interAgentMessages'][_0x157584(0x19c)](_0x44770a),await this[_0x157584(0x1ff)](_0x43ada5),this[_0x157584(0x17f)]['info']('Inter-agent\x20message\x20queued\x20for\x20agent:\x20'+_0x43ada5,{'messageId':_0x44770a['id'],'sender':_0x32bc50['sender']||_0x32bc50[_0x157584(0x1a0)],'queueSize':_0x857339[_0x157584(0x1fd)]['interAgentMessages']['length']});}async[a0_0x1eaa50(0x1e4)](_0x53d982,_0x1a65b0){const _0x473d48=a0_0x1eaa50,_0x2ff841=await this['getAgent'](_0x53d982);if(!_0x2ff841)throw new Error('Agent\x20not\x20found:\x20'+_0x53d982);const _0xb35c9={..._0x1a65b0,'id':_0x1a65b0['id']||'tool-result-'+Date['now']()+'-'+Math['random']()[_0x473d48(0x1ab)](0x24)['substr'](0x2,0x9),'queuedAt':new Date()['toISOString'](),'timestamp':_0x1a65b0['timestamp']||new Date()[_0x473d48(0x182)]()};_0x2ff841[_0x473d48(0x1fd)]['toolResults'][_0x473d48(0x19c)](_0xb35c9),await this[_0x473d48(0x1ff)](_0x53d982),this[_0x473d48(0x17f)][_0x473d48(0x169)](_0x473d48(0x1c5)+_0x53d982,{'toolId':_0x1a65b0[_0x473d48(0x1fe)],'status':_0x1a65b0[_0x473d48(0x1ba)],'queueSize':_0x2ff841[_0x473d48(0x1fd)]['toolResults']['length']});}async[a0_0x1eaa50(0x19e)](_0x3a41dc){const _0x37acc1=a0_0x1eaa50,_0x541725=await this['getAgent'](_0x3a41dc);if(!_0x541725)throw new Error(_0x37acc1(0x15e)+_0x3a41dc);_0x541725[_0x37acc1(0x1fd)]['toolResults']=[],_0x541725[_0x37acc1(0x1fd)]['interAgentMessages']=[],_0x541725[_0x37acc1(0x1fd)]['userMessages']=[],await this[_0x37acc1(0x1ff)](_0x3a41dc),this[_0x37acc1(0x17f)]['info']('Message\x20queues\x20cleared\x20for\x20agent:\x20'+_0x3a41dc);}async['getQueueCounts'](_0x26d387){const _0x22ba17=a0_0x1eaa50,_0x2cd7d2=await this['getAgent'](_0x26d387);if(!_0x2cd7d2)return{'toolResults':0x0,'interAgentMessages':0x0,'userMessages':0x0,'total':0x0};const _0x588328={'toolResults':_0x2cd7d2[_0x22ba17(0x1fd)][_0x22ba17(0x1a3)]['length'],'interAgentMessages':_0x2cd7d2['messageQueues'][_0x22ba17(0x1d6)]['length'],'userMessages':_0x2cd7d2[_0x22ba17(0x1fd)]['userMessages'][_0x22ba17(0x1b4)]};return _0x588328[_0x22ba17(0x1c8)]=_0x588328[_0x22ba17(0x1a3)]+_0x588328[_0x22ba17(0x1d6)]+_0x588328['userMessages'],_0x588328;}async[a0_0x1eaa50(0x168)](_0x4d3120,_0x5e10ee){const _0x165cdf=a0_0x1eaa50,_0x5aaec9=process['env'][_0x165cdf(0x203)]==='true',_0x5c8bdc=await this[_0x165cdf(0x214)](_0x4d3120);if(!_0x5c8bdc)throw new Error('Agent\x20not\x20found:\x20'+_0x4d3120);const _0x3e5214=_0x5c8bdc['conversations'][_0x5e10ee];if(!_0x3e5214)return this['logger']['warn'](_0x165cdf(0x167)+_0x5e10ee,{'agentId':_0x4d3120}),[];if(!_0x3e5214['compactizedMessages'])return this[_0x165cdf(0x17f)][_0x165cdf(0x169)](_0x165cdf(0x1e9),{'agentId':_0x4d3120,'modelId':_0x5e10ee,'messageCount':_0x3e5214['messages'][_0x165cdf(0x1b4)]}),_0x5aaec9&&console['log'](_0x165cdf(0x1a6),{'agentId':_0x4d3120,'modelId':_0x5e10ee,'returnedArray':'originalMessages','messageCount':_0x3e5214['messages'][_0x165cdf(0x1b4)],'reason':'No\x20compacted\x20messages\x20exist'}),_0x3e5214['messages'];const _0x524495=_0x3e5214['compactizedMessages']['length'],_0x31785e=_0x3e5214['messages'][_0x165cdf(0x1b4)];if(_0x31785e>_0x524495){const _0xe3159b=_0x3e5214['messages'][_0x165cdf(0x173)](_0x524495);this['logger'][_0x165cdf(0x15d)]('Syncing\x20compacted\x20messages\x20with\x20new\x20messages',{'agentId':_0x4d3120,'modelId':_0x5e10ee,'compactedLength':_0x524495,'originalLength':_0x31785e,'missingCount':_0xe3159b[_0x165cdf(0x1b4)]}),_0x3e5214['compactizedMessages']['push'](..._0xe3159b),await this[_0x165cdf(0x1ff)](_0x4d3120);}return this[_0x165cdf(0x17f)][_0x165cdf(0x169)]('Retrieved\x20messages\x20for\x20AI\x20(compacted\x20+\x20synced)',{'agentId':_0x4d3120,'modelId':_0x5e10ee,'messageCount':_0x3e5214['compactizedMessages']['length'],'wasResynced':_0x31785e>_0x524495}),_0x5aaec9&&console[_0x165cdf(0x194)]('[GET-MESSAGES-FOR-AI]',{'agentId':_0x4d3120,'modelId':_0x5e10ee,'returnedArray':'compactizedMessages','messageCount':_0x3e5214['compactizedMessages']['length'],'originalMessageCount':_0x3e5214[_0x165cdf(0x1cd)][_0x165cdf(0x1b4)],'wasSynced':_0x31785e>_0x524495,'syncedMessageCount':_0x31785e>_0x524495?_0x31785e-_0x524495:0x0,'reason':_0x165cdf(0x1d1)}),_0x3e5214[_0x165cdf(0x1c0)];}async['addMessageToConversation'](_0x5ef8b5,_0x428da1,_0x4e929b){const _0x219d6c=a0_0x1eaa50,_0x4c34ec=process[_0x219d6c(0x1c7)]['COMPACT_DEBUG']==='true',_0x5bf833=await this['getAgent'](_0x5ef8b5);if(!_0x5bf833)throw new Error('Agent\x20not\x20found:\x20'+_0x5ef8b5);!_0x5bf833[_0x219d6c(0x1f4)][_0x428da1]&&(_0x5bf833['conversations'][_0x428da1]=this['_createEmptyConversation'](_0x428da1));const _0x5e1b20=_0x5bf833[_0x219d6c(0x1f4)][_0x428da1],_0x3eb7fa=_0x5e1b20[_0x219d6c(0x1cd)]['length'],_0x450278=_0x5e1b20['compactizedMessages']?.['length']||0x0;_0x5e1b20['messages']['push']({..._0x4e929b,'timestamp':_0x4e929b[_0x219d6c(0x207)]||new Date()[_0x219d6c(0x182)]()}),_0x5e1b20[_0x219d6c(0x1c0)]&&_0x5e1b20[_0x219d6c(0x1c0)]['push']({..._0x4e929b,'timestamp':_0x4e929b['timestamp']||new Date()[_0x219d6c(0x182)]()}),_0x5e1b20['lastUpdated']=new Date()['toISOString'](),_0x4c34ec&&console[_0x219d6c(0x194)](_0x219d6c(0x160),{'agentId':_0x5ef8b5,'modelId':_0x428da1,'role':_0x4e929b['role'],'hasCompactedVersion':!!_0x5e1b20['compactizedMessages'],'originalMessages':{'before':_0x3eb7fa,'after':_0x5e1b20['messages'][_0x219d6c(0x1b4)],'added':0x1},'compactizedMessages':_0x5e1b20['compactizedMessages']?{'before':_0x450278,'after':_0x5e1b20['compactizedMessages']['length'],'added':0x1}:null,'behavior':_0x5e1b20['compactizedMessages']?'Added\x20to\x20BOTH\x20arrays':'Added\x20to\x20original\x20only'}),await this['persistAgentState'](_0x5ef8b5),this[_0x219d6c(0x17f)][_0x219d6c(0x169)](_0x219d6c(0x1bb),{'agentId':_0x5ef8b5,'modelId':_0x428da1,'role':_0x4e929b[_0x219d6c(0x1bd)],'hasCompacted':!!_0x5e1b20['compactizedMessages']});}async[a0_0x1eaa50(0x15c)](_0xc81e89,_0xb24f2c,_0x5ae111){const _0x22c742=a0_0x1eaa50,_0x60ac23=await this['getAgent'](_0xc81e89);if(!_0x60ac23)throw new Error('Agent\x20not\x20found:\x20'+_0xc81e89);!_0x60ac23[_0x22c742(0x1f4)][_0xb24f2c]&&(_0x60ac23[_0x22c742(0x1f4)][_0xb24f2c]=this[_0x22c742(0x1c9)](_0xb24f2c),this[_0x22c742(0x17f)][_0x22c742(0x169)]('Created\x20conversation\x20for\x20model\x20switching:\x20'+_0xb24f2c));const _0x158e4a=_0x60ac23['conversations'][_0xb24f2c];_0x158e4a[_0x22c742(0x1c0)]=_0x5ae111[_0x22c742(0x196)],_0x158e4a['lastCompactization']=new Date()['toISOString'](),_0x158e4a[_0x22c742(0x1f7)]+=0x1,_0x158e4a['compactizationStrategy']=_0x5ae111[_0x22c742(0x162)],_0x158e4a['originalTokenCount']=_0x5ae111[_0x22c742(0x1d4)],_0x158e4a['compactedTokenCount']=_0x5ae111[_0x22c742(0x19a)],_0x158e4a[_0x22c742(0x16b)]=_0x5ae111[_0x22c742(0x19a)],_0x158e4a[_0x22c742(0x18c)]=new Date()[_0x22c742(0x182)](),await this[_0x22c742(0x1ff)](_0xc81e89),this[_0x22c742(0x17f)]['info'](_0x22c742(0x18d),{'agentId':_0xc81e89,'modelId':_0xb24f2c,'strategy':_0x5ae111[_0x22c742(0x162)],'originalTokens':_0x5ae111['originalTokenCount'],'compactedTokens':_0x5ae111['compactedTokenCount'],'reductionPercent':_0x5ae111[_0x22c742(0x20d)],'compactizationCount':_0x158e4a[_0x22c742(0x1f7)]});}async[a0_0x1eaa50(0x1f5)](_0x2de9af,_0x19d129){const _0x314435=a0_0x1eaa50,_0x1b6081=await this[_0x314435(0x214)](_0x2de9af);if(!_0x1b6081)throw new Error(_0x314435(0x15e)+_0x2de9af);const _0x59d238=_0x1b6081['conversations'][_0x19d129];if(!_0x59d238)return;_0x59d238[_0x314435(0x1c0)]=null,_0x59d238['lastCompactization']=null,_0x59d238[_0x314435(0x1f7)]=0x0,_0x59d238[_0x314435(0x1a4)]=null,_0x59d238[_0x314435(0x1d4)]=0x0,_0x59d238[_0x314435(0x19a)]=0x0,_0x59d238['tokenCount']=0x0,await this[_0x314435(0x1ff)](_0x2de9af),this[_0x314435(0x17f)]['info']('Compacted\x20messages\x20cleared',{'agentId':_0x2de9af,'modelId':_0x19d129});}async['getCompactionMetadata'](_0x188f1f,_0x1abf04){const _0x221afa=a0_0x1eaa50,_0xc3e76b=await this[_0x221afa(0x214)](_0x188f1f);if(!_0xc3e76b)return null;const _0x4c0897=_0xc3e76b[_0x221afa(0x1f4)][_0x1abf04];if(!_0x4c0897)return null;const _0x98cc09=!!_0x4c0897['compactizedMessages'];return{'isCompacted':_0x98cc09,'lastCompactization':_0x4c0897[_0x221afa(0x1d0)]||null,'compactizationCount':_0x4c0897['compactizationCount']||0x0,'strategy':_0x4c0897[_0x221afa(0x1a4)]||null,'originalTokenCount':_0x4c0897['originalTokenCount']||0x0,'compactedTokenCount':_0x4c0897['compactedTokenCount']||0x0,'reductionPercent':_0x4c0897['originalTokenCount']>0x0?(_0x4c0897[_0x221afa(0x1d4)]-_0x4c0897[_0x221afa(0x19a)])/_0x4c0897[_0x221afa(0x1d4)]*0x64:0x0,'originalMessages':_0x4c0897[_0x221afa(0x1cd)]||[],'compactedMessages':_0x4c0897['compactizedMessages']||null,'originalMessageCount':_0x4c0897[_0x221afa(0x1cd)]?.['length']||0x0,'compactedMessageCount':_0x4c0897[_0x221afa(0x1c0)]?.['length']||0x0};}async[a0_0x1eaa50(0x1d8)](_0x52bf94){const _0x16f365=a0_0x1eaa50,_0x2a6f79=await this[_0x16f365(0x214)](_0x52bf94);if(!_0x2a6f79)return![];let _0x18e50c=![];for(const [_0x15b13c,_0x52622e]of Object[_0x16f365(0x18b)](_0x2a6f79['conversations'])){if(_0x15b13c===_0x16f365(0x208))continue;_0x52622e[_0x16f365(0x1c0)]===undefined&&(_0x52622e['compactizedMessages']=null,_0x52622e['lastCompactization']=null,_0x52622e['compactizationCount']=0x0,_0x52622e[_0x16f365(0x1a4)]=null,_0x52622e[_0x16f365(0x1d4)]=0x0,_0x52622e[_0x16f365(0x19a)]=0x0,_0x18e50c=!![],this[_0x16f365(0x17f)]['info'](_0x16f365(0x1ca),{'agentId':_0x52bf94,'modelId':_0x15b13c,'messageCount':_0x52622e[_0x16f365(0x1cd)]?.[_0x16f365(0x1b4)]||0x0}));}return _0x18e50c&&await this[_0x16f365(0x1ff)](_0x52bf94),_0x18e50c;}['_createEmptyConversation'](_0x37dce2){const _0x16c395=a0_0x1eaa50;return{'messages':[],'compactizedMessages':null,'lastCompactization':null,'compactizationCount':0x0,'compactizationStrategy':null,'originalTokenCount':0x0,'compactedTokenCount':0x0,'tokenCount':0x0,'lastUpdated':new Date()['toISOString'](),'formatVersion':this[_0x16c395(0x1b3)](_0x37dce2)};}}export default AgentPool;