@dexto/tools-filesystem 1.5.0
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 +44 -0
- package/dist/directory-approval.integration.test.cjs +467 -0
- package/dist/directory-approval.integration.test.d.cts +2 -0
- package/dist/directory-approval.integration.test.d.ts +2 -0
- package/dist/directory-approval.integration.test.js +444 -0
- package/dist/edit-file-tool.cjs +181 -0
- package/dist/edit-file-tool.d.cts +17 -0
- package/dist/edit-file-tool.d.ts +17 -0
- package/dist/edit-file-tool.js +147 -0
- package/dist/error-codes.cjs +53 -0
- package/dist/error-codes.d.cts +32 -0
- package/dist/error-codes.d.ts +32 -0
- package/dist/error-codes.js +29 -0
- package/dist/errors.cjs +302 -0
- package/dist/errors.d.cts +112 -0
- package/dist/errors.d.ts +112 -0
- package/dist/errors.js +278 -0
- package/dist/file-tool-types.cjs +16 -0
- package/dist/file-tool-types.d.cts +46 -0
- package/dist/file-tool-types.d.ts +46 -0
- package/dist/file-tool-types.js +0 -0
- package/dist/filesystem-service.cjs +526 -0
- package/dist/filesystem-service.d.cts +107 -0
- package/dist/filesystem-service.d.ts +107 -0
- package/dist/filesystem-service.js +492 -0
- package/dist/glob-files-tool.cjs +70 -0
- package/dist/glob-files-tool.d.cts +16 -0
- package/dist/glob-files-tool.d.ts +16 -0
- package/dist/glob-files-tool.js +46 -0
- package/dist/grep-content-tool.cjs +86 -0
- package/dist/grep-content-tool.d.cts +16 -0
- package/dist/grep-content-tool.d.ts +16 -0
- package/dist/grep-content-tool.js +62 -0
- package/dist/index.cjs +55 -0
- package/dist/index.d.cts +14 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +22 -0
- package/dist/path-validator.cjs +232 -0
- package/dist/path-validator.d.cts +90 -0
- package/dist/path-validator.d.ts +90 -0
- package/dist/path-validator.js +198 -0
- package/dist/path-validator.test.cjs +444 -0
- package/dist/path-validator.test.d.cts +2 -0
- package/dist/path-validator.test.d.ts +2 -0
- package/dist/path-validator.test.js +443 -0
- package/dist/read-file-tool.cjs +117 -0
- package/dist/read-file-tool.d.cts +17 -0
- package/dist/read-file-tool.d.ts +17 -0
- package/dist/read-file-tool.js +83 -0
- package/dist/tool-provider.cjs +108 -0
- package/dist/tool-provider.d.cts +74 -0
- package/dist/tool-provider.d.ts +74 -0
- package/dist/tool-provider.js +84 -0
- package/dist/types.cjs +16 -0
- package/dist/types.d.cts +172 -0
- package/dist/types.d.ts +172 -0
- package/dist/types.js +0 -0
- package/dist/write-file-tool.cjs +177 -0
- package/dist/write-file-tool.d.cts +17 -0
- package/dist/write-file-tool.d.ts +17 -0
- package/dist/write-file-tool.js +143 -0
- package/package.json +42 -0
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var filesystem_service_exports = {};
|
|
30
|
+
__export(filesystem_service_exports, {
|
|
31
|
+
FileSystemService: () => FileSystemService
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(filesystem_service_exports);
|
|
34
|
+
var fs = __toESM(require("node:fs/promises"), 1);
|
|
35
|
+
var path = __toESM(require("node:path"), 1);
|
|
36
|
+
var import_glob = require("glob");
|
|
37
|
+
var import_safe_regex = __toESM(require("safe-regex"), 1);
|
|
38
|
+
var import_core = require("@dexto/core");
|
|
39
|
+
var import_path_validator = require("./path-validator.js");
|
|
40
|
+
var import_errors = require("./errors.js");
|
|
41
|
+
const DEFAULT_ENCODING = "utf-8";
|
|
42
|
+
const DEFAULT_MAX_RESULTS = 1e3;
|
|
43
|
+
const DEFAULT_MAX_SEARCH_RESULTS = 100;
|
|
44
|
+
class FileSystemService {
|
|
45
|
+
config;
|
|
46
|
+
pathValidator;
|
|
47
|
+
initialized = false;
|
|
48
|
+
initPromise = null;
|
|
49
|
+
logger;
|
|
50
|
+
/**
|
|
51
|
+
* Create a new FileSystemService with validated configuration.
|
|
52
|
+
*
|
|
53
|
+
* @param config - Fully-validated configuration from provider schema.
|
|
54
|
+
* All required fields have values, defaults already applied.
|
|
55
|
+
* @param logger - Logger instance for this service
|
|
56
|
+
*/
|
|
57
|
+
constructor(config, logger) {
|
|
58
|
+
this.config = config;
|
|
59
|
+
this.logger = logger.createChild(import_core.DextoLogComponent.FILESYSTEM);
|
|
60
|
+
this.pathValidator = new import_path_validator.PathValidator(this.config, this.logger);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Get backup directory path (context-aware with optional override)
|
|
64
|
+
* TODO: Migrate to explicit configuration via CLI enrichment layer (per-agent paths)
|
|
65
|
+
*/
|
|
66
|
+
getBackupDir() {
|
|
67
|
+
return this.config.backupPath || (0, import_core.getDextoPath)("backups");
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Initialize the service.
|
|
71
|
+
* Safe to call multiple times - subsequent calls return the same promise.
|
|
72
|
+
*/
|
|
73
|
+
initialize() {
|
|
74
|
+
if (this.initPromise) {
|
|
75
|
+
return this.initPromise;
|
|
76
|
+
}
|
|
77
|
+
this.initPromise = this.doInitialize();
|
|
78
|
+
return this.initPromise;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Internal initialization logic.
|
|
82
|
+
*/
|
|
83
|
+
async doInitialize() {
|
|
84
|
+
if (this.initialized) {
|
|
85
|
+
this.logger.debug("FileSystemService already initialized");
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (this.config.enableBackups) {
|
|
89
|
+
try {
|
|
90
|
+
const backupDir = this.getBackupDir();
|
|
91
|
+
await fs.mkdir(backupDir, { recursive: true });
|
|
92
|
+
this.logger.debug(`Backup directory created/verified: ${backupDir}`);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
this.logger.warn(
|
|
95
|
+
`Failed to create backup directory: ${error instanceof Error ? error.message : String(error)}`
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
this.initialized = true;
|
|
100
|
+
this.logger.info("FileSystemService initialized successfully");
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Ensure the service is initialized before use.
|
|
104
|
+
* Tools should call this at the start of their execute methods.
|
|
105
|
+
* Safe to call multiple times - will await the same initialization promise.
|
|
106
|
+
*/
|
|
107
|
+
async ensureInitialized() {
|
|
108
|
+
if (this.initialized) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
await this.initialize();
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Set a callback to check if a path is in an approved directory.
|
|
115
|
+
* This allows PathValidator to consult ApprovalManager without a direct dependency.
|
|
116
|
+
*
|
|
117
|
+
* @param checker Function that returns true if path is in an approved directory
|
|
118
|
+
*/
|
|
119
|
+
setDirectoryApprovalChecker(checker) {
|
|
120
|
+
this.pathValidator.setDirectoryApprovalChecker(checker);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Check if a file path is within the configured allowed paths (config only).
|
|
124
|
+
* This is used by file tools to determine if directory approval is needed.
|
|
125
|
+
*
|
|
126
|
+
* @param filePath The file path to check (can be relative or absolute)
|
|
127
|
+
* @returns true if the path is within config-allowed paths, false otherwise
|
|
128
|
+
*/
|
|
129
|
+
isPathWithinConfigAllowed(filePath) {
|
|
130
|
+
return this.pathValidator.isPathWithinAllowed(filePath);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Read a file with validation and size limits
|
|
134
|
+
*/
|
|
135
|
+
async readFile(filePath, options = {}) {
|
|
136
|
+
await this.ensureInitialized();
|
|
137
|
+
const validation = this.pathValidator.validatePath(filePath);
|
|
138
|
+
if (!validation.isValid || !validation.normalizedPath) {
|
|
139
|
+
throw import_errors.FileSystemError.invalidPath(filePath, validation.error || "Unknown error");
|
|
140
|
+
}
|
|
141
|
+
const normalizedPath = validation.normalizedPath;
|
|
142
|
+
try {
|
|
143
|
+
const stats = await fs.stat(normalizedPath);
|
|
144
|
+
if (!stats.isFile()) {
|
|
145
|
+
throw import_errors.FileSystemError.invalidPath(normalizedPath, "Path is not a file");
|
|
146
|
+
}
|
|
147
|
+
if (stats.size > this.config.maxFileSize) {
|
|
148
|
+
throw import_errors.FileSystemError.fileTooLarge(
|
|
149
|
+
normalizedPath,
|
|
150
|
+
stats.size,
|
|
151
|
+
this.config.maxFileSize
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error.code === "ENOENT") {
|
|
156
|
+
throw import_errors.FileSystemError.fileNotFound(normalizedPath);
|
|
157
|
+
}
|
|
158
|
+
if (error.code === "EACCES") {
|
|
159
|
+
throw import_errors.FileSystemError.permissionDenied(normalizedPath, "read");
|
|
160
|
+
}
|
|
161
|
+
throw import_errors.FileSystemError.readFailed(
|
|
162
|
+
normalizedPath,
|
|
163
|
+
error instanceof Error ? error.message : String(error)
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const encoding = options.encoding || DEFAULT_ENCODING;
|
|
168
|
+
const content = await fs.readFile(normalizedPath, encoding);
|
|
169
|
+
const lines = content.split("\n");
|
|
170
|
+
const limit = options.limit;
|
|
171
|
+
const offset1 = options.offset;
|
|
172
|
+
let selectedLines;
|
|
173
|
+
let truncated = false;
|
|
174
|
+
if (offset1 && offset1 > 0 || limit !== void 0) {
|
|
175
|
+
const start = offset1 && offset1 > 0 ? Math.max(0, offset1 - 1) : 0;
|
|
176
|
+
const end = limit !== void 0 ? start + limit : lines.length;
|
|
177
|
+
selectedLines = lines.slice(start, end);
|
|
178
|
+
truncated = end < lines.length;
|
|
179
|
+
} else {
|
|
180
|
+
selectedLines = lines;
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
content: selectedLines.join("\n"),
|
|
184
|
+
lines: selectedLines.length,
|
|
185
|
+
encoding,
|
|
186
|
+
truncated,
|
|
187
|
+
size: Buffer.byteLength(content, encoding)
|
|
188
|
+
};
|
|
189
|
+
} catch (error) {
|
|
190
|
+
throw import_errors.FileSystemError.readFailed(
|
|
191
|
+
normalizedPath,
|
|
192
|
+
error instanceof Error ? error.message : String(error)
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Find files matching a glob pattern
|
|
198
|
+
*/
|
|
199
|
+
async globFiles(pattern, options = {}) {
|
|
200
|
+
await this.ensureInitialized();
|
|
201
|
+
const cwd = options.cwd || this.config.workingDirectory || process.cwd();
|
|
202
|
+
const maxResults = options.maxResults || DEFAULT_MAX_RESULTS;
|
|
203
|
+
try {
|
|
204
|
+
const files = await (0, import_glob.glob)(pattern, {
|
|
205
|
+
cwd,
|
|
206
|
+
absolute: true,
|
|
207
|
+
nodir: true,
|
|
208
|
+
// Only files
|
|
209
|
+
follow: false
|
|
210
|
+
// Don't follow symlinks
|
|
211
|
+
});
|
|
212
|
+
const validFiles = [];
|
|
213
|
+
for (const file of files) {
|
|
214
|
+
const validation = this.pathValidator.validatePath(file);
|
|
215
|
+
if (!validation.isValid || !validation.normalizedPath) {
|
|
216
|
+
this.logger.debug(`Skipping invalid path: ${file}`);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (options.includeMetadata !== false) {
|
|
220
|
+
try {
|
|
221
|
+
const stats = await fs.stat(validation.normalizedPath);
|
|
222
|
+
validFiles.push({
|
|
223
|
+
path: validation.normalizedPath,
|
|
224
|
+
size: stats.size,
|
|
225
|
+
modified: stats.mtime,
|
|
226
|
+
isDirectory: stats.isDirectory()
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
this.logger.debug(
|
|
230
|
+
`Failed to stat file ${file}: ${error instanceof Error ? error.message : String(error)}`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
} else {
|
|
234
|
+
validFiles.push({
|
|
235
|
+
path: validation.normalizedPath,
|
|
236
|
+
size: 0,
|
|
237
|
+
modified: /* @__PURE__ */ new Date(),
|
|
238
|
+
isDirectory: false
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
if (validFiles.length >= maxResults) {
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const limited = validFiles.length >= maxResults;
|
|
246
|
+
return {
|
|
247
|
+
files: validFiles,
|
|
248
|
+
truncated: limited,
|
|
249
|
+
totalFound: validFiles.length
|
|
250
|
+
};
|
|
251
|
+
} catch (error) {
|
|
252
|
+
throw import_errors.FileSystemError.globFailed(
|
|
253
|
+
pattern,
|
|
254
|
+
error instanceof Error ? error.message : String(error)
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Search for content in files (grep-like functionality)
|
|
260
|
+
*/
|
|
261
|
+
async searchContent(pattern, options = {}) {
|
|
262
|
+
await this.ensureInitialized();
|
|
263
|
+
const searchPath = options.path || this.config.workingDirectory || process.cwd();
|
|
264
|
+
const globPattern = options.glob || "**/*";
|
|
265
|
+
const maxResults = options.maxResults || DEFAULT_MAX_SEARCH_RESULTS;
|
|
266
|
+
const contextLines = options.contextLines || 0;
|
|
267
|
+
try {
|
|
268
|
+
if (!(0, import_safe_regex.default)(pattern)) {
|
|
269
|
+
throw import_errors.FileSystemError.invalidPattern(
|
|
270
|
+
pattern,
|
|
271
|
+
"Pattern may cause catastrophic backtracking (ReDoS). Please simplify the regex."
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
const flags = options.caseInsensitive ? "i" : "";
|
|
275
|
+
const regex = new RegExp(pattern, flags);
|
|
276
|
+
const globResult = await this.globFiles(globPattern, {
|
|
277
|
+
cwd: searchPath,
|
|
278
|
+
maxResults: 1e4
|
|
279
|
+
// Search more files, but limit results
|
|
280
|
+
});
|
|
281
|
+
const matches = [];
|
|
282
|
+
let filesSearched = 0;
|
|
283
|
+
for (const fileInfo of globResult.files) {
|
|
284
|
+
try {
|
|
285
|
+
const fileContent = await this.readFile(fileInfo.path);
|
|
286
|
+
const lines = fileContent.content.split("\n");
|
|
287
|
+
filesSearched++;
|
|
288
|
+
for (let i = 0; i < lines.length; i++) {
|
|
289
|
+
const line = lines[i];
|
|
290
|
+
if (regex.test(line)) {
|
|
291
|
+
let context;
|
|
292
|
+
if (contextLines > 0) {
|
|
293
|
+
const before = [];
|
|
294
|
+
const after = [];
|
|
295
|
+
for (let j = Math.max(0, i - contextLines); j < i; j++) {
|
|
296
|
+
before.push(lines[j]);
|
|
297
|
+
}
|
|
298
|
+
for (let j = i + 1; j < Math.min(lines.length, i + contextLines + 1); j++) {
|
|
299
|
+
after.push(lines[j]);
|
|
300
|
+
}
|
|
301
|
+
context = { before, after };
|
|
302
|
+
}
|
|
303
|
+
matches.push({
|
|
304
|
+
file: fileInfo.path,
|
|
305
|
+
lineNumber: i + 1,
|
|
306
|
+
// 1-based line numbers
|
|
307
|
+
line,
|
|
308
|
+
...context !== void 0 && { context }
|
|
309
|
+
});
|
|
310
|
+
if (matches.length >= maxResults) {
|
|
311
|
+
return {
|
|
312
|
+
matches,
|
|
313
|
+
totalMatches: matches.length,
|
|
314
|
+
truncated: true,
|
|
315
|
+
filesSearched
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
} catch (error) {
|
|
321
|
+
this.logger.debug(
|
|
322
|
+
`Skipping file ${fileInfo.path}: ${error instanceof Error ? error.message : String(error)}`
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
matches,
|
|
328
|
+
totalMatches: matches.length,
|
|
329
|
+
truncated: false,
|
|
330
|
+
filesSearched
|
|
331
|
+
};
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (error instanceof Error && error.message.includes("Invalid regular expression")) {
|
|
334
|
+
throw import_errors.FileSystemError.invalidPattern(pattern, "Invalid regular expression syntax");
|
|
335
|
+
}
|
|
336
|
+
throw import_errors.FileSystemError.searchFailed(
|
|
337
|
+
pattern,
|
|
338
|
+
error instanceof Error ? error.message : String(error)
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Write content to a file
|
|
344
|
+
*/
|
|
345
|
+
async writeFile(filePath, content, options = {}) {
|
|
346
|
+
await this.ensureInitialized();
|
|
347
|
+
const validation = this.pathValidator.validatePath(filePath);
|
|
348
|
+
if (!validation.isValid || !validation.normalizedPath) {
|
|
349
|
+
throw import_errors.FileSystemError.invalidPath(filePath, validation.error || "Unknown error");
|
|
350
|
+
}
|
|
351
|
+
const normalizedPath = validation.normalizedPath;
|
|
352
|
+
const encoding = options.encoding || DEFAULT_ENCODING;
|
|
353
|
+
let backupPath;
|
|
354
|
+
let fileExists = false;
|
|
355
|
+
try {
|
|
356
|
+
await fs.access(normalizedPath);
|
|
357
|
+
fileExists = true;
|
|
358
|
+
} catch {
|
|
359
|
+
}
|
|
360
|
+
if (fileExists && (options.backup ?? this.config.enableBackups)) {
|
|
361
|
+
backupPath = await this.createBackup(normalizedPath);
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
if (options.createDirs) {
|
|
365
|
+
const dir = path.dirname(normalizedPath);
|
|
366
|
+
await fs.mkdir(dir, { recursive: true });
|
|
367
|
+
}
|
|
368
|
+
await fs.writeFile(normalizedPath, content, encoding);
|
|
369
|
+
const bytesWritten = Buffer.byteLength(content, encoding);
|
|
370
|
+
this.logger.debug(`File written: ${normalizedPath} (${bytesWritten} bytes)`);
|
|
371
|
+
return {
|
|
372
|
+
success: true,
|
|
373
|
+
path: normalizedPath,
|
|
374
|
+
bytesWritten,
|
|
375
|
+
backupPath
|
|
376
|
+
};
|
|
377
|
+
} catch (error) {
|
|
378
|
+
throw import_errors.FileSystemError.writeFailed(
|
|
379
|
+
normalizedPath,
|
|
380
|
+
error instanceof Error ? error.message : String(error)
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Edit a file by replacing text
|
|
386
|
+
*/
|
|
387
|
+
async editFile(filePath, operation, options = {}) {
|
|
388
|
+
await this.ensureInitialized();
|
|
389
|
+
const validation = this.pathValidator.validatePath(filePath);
|
|
390
|
+
if (!validation.isValid || !validation.normalizedPath) {
|
|
391
|
+
throw import_errors.FileSystemError.invalidPath(filePath, validation.error || "Unknown error");
|
|
392
|
+
}
|
|
393
|
+
const normalizedPath = validation.normalizedPath;
|
|
394
|
+
const fileContent = await this.readFile(normalizedPath);
|
|
395
|
+
let content = fileContent.content;
|
|
396
|
+
const occurrences = (content.match(
|
|
397
|
+
new RegExp(operation.oldString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")
|
|
398
|
+
) || []).length;
|
|
399
|
+
if (occurrences === 0) {
|
|
400
|
+
throw import_errors.FileSystemError.stringNotFound(normalizedPath, operation.oldString);
|
|
401
|
+
}
|
|
402
|
+
if (!operation.replaceAll && occurrences > 1) {
|
|
403
|
+
throw import_errors.FileSystemError.stringNotUnique(normalizedPath, operation.oldString, occurrences);
|
|
404
|
+
}
|
|
405
|
+
let backupPath;
|
|
406
|
+
if (options.backup ?? this.config.enableBackups) {
|
|
407
|
+
backupPath = await this.createBackup(normalizedPath);
|
|
408
|
+
}
|
|
409
|
+
try {
|
|
410
|
+
if (operation.replaceAll) {
|
|
411
|
+
content = content.replace(
|
|
412
|
+
new RegExp(operation.oldString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
|
|
413
|
+
operation.newString
|
|
414
|
+
);
|
|
415
|
+
} else {
|
|
416
|
+
content = content.replace(operation.oldString, operation.newString);
|
|
417
|
+
}
|
|
418
|
+
await fs.writeFile(normalizedPath, content, options.encoding || DEFAULT_ENCODING);
|
|
419
|
+
this.logger.debug(`File edited: ${normalizedPath} (${occurrences} replacements)`);
|
|
420
|
+
return {
|
|
421
|
+
success: true,
|
|
422
|
+
path: normalizedPath,
|
|
423
|
+
changesCount: occurrences,
|
|
424
|
+
backupPath
|
|
425
|
+
};
|
|
426
|
+
} catch (error) {
|
|
427
|
+
throw import_errors.FileSystemError.editFailed(
|
|
428
|
+
normalizedPath,
|
|
429
|
+
error instanceof Error ? error.message : String(error)
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Create a backup of a file
|
|
435
|
+
*/
|
|
436
|
+
async createBackup(filePath) {
|
|
437
|
+
const backupDir = this.getBackupDir();
|
|
438
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
439
|
+
const basename = path.basename(filePath);
|
|
440
|
+
const backupFilename = `${basename}.${timestamp}.backup`;
|
|
441
|
+
const backupPath = path.join(backupDir, backupFilename);
|
|
442
|
+
try {
|
|
443
|
+
await fs.mkdir(backupDir, { recursive: true });
|
|
444
|
+
await fs.copyFile(filePath, backupPath);
|
|
445
|
+
this.logger.debug(`Backup created: ${backupPath}`);
|
|
446
|
+
await this.cleanupOldBackups();
|
|
447
|
+
return backupPath;
|
|
448
|
+
} catch (error) {
|
|
449
|
+
throw import_errors.FileSystemError.backupFailed(
|
|
450
|
+
filePath,
|
|
451
|
+
error instanceof Error ? error.message : String(error)
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Clean up old backup files based on retention policy
|
|
457
|
+
*/
|
|
458
|
+
async cleanupOldBackups() {
|
|
459
|
+
if (!this.config.enableBackups) {
|
|
460
|
+
return 0;
|
|
461
|
+
}
|
|
462
|
+
let backupDir;
|
|
463
|
+
try {
|
|
464
|
+
backupDir = this.getBackupDir();
|
|
465
|
+
} catch (error) {
|
|
466
|
+
this.logger.warn(
|
|
467
|
+
`Failed to resolve backup directory: ${error instanceof Error ? error.message : String(error)}`
|
|
468
|
+
);
|
|
469
|
+
return 0;
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
await fs.access(backupDir);
|
|
473
|
+
} catch {
|
|
474
|
+
return 0;
|
|
475
|
+
}
|
|
476
|
+
const cutoffDate = new Date(
|
|
477
|
+
Date.now() - this.config.backupRetentionDays * 24 * 60 * 60 * 1e3
|
|
478
|
+
);
|
|
479
|
+
let deletedCount = 0;
|
|
480
|
+
try {
|
|
481
|
+
const files = await fs.readdir(backupDir);
|
|
482
|
+
const backupFiles = files.filter((file) => file.endsWith(".backup"));
|
|
483
|
+
for (const file of backupFiles) {
|
|
484
|
+
const filePath = path.join(backupDir, file);
|
|
485
|
+
try {
|
|
486
|
+
const stats = await fs.stat(filePath);
|
|
487
|
+
if (stats.mtime < cutoffDate) {
|
|
488
|
+
await fs.unlink(filePath);
|
|
489
|
+
deletedCount++;
|
|
490
|
+
this.logger.debug(`Cleaned up old backup: ${file}`);
|
|
491
|
+
}
|
|
492
|
+
} catch (error) {
|
|
493
|
+
this.logger.warn(
|
|
494
|
+
`Failed to process backup file ${file}: ${error instanceof Error ? error.message : String(error)}`
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (deletedCount > 0) {
|
|
499
|
+
this.logger.info(`Backup cleanup: removed ${deletedCount} old backup files`);
|
|
500
|
+
}
|
|
501
|
+
return deletedCount;
|
|
502
|
+
} catch (error) {
|
|
503
|
+
this.logger.warn(
|
|
504
|
+
`Failed to cleanup backup directory: ${error instanceof Error ? error.message : String(error)}`
|
|
505
|
+
);
|
|
506
|
+
return 0;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Get service configuration
|
|
511
|
+
*/
|
|
512
|
+
getConfig() {
|
|
513
|
+
return { ...this.config };
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Check if a path is allowed
|
|
517
|
+
*/
|
|
518
|
+
isPathAllowed(filePath) {
|
|
519
|
+
const validation = this.pathValidator.validatePath(filePath);
|
|
520
|
+
return validation.isValid;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
524
|
+
0 && (module.exports = {
|
|
525
|
+
FileSystemService
|
|
526
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { IDextoLogger } from '@dexto/core';
|
|
2
|
+
import { FileSystemConfig, ReadFileOptions, FileContent, GlobOptions, GlobResult, GrepOptions, SearchResult, WriteFileOptions, WriteResult, EditOperation, EditFileOptions, EditResult } from './types.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* FileSystem Service
|
|
6
|
+
*
|
|
7
|
+
* Secure file system operations for Dexto internal tools
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* FileSystemService - Handles all file system operations with security checks
|
|
12
|
+
*
|
|
13
|
+
* This service receives fully-validated configuration from the FileSystem Tools Provider.
|
|
14
|
+
* All defaults have been applied by the provider's schema, so the service trusts the config
|
|
15
|
+
* and uses it as-is without any fallback logic.
|
|
16
|
+
*
|
|
17
|
+
* TODO: Add tests for this class
|
|
18
|
+
* TODO: instantiate only when internal file tools are enabled to avoid file dependencies which won't work in serverless
|
|
19
|
+
*/
|
|
20
|
+
declare class FileSystemService {
|
|
21
|
+
private config;
|
|
22
|
+
private pathValidator;
|
|
23
|
+
private initialized;
|
|
24
|
+
private initPromise;
|
|
25
|
+
private logger;
|
|
26
|
+
/**
|
|
27
|
+
* Create a new FileSystemService with validated configuration.
|
|
28
|
+
*
|
|
29
|
+
* @param config - Fully-validated configuration from provider schema.
|
|
30
|
+
* All required fields have values, defaults already applied.
|
|
31
|
+
* @param logger - Logger instance for this service
|
|
32
|
+
*/
|
|
33
|
+
constructor(config: FileSystemConfig, logger: IDextoLogger);
|
|
34
|
+
/**
|
|
35
|
+
* Get backup directory path (context-aware with optional override)
|
|
36
|
+
* TODO: Migrate to explicit configuration via CLI enrichment layer (per-agent paths)
|
|
37
|
+
*/
|
|
38
|
+
private getBackupDir;
|
|
39
|
+
/**
|
|
40
|
+
* Initialize the service.
|
|
41
|
+
* Safe to call multiple times - subsequent calls return the same promise.
|
|
42
|
+
*/
|
|
43
|
+
initialize(): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Internal initialization logic.
|
|
46
|
+
*/
|
|
47
|
+
private doInitialize;
|
|
48
|
+
/**
|
|
49
|
+
* Ensure the service is initialized before use.
|
|
50
|
+
* Tools should call this at the start of their execute methods.
|
|
51
|
+
* Safe to call multiple times - will await the same initialization promise.
|
|
52
|
+
*/
|
|
53
|
+
ensureInitialized(): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Set a callback to check if a path is in an approved directory.
|
|
56
|
+
* This allows PathValidator to consult ApprovalManager without a direct dependency.
|
|
57
|
+
*
|
|
58
|
+
* @param checker Function that returns true if path is in an approved directory
|
|
59
|
+
*/
|
|
60
|
+
setDirectoryApprovalChecker(checker: (filePath: string) => boolean): void;
|
|
61
|
+
/**
|
|
62
|
+
* Check if a file path is within the configured allowed paths (config only).
|
|
63
|
+
* This is used by file tools to determine if directory approval is needed.
|
|
64
|
+
*
|
|
65
|
+
* @param filePath The file path to check (can be relative or absolute)
|
|
66
|
+
* @returns true if the path is within config-allowed paths, false otherwise
|
|
67
|
+
*/
|
|
68
|
+
isPathWithinConfigAllowed(filePath: string): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Read a file with validation and size limits
|
|
71
|
+
*/
|
|
72
|
+
readFile(filePath: string, options?: ReadFileOptions): Promise<FileContent>;
|
|
73
|
+
/**
|
|
74
|
+
* Find files matching a glob pattern
|
|
75
|
+
*/
|
|
76
|
+
globFiles(pattern: string, options?: GlobOptions): Promise<GlobResult>;
|
|
77
|
+
/**
|
|
78
|
+
* Search for content in files (grep-like functionality)
|
|
79
|
+
*/
|
|
80
|
+
searchContent(pattern: string, options?: GrepOptions): Promise<SearchResult>;
|
|
81
|
+
/**
|
|
82
|
+
* Write content to a file
|
|
83
|
+
*/
|
|
84
|
+
writeFile(filePath: string, content: string, options?: WriteFileOptions): Promise<WriteResult>;
|
|
85
|
+
/**
|
|
86
|
+
* Edit a file by replacing text
|
|
87
|
+
*/
|
|
88
|
+
editFile(filePath: string, operation: EditOperation, options?: EditFileOptions): Promise<EditResult>;
|
|
89
|
+
/**
|
|
90
|
+
* Create a backup of a file
|
|
91
|
+
*/
|
|
92
|
+
private createBackup;
|
|
93
|
+
/**
|
|
94
|
+
* Clean up old backup files based on retention policy
|
|
95
|
+
*/
|
|
96
|
+
cleanupOldBackups(): Promise<number>;
|
|
97
|
+
/**
|
|
98
|
+
* Get service configuration
|
|
99
|
+
*/
|
|
100
|
+
getConfig(): Readonly<FileSystemConfig>;
|
|
101
|
+
/**
|
|
102
|
+
* Check if a path is allowed
|
|
103
|
+
*/
|
|
104
|
+
isPathAllowed(filePath: string): boolean;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export { FileSystemService };
|