@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,956 @@
1
+ /**
2
+ * SeekTool - Search for content within project files
3
+ *
4
+ * Purpose:
5
+ * - Search for specific content/patterns within files
6
+ * - Support glob patterns for file paths
7
+ * - Verify imports, function usage, and variable references
8
+ * - Provide detailed match information with line numbers
9
+ */
10
+
11
+ import { BaseTool } from './baseTool.js';
12
+ import TagParser from '../utilities/tagParser.js';
13
+ import { promises as fs } from 'fs';
14
+ import path from 'path';
15
+
16
+ // Configuration constants
17
+ const SEEK_CONFIG = {
18
+ // File size limits
19
+ MAX_FILE_SIZE: 10 * 1024 * 1024, // 10MB - don't search files larger than this
20
+
21
+ // Search limits
22
+ MAX_FILES_PER_SEARCH: 1000, // Maximum files to search in one operation
23
+ MAX_MATCHES_PER_FILE: 100, // Maximum matches to return per file
24
+ MAX_TOTAL_MATCHES: 500, // Maximum total matches to return
25
+
26
+ // Performance limits
27
+ MAX_SEARCH_TERMS: 50, // Maximum number of search terms
28
+ MAX_FILE_PATHS: 100, // Maximum number of file path patterns
29
+
30
+ // Recursion limits
31
+ MAX_DIRECTORY_DEPTH: 20, // Maximum directory recursion depth
32
+
33
+ // Result formatting
34
+ MAX_LINE_CONTENT_LENGTH: 200, // Maximum line content to show in results
35
+ CONTEXT_LINES_BEFORE: 0, // Lines of context before match
36
+ CONTEXT_LINES_AFTER: 0, // Lines of context after match
37
+ };
38
+
39
+ // File encoding
40
+ const FILE_ENCODING = 'utf-8';
41
+
42
+ // Common binary file extensions to skip
43
+ const BINARY_EXTENSIONS = new Set([
44
+ '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.ico', '.svg',
45
+ '.pdf', '.zip', '.tar', '.gz', '.rar', '.7z',
46
+ '.exe', '.dll', '.so', '.dylib',
47
+ '.mp3', '.mp4', '.avi', '.mov', '.wmv',
48
+ '.woff', '.woff2', '.ttf', '.eot',
49
+ '.bin', '.dat', '.db', '.sqlite'
50
+ ]);
51
+
52
+ class SeekTool extends BaseTool {
53
+ constructor(config = {}, logger = null) {
54
+ super(config, logger);
55
+
56
+ // Tool metadata
57
+ this.requiresProject = true; // Requires project directory
58
+ this.isAsync = true; // File operations are async
59
+ this.timeout = config.timeout || 120000; // 2 minutes default
60
+
61
+ // Merge config with defaults
62
+ this.seekConfig = {
63
+ ...SEEK_CONFIG,
64
+ ...config.seekConfig
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Get tool description for LLM consumption
70
+ * @returns {string} Tool description
71
+ */
72
+ getDescription() {
73
+ return `
74
+ Seek Tool: Search for specific content within project files. Highly recommended for verifying imports, function usage, and variable references.
75
+
76
+ XML USAGE:
77
+ <seek>
78
+ <in-files>
79
+ file/path/one.js
80
+ file/path/two.js
81
+ src/**/*.js
82
+ </in-files>
83
+ <search-terms>
84
+ <term>search phrase one</term>
85
+ <term>search phrase two</term>
86
+ <term>search phrase three</term>
87
+ </search-terms>
88
+ </seek>
89
+
90
+ JSON USAGE:
91
+ \`\`\`json
92
+ {
93
+ "toolId": "seek",
94
+ "filePaths": [
95
+ "src/components/Header.js",
96
+ "src/utils/*.js",
97
+ "src/**/*.jsx"
98
+ ],
99
+ "searchTerms": [
100
+ "import React",
101
+ "useState",
102
+ "function handleSubmit"
103
+ ]
104
+ }
105
+ \`\`\`
106
+
107
+ SUPPORTED GLOB PATTERNS:
108
+ - *.js - All .js files in a directory
109
+ - **/*.js - All .js files recursively
110
+ - src/**/*.jsx - All .jsx files under src/ recursively
111
+ - components/*.* - All files in components/
112
+
113
+ EXAMPLES:
114
+
115
+ Example 1 - Find function usage:
116
+ <seek>
117
+ <in-files>
118
+ src/components/*.js
119
+ src/utils/helpers.js
120
+ </in-files>
121
+ <search-terms>
122
+ <term>function handleSubmit</term>
123
+ <term>useState(</term>
124
+ </search-terms>
125
+ </seek>
126
+
127
+ Example 2 - Verify imports:
128
+ <seek>
129
+ <in-files>
130
+ src/components/Header.js
131
+ src/components/Footer.js
132
+ </in-files>
133
+ <search-terms>
134
+ <term>import React</term>
135
+ <term>import { useState }</term>
136
+ <term>from 'react'</term>
137
+ </search-terms>
138
+ </seek>
139
+
140
+ Example 3 - Find variable references:
141
+ <seek>
142
+ <in-files>
143
+ src/**/*.js
144
+ </in-files>
145
+ <search-terms>
146
+ <term>apiClient</term>
147
+ <term>config.apiUrl</term>
148
+ </search-terms>
149
+ </seek>
150
+
151
+ Example 4 - Search specific files only:
152
+ <seek>
153
+ <in-files>
154
+ package.json
155
+ tsconfig.json
156
+ .gitignore
157
+ </in-files>
158
+ <search-terms>
159
+ <term>react</term>
160
+ <term>typescript</term>
161
+ </search-terms>
162
+ </seek>
163
+
164
+ FEATURES:
165
+ - Searches for exact string matches (case-sensitive)
166
+ - Returns file path, line number, and line content for each match
167
+ - Supports glob patterns for flexible file selection
168
+ - Skips binary files automatically
169
+ - Reports files not found and files with errors
170
+ - Limited to ${SEEK_CONFIG.MAX_FILE_SIZE / (1024 * 1024)}MB per file
171
+ - Returns up to ${SEEK_CONFIG.MAX_TOTAL_MATCHES} matches total
172
+
173
+ RESULT FORMAT:
174
+ The tool returns:
175
+ - List of files that were not found
176
+ - List of files that had errors during search
177
+ - For each search term:
178
+ - File path where found
179
+ - Line number
180
+ - Line content (trimmed)
181
+
182
+ MULTI-DIRECTORY SUPPORT:
183
+ When an agent has multiple directories configured, the SeekTool can search across all of them:
184
+ - Relative paths are resolved from the working directory
185
+ - Absolute paths can reference any accessible directory
186
+ - Automatic validation ensures paths are within allowed directories
187
+
188
+ Example with multiple directories:
189
+ If agent has access to:
190
+ - /home/user/project1 (working directory)
191
+ - /home/user/project2 (read-only)
192
+ - /home/user/shared (read-only)
193
+
194
+ You can search:
195
+ src/**/*.js → Searches in /home/user/project1/src/**/*.js
196
+ /home/user/project2/config.json → Searches in project2 (absolute path)
197
+ /home/user/shared/docs/*.md → Searches in shared directory
198
+
199
+ LIMITATIONS:
200
+ - Maximum ${SEEK_CONFIG.MAX_FILES_PER_SEARCH} files per search
201
+ - Maximum ${SEEK_CONFIG.MAX_SEARCH_TERMS} search terms
202
+ - Maximum ${SEEK_CONFIG.MAX_FILE_SIZE / (1024 * 1024)}MB per file
203
+ - Case-sensitive search only
204
+ - Exact string matching (not regex)
205
+ - Paths outside accessible directories will be reported as "not found"
206
+ `;
207
+ }
208
+
209
+ /**
210
+ * Parse parameters from tool command content
211
+ * @param {string} content - Raw tool command content
212
+ * @returns {Object} Parsed parameters
213
+ */
214
+ parseParameters(content) {
215
+ try {
216
+ // Try JSON first
217
+ if (content.trim().startsWith('{')) {
218
+ const parsed = JSON.parse(content);
219
+
220
+ return {
221
+ filePaths: parsed.filePaths || [],
222
+ searchTerms: parsed.searchTerms || []
223
+ };
224
+ }
225
+
226
+ // XML parsing
227
+ const params = {
228
+ filePaths: [],
229
+ searchTerms: []
230
+ };
231
+
232
+ // Extract in-files content
233
+ const inFilesPattern = /<in-files>([\s\S]*?)<\/in-files>/i;
234
+ const inFilesMatch = inFilesPattern.exec(content);
235
+
236
+ if (inFilesMatch) {
237
+ const filesContent = inFilesMatch[1];
238
+ params.filePaths = filesContent
239
+ .split('\n')
240
+ .map(line => line.trim())
241
+ .filter(line => line.length > 0);
242
+ }
243
+
244
+ // Extract search-terms content
245
+ const searchTermsPattern = /<search-terms>([\s\S]*?)<\/search-terms>/i;
246
+ const searchTermsMatch = searchTermsPattern.exec(content);
247
+
248
+ if (searchTermsMatch) {
249
+ const termsContent = searchTermsMatch[1];
250
+
251
+ // Extract individual <term> tags
252
+ const termPattern = /<term>(.*?)<\/term>/gi;
253
+ let termMatch;
254
+
255
+ while ((termMatch = termPattern.exec(termsContent)) !== null) {
256
+ const term = termMatch[1].trim();
257
+ if (term.length > 0) {
258
+ params.searchTerms.push(term);
259
+ }
260
+ }
261
+ }
262
+
263
+ return params;
264
+
265
+ } catch (error) {
266
+ this.logger?.error('Failed to parse seek parameters', { error: error.message });
267
+ return {
268
+ filePaths: [],
269
+ searchTerms: [],
270
+ parseError: error.message
271
+ };
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Get required parameters
277
+ * @returns {Array<string>} Array of required parameter names
278
+ */
279
+ getRequiredParameters() {
280
+ return ['filePaths', 'searchTerms'];
281
+ }
282
+
283
+ /**
284
+ * Custom parameter validation
285
+ * @param {Object} params - Parameters to validate
286
+ * @returns {Object} Validation result
287
+ */
288
+ customValidateParameters(params) {
289
+ const errors = [];
290
+
291
+ // Validate filePaths
292
+ if (!params.filePaths || !Array.isArray(params.filePaths) || params.filePaths.length === 0) {
293
+ errors.push('At least one file path is required');
294
+ } else if (params.filePaths.length > this.seekConfig.MAX_FILE_PATHS) {
295
+ errors.push(`Too many file paths (max ${this.seekConfig.MAX_FILE_PATHS})`);
296
+ }
297
+
298
+ // Validate searchTerms
299
+ if (!params.searchTerms || !Array.isArray(params.searchTerms) || params.searchTerms.length === 0) {
300
+ errors.push('At least one search term is required');
301
+ } else if (params.searchTerms.length > this.seekConfig.MAX_SEARCH_TERMS) {
302
+ errors.push(`Too many search terms (max ${this.seekConfig.MAX_SEARCH_TERMS})`);
303
+ }
304
+
305
+ // Validate search terms are non-empty strings
306
+ if (params.searchTerms && Array.isArray(params.searchTerms)) {
307
+ for (const [index, term] of params.searchTerms.entries()) {
308
+ if (typeof term !== 'string' || term.trim().length === 0) {
309
+ errors.push(`Search term ${index + 1}: must be a non-empty string`);
310
+ }
311
+ }
312
+ }
313
+
314
+ // Validate file paths are non-empty strings
315
+ if (params.filePaths && Array.isArray(params.filePaths)) {
316
+ for (const [index, filePath] of params.filePaths.entries()) {
317
+ if (typeof filePath !== 'string' || filePath.trim().length === 0) {
318
+ errors.push(`File path ${index + 1}: must be a non-empty string`);
319
+ }
320
+
321
+ // Check for path traversal attempts
322
+ if (filePath.includes('..')) {
323
+ errors.push(`File path ${index + 1}: path traversal (..) not allowed for security`);
324
+ }
325
+ }
326
+ }
327
+
328
+ return {
329
+ valid: errors.length === 0,
330
+ errors
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Execute tool with parsed parameters
336
+ * @param {Object} params - Parsed parameters
337
+ * @param {Object} context - Execution context
338
+ * @returns {Promise<Object>} Execution result
339
+ */
340
+ async execute(params, context) {
341
+ const { filePaths, searchTerms } = params;
342
+ const { projectDir, agentId, directoryAccess } = context;
343
+
344
+ // IMPORTANT: Get all accessible directories for the agent
345
+ // This includes workingDirectory, readOnlyDirectories, and writeEnabledDirectories
346
+ let workingDirectory = projectDir || process.cwd();
347
+ let accessibleDirectories = [workingDirectory];
348
+
349
+ if (directoryAccess && directoryAccess.workingDirectory) {
350
+ workingDirectory = directoryAccess.workingDirectory;
351
+
352
+ // Collect all accessible directories (for read operations)
353
+ accessibleDirectories = this.getAllAccessibleDirectories(directoryAccess);
354
+
355
+ this.logger?.info('Using agent configured directory access', {
356
+ workingDirectory: directoryAccess.workingDirectory,
357
+ totalAccessibleDirs: accessibleDirectories.length,
358
+ readOnlyDirs: directoryAccess.readOnlyDirectories?.length || 0,
359
+ writeEnabledDirs: directoryAccess.writeEnabledDirectories?.length || 0,
360
+ agentId
361
+ });
362
+ }
363
+
364
+ if (!workingDirectory) {
365
+ throw new Error('Project directory is required for seek tool');
366
+ }
367
+
368
+ this.logger?.info('Executing seek tool', {
369
+ filePathCount: filePaths.length,
370
+ searchTermCount: searchTerms.length,
371
+ workingDirectory,
372
+ accessibleDirectories: accessibleDirectories.length,
373
+ agentId
374
+ });
375
+
376
+ try {
377
+ // Resolve file paths (expand globs)
378
+ // Pass accessible directories for validation (if agent has directoryAccess configured)
379
+ const resolveResult = await this.resolveFilePaths(
380
+ filePaths,
381
+ workingDirectory,
382
+ directoryAccess ? accessibleDirectories : null
383
+ );
384
+
385
+ const resolvedFiles = resolveResult.found;
386
+ const notFoundFiles = resolveResult.notFound;
387
+
388
+ // Check file count limit
389
+ if (resolvedFiles.length > this.seekConfig.MAX_FILES_PER_SEARCH) {
390
+ return {
391
+ success: false,
392
+ error: `Too many files to search (${resolvedFiles.length}). Maximum is ${this.seekConfig.MAX_FILES_PER_SEARCH}. Use more specific file patterns.`,
393
+ filesResolved: resolvedFiles.length,
394
+ filesNotFound: notFoundFiles.length
395
+ };
396
+ }
397
+
398
+ // Search in files
399
+ const searchResult = await this.searchFiles(resolvedFiles, searchTerms, workingDirectory);
400
+
401
+ // Format results
402
+ const formattedResults = this.formatResults(
403
+ searchResult.matches,
404
+ searchResult.errorFiles,
405
+ notFoundFiles,
406
+ resolvedFiles.length
407
+ );
408
+
409
+ return {
410
+ success: true,
411
+ filesSearched: resolvedFiles.length,
412
+ filesNotFound: notFoundFiles.length,
413
+ filesWithErrors: searchResult.errorFiles.length,
414
+ totalMatches: searchResult.matches.length,
415
+ matchesByTerm: searchResult.matchesByTerm,
416
+ formattedResults,
417
+ toolUsed: 'seek'
418
+ };
419
+
420
+ } catch (error) {
421
+ this.logger?.error('Seek tool execution failed', { error: error.message });
422
+ throw error;
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Get all accessible directories for read operations
428
+ * @param {Object} directoryAccess - Directory access configuration
429
+ * @returns {Array<string>} Array of accessible directory paths
430
+ * @private
431
+ */
432
+ getAllAccessibleDirectories(directoryAccess) {
433
+ const directories = new Set();
434
+
435
+ // Add working directory
436
+ if (directoryAccess.workingDirectory) {
437
+ directories.add(directoryAccess.workingDirectory);
438
+ }
439
+
440
+ // Add read-only directories
441
+ if (directoryAccess.readOnlyDirectories && Array.isArray(directoryAccess.readOnlyDirectories)) {
442
+ for (const dir of directoryAccess.readOnlyDirectories) {
443
+ directories.add(dir);
444
+ }
445
+ }
446
+
447
+ // Add write-enabled directories (if you can write, you can read)
448
+ if (directoryAccess.writeEnabledDirectories && Array.isArray(directoryAccess.writeEnabledDirectories)) {
449
+ for (const dir of directoryAccess.writeEnabledDirectories) {
450
+ directories.add(dir);
451
+ }
452
+ }
453
+
454
+ return Array.from(directories);
455
+ }
456
+
457
+ /**
458
+ * Check if a path is within any accessible directory
459
+ * @param {string} targetPath - Path to check
460
+ * @param {Array<string>} accessibleDirs - Array of accessible directories
461
+ * @returns {boolean} True if path is accessible
462
+ * @private
463
+ */
464
+ isPathAccessible(targetPath, accessibleDirs) {
465
+ for (const dir of accessibleDirs) {
466
+ const relative = path.relative(dir, targetPath);
467
+ const isWithin = !relative.startsWith('..') && !path.isAbsolute(relative);
468
+ if (isWithin) {
469
+ return true;
470
+ }
471
+ }
472
+ return false;
473
+ }
474
+
475
+ /**
476
+ * Resolve file paths, expanding glob patterns
477
+ * @param {Array<string>} filePaths - File paths with possible glob patterns
478
+ * @param {string} projectDir - Project directory
479
+ * @param {Array<string>} accessibleDirs - Optional array of accessible directories
480
+ * @returns {Promise<Object>} Object with found and notFound arrays
481
+ * @private
482
+ */
483
+ async resolveFilePaths(filePaths, projectDir, accessibleDirs = null) {
484
+ const result = {
485
+ found: [],
486
+ notFound: []
487
+ };
488
+
489
+ for (const filePath of filePaths) {
490
+ const normalizedPath = filePath.trim();
491
+
492
+ if (normalizedPath.includes('*')) {
493
+ // Handle glob patterns
494
+ const globResult = await this.expandGlobPattern(normalizedPath, projectDir);
495
+
496
+ if (globResult.found.length > 0) {
497
+ result.found.push(...globResult.found);
498
+ } else {
499
+ result.notFound.push(`${normalizedPath} (no matching files)`);
500
+ }
501
+ } else {
502
+ // Handle direct file reference
503
+ const absolutePath = path.isAbsolute(normalizedPath)
504
+ ? normalizedPath
505
+ : path.resolve(projectDir, normalizedPath);
506
+
507
+ // Check if path is within accessible directories (if configured)
508
+ if (accessibleDirs && accessibleDirs.length > 0) {
509
+ if (!this.isPathAccessible(absolutePath, accessibleDirs)) {
510
+ result.notFound.push(`${normalizedPath} (not in accessible directories)`);
511
+ continue;
512
+ }
513
+ }
514
+
515
+ try {
516
+ const stats = await fs.stat(absolutePath);
517
+
518
+ if (stats.isFile()) {
519
+ result.found.push(absolutePath);
520
+ } else if (stats.isDirectory()) {
521
+ result.notFound.push(`${normalizedPath} (is a directory, not a file)`);
522
+ } else {
523
+ result.notFound.push(`${normalizedPath} (not a regular file)`);
524
+ }
525
+ } catch (error) {
526
+ result.notFound.push(`${normalizedPath} (${error.code || error.message})`);
527
+ }
528
+ }
529
+ }
530
+
531
+ return result;
532
+ }
533
+
534
+ /**
535
+ * Expand glob pattern to matching file paths
536
+ * @param {string} pattern - Glob pattern
537
+ * @param {string} projectDir - Project directory
538
+ * @returns {Promise<Object>} Object with found files
539
+ * @private
540
+ */
541
+ async expandGlobPattern(pattern, projectDir) {
542
+ const result = { found: [] };
543
+
544
+ // Handle recursive pattern: src/**/*.js
545
+ if (pattern.includes('**/')) {
546
+ const [baseDir, filePattern] = pattern.split('**/');
547
+ const basePath = path.resolve(projectDir, baseDir);
548
+
549
+ try {
550
+ const stats = await fs.stat(basePath);
551
+
552
+ if (stats.isDirectory()) {
553
+ await this.findFilesRecursively(
554
+ basePath,
555
+ filePattern,
556
+ result.found,
557
+ 0,
558
+ this.seekConfig.MAX_DIRECTORY_DEPTH
559
+ );
560
+ }
561
+ } catch (error) {
562
+ // Directory doesn't exist
563
+ this.logger?.warn('Base directory not found for glob pattern', { basePath, error: error.message });
564
+ }
565
+ }
566
+ // Handle simple pattern: src/*.js
567
+ else if (pattern.includes('*')) {
568
+ const dirPath = path.dirname(path.resolve(projectDir, pattern));
569
+ const filePattern = path.basename(pattern);
570
+
571
+ try {
572
+ const stats = await fs.stat(dirPath);
573
+
574
+ if (stats.isDirectory()) {
575
+ const files = await fs.readdir(dirPath);
576
+
577
+ for (const file of files) {
578
+ const filePath = path.join(dirPath, file);
579
+
580
+ try {
581
+ const fileStats = await fs.stat(filePath);
582
+
583
+ if (fileStats.isFile() && this.matchesPattern(file, filePattern)) {
584
+ result.found.push(filePath);
585
+ }
586
+ } catch (error) {
587
+ // Skip files we can't stat
588
+ continue;
589
+ }
590
+ }
591
+ }
592
+ } catch (error) {
593
+ // Directory doesn't exist
594
+ this.logger?.warn('Directory not found for glob pattern', { dirPath, error: error.message });
595
+ }
596
+ }
597
+
598
+ return result;
599
+ }
600
+
601
+ /**
602
+ * Find files recursively matching a pattern
603
+ * @param {string} dir - Directory to search
604
+ * @param {string} filePattern - File pattern to match
605
+ * @param {Array<string>} results - Results array
606
+ * @param {number} currentDepth - Current recursion depth
607
+ * @param {number} maxDepth - Maximum recursion depth
608
+ * @returns {Promise<void>}
609
+ * @private
610
+ */
611
+ async findFilesRecursively(dir, filePattern, results, currentDepth, maxDepth) {
612
+ // Prevent infinite recursion
613
+ if (currentDepth >= maxDepth) {
614
+ this.logger?.warn('Maximum directory depth reached', { dir, currentDepth });
615
+ return;
616
+ }
617
+
618
+ try {
619
+ const entries = await fs.readdir(dir, { withFileTypes: true });
620
+
621
+ for (const entry of entries) {
622
+ // Skip hidden files and directories
623
+ if (entry.name.startsWith('.')) {
624
+ continue;
625
+ }
626
+
627
+ const fullPath = path.join(dir, entry.name);
628
+
629
+ try {
630
+ if (entry.isDirectory()) {
631
+ // Skip common large directories
632
+ if (this.shouldSkipDirectory(entry.name)) {
633
+ continue;
634
+ }
635
+
636
+ await this.findFilesRecursively(
637
+ fullPath,
638
+ filePattern,
639
+ results,
640
+ currentDepth + 1,
641
+ maxDepth
642
+ );
643
+ } else if (entry.isFile()) {
644
+ if (this.matchesPattern(entry.name, filePattern)) {
645
+ results.push(fullPath);
646
+
647
+ // Stop if we've found too many files
648
+ if (results.length >= this.seekConfig.MAX_FILES_PER_SEARCH) {
649
+ return;
650
+ }
651
+ }
652
+ }
653
+ } catch (error) {
654
+ // Skip entries we can't access
655
+ continue;
656
+ }
657
+ }
658
+ } catch (error) {
659
+ this.logger?.warn('Error reading directory', { dir, error: error.message });
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Check if filename matches a wildcard pattern
665
+ * @param {string} filename - Filename to check
666
+ * @param {string} pattern - Wildcard pattern
667
+ * @returns {boolean} True if matches
668
+ * @private
669
+ */
670
+ matchesPattern(filename, pattern) {
671
+ // Simple wildcard matching
672
+ const regexPattern = pattern
673
+ .split('*')
674
+ .map(part => this.escapeRegExp(part))
675
+ .join('.*');
676
+
677
+ const regex = new RegExp(`^${regexPattern}$`, 'i');
678
+ return regex.test(filename);
679
+ }
680
+
681
+ /**
682
+ * Escape special regex characters
683
+ * @param {string} string - String to escape
684
+ * @returns {string} Escaped string
685
+ * @private
686
+ */
687
+ escapeRegExp(string) {
688
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
689
+ }
690
+
691
+ /**
692
+ * Check if directory should be skipped during recursive search
693
+ * @param {string} dirName - Directory name
694
+ * @returns {boolean} True if should skip
695
+ * @private
696
+ */
697
+ shouldSkipDirectory(dirName) {
698
+ const skipDirs = new Set([
699
+ 'node_modules',
700
+ '.git',
701
+ 'dist',
702
+ 'build',
703
+ 'coverage',
704
+ '.next',
705
+ '.nuxt',
706
+ 'out',
707
+ 'target',
708
+ 'vendor',
709
+ '__pycache__',
710
+ '.cache',
711
+ 'tmp',
712
+ 'temp'
713
+ ]);
714
+
715
+ return skipDirs.has(dirName.toLowerCase());
716
+ }
717
+
718
+ /**
719
+ * Check if file should be skipped (binary files)
720
+ * @param {string} filePath - File path
721
+ * @returns {boolean} True if should skip
722
+ * @private
723
+ */
724
+ shouldSkipFile(filePath) {
725
+ const ext = path.extname(filePath).toLowerCase();
726
+ return BINARY_EXTENSIONS.has(ext);
727
+ }
728
+
729
+ /**
730
+ * Search for terms in multiple files
731
+ * @param {Array<string>} filePaths - File paths to search
732
+ * @param {Array<string>} searchTerms - Search terms
733
+ * @param {string} projectDir - Project directory for relative paths
734
+ * @returns {Promise<Object>} Search results
735
+ * @private
736
+ */
737
+ async searchFiles(filePaths, searchTerms, projectDir) {
738
+ const allMatches = [];
739
+ const errorFiles = [];
740
+ let totalMatches = 0;
741
+
742
+ for (const filePath of filePaths) {
743
+ // Skip binary files
744
+ if (this.shouldSkipFile(filePath)) {
745
+ continue;
746
+ }
747
+
748
+ try {
749
+ // Check file size
750
+ const stats = await fs.stat(filePath);
751
+
752
+ if (stats.size > this.seekConfig.MAX_FILE_SIZE) {
753
+ errorFiles.push({
754
+ filePath: path.relative(projectDir, filePath),
755
+ error: `File too large (${Math.round(stats.size / (1024 * 1024))}MB, max ${Math.round(this.seekConfig.MAX_FILE_SIZE / (1024 * 1024))}MB)`
756
+ });
757
+ continue;
758
+ }
759
+
760
+ // Search in file
761
+ const matches = await this.searchInFile(filePath, searchTerms, projectDir);
762
+
763
+ allMatches.push(...matches);
764
+ totalMatches += matches.length;
765
+
766
+ // Stop if we've exceeded max total matches
767
+ if (totalMatches >= this.seekConfig.MAX_TOTAL_MATCHES) {
768
+ this.logger?.warn('Maximum total matches reached', { totalMatches });
769
+ break;
770
+ }
771
+
772
+ } catch (error) {
773
+ errorFiles.push({
774
+ filePath: path.relative(projectDir, filePath),
775
+ error: error.message
776
+ });
777
+ }
778
+ }
779
+
780
+ // Group matches by search term
781
+ const matchesByTerm = {};
782
+
783
+ for (const match of allMatches) {
784
+ if (!matchesByTerm[match.term]) {
785
+ matchesByTerm[match.term] = [];
786
+ }
787
+
788
+ matchesByTerm[match.term].push({
789
+ filePath: match.filePath,
790
+ lineNumber: match.lineNumber,
791
+ lineContent: match.lineContent
792
+ });
793
+ }
794
+
795
+ return {
796
+ matches: allMatches,
797
+ matchesByTerm,
798
+ errorFiles
799
+ };
800
+ }
801
+
802
+ /**
803
+ * Search for terms in a single file
804
+ * @param {string} filePath - File path
805
+ * @param {Array<string>} searchTerms - Search terms
806
+ * @param {string} projectDir - Project directory for relative paths
807
+ * @returns {Promise<Array<Object>>} Matches found
808
+ * @private
809
+ */
810
+ async searchInFile(filePath, searchTerms, projectDir) {
811
+ const matches = [];
812
+ let matchesInFile = 0;
813
+
814
+ try {
815
+ // Read file content
816
+ const content = await fs.readFile(filePath, FILE_ENCODING);
817
+
818
+ // Split into lines
819
+ const lines = content.split('\n');
820
+ const relativePath = path.relative(projectDir, filePath);
821
+
822
+ // Search each line
823
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
824
+ const line = lines[lineIndex];
825
+ const lineNumber = lineIndex + 1; // 1-based line numbers
826
+
827
+ // Check each search term
828
+ for (const term of searchTerms) {
829
+ if (line.includes(term)) {
830
+ // Truncate line content if too long
831
+ let lineContent = line;
832
+ if (lineContent.length > this.seekConfig.MAX_LINE_CONTENT_LENGTH) {
833
+ const termIndex = lineContent.indexOf(term);
834
+ const start = Math.max(0, termIndex - 50);
835
+ const end = Math.min(lineContent.length, termIndex + term.length + 50);
836
+ lineContent = (start > 0 ? '...' : '') +
837
+ lineContent.substring(start, end) +
838
+ (end < lineContent.length ? '...' : '');
839
+ }
840
+
841
+ matches.push({
842
+ term,
843
+ filePath: relativePath,
844
+ lineNumber,
845
+ lineContent: lineContent.trim()
846
+ });
847
+
848
+ matchesInFile++;
849
+
850
+ // Limit matches per file
851
+ if (matchesInFile >= this.seekConfig.MAX_MATCHES_PER_FILE) {
852
+ this.logger?.warn('Maximum matches per file reached', { filePath: relativePath });
853
+ return matches;
854
+ }
855
+ }
856
+ }
857
+ }
858
+
859
+ } catch (error) {
860
+ throw new Error(`Failed to read file: ${error.message}`);
861
+ }
862
+
863
+ return matches;
864
+ }
865
+
866
+ /**
867
+ * Format search results for display
868
+ * @param {Array<Object>} matches - Search matches
869
+ * @param {Array<Object>} errorFiles - Files with errors
870
+ * @param {Array<string>} notFoundFiles - Files not found
871
+ * @param {number} filesSearched - Number of files searched
872
+ * @returns {string} Formatted results
873
+ * @private
874
+ */
875
+ formatResults(matches, errorFiles, notFoundFiles, filesSearched) {
876
+ let output = '';
877
+
878
+ // Report files not found
879
+ if (notFoundFiles.length > 0) {
880
+ output += 'FILES NOT FOUND:\n';
881
+ for (const file of notFoundFiles) {
882
+ output += ` - ${file}\n`;
883
+ }
884
+ output += '\n';
885
+ }
886
+
887
+ // Report files with errors
888
+ if (errorFiles.length > 0) {
889
+ output += 'FILES WITH ERRORS:\n';
890
+ for (const file of errorFiles) {
891
+ output += ` - ${file.filePath}: ${file.error}\n`;
892
+ }
893
+ output += '\n';
894
+ }
895
+
896
+ // Report search results
897
+ if (matches.length === 0) {
898
+ output += `No matches found for the specified search terms in ${filesSearched} file(s).\n`;
899
+ } else {
900
+ // Group by term
901
+ const matchesByTerm = {};
902
+ for (const match of matches) {
903
+ if (!matchesByTerm[match.term]) {
904
+ matchesByTerm[match.term] = [];
905
+ }
906
+ matchesByTerm[match.term].push(match);
907
+ }
908
+
909
+ output += `SEARCH RESULTS (${matches.length} total matches in ${filesSearched} file(s)):\n\n`;
910
+
911
+ for (const [term, termMatches] of Object.entries(matchesByTerm)) {
912
+ output += `Search term: "${term}" (${termMatches.length} matches)\n`;
913
+
914
+ for (const match of termMatches) {
915
+ output += ` ${match.filePath}:${match.lineNumber} - ${match.lineContent}\n`;
916
+ }
917
+
918
+ output += '\n';
919
+ }
920
+
921
+ // Add warning if max matches reached
922
+ if (matches.length >= this.seekConfig.MAX_TOTAL_MATCHES) {
923
+ output += `⚠️ Maximum matches limit reached (${this.seekConfig.MAX_TOTAL_MATCHES}). Some matches may not be shown.\n`;
924
+ }
925
+ }
926
+
927
+ return output.trim();
928
+ }
929
+
930
+ /**
931
+ * Get supported file extensions
932
+ * @returns {Array<string>} Array of supported extensions
933
+ */
934
+ getSupportedExtensions() {
935
+ return [
936
+ '.js', '.jsx', '.ts', '.tsx',
937
+ '.json', '.xml', '.html', '.css', '.scss', '.sass', '.less',
938
+ '.md', '.txt', '.log',
939
+ '.py', '.rb', '.java', '.go', '.rs',
940
+ '.c', '.cpp', '.h', '.hpp',
941
+ '.sh', '.bash', '.zsh',
942
+ '.yml', '.yaml', '.toml', '.ini', '.conf'
943
+ ];
944
+ }
945
+
946
+ /**
947
+ * Resource cleanup
948
+ * @param {string} operationId - Operation identifier
949
+ */
950
+ async cleanup(operationId) {
951
+ // No persistent resources to clean up
952
+ this.logger?.info('Seek tool cleanup completed', { operationId });
953
+ }
954
+ }
955
+
956
+ export default SeekTool;