@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.
- package/LICENSE +267 -0
- package/README.md +509 -0
- package/bin/cli.js +117 -0
- package/package.json +94 -0
- package/scripts/install-scanners.js +236 -0
- package/src/analyzers/CSSAnalyzer.js +297 -0
- package/src/analyzers/ConfigValidator.js +690 -0
- package/src/analyzers/ESLintAnalyzer.js +320 -0
- package/src/analyzers/JavaScriptAnalyzer.js +261 -0
- package/src/analyzers/PrettierFormatter.js +247 -0
- package/src/analyzers/PythonAnalyzer.js +266 -0
- package/src/analyzers/SecurityAnalyzer.js +729 -0
- package/src/analyzers/TypeScriptAnalyzer.js +247 -0
- package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
- package/src/analyzers/codeCloneDetector/detector.js +203 -0
- package/src/analyzers/codeCloneDetector/index.js +160 -0
- package/src/analyzers/codeCloneDetector/parser.js +199 -0
- package/src/analyzers/codeCloneDetector/reporter.js +148 -0
- package/src/analyzers/codeCloneDetector/scanner.js +59 -0
- package/src/core/agentPool.js +1474 -0
- package/src/core/agentScheduler.js +2147 -0
- package/src/core/contextManager.js +709 -0
- package/src/core/messageProcessor.js +732 -0
- package/src/core/orchestrator.js +548 -0
- package/src/core/stateManager.js +877 -0
- package/src/index.js +631 -0
- package/src/interfaces/cli.js +549 -0
- package/src/interfaces/webServer.js +2162 -0
- package/src/modules/fileExplorer/controller.js +280 -0
- package/src/modules/fileExplorer/index.js +37 -0
- package/src/modules/fileExplorer/middleware.js +92 -0
- package/src/modules/fileExplorer/routes.js +125 -0
- package/src/modules/fileExplorer/types.js +44 -0
- package/src/services/aiService.js +1232 -0
- package/src/services/apiKeyManager.js +164 -0
- package/src/services/benchmarkService.js +366 -0
- package/src/services/budgetService.js +539 -0
- package/src/services/contextInjectionService.js +247 -0
- package/src/services/conversationCompactionService.js +637 -0
- package/src/services/errorHandler.js +810 -0
- package/src/services/fileAttachmentService.js +544 -0
- package/src/services/modelRouterService.js +366 -0
- package/src/services/modelsService.js +322 -0
- package/src/services/qualityInspector.js +796 -0
- package/src/services/tokenCountingService.js +536 -0
- package/src/tools/agentCommunicationTool.js +1344 -0
- package/src/tools/agentDelayTool.js +485 -0
- package/src/tools/asyncToolManager.js +604 -0
- package/src/tools/baseTool.js +800 -0
- package/src/tools/browserTool.js +920 -0
- package/src/tools/cloneDetectionTool.js +621 -0
- package/src/tools/dependencyResolverTool.js +1215 -0
- package/src/tools/fileContentReplaceTool.js +875 -0
- package/src/tools/fileSystemTool.js +1107 -0
- package/src/tools/fileTreeTool.js +853 -0
- package/src/tools/imageTool.js +901 -0
- package/src/tools/importAnalyzerTool.js +1060 -0
- package/src/tools/jobDoneTool.js +248 -0
- package/src/tools/seekTool.js +956 -0
- package/src/tools/staticAnalysisTool.js +1778 -0
- package/src/tools/taskManagerTool.js +2873 -0
- package/src/tools/terminalTool.js +2304 -0
- package/src/tools/webTool.js +1430 -0
- package/src/types/agent.js +519 -0
- package/src/types/contextReference.js +972 -0
- package/src/types/conversation.js +730 -0
- package/src/types/toolCommand.js +747 -0
- package/src/utilities/attachmentValidator.js +292 -0
- package/src/utilities/configManager.js +582 -0
- package/src/utilities/constants.js +722 -0
- package/src/utilities/directoryAccessManager.js +535 -0
- package/src/utilities/fileProcessor.js +307 -0
- package/src/utilities/logger.js +436 -0
- package/src/utilities/tagParser.js +1246 -0
- package/src/utilities/toolConstants.js +317 -0
- package/web-ui/build/index.html +15 -0
- package/web-ui/build/logo.png +0 -0
- package/web-ui/build/logo2.png +0 -0
- package/web-ui/build/static/index-CjkkcnFA.js +344 -0
- package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FileContentReplaceTool - Replace specific content within files
|
|
3
|
+
*
|
|
4
|
+
* Purpose:
|
|
5
|
+
* - Replace text content in files with precision
|
|
6
|
+
* - Support line-limited replacements
|
|
7
|
+
* - Handle whitespace intelligently with trim modes
|
|
8
|
+
* - Create backups before modifications
|
|
9
|
+
* - Generate diff reports
|
|
10
|
+
* - Support multi-file operations
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { BaseTool } from './baseTool.js';
|
|
14
|
+
import { promises as fs } from 'fs';
|
|
15
|
+
import path from 'path';
|
|
16
|
+
|
|
17
|
+
// Configuration constants
|
|
18
|
+
const REPLACE_CONFIG = {
|
|
19
|
+
// File size limits
|
|
20
|
+
MAX_FILE_SIZE: 10 * 1024 * 1024, // 10MB max file size
|
|
21
|
+
MAX_OLD_CONTENT_SIZE: 100 * 1024, // 100KB max old content
|
|
22
|
+
MAX_NEW_CONTENT_SIZE: 100 * 1024, // 100KB max new content
|
|
23
|
+
|
|
24
|
+
// Operation limits
|
|
25
|
+
MAX_REPLACEMENTS_PER_FILE: 1000, // Max replacements in single file
|
|
26
|
+
MAX_FILES_PER_OPERATION: 50, // Max files in one operation
|
|
27
|
+
MAX_LINE_RANGE_SIZE: 10000, // Max lines in a range
|
|
28
|
+
|
|
29
|
+
// Backup settings
|
|
30
|
+
CREATE_BACKUPS: true,
|
|
31
|
+
BACKUP_EXTENSION: '.bak',
|
|
32
|
+
|
|
33
|
+
// Diff settings
|
|
34
|
+
DIFF_CONTEXT_LINES: 3, // Lines of context in diff
|
|
35
|
+
MAX_DIFF_LINES: 100, // Max lines to show in diff
|
|
36
|
+
|
|
37
|
+
// Default settings
|
|
38
|
+
DEFAULT_TRIM_MODE: 'trim'
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
class FileContentReplaceTool extends BaseTool {
|
|
42
|
+
constructor(config = {}, logger = null) {
|
|
43
|
+
super(config, logger);
|
|
44
|
+
|
|
45
|
+
// Tool metadata
|
|
46
|
+
this.requiresProject = true;
|
|
47
|
+
this.isAsync = true;
|
|
48
|
+
this.timeout = config.timeout || 120000; // 2 minutes default
|
|
49
|
+
|
|
50
|
+
// Merge config with defaults
|
|
51
|
+
this.replaceConfig = {
|
|
52
|
+
...REPLACE_CONFIG,
|
|
53
|
+
...config.replaceConfig
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Get tool description for LLM consumption
|
|
59
|
+
* @returns {string} Tool description
|
|
60
|
+
*/
|
|
61
|
+
getDescription() {
|
|
62
|
+
return `
|
|
63
|
+
File Content Replace Tool: Replace specific content within files with precision.
|
|
64
|
+
|
|
65
|
+
XML USAGE:
|
|
66
|
+
<file-content-replace>
|
|
67
|
+
<file path="src/app.js">
|
|
68
|
+
<replace mode="trim" lines-limit="5,7-10">
|
|
69
|
+
<old-content>
|
|
70
|
+
const oldFunction = () => {
|
|
71
|
+
console.log('old');
|
|
72
|
+
}
|
|
73
|
+
</old-content>
|
|
74
|
+
<new-content>
|
|
75
|
+
const newFunction = () => {
|
|
76
|
+
console.log('new');
|
|
77
|
+
}
|
|
78
|
+
</new-content>
|
|
79
|
+
</replace>
|
|
80
|
+
</file>
|
|
81
|
+
</file-content-replace>
|
|
82
|
+
|
|
83
|
+
JSON USAGE:
|
|
84
|
+
\`\`\`json
|
|
85
|
+
{
|
|
86
|
+
"toolId": "file-content-replace",
|
|
87
|
+
"files": [
|
|
88
|
+
{
|
|
89
|
+
"path": "src/app.js",
|
|
90
|
+
"replacements": [
|
|
91
|
+
{
|
|
92
|
+
"oldContent": "const oldFunction = () => {}",
|
|
93
|
+
"newContent": "const newFunction = () => {}",
|
|
94
|
+
"mode": "trim",
|
|
95
|
+
"linesLimit": "5,7-10"
|
|
96
|
+
}
|
|
97
|
+
]
|
|
98
|
+
}
|
|
99
|
+
]
|
|
100
|
+
}
|
|
101
|
+
\`\`\`
|
|
102
|
+
|
|
103
|
+
PARAMETERS:
|
|
104
|
+
|
|
105
|
+
path (required):
|
|
106
|
+
- Path to the file to modify
|
|
107
|
+
- Can be relative or absolute
|
|
108
|
+
- Examples: "src/app.js", "./config.json"
|
|
109
|
+
|
|
110
|
+
oldContent (required):
|
|
111
|
+
- Content to find and replace
|
|
112
|
+
- Subject to trim mode processing
|
|
113
|
+
- Must exist in file
|
|
114
|
+
|
|
115
|
+
newContent (required):
|
|
116
|
+
- Replacement content
|
|
117
|
+
- Subject to trim mode processing
|
|
118
|
+
- Can be same length, shorter, or longer
|
|
119
|
+
|
|
120
|
+
mode (optional):
|
|
121
|
+
- Whitespace handling mode
|
|
122
|
+
- Options:
|
|
123
|
+
* "trim" (default): Trim all whitespace from both ends
|
|
124
|
+
* "newlines": Only trim newline characters
|
|
125
|
+
* "none": Use content exactly as provided
|
|
126
|
+
- Helps with matching despite indentation differences
|
|
127
|
+
|
|
128
|
+
linesLimit (optional):
|
|
129
|
+
- Restrict replacement to specific lines
|
|
130
|
+
- Format: Comma-separated line numbers or ranges
|
|
131
|
+
- Examples:
|
|
132
|
+
* "5" - Only line 5
|
|
133
|
+
* "5,10,15" - Lines 5, 10, and 15
|
|
134
|
+
* "5-10" - Lines 5 through 10
|
|
135
|
+
* "1-5,10,15-20" - Lines 1-5, 10, and 15-20
|
|
136
|
+
- Line numbers are 1-based
|
|
137
|
+
|
|
138
|
+
TRIM MODES EXPLAINED:
|
|
139
|
+
|
|
140
|
+
Mode: "trim" (Recommended for most cases)
|
|
141
|
+
Input:
|
|
142
|
+
" const x = 1; \\n"
|
|
143
|
+
After trim:
|
|
144
|
+
"const x = 1;"
|
|
145
|
+
Use when: Indentation may vary
|
|
146
|
+
|
|
147
|
+
Mode: "newlines"
|
|
148
|
+
Input:
|
|
149
|
+
"\\n const x = 1; \\n"
|
|
150
|
+
After trim:
|
|
151
|
+
" const x = 1; "
|
|
152
|
+
Use when: Preserving internal whitespace
|
|
153
|
+
|
|
154
|
+
Mode: "none"
|
|
155
|
+
Input:
|
|
156
|
+
" const x = 1; \\n"
|
|
157
|
+
After trim:
|
|
158
|
+
" const x = 1; \\n"
|
|
159
|
+
Use when: Exact character match needed
|
|
160
|
+
|
|
161
|
+
EXAMPLES:
|
|
162
|
+
|
|
163
|
+
Example 1 - Basic replacement with trim:
|
|
164
|
+
<file-content-replace>
|
|
165
|
+
<file path="src/components/Button.js">
|
|
166
|
+
<replace mode="trim">
|
|
167
|
+
<old-content>
|
|
168
|
+
const handleClick = (event) => {
|
|
169
|
+
console.log('clicked');
|
|
170
|
+
}
|
|
171
|
+
</old-content>
|
|
172
|
+
<new-content>
|
|
173
|
+
const handleClick = (event) => {
|
|
174
|
+
console.log('clicked');
|
|
175
|
+
props.onClick?.(event);
|
|
176
|
+
}
|
|
177
|
+
</new-content>
|
|
178
|
+
</replace>
|
|
179
|
+
</file>
|
|
180
|
+
</file-content-replace>
|
|
181
|
+
|
|
182
|
+
Example 2 - Line-limited replacement:
|
|
183
|
+
<file-content-replace>
|
|
184
|
+
<file path="src/App.js">
|
|
185
|
+
<replace lines-limit="10-20">
|
|
186
|
+
<old-content>const API_URL = 'http://localhost:3000'</old-content>
|
|
187
|
+
<new-content>const API_URL = process.env.API_URL</new-content>
|
|
188
|
+
</replace>
|
|
189
|
+
</file>
|
|
190
|
+
</file-content-replace>
|
|
191
|
+
|
|
192
|
+
Example 3 - Multiple replacements in one file:
|
|
193
|
+
<file-content-replace>
|
|
194
|
+
<file path="src/config.js">
|
|
195
|
+
<replace>
|
|
196
|
+
<old-content>DEBUG = false</old-content>
|
|
197
|
+
<new-content>DEBUG = true</new-content>
|
|
198
|
+
</replace>
|
|
199
|
+
<replace>
|
|
200
|
+
<old-content>LOG_LEVEL = 'error'</old-content>
|
|
201
|
+
<new-content>LOG_LEVEL = 'debug'</new-content>
|
|
202
|
+
</replace>
|
|
203
|
+
</file>
|
|
204
|
+
</file-content-replace>
|
|
205
|
+
|
|
206
|
+
Example 4 - Multiple files:
|
|
207
|
+
<file-content-replace>
|
|
208
|
+
<file path="src/app.js">
|
|
209
|
+
<replace>
|
|
210
|
+
<old-content>version = '1.0.0'</old-content>
|
|
211
|
+
<new-content>version = '1.1.0'</new-content>
|
|
212
|
+
</replace>
|
|
213
|
+
</file>
|
|
214
|
+
<file path="package.json">
|
|
215
|
+
<replace mode="none">
|
|
216
|
+
<old-content>"version": "1.0.0"</old-content>
|
|
217
|
+
<new-content>"version": "1.1.0"</new-content>
|
|
218
|
+
</replace>
|
|
219
|
+
</file>
|
|
220
|
+
</file-content-replace>
|
|
221
|
+
|
|
222
|
+
Example 5 - Exact whitespace matching:
|
|
223
|
+
<file-content-replace>
|
|
224
|
+
<file path="Makefile">
|
|
225
|
+
<replace mode="none">
|
|
226
|
+
<old-content>\\tbuild:\\n\\t\\tgcc</old-content>
|
|
227
|
+
<new-content>\\tbuild:\\n\\t\\tclang</new-content>
|
|
228
|
+
</replace>
|
|
229
|
+
</file>
|
|
230
|
+
</file-content-replace>
|
|
231
|
+
|
|
232
|
+
FEATURES:
|
|
233
|
+
|
|
234
|
+
✓ Automatic backup creation (.bak files)
|
|
235
|
+
✓ Before/after diff reports
|
|
236
|
+
✓ Replacement counting and statistics
|
|
237
|
+
✓ Multi-file operations
|
|
238
|
+
✓ Line-limited replacements
|
|
239
|
+
✓ Intelligent whitespace handling
|
|
240
|
+
✓ Security validation (path access)
|
|
241
|
+
✓ Creates parent directories if needed
|
|
242
|
+
|
|
243
|
+
LIMITATIONS:
|
|
244
|
+
|
|
245
|
+
- Maximum file size: ${REPLACE_CONFIG.MAX_FILE_SIZE / (1024 * 1024)}MB
|
|
246
|
+
- Maximum old content size: ${REPLACE_CONFIG.MAX_OLD_CONTENT_SIZE / 1024}KB
|
|
247
|
+
- Maximum new content size: ${REPLACE_CONFIG.MAX_NEW_CONTENT_SIZE / 1024}KB
|
|
248
|
+
- Maximum replacements per file: ${REPLACE_CONFIG.MAX_REPLACEMENTS_PER_FILE}
|
|
249
|
+
- Maximum files per operation: ${REPLACE_CONFIG.MAX_FILES_PER_OPERATION}
|
|
250
|
+
|
|
251
|
+
NOTES:
|
|
252
|
+
|
|
253
|
+
- Use the seek tool first to verify content exists
|
|
254
|
+
- Backups are created automatically (.bak extension)
|
|
255
|
+
- Replacements are case-sensitive
|
|
256
|
+
- Old content must match exactly (after trim mode applied)
|
|
257
|
+
- Multiple occurrences are all replaced unless linesLimit specified
|
|
258
|
+
- Tool validates paths against agent's accessible directories
|
|
259
|
+
|
|
260
|
+
MULTI-DIRECTORY SUPPORT:
|
|
261
|
+
|
|
262
|
+
Works with agent's configured accessible directories.
|
|
263
|
+
Validates paths against directoryAccess configuration.
|
|
264
|
+
`;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Parse parameters from tool command content
|
|
269
|
+
* @param {string} content - Raw tool command content
|
|
270
|
+
* @returns {Object} Parsed parameters
|
|
271
|
+
*/
|
|
272
|
+
parseParameters(content) {
|
|
273
|
+
try {
|
|
274
|
+
// Try JSON first
|
|
275
|
+
if (content.trim().startsWith('{')) {
|
|
276
|
+
return this.parseJSON(content);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Otherwise parse XML
|
|
280
|
+
return this.parseXML(content);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
this.logger?.error('Failed to parse file-content-replace parameters', {
|
|
283
|
+
error: error.message
|
|
284
|
+
});
|
|
285
|
+
throw new Error(`Parameter parsing failed: ${error.message}`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Parse JSON format
|
|
291
|
+
* @param {string} content - JSON string
|
|
292
|
+
* @returns {Object} Parsed parameters
|
|
293
|
+
*/
|
|
294
|
+
parseJSON(content) {
|
|
295
|
+
const parsed = JSON.parse(content);
|
|
296
|
+
|
|
297
|
+
if (!parsed.files || !Array.isArray(parsed.files)) {
|
|
298
|
+
throw new Error('JSON must have "files" array');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return {
|
|
302
|
+
files: parsed.files.map(file => ({
|
|
303
|
+
path: file.path,
|
|
304
|
+
replacements: (file.replacements || []).map(r => ({
|
|
305
|
+
oldContent: r.oldContent,
|
|
306
|
+
newContent: r.newContent,
|
|
307
|
+
mode: r.mode || REPLACE_CONFIG.DEFAULT_TRIM_MODE,
|
|
308
|
+
linesLimit: r.linesLimit || null
|
|
309
|
+
}))
|
|
310
|
+
}))
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Parse XML format
|
|
316
|
+
* @param {string} content - XML string
|
|
317
|
+
* @returns {Object} Parsed parameters
|
|
318
|
+
*/
|
|
319
|
+
parseXML(content) {
|
|
320
|
+
const files = [];
|
|
321
|
+
|
|
322
|
+
// Extract <file> tags
|
|
323
|
+
const filePattern = /<file\s+path="([^"]+)">([\s\S]*?)<\/file>/gi;
|
|
324
|
+
let fileMatch;
|
|
325
|
+
|
|
326
|
+
while ((fileMatch = filePattern.exec(content)) !== null) {
|
|
327
|
+
const filePath = fileMatch[1];
|
|
328
|
+
const fileContent = fileMatch[2];
|
|
329
|
+
|
|
330
|
+
const replacements = [];
|
|
331
|
+
|
|
332
|
+
// Extract <replace> tags within this file
|
|
333
|
+
const replacePattern = /<replace(?:\s+([^>]*?))?>([\s\S]*?)<\/replace>/gi;
|
|
334
|
+
let replaceMatch;
|
|
335
|
+
|
|
336
|
+
while ((replaceMatch = replacePattern.exec(fileContent)) !== null) {
|
|
337
|
+
const attributes = replaceMatch[1] || '';
|
|
338
|
+
const replaceContent = replaceMatch[2];
|
|
339
|
+
|
|
340
|
+
// Parse attributes
|
|
341
|
+
const mode = this.extractAttribute(attributes, 'mode') || REPLACE_CONFIG.DEFAULT_TRIM_MODE;
|
|
342
|
+
const linesLimit = this.extractAttribute(attributes, 'lines-limit');
|
|
343
|
+
|
|
344
|
+
// Extract old-content
|
|
345
|
+
const oldContentMatch = /<old-content>([\s\S]*?)<\/old-content>/i.exec(replaceContent);
|
|
346
|
+
if (!oldContentMatch) {
|
|
347
|
+
this.logger?.warn('Missing old-content in replace tag');
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const oldContentRaw = oldContentMatch[1];
|
|
351
|
+
|
|
352
|
+
// Extract new-content
|
|
353
|
+
const newContentMatch = /<new-content>([\s\S]*?)<\/new-content>/i.exec(replaceContent);
|
|
354
|
+
if (!newContentMatch) {
|
|
355
|
+
this.logger?.warn('Missing new-content in replace tag');
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const newContentRaw = newContentMatch[1];
|
|
359
|
+
|
|
360
|
+
// Apply trim mode
|
|
361
|
+
const oldContent = this.applyTrimMode(oldContentRaw, mode);
|
|
362
|
+
const newContent = this.applyTrimMode(newContentRaw, mode);
|
|
363
|
+
|
|
364
|
+
replacements.push({
|
|
365
|
+
oldContent,
|
|
366
|
+
newContent,
|
|
367
|
+
mode,
|
|
368
|
+
linesLimit
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (replacements.length > 0) {
|
|
373
|
+
files.push({
|
|
374
|
+
path: filePath,
|
|
375
|
+
replacements
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return { files };
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Extract attribute value from attribute string
|
|
385
|
+
* @param {string} attributes - Attribute string
|
|
386
|
+
* @param {string} name - Attribute name
|
|
387
|
+
* @returns {string|null} Attribute value
|
|
388
|
+
*/
|
|
389
|
+
extractAttribute(attributes, name) {
|
|
390
|
+
const pattern = new RegExp(`${name}=["']([^"']*)["']`, 'i');
|
|
391
|
+
const match = pattern.exec(attributes);
|
|
392
|
+
return match ? match[1] : null;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Apply trim mode to content
|
|
397
|
+
* @param {string} content - Content to process
|
|
398
|
+
* @param {string} mode - Trim mode
|
|
399
|
+
* @returns {string} Processed content
|
|
400
|
+
*/
|
|
401
|
+
applyTrimMode(content, mode) {
|
|
402
|
+
switch (mode) {
|
|
403
|
+
case 'newlines':
|
|
404
|
+
return content.replace(/^\n+|\n+$/g, '');
|
|
405
|
+
case 'none':
|
|
406
|
+
return content;
|
|
407
|
+
case 'trim':
|
|
408
|
+
default:
|
|
409
|
+
return content.trim();
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Get required parameters
|
|
415
|
+
* @returns {Array<string>} Array of required parameter names
|
|
416
|
+
*/
|
|
417
|
+
getRequiredParameters() {
|
|
418
|
+
return ['files'];
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Custom parameter validation
|
|
423
|
+
* @param {Object} params - Parameters to validate
|
|
424
|
+
* @returns {Object} Validation result
|
|
425
|
+
*/
|
|
426
|
+
customValidateParameters(params) {
|
|
427
|
+
const errors = [];
|
|
428
|
+
|
|
429
|
+
// Validate files array
|
|
430
|
+
if (!params.files || !Array.isArray(params.files)) {
|
|
431
|
+
errors.push('files must be an array');
|
|
432
|
+
} else {
|
|
433
|
+
if (params.files.length === 0) {
|
|
434
|
+
errors.push('files array cannot be empty');
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
if (params.files.length > this.replaceConfig.MAX_FILES_PER_OPERATION) {
|
|
438
|
+
errors.push(`Cannot process more than ${this.replaceConfig.MAX_FILES_PER_OPERATION} files in one operation`);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Validate each file
|
|
442
|
+
for (const file of params.files) {
|
|
443
|
+
if (!file.path) {
|
|
444
|
+
errors.push('Each file must have a path');
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Check for path traversal
|
|
448
|
+
if (file.path && file.path.includes('..')) {
|
|
449
|
+
errors.push(`Path traversal (..) not allowed for security: ${file.path}`);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (!file.replacements || !Array.isArray(file.replacements)) {
|
|
453
|
+
errors.push(`File ${file.path} must have replacements array`);
|
|
454
|
+
} else if (file.replacements.length === 0) {
|
|
455
|
+
errors.push(`File ${file.path} replacements array cannot be empty`);
|
|
456
|
+
} else {
|
|
457
|
+
// Validate each replacement
|
|
458
|
+
for (const replacement of file.replacements) {
|
|
459
|
+
if (!replacement.oldContent && replacement.oldContent !== '') {
|
|
460
|
+
errors.push(`Replacement in ${file.path} missing oldContent`);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
if (!replacement.newContent && replacement.newContent !== '') {
|
|
464
|
+
errors.push(`Replacement in ${file.path} missing newContent`);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Validate content sizes
|
|
468
|
+
if (replacement.oldContent && replacement.oldContent.length > this.replaceConfig.MAX_OLD_CONTENT_SIZE) {
|
|
469
|
+
errors.push(`oldContent too large (max ${this.replaceConfig.MAX_OLD_CONTENT_SIZE / 1024}KB)`);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (replacement.newContent && replacement.newContent.length > this.replaceConfig.MAX_NEW_CONTENT_SIZE) {
|
|
473
|
+
errors.push(`newContent too large (max ${this.replaceConfig.MAX_NEW_CONTENT_SIZE / 1024}KB)`);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Validate mode
|
|
477
|
+
if (replacement.mode && !['trim', 'newlines', 'none'].includes(replacement.mode)) {
|
|
478
|
+
errors.push(`Invalid mode: ${replacement.mode}. Must be 'trim', 'newlines', or 'none'`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// Throw error if validation fails
|
|
486
|
+
if (errors.length > 0) {
|
|
487
|
+
throw new Error(`Parameter validation failed: ${errors.join(', ')}`);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
return {
|
|
491
|
+
valid: true,
|
|
492
|
+
errors: []
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Execute tool with parsed parameters
|
|
498
|
+
* @param {Object} params - Parsed parameters
|
|
499
|
+
* @param {Object} context - Execution context
|
|
500
|
+
* @returns {Promise<Object>} Execution result
|
|
501
|
+
*/
|
|
502
|
+
async execute(params, context) {
|
|
503
|
+
const { files } = params;
|
|
504
|
+
const { projectDir, agentId, directoryAccess } = context;
|
|
505
|
+
|
|
506
|
+
// Determine working directory (respect multi-directory access)
|
|
507
|
+
let workingDirectory = projectDir || process.cwd();
|
|
508
|
+
|
|
509
|
+
if (directoryAccess && directoryAccess.workingDirectory) {
|
|
510
|
+
workingDirectory = directoryAccess.workingDirectory;
|
|
511
|
+
this.logger?.info('Using agent configured working directory', {
|
|
512
|
+
workingDirectory: directoryAccess.workingDirectory,
|
|
513
|
+
agentId
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
this.logger?.info('Executing file content replace', {
|
|
518
|
+
fileCount: files.length,
|
|
519
|
+
workingDirectory,
|
|
520
|
+
agentId
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
const results = [];
|
|
524
|
+
const stats = {
|
|
525
|
+
filesProcessed: 0,
|
|
526
|
+
filesModified: 0,
|
|
527
|
+
totalReplacements: 0,
|
|
528
|
+
backupsCreated: 0,
|
|
529
|
+
errors: 0
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
// Process each file
|
|
533
|
+
for (const file of files) {
|
|
534
|
+
try {
|
|
535
|
+
const fileResult = await this.processFile(file, workingDirectory, directoryAccess);
|
|
536
|
+
results.push(fileResult);
|
|
537
|
+
|
|
538
|
+
stats.filesProcessed++;
|
|
539
|
+
if (fileResult.replacementsMade > 0) {
|
|
540
|
+
stats.filesModified++;
|
|
541
|
+
stats.totalReplacements += fileResult.replacementsMade;
|
|
542
|
+
}
|
|
543
|
+
if (fileResult.backupCreated) {
|
|
544
|
+
stats.backupsCreated++;
|
|
545
|
+
}
|
|
546
|
+
} catch (error) {
|
|
547
|
+
this.logger?.error(`Error processing file ${file.path}`, { error: error.message });
|
|
548
|
+
results.push({
|
|
549
|
+
filePath: file.path,
|
|
550
|
+
success: false,
|
|
551
|
+
error: error.message
|
|
552
|
+
});
|
|
553
|
+
stats.errors++;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
return {
|
|
558
|
+
success: stats.errors === 0,
|
|
559
|
+
results,
|
|
560
|
+
statistics: stats,
|
|
561
|
+
summary: this.generateSummary(stats),
|
|
562
|
+
toolUsed: 'file-content-replace'
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Process a single file
|
|
568
|
+
* @param {Object} file - File object with path and replacements
|
|
569
|
+
* @param {string} workingDirectory - Working directory
|
|
570
|
+
* @param {Object} directoryAccess - Directory access config
|
|
571
|
+
* @returns {Promise<Object>} File processing result
|
|
572
|
+
*/
|
|
573
|
+
async processFile(file, workingDirectory, directoryAccess) {
|
|
574
|
+
const { path: filePath, replacements } = file;
|
|
575
|
+
|
|
576
|
+
// Resolve path
|
|
577
|
+
const resolvedPath = path.isAbsolute(filePath)
|
|
578
|
+
? filePath
|
|
579
|
+
: path.resolve(workingDirectory, filePath);
|
|
580
|
+
|
|
581
|
+
// Validate path access (if directoryAccess provided)
|
|
582
|
+
if (directoryAccess) {
|
|
583
|
+
const accessible = this.isPathAccessible(resolvedPath, workingDirectory, directoryAccess);
|
|
584
|
+
if (!accessible) {
|
|
585
|
+
throw new Error(`Path not accessible: ${filePath}`);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// Check file exists
|
|
590
|
+
try {
|
|
591
|
+
await fs.access(resolvedPath);
|
|
592
|
+
} catch (error) {
|
|
593
|
+
throw new Error(`File not found: ${filePath}`);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// Check file size
|
|
597
|
+
const stats = await fs.stat(resolvedPath);
|
|
598
|
+
if (stats.size > this.replaceConfig.MAX_FILE_SIZE) {
|
|
599
|
+
throw new Error(`File too large (max ${this.replaceConfig.MAX_FILE_SIZE / (1024 * 1024)}MB): ${filePath}`);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Read file content
|
|
603
|
+
let content = await fs.readFile(resolvedPath, 'utf-8');
|
|
604
|
+
const originalContent = content;
|
|
605
|
+
|
|
606
|
+
// Create backup
|
|
607
|
+
let backupCreated = false;
|
|
608
|
+
if (this.replaceConfig.CREATE_BACKUPS) {
|
|
609
|
+
const backupPath = resolvedPath + this.replaceConfig.BACKUP_EXTENSION;
|
|
610
|
+
try {
|
|
611
|
+
await fs.writeFile(backupPath, originalContent, 'utf-8');
|
|
612
|
+
backupCreated = true;
|
|
613
|
+
} catch (error) {
|
|
614
|
+
this.logger?.warn(`Failed to create backup: ${error.message}`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// Apply replacements
|
|
619
|
+
let replacementsMade = 0;
|
|
620
|
+
const replacementDetails = [];
|
|
621
|
+
|
|
622
|
+
for (const replacement of replacements) {
|
|
623
|
+
const result = await this.applyReplacement(
|
|
624
|
+
content,
|
|
625
|
+
replacement.oldContent,
|
|
626
|
+
replacement.newContent,
|
|
627
|
+
replacement.linesLimit,
|
|
628
|
+
replacement.mode
|
|
629
|
+
);
|
|
630
|
+
|
|
631
|
+
content = result.newContent;
|
|
632
|
+
replacementsMade += result.count;
|
|
633
|
+
|
|
634
|
+
replacementDetails.push({
|
|
635
|
+
oldContent: replacement.oldContent.substring(0, 50) + (replacement.oldContent.length > 50 ? '...' : ''),
|
|
636
|
+
newContent: replacement.newContent.substring(0, 50) + (replacement.newContent.length > 50 ? '...' : ''),
|
|
637
|
+
count: result.count,
|
|
638
|
+
mode: replacement.mode,
|
|
639
|
+
linesLimit: replacement.linesLimit
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// Write back if changes were made
|
|
644
|
+
if (replacementsMade > 0) {
|
|
645
|
+
await fs.writeFile(resolvedPath, content, 'utf-8');
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// Generate diff
|
|
649
|
+
const diff = replacementsMade > 0
|
|
650
|
+
? this.generateDiff(originalContent, content)
|
|
651
|
+
: null;
|
|
652
|
+
|
|
653
|
+
return {
|
|
654
|
+
filePath,
|
|
655
|
+
resolvedPath,
|
|
656
|
+
success: true,
|
|
657
|
+
replacementsMade,
|
|
658
|
+
backupCreated,
|
|
659
|
+
replacementDetails,
|
|
660
|
+
diff,
|
|
661
|
+
message: replacementsMade > 0
|
|
662
|
+
? `Made ${replacementsMade} replacement(s) in ${filePath}`
|
|
663
|
+
: `No replacements made in ${filePath} (content not found)`
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* Check if path is accessible
|
|
669
|
+
* @param {string} targetPath - Path to check
|
|
670
|
+
* @param {string} workingDirectory - Working directory
|
|
671
|
+
* @param {Object} directoryAccess - Directory access config
|
|
672
|
+
* @returns {boolean} True if accessible
|
|
673
|
+
*/
|
|
674
|
+
isPathAccessible(targetPath, workingDirectory, directoryAccess) {
|
|
675
|
+
// Always allow paths within working directory
|
|
676
|
+
const relativeToWorking = path.relative(workingDirectory, targetPath);
|
|
677
|
+
if (!relativeToWorking.startsWith('..') && !path.isAbsolute(relativeToWorking)) {
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Check writeEnabledDirectories
|
|
682
|
+
if (directoryAccess.writeEnabledDirectories) {
|
|
683
|
+
for (const dir of directoryAccess.writeEnabledDirectories) {
|
|
684
|
+
const relative = path.relative(dir, targetPath);
|
|
685
|
+
if (!relative.startsWith('..') && !path.isAbsolute(relative)) {
|
|
686
|
+
return true;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
return false;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Apply a single replacement
|
|
696
|
+
* @param {string} content - File content
|
|
697
|
+
* @param {string} oldContent - Content to replace
|
|
698
|
+
* @param {string} newContent - Replacement content
|
|
699
|
+
* @param {string|null} linesLimit - Line limit specification
|
|
700
|
+
* @param {string} mode - Trim mode
|
|
701
|
+
* @returns {Object} Result with newContent and count
|
|
702
|
+
*/
|
|
703
|
+
async applyReplacement(content, oldContent, newContent, linesLimit, mode) {
|
|
704
|
+
if (!linesLimit) {
|
|
705
|
+
// Replace in entire file (simple string replace, not regex)
|
|
706
|
+
const count = this.countOccurrences(content, oldContent);
|
|
707
|
+
|
|
708
|
+
if (count === 0) {
|
|
709
|
+
return { newContent: content, count: 0 };
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// Simple replaceAll
|
|
713
|
+
const newFileContent = content.split(oldContent).join(newContent);
|
|
714
|
+
|
|
715
|
+
return { newContent: newFileContent, count };
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// Line-limited replacement
|
|
719
|
+
const lineNumbers = this.parseLineRanges(linesLimit);
|
|
720
|
+
const lines = content.split('\n');
|
|
721
|
+
let replacementCount = 0;
|
|
722
|
+
|
|
723
|
+
// Process each line
|
|
724
|
+
for (let i = 0; i < lines.length; i++) {
|
|
725
|
+
const lineNumber = i + 1; // 1-based
|
|
726
|
+
|
|
727
|
+
if (lineNumbers.has(lineNumber)) {
|
|
728
|
+
// Check if this line contains the old content
|
|
729
|
+
if (lines[i].includes(oldContent)) {
|
|
730
|
+
const occurrencesInLine = this.countOccurrences(lines[i], oldContent);
|
|
731
|
+
lines[i] = lines[i].split(oldContent).join(newContent);
|
|
732
|
+
replacementCount += occurrencesInLine;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return {
|
|
738
|
+
newContent: lines.join('\n'),
|
|
739
|
+
count: replacementCount
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Count occurrences of substring in string
|
|
745
|
+
* @param {string} str - String to search
|
|
746
|
+
* @param {string} substr - Substring to count
|
|
747
|
+
* @returns {number} Count of occurrences
|
|
748
|
+
*/
|
|
749
|
+
countOccurrences(str, substr) {
|
|
750
|
+
if (!substr) return 0;
|
|
751
|
+
return str.split(substr).length - 1;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Parse line ranges from string like "3,5,7-9"
|
|
756
|
+
* @param {string} rangesStr - Line range string
|
|
757
|
+
* @returns {Set<number>} Set of line numbers
|
|
758
|
+
*/
|
|
759
|
+
parseLineRanges(rangesStr) {
|
|
760
|
+
const result = new Set();
|
|
761
|
+
|
|
762
|
+
if (!rangesStr || rangesStr.trim() === '') {
|
|
763
|
+
return result;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const ranges = rangesStr.split(',');
|
|
767
|
+
|
|
768
|
+
for (const range of ranges) {
|
|
769
|
+
const trimmed = range.trim();
|
|
770
|
+
|
|
771
|
+
if (trimmed === '') continue;
|
|
772
|
+
|
|
773
|
+
// Check if it's a range (e.g., "7-9")
|
|
774
|
+
if (trimmed.includes('-')) {
|
|
775
|
+
const [start, end] = trimmed.split('-').map(n => parseInt(n.trim(), 10));
|
|
776
|
+
|
|
777
|
+
if (!isNaN(start) && !isNaN(end) && end - start < this.replaceConfig.MAX_LINE_RANGE_SIZE) {
|
|
778
|
+
for (let i = start; i <= end; i++) {
|
|
779
|
+
result.add(i);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
} else {
|
|
783
|
+
// Single line number
|
|
784
|
+
const lineNum = parseInt(trimmed, 10);
|
|
785
|
+
if (!isNaN(lineNum)) {
|
|
786
|
+
result.add(lineNum);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
return result;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Generate diff between original and new content
|
|
796
|
+
* @param {string} original - Original content
|
|
797
|
+
* @param {string} modified - Modified content
|
|
798
|
+
* @returns {string} Diff string
|
|
799
|
+
*/
|
|
800
|
+
generateDiff(original, modified) {
|
|
801
|
+
const oldLines = original.split('\n');
|
|
802
|
+
const newLines = modified.split('\n');
|
|
803
|
+
|
|
804
|
+
// Find first and last lines that differ
|
|
805
|
+
let firstDiff = -1;
|
|
806
|
+
let lastDiff = -1;
|
|
807
|
+
|
|
808
|
+
const maxLines = Math.max(oldLines.length, newLines.length);
|
|
809
|
+
|
|
810
|
+
for (let i = 0; i < maxLines; i++) {
|
|
811
|
+
const oldLine = i < oldLines.length ? oldLines[i] : '';
|
|
812
|
+
const newLine = i < newLines.length ? newLines[i] : '';
|
|
813
|
+
|
|
814
|
+
if (oldLine !== newLine) {
|
|
815
|
+
if (firstDiff === -1) firstDiff = i;
|
|
816
|
+
lastDiff = i;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (firstDiff === -1) return 'No differences';
|
|
821
|
+
|
|
822
|
+
// Add context
|
|
823
|
+
const contextLines = this.replaceConfig.DIFF_CONTEXT_LINES;
|
|
824
|
+
const startLine = Math.max(0, firstDiff - contextLines);
|
|
825
|
+
const endLine = Math.min(maxLines - 1, lastDiff + contextLines);
|
|
826
|
+
|
|
827
|
+
// Limit total lines shown
|
|
828
|
+
if (endLine - startLine > this.replaceConfig.MAX_DIFF_LINES) {
|
|
829
|
+
return `Diff too large (${endLine - startLine + 1} lines), showing summary only:\n` +
|
|
830
|
+
`Changed lines: ${firstDiff + 1} to ${lastDiff + 1}`;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
let diff = `@@ -${startLine + 1},${endLine - startLine + 1} +${startLine + 1},${endLine - startLine + 1} @@\n`;
|
|
834
|
+
|
|
835
|
+
for (let i = startLine; i <= endLine; i++) {
|
|
836
|
+
const oldLine = i < oldLines.length ? oldLines[i] : '';
|
|
837
|
+
const newLine = i < newLines.length ? newLines[i] : '';
|
|
838
|
+
|
|
839
|
+
if (oldLine === newLine) {
|
|
840
|
+
diff += ` ${oldLine}\n`;
|
|
841
|
+
} else {
|
|
842
|
+
diff += `- ${oldLine}\n`;
|
|
843
|
+
diff += `+ ${newLine}\n`;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
return diff;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Generate summary text
|
|
852
|
+
* @param {Object} stats - Statistics object
|
|
853
|
+
* @returns {string} Summary text
|
|
854
|
+
*/
|
|
855
|
+
generateSummary(stats) {
|
|
856
|
+
return `
|
|
857
|
+
Processed ${stats.filesProcessed} file(s)
|
|
858
|
+
Modified ${stats.filesModified} file(s)
|
|
859
|
+
Total replacements: ${stats.totalReplacements}
|
|
860
|
+
Backups created: ${stats.backupsCreated}
|
|
861
|
+
Errors: ${stats.errors}
|
|
862
|
+
`.trim();
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Resource cleanup
|
|
867
|
+
* @param {string} operationId - Operation identifier
|
|
868
|
+
*/
|
|
869
|
+
async cleanup(operationId) {
|
|
870
|
+
// No persistent resources to clean up
|
|
871
|
+
this.logger?.info('File content replace tool cleanup completed', { operationId });
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
export default FileContentReplaceTool;
|