@loxia-labs/loxia-autopilot-one 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +267 -0
  2. package/README.md +509 -0
  3. package/bin/cli.js +117 -0
  4. package/package.json +94 -0
  5. package/scripts/install-scanners.js +236 -0
  6. package/src/analyzers/CSSAnalyzer.js +297 -0
  7. package/src/analyzers/ConfigValidator.js +690 -0
  8. package/src/analyzers/ESLintAnalyzer.js +320 -0
  9. package/src/analyzers/JavaScriptAnalyzer.js +261 -0
  10. package/src/analyzers/PrettierFormatter.js +247 -0
  11. package/src/analyzers/PythonAnalyzer.js +266 -0
  12. package/src/analyzers/SecurityAnalyzer.js +729 -0
  13. package/src/analyzers/TypeScriptAnalyzer.js +247 -0
  14. package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
  15. package/src/analyzers/codeCloneDetector/detector.js +203 -0
  16. package/src/analyzers/codeCloneDetector/index.js +160 -0
  17. package/src/analyzers/codeCloneDetector/parser.js +199 -0
  18. package/src/analyzers/codeCloneDetector/reporter.js +148 -0
  19. package/src/analyzers/codeCloneDetector/scanner.js +59 -0
  20. package/src/core/agentPool.js +1474 -0
  21. package/src/core/agentScheduler.js +2147 -0
  22. package/src/core/contextManager.js +709 -0
  23. package/src/core/messageProcessor.js +732 -0
  24. package/src/core/orchestrator.js +548 -0
  25. package/src/core/stateManager.js +877 -0
  26. package/src/index.js +631 -0
  27. package/src/interfaces/cli.js +549 -0
  28. package/src/interfaces/webServer.js +2162 -0
  29. package/src/modules/fileExplorer/controller.js +280 -0
  30. package/src/modules/fileExplorer/index.js +37 -0
  31. package/src/modules/fileExplorer/middleware.js +92 -0
  32. package/src/modules/fileExplorer/routes.js +125 -0
  33. package/src/modules/fileExplorer/types.js +44 -0
  34. package/src/services/aiService.js +1232 -0
  35. package/src/services/apiKeyManager.js +164 -0
  36. package/src/services/benchmarkService.js +366 -0
  37. package/src/services/budgetService.js +539 -0
  38. package/src/services/contextInjectionService.js +247 -0
  39. package/src/services/conversationCompactionService.js +637 -0
  40. package/src/services/errorHandler.js +810 -0
  41. package/src/services/fileAttachmentService.js +544 -0
  42. package/src/services/modelRouterService.js +366 -0
  43. package/src/services/modelsService.js +322 -0
  44. package/src/services/qualityInspector.js +796 -0
  45. package/src/services/tokenCountingService.js +536 -0
  46. package/src/tools/agentCommunicationTool.js +1344 -0
  47. package/src/tools/agentDelayTool.js +485 -0
  48. package/src/tools/asyncToolManager.js +604 -0
  49. package/src/tools/baseTool.js +800 -0
  50. package/src/tools/browserTool.js +920 -0
  51. package/src/tools/cloneDetectionTool.js +621 -0
  52. package/src/tools/dependencyResolverTool.js +1215 -0
  53. package/src/tools/fileContentReplaceTool.js +875 -0
  54. package/src/tools/fileSystemTool.js +1107 -0
  55. package/src/tools/fileTreeTool.js +853 -0
  56. package/src/tools/imageTool.js +901 -0
  57. package/src/tools/importAnalyzerTool.js +1060 -0
  58. package/src/tools/jobDoneTool.js +248 -0
  59. package/src/tools/seekTool.js +956 -0
  60. package/src/tools/staticAnalysisTool.js +1778 -0
  61. package/src/tools/taskManagerTool.js +2873 -0
  62. package/src/tools/terminalTool.js +2304 -0
  63. package/src/tools/webTool.js +1430 -0
  64. package/src/types/agent.js +519 -0
  65. package/src/types/contextReference.js +972 -0
  66. package/src/types/conversation.js +730 -0
  67. package/src/types/toolCommand.js +747 -0
  68. package/src/utilities/attachmentValidator.js +292 -0
  69. package/src/utilities/configManager.js +582 -0
  70. package/src/utilities/constants.js +722 -0
  71. package/src/utilities/directoryAccessManager.js +535 -0
  72. package/src/utilities/fileProcessor.js +307 -0
  73. package/src/utilities/logger.js +436 -0
  74. package/src/utilities/tagParser.js +1246 -0
  75. package/src/utilities/toolConstants.js +317 -0
  76. package/web-ui/build/index.html +15 -0
  77. package/web-ui/build/logo.png +0 -0
  78. package/web-ui/build/logo2.png +0 -0
  79. package/web-ui/build/static/index-CjkkcnFA.js +344 -0
  80. package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
@@ -0,0 +1,800 @@
1
+ /**
2
+ * BaseTool - Abstract base class for all tools in the Loxia AI Agents System
3
+ *
4
+ * Purpose:
5
+ * - Define standardized tool interface
6
+ * - Provide common tool functionality
7
+ * - Handle parameter validation
8
+ * - Manage tool execution lifecycle
9
+ * - Support both sync and async operations
10
+ */
11
+
12
+ import {
13
+ TOOL_STATUS,
14
+ OPERATION_STATUS,
15
+ ERROR_TYPES,
16
+ SYSTEM_DEFAULTS
17
+ } from '../utilities/constants.js';
18
+
19
+ class BaseTool {
20
+ constructor(config = {}, logger = null) {
21
+ this.id = this.constructor.name.toLowerCase().replace('tool', '');
22
+ this.config = config;
23
+ this.logger = logger;
24
+
25
+ // Tool capabilities
26
+ this.requiresProject = false;
27
+ this.isAsync = false;
28
+ this.timeout = config.timeout || SYSTEM_DEFAULTS.MAX_TOOL_EXECUTION_TIME;
29
+ this.maxConcurrentOperations = config.maxConcurrentOperations || 1;
30
+
31
+ // Operation tracking
32
+ this.activeOperations = new Map();
33
+ this.operationHistory = [];
34
+
35
+ // Tool state
36
+ this.isEnabled = config.enabled !== false;
37
+ this.lastUsed = null;
38
+ this.usageCount = 0;
39
+ }
40
+
41
+ /**
42
+ * Get tool description for LLM consumption
43
+ * Must be implemented by subclasses
44
+ * @returns {string} Tool description
45
+ */
46
+ getDescription() {
47
+ throw new Error(`Tool ${this.id} must implement getDescription()`);
48
+ }
49
+
50
+ /**
51
+ * Parse parameters from tool command content
52
+ * Must be implemented by subclasses
53
+ * @param {string} content - Raw tool command content
54
+ * @returns {Object} Parsed parameters object
55
+ */
56
+ parseParameters(content) {
57
+ throw new Error(`Tool ${this.id} must implement parseParameters()`);
58
+ }
59
+
60
+ /**
61
+ * Execute tool with parsed parameters
62
+ * Must be implemented by subclasses
63
+ * @param {Object} params - Parsed parameters
64
+ * @param {Object} context - Execution context
65
+ * @returns {Promise<*>} Execution result
66
+ */
67
+ async execute(params, context) {
68
+ throw new Error(`Tool ${this.id} must implement execute()`);
69
+ }
70
+
71
+ /**
72
+ * Get tool capabilities metadata
73
+ * @returns {Object} Capabilities object
74
+ */
75
+ getCapabilities() {
76
+ return {
77
+ id: this.id,
78
+ async: this.isAsync,
79
+ requiresProject: this.requiresProject,
80
+ timeout: this.timeout,
81
+ maxConcurrentOperations: this.maxConcurrentOperations,
82
+ enabled: this.isEnabled,
83
+ supportedActions: this.getSupportedActions(),
84
+ parameterSchema: this.getParameterSchema()
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Validate tool parameters
90
+ * Can be overridden by subclasses for custom validation
91
+ * @param {Object} params - Parameters to validate
92
+ * @returns {Object} Validation result with valid flag and error message
93
+ */
94
+ validateParameters(params) {
95
+ try {
96
+ if (!params || typeof params !== 'object') {
97
+ return {
98
+ valid: false,
99
+ error: 'Parameters must be an object'
100
+ };
101
+ }
102
+
103
+ // Check required parameters
104
+ const requiredParams = this.getRequiredParameters();
105
+ for (const required of requiredParams) {
106
+ if (!(required in params)) {
107
+ return {
108
+ valid: false,
109
+ error: `Missing required parameter: ${required}`
110
+ };
111
+ }
112
+ }
113
+
114
+ // Validate parameter types
115
+ const typeValidation = this.validateParameterTypes(params);
116
+ if (!typeValidation.valid) {
117
+ return typeValidation;
118
+ }
119
+
120
+ // Custom validation
121
+ const customValidation = this.customValidateParameters(params);
122
+ if (!customValidation.valid) {
123
+ return customValidation;
124
+ }
125
+
126
+ return { valid: true };
127
+
128
+ } catch (error) {
129
+ return {
130
+ valid: false,
131
+ error: `Parameter validation failed: ${error.message}`
132
+ };
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Execute tool with full lifecycle management
138
+ * @param {Object} params - Tool parameters
139
+ * @param {Object} context - Execution context
140
+ * @returns {Promise<Object>} Execution result with metadata
141
+ */
142
+ async executeWithLifecycle(params, context) {
143
+ const operationId = this.generateOperationId();
144
+ const startTime = Date.now();
145
+
146
+ // Check if tool is enabled
147
+ if (!this.isEnabled) {
148
+ throw new Error(`Tool ${this.id} is disabled`);
149
+ }
150
+
151
+ // Check concurrent operation limits
152
+ if (this.activeOperations.size >= this.maxConcurrentOperations) {
153
+ throw new Error(`Tool ${this.id} has reached maximum concurrent operations limit`);
154
+ }
155
+
156
+ // Validate parameters
157
+ const validation = this.validateParameters(params);
158
+ if (!validation.valid) {
159
+ throw new Error(`Parameter validation failed: ${validation.error}`);
160
+ }
161
+
162
+ // Create operation record
163
+ const operation = {
164
+ id: operationId,
165
+ toolId: this.id,
166
+ status: TOOL_STATUS.EXECUTING,
167
+ startTime: new Date().toISOString(),
168
+ params,
169
+ context: this.sanitizeContext(context)
170
+ };
171
+
172
+ this.activeOperations.set(operationId, operation);
173
+
174
+ try {
175
+ this.logger?.info(`Tool execution started: ${this.id}`, {
176
+ operationId,
177
+ toolId: this.id,
178
+ context: operation.context
179
+ });
180
+
181
+ // Execute with timeout
182
+ const result = await this.executeWithTimeout(params, context);
183
+
184
+ // Update operation status
185
+ operation.status = TOOL_STATUS.COMPLETED;
186
+ operation.result = result;
187
+ operation.endTime = new Date().toISOString();
188
+ operation.executionTime = Date.now() - startTime;
189
+
190
+ // Update tool statistics
191
+ this.lastUsed = new Date().toISOString();
192
+ this.usageCount++;
193
+
194
+ this.logger?.info(`Tool execution completed: ${this.id}`, {
195
+ operationId,
196
+ executionTime: operation.executionTime,
197
+ success: true
198
+ });
199
+
200
+ return {
201
+ success: true,
202
+ operationId,
203
+ result,
204
+ executionTime: operation.executionTime,
205
+ toolId: this.id
206
+ };
207
+
208
+ } catch (error) {
209
+ // Update operation status
210
+ operation.status = TOOL_STATUS.FAILED;
211
+ operation.error = error.message;
212
+ operation.endTime = new Date().toISOString();
213
+ operation.executionTime = Date.now() - startTime;
214
+
215
+ this.logger?.error(`Tool execution failed: ${this.id}`, {
216
+ operationId,
217
+ error: error.message,
218
+ executionTime: operation.executionTime
219
+ });
220
+
221
+ throw error;
222
+
223
+ } finally {
224
+ // Move to history and cleanup
225
+ this.operationHistory.push({ ...operation });
226
+ this.activeOperations.delete(operationId);
227
+
228
+ // Cleanup old history entries
229
+ this.cleanupHistory();
230
+
231
+ // Perform tool-specific cleanup
232
+ await this.cleanup(operationId);
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Get status of async operation
238
+ * @param {string} operationId - Operation identifier
239
+ * @returns {Promise<Object>} Operation status
240
+ */
241
+ async getStatus(operationId) {
242
+ const operation = this.activeOperations.get(operationId);
243
+
244
+ if (!operation) {
245
+ // Check history
246
+ const historyEntry = this.operationHistory.find(op => op.id === operationId);
247
+ if (historyEntry) {
248
+ return {
249
+ operationId,
250
+ status: historyEntry.status,
251
+ result: historyEntry.result,
252
+ error: historyEntry.error,
253
+ executionTime: historyEntry.executionTime
254
+ };
255
+ }
256
+
257
+ return {
258
+ operationId,
259
+ status: OPERATION_STATUS.NOT_FOUND,
260
+ error: 'Operation not found'
261
+ };
262
+ }
263
+
264
+ return {
265
+ operationId,
266
+ status: operation.status,
267
+ startTime: operation.startTime,
268
+ executionTime: operation.endTime ?
269
+ new Date(operation.endTime).getTime() - new Date(operation.startTime).getTime() :
270
+ Date.now() - new Date(operation.startTime).getTime()
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Resource cleanup after tool execution
276
+ * Can be overridden by subclasses
277
+ * @param {string} operationId - Operation identifier
278
+ * @returns {Promise<void>}
279
+ */
280
+ async cleanup(operationId) {
281
+ // Default implementation - no cleanup needed
282
+ }
283
+
284
+ /**
285
+ * Get supported actions for this tool
286
+ * Can be overridden by subclasses
287
+ * @returns {Array<string>} Array of supported action names
288
+ */
289
+ getSupportedActions() {
290
+ return ['execute'];
291
+ }
292
+
293
+ /**
294
+ * Get parameter schema for validation
295
+ * Can be overridden by subclasses
296
+ * @returns {Object} Parameter schema
297
+ */
298
+ getParameterSchema() {
299
+ return {
300
+ type: 'object',
301
+ properties: {},
302
+ required: []
303
+ };
304
+ }
305
+
306
+ /**
307
+ * Get required parameters
308
+ * Can be overridden by subclasses
309
+ * @returns {Array<string>} Array of required parameter names
310
+ */
311
+ getRequiredParameters() {
312
+ return [];
313
+ }
314
+
315
+ /**
316
+ * Validate parameter types
317
+ * Can be overridden by subclasses
318
+ * @param {Object} params - Parameters to validate
319
+ * @returns {Object} Validation result
320
+ */
321
+ validateParameterTypes(params) {
322
+ // Default implementation - all parameters are valid
323
+ return { valid: true };
324
+ }
325
+
326
+ /**
327
+ * Custom parameter validation
328
+ * Can be overridden by subclasses
329
+ * @param {Object} params - Parameters to validate
330
+ * @returns {Object} Validation result
331
+ */
332
+ customValidateParameters(params) {
333
+ // Default implementation - no custom validation
334
+ return { valid: true };
335
+ }
336
+
337
+ /**
338
+ * Execute tool with timeout protection
339
+ * @private
340
+ */
341
+ async executeWithTimeout(params, context) {
342
+ return new Promise(async (resolve, reject) => {
343
+ const timeoutId = setTimeout(() => {
344
+ reject(new Error(`Tool execution timed out after ${this.timeout}ms`));
345
+ }, this.timeout);
346
+
347
+ try {
348
+ const result = await this.execute(params, context);
349
+ clearTimeout(timeoutId);
350
+ resolve(result);
351
+ } catch (error) {
352
+ clearTimeout(timeoutId);
353
+ reject(error);
354
+ }
355
+ });
356
+ }
357
+
358
+ /**
359
+ * Generate unique operation ID
360
+ * @private
361
+ */
362
+ generateOperationId() {
363
+ return `${this.id}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
364
+ }
365
+
366
+ /**
367
+ * Sanitize context for logging
368
+ * @private
369
+ */
370
+ sanitizeContext(context) {
371
+ const sanitized = { ...context };
372
+
373
+ // Remove sensitive information
374
+ delete sanitized.apiKeys;
375
+ delete sanitized.secrets;
376
+ delete sanitized.passwords;
377
+
378
+ // Truncate large content
379
+ if (sanitized.content && sanitized.content.length > 500) {
380
+ sanitized.content = sanitized.content.substring(0, 500) + '... [truncated]';
381
+ }
382
+
383
+ return sanitized;
384
+ }
385
+
386
+ /**
387
+ * Cleanup old history entries
388
+ * @private
389
+ */
390
+ cleanupHistory() {
391
+ const maxHistoryEntries = 100;
392
+ if (this.operationHistory.length > maxHistoryEntries) {
393
+ this.operationHistory = this.operationHistory.slice(-maxHistoryEntries);
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Get tool usage statistics
399
+ * @returns {Object} Usage statistics
400
+ */
401
+ getUsageStats() {
402
+ return {
403
+ toolId: this.id,
404
+ usageCount: this.usageCount,
405
+ lastUsed: this.lastUsed,
406
+ activeOperations: this.activeOperations.size,
407
+ totalOperations: this.operationHistory.length,
408
+ averageExecutionTime: this.calculateAverageExecutionTime(),
409
+ successRate: this.calculateSuccessRate(),
410
+ isEnabled: this.isEnabled
411
+ };
412
+ }
413
+
414
+ /**
415
+ * Calculate average execution time
416
+ * @private
417
+ */
418
+ calculateAverageExecutionTime() {
419
+ const completedOps = this.operationHistory.filter(op =>
420
+ op.status === TOOL_STATUS.COMPLETED && op.executionTime
421
+ );
422
+
423
+ if (completedOps.length === 0) return 0;
424
+
425
+ const totalTime = completedOps.reduce((sum, op) => sum + op.executionTime, 0);
426
+ return Math.round(totalTime / completedOps.length);
427
+ }
428
+
429
+ /**
430
+ * Calculate success rate
431
+ * @private
432
+ */
433
+ calculateSuccessRate() {
434
+ if (this.operationHistory.length === 0) return 0;
435
+
436
+ const successfulOps = this.operationHistory.filter(op =>
437
+ op.status === TOOL_STATUS.COMPLETED
438
+ );
439
+
440
+ return (successfulOps.length / this.operationHistory.length) * 100;
441
+ }
442
+
443
+ /**
444
+ * Enable tool
445
+ */
446
+ enable() {
447
+ this.isEnabled = true;
448
+ this.logger?.info(`Tool enabled: ${this.id}`);
449
+ }
450
+
451
+ /**
452
+ * Disable tool
453
+ */
454
+ disable() {
455
+ this.isEnabled = false;
456
+ this.logger?.info(`Tool disabled: ${this.id}`);
457
+ }
458
+
459
+ /**
460
+ * Reset tool statistics
461
+ */
462
+ resetStats() {
463
+ this.usageCount = 0;
464
+ this.lastUsed = null;
465
+ this.operationHistory = [];
466
+ this.logger?.info(`Tool statistics reset: ${this.id}`);
467
+ }
468
+ }
469
+
470
+ /**
471
+ * ToolsRegistry - Manages registration and discovery of tools
472
+ */
473
+ class ToolsRegistry {
474
+ constructor(logger = null) {
475
+ this.logger = logger;
476
+ this.tools = new Map();
477
+ this.toolDescriptions = new Map();
478
+ this.toolCapabilities = new Map();
479
+ this.asyncOperations = new Map();
480
+ }
481
+
482
+ /**
483
+ * Register a tool class
484
+ * @param {Class} toolClass - Tool class to register
485
+ * @returns {Promise<void>}
486
+ */
487
+ async registerTool(toolClass) {
488
+ try {
489
+ const tool = new toolClass();
490
+
491
+ if (!(tool instanceof BaseTool)) {
492
+ throw new Error(`Tool ${toolClass.name} must extend BaseTool`);
493
+ }
494
+
495
+ const capabilities = tool.getCapabilities();
496
+
497
+ // Validate tool implementation
498
+ await this.validateTool(tool);
499
+
500
+ this.tools.set(tool.id, tool);
501
+ this.toolDescriptions.set(tool.id, tool.getDescription());
502
+ this.toolCapabilities.set(tool.id, capabilities);
503
+
504
+ this.logger?.info(`Tool registered: ${tool.id}`, {
505
+ capabilities: capabilities.supportedActions,
506
+ async: capabilities.async,
507
+ requiresProject: capabilities.requiresProject
508
+ });
509
+
510
+ } catch (error) {
511
+ this.logger?.error(`Tool registration failed: ${error.message}`, {
512
+ toolClass: toolClass.name
513
+ });
514
+ throw error;
515
+ }
516
+ }
517
+
518
+ /**
519
+ * Auto-discover tools in directory
520
+ * @param {string} directory - Directory path to scan
521
+ * @returns {Promise<number>} Number of tools discovered
522
+ */
523
+ async discoverTools(directory) {
524
+ // Implementation would scan directory for tool files
525
+ // For now, return 0
526
+ return 0;
527
+ }
528
+
529
+ /**
530
+ * Validate tool implementation
531
+ * @param {BaseTool} tool - Tool instance to validate
532
+ * @returns {Promise<void>}
533
+ */
534
+ async validateTool(tool) {
535
+ // Check required methods
536
+ const requiredMethods = ['getDescription', 'parseParameters', 'execute'];
537
+
538
+ for (const method of requiredMethods) {
539
+ if (typeof tool[method] !== 'function') {
540
+ throw new Error(`Tool ${tool.id} missing required method: ${method}`);
541
+ }
542
+ }
543
+
544
+ // Test parameter parsing
545
+ try {
546
+ const testParams = tool.parseParameters('test content');
547
+ if (typeof testParams !== 'object') {
548
+ throw new Error(`Tool ${tool.id} parseParameters must return an object`);
549
+ }
550
+ } catch (error) {
551
+ // Parsing may fail for test content, that's okay
552
+ }
553
+
554
+ // Validate capabilities
555
+ const capabilities = tool.getCapabilities();
556
+ if (!capabilities || typeof capabilities !== 'object') {
557
+ throw new Error(`Tool ${tool.id} getCapabilities must return an object`);
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Get tool by ID
563
+ * @param {string} toolId - Tool identifier
564
+ * @returns {BaseTool|null} Tool instance or null
565
+ */
566
+ getTool(toolId) {
567
+ return this.tools.get(toolId) || null;
568
+ }
569
+
570
+ /**
571
+ * Get all tool capabilities for LLM consumption
572
+ * @returns {Object} All tool capabilities
573
+ */
574
+ getToolCapabilities() {
575
+ const capabilities = {};
576
+
577
+ for (const [toolId, tool] of this.tools.entries()) {
578
+ if (tool.isEnabled) {
579
+ capabilities[toolId] = {
580
+ description: this.toolDescriptions.get(toolId),
581
+ capabilities: this.toolCapabilities.get(toolId),
582
+ usageStats: tool.getUsageStats()
583
+ };
584
+ }
585
+ }
586
+
587
+ return capabilities;
588
+ }
589
+
590
+ /**
591
+ * Execute tool securely with validation
592
+ * @param {string} toolId - Tool identifier
593
+ * @param {Object} params - Tool parameters
594
+ * @param {Object} context - Execution context
595
+ * @returns {Promise<*>} Execution result
596
+ */
597
+ async executeToolSecurely(toolId, params, context) {
598
+ const tool = this.getTool(toolId);
599
+ if (!tool) {
600
+ throw new Error(`Tool not found: ${toolId}`);
601
+ }
602
+
603
+ if (!tool.isEnabled) {
604
+ throw new Error(`Tool is disabled: ${toolId}`);
605
+ }
606
+
607
+ return await tool.executeWithLifecycle(params, context);
608
+ }
609
+
610
+ /**
611
+ * List all registered tools
612
+ * @returns {Array<string>} Array of tool IDs
613
+ */
614
+ listTools() {
615
+ return Array.from(this.tools.keys());
616
+ }
617
+
618
+ /**
619
+ * Generate comprehensive tool descriptions for agent system prompts
620
+ * @param {Array<string>} capabilities - Specific tool IDs to include (empty = all)
621
+ * @param {Object} options - Generation options
622
+ * @returns {string} Formatted tool descriptions section
623
+ */
624
+ generateToolDescriptionsForPrompt(capabilities = [], options = {}) {
625
+ const {
626
+ includeExamples = true,
627
+ includeUsageGuidelines = true,
628
+ includeSecurityNotes = true,
629
+ compact = false
630
+ } = options;
631
+
632
+ // Get tools to include
633
+ const toolIds = capabilities.length > 0
634
+ ? capabilities.filter(cap => this.tools.has(cap))
635
+ : Array.from(this.tools.keys());
636
+
637
+ if (toolIds.length === 0) {
638
+ return '';
639
+ }
640
+
641
+ let description = '\n## AVAILABLE TOOLS\n\n';
642
+ description += 'You have access to the following tools to perform operations and tasks:\n\n';
643
+
644
+ // Add individual tool descriptions
645
+ for (const toolId of toolIds) {
646
+ const tool = this.tools.get(toolId);
647
+ if (!tool || !tool.isEnabled) continue;
648
+
649
+ try {
650
+ if (compact) {
651
+ // Compact format - just tool name and brief description
652
+ const capabilities = tool.getCapabilities();
653
+ const actions = capabilities.supportedActions || ['execute'];
654
+ description += `**${toolId}**: ${actions.join(', ')}\n`;
655
+ } else {
656
+ // Full format - complete tool description
657
+ description += `### ${toolId.toUpperCase()} TOOL\n\n`;
658
+ description += tool.getDescription();
659
+ description += '\n\n---\n\n';
660
+ }
661
+ } catch (error) {
662
+ this.logger?.warn(`Failed to get description for tool: ${toolId}`, {
663
+ error: error.message
664
+ });
665
+ }
666
+ }
667
+
668
+ if (compact) {
669
+ description += '\nUse [tool id="tool-name"]<parameters>[/tool] or JSON format to invoke tools.\n\n';
670
+ }
671
+
672
+ // Add comprehensive tool invocation instructions
673
+ description += '## TOOL INVOCATION SYNTAX\n\n';
674
+ description += '**IMPORTANT**: You MUST use one of these exact formats to invoke tools:\n\n';
675
+ description += '### Format 1: Bracket Notation\n';
676
+ description += '```\n';
677
+ description += '[tool id="toolname"]\n';
678
+ description += '<parameters here>\n';
679
+ description += '[/tool]\n';
680
+ description += '```\n\n';
681
+ description += '### Format 2: JSON in Markdown Code Block (REQUIRED for JSON)\n';
682
+ description += '```\n';
683
+ description += '```json\n';
684
+ description += '{\n';
685
+ description += ' "toolId": "toolname",\n';
686
+ description += ' "parameters": { ... } or "actions": [ ... ]\n';
687
+ description += '}\n';
688
+ description += '```\n';
689
+ description += '```\n\n';
690
+ description += '**WARNING**: Plain JSON without markdown code blocks (```json) will NOT be executed!\n';
691
+ description += 'Always wrap JSON tool commands in ```json ... ``` blocks.\n\n';
692
+ description += '### Format 3: XML Format\n';
693
+ description += '```xml\n';
694
+ description += '<tool-command>\n';
695
+ description += ' <tool id="toolname">\n';
696
+ description += ' <parameter>value</parameter>\n';
697
+ description += ' </tool>\n';
698
+ description += '</tool-command>\n';
699
+ description += '```\n\n';
700
+ description += 'After invoking a tool, WAIT for the actual response. Do NOT generate imaginary responses.\n';
701
+
702
+ return description;
703
+ }
704
+
705
+ /**
706
+ * Enhance existing system prompt with tool descriptions
707
+ * @param {string} existingPrompt - Current system prompt
708
+ * @param {Array<string>} capabilities - Agent capabilities
709
+ * @param {Object} options - Enhancement options
710
+ * @returns {string} Enhanced system prompt
711
+ */
712
+ enhanceSystemPrompt(existingPrompt, capabilities = [], options = {}) {
713
+ const toolSection = this.generateToolDescriptionsForPrompt(capabilities, options);
714
+
715
+ if (!toolSection.trim()) {
716
+ return existingPrompt || '';
717
+ }
718
+
719
+ const prompt = existingPrompt || '';
720
+
721
+ // If prompt already contains tool section, replace it
722
+ if (prompt.includes('## AVAILABLE TOOLS')) {
723
+ return prompt.replace(
724
+ /## AVAILABLE TOOLS[\s\S]*?(?=##|$)/,
725
+ toolSection + '\n'
726
+ );
727
+ }
728
+
729
+ const orientationParagraph = `IMPORTANT: when asked to perform an action or operation, use each response to invoke a tool if needed, and update the user on the progress (same message).`;
730
+
731
+ // Otherwise, append to the end
732
+ return prompt + (prompt.endsWith('\n') ? '' : '\n') + toolSection + orientationParagraph + '\n';
733
+ }
734
+
735
+ /**
736
+ * Get available tools with metadata for web UI
737
+ * @returns {Array} Array of tool information objects
738
+ */
739
+ getAvailableToolsForUI() {
740
+ const tools = [];
741
+
742
+ for (const [toolId, tool] of this.tools.entries()) {
743
+ const capabilities = tool.getCapabilities();
744
+
745
+ // Extract tool name and description from the tool's description
746
+ const fullDescription = tool.getDescription();
747
+ const firstLine = fullDescription.split('\n').find(line => line.trim().length > 0) || '';
748
+ const toolName = firstLine.replace(/^.*Tool:\s*/i, '').replace(/\s*-.*$/, '').trim();
749
+
750
+ tools.push({
751
+ id: toolId, // This is the correct ID to use in capabilities
752
+ name: toolName || toolId.charAt(0).toUpperCase() + toolId.slice(1),
753
+ description: firstLine,
754
+ category: this._getToolCategory(toolId),
755
+ enabled: capabilities.enabled,
756
+ async: capabilities.async,
757
+ requiresProject: capabilities.requiresProject,
758
+ className: tool.constructor.name
759
+ });
760
+ }
761
+
762
+ return tools.sort((a, b) => a.name.localeCompare(b.name));
763
+ }
764
+
765
+ /**
766
+ * Get tool category for organization
767
+ * @param {string} toolId - Tool identifier
768
+ * @returns {string} Tool category
769
+ * @private
770
+ */
771
+ _getToolCategory(toolId) {
772
+ const categories = {
773
+ 'terminal': 'System',
774
+ 'filesystem': 'File Operations',
775
+ 'browser': 'Automation',
776
+ 'agentdelay': 'Utility'
777
+ };
778
+
779
+ return categories[toolId] || 'Other';
780
+ }
781
+
782
+ /**
783
+ * Get registry statistics
784
+ * @returns {Object} Registry statistics
785
+ */
786
+ getRegistryStats() {
787
+ const enabledTools = Array.from(this.tools.values()).filter(tool => tool.isEnabled);
788
+ const totalOperations = Array.from(this.tools.values())
789
+ .reduce((sum, tool) => sum + tool.usageCount, 0);
790
+
791
+ return {
792
+ totalTools: this.tools.size,
793
+ enabledTools: enabledTools.length,
794
+ totalOperations,
795
+ activeOperations: this.asyncOperations.size
796
+ };
797
+ }
798
+ }
799
+
800
+ export { BaseTool, ToolsRegistry };