Skip to content

Commit ee20255

Browse files
authored
feat: add build-in file operationg tool (#89)
1 parent c782c66 commit ee20255

8 files changed

Lines changed: 2306 additions & 19 deletions

File tree

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
/*
2+
* Copyright 2024-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.agentscope.core.tool.file;
17+
18+
import java.io.IOException;
19+
import java.nio.charset.StandardCharsets;
20+
import java.nio.file.Files;
21+
import java.nio.file.Path;
22+
import java.nio.file.Paths;
23+
import java.util.List;
24+
25+
/**
26+
* Utility methods shared by text file tools.
27+
*/
28+
public class FileToolUtils {
29+
30+
private FileToolUtils() {
31+
// Utility class, prevent instantiation
32+
}
33+
34+
/**
35+
* Validate that the given file path is within the base directory.
36+
* This prevents path traversal attacks and unauthorized file access.
37+
*
38+
* @param filePath The file path to validate
39+
* @param baseDir The base directory to restrict access to (null means no restriction)
40+
* @return The normalized absolute path if valid
41+
* @throws IOException if the path is invalid or outside the base directory
42+
*/
43+
static Path validatePath(String filePath, Path baseDir) throws IOException {
44+
if (filePath == null || filePath.trim().isEmpty()) {
45+
throw new IOException("File path cannot be null or empty.");
46+
}
47+
48+
Path path = Paths.get(filePath).toAbsolutePath().normalize();
49+
50+
// If baseDir is specified, ensure the path is within it
51+
if (baseDir != null) {
52+
Path normalizedBaseDir = baseDir.toAbsolutePath().normalize();
53+
if (!path.startsWith(normalizedBaseDir)) {
54+
throw new IOException(
55+
String.format(
56+
"Access denied: The file path '%s' is outside the allowed base"
57+
+ " directory '%s'.",
58+
filePath, normalizedBaseDir));
59+
}
60+
}
61+
62+
return path;
63+
}
64+
65+
/**
66+
* Calculate the view ranges for displaying file content after modifications.
67+
*
68+
* @param originalLineCount Original number of lines
69+
* @param newLineCount New number of lines after modification
70+
* @param modifyStart Start line of modification
71+
* @param modifyEnd End line of modification
72+
* @param extraViewLines Extra lines to show before and after
73+
* @return Array of [viewStart, viewEnd]
74+
*/
75+
static int[] calculateViewRanges(
76+
int originalLineCount,
77+
int newLineCount,
78+
int modifyStart,
79+
int modifyEnd,
80+
int extraViewLines) {
81+
82+
int viewStart = Math.max(1, modifyStart - extraViewLines);
83+
int viewEnd =
84+
Math.min(
85+
newLineCount,
86+
modifyStart
87+
+ (newLineCount - originalLineCount)
88+
+ (modifyEnd - modifyStart)
89+
+ extraViewLines);
90+
91+
return new int[] {viewStart, viewEnd};
92+
}
93+
94+
/**
95+
* View a specific range of lines from a text file.
96+
*
97+
* @param filePath The file path
98+
* @param startLine Start line number (1-based)
99+
* @param endLine End line number (1-based, inclusive)
100+
* @return The content with line numbers
101+
*/
102+
static String viewTextFile(String filePath, int startLine, int endLine) {
103+
try {
104+
List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
105+
StringBuilder result = new StringBuilder();
106+
107+
int start = Math.max(0, startLine - 1);
108+
int end = Math.min(lines.size(), endLine);
109+
110+
for (int i = start; i < end; i++) {
111+
result.append(String.format("%d: %s\n", i + 1, lines.get(i)));
112+
}
113+
114+
return result.toString();
115+
} catch (IOException e) {
116+
return "Error reading file: " + e.getMessage();
117+
}
118+
}
119+
120+
/**
121+
* Parse range string like "[1,5]" or "1,5" into [start, end] array.
122+
*
123+
* @param ranges The range string
124+
* @return Array of [start, end] or null if invalid
125+
*/
126+
static int[] parseRanges(String ranges) {
127+
try {
128+
// Remove brackets and spaces
129+
String cleaned = ranges.trim().replaceAll("^\\[", "").replaceAll("\\]$", "").trim();
130+
131+
String[] parts = cleaned.split(",");
132+
if (parts.length != 2) {
133+
return null;
134+
}
135+
136+
int start = Integer.parseInt(parts[0].trim());
137+
int end = Integer.parseInt(parts[1].trim());
138+
139+
return new int[] {start, end};
140+
} catch (NumberFormatException e) {
141+
return null;
142+
}
143+
}
144+
}
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
/*
2+
* Copyright 2024-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.agentscope.core.tool.file;
17+
18+
import io.agentscope.core.message.ToolResultBlock;
19+
import io.agentscope.core.tool.Tool;
20+
import io.agentscope.core.tool.ToolParam;
21+
import java.nio.charset.StandardCharsets;
22+
import java.nio.file.Files;
23+
import java.nio.file.Path;
24+
import java.nio.file.Paths;
25+
import java.util.List;
26+
import org.slf4j.Logger;
27+
import org.slf4j.LoggerFactory;
28+
import reactor.core.publisher.Mono;
29+
30+
/**
31+
* Tool for viewing text file content with optional line range specification.
32+
*
33+
* <p>This tool allows reading file content with line numbers, supporting:
34+
* <ul>
35+
* <li>Viewing entire file content</li>
36+
* <li>Viewing specific line ranges (e.g., lines 1-100)</li>
37+
* <li>Viewing from the end using negative indices (e.g., last 100 lines: [-100, -1])</li>
38+
* </ul>
39+
*
40+
* <p>Security: When baseDir is specified, all file operations are restricted to that directory
41+
* to prevent unauthorized file access.
42+
*/
43+
public class ReadFileTool {
44+
45+
private static final Logger logger = LoggerFactory.getLogger(ReadFileTool.class);
46+
47+
/**
48+
* Base directory to restrict file access. If null, no restriction is applied.
49+
* This prevents path traversal attacks and unauthorized file access.
50+
*/
51+
private final Path baseDir;
52+
53+
/**
54+
* Creates a ReadFileTool with no base directory restriction.
55+
*/
56+
public ReadFileTool() {
57+
this(null);
58+
}
59+
60+
/**
61+
* Creates a ReadFileTool with a base directory restriction.
62+
*
63+
* @param baseDir The base directory to restrict file access to. If null, no restriction is applied.
64+
*/
65+
public ReadFileTool(String baseDir) {
66+
this.baseDir = baseDir != null ? Paths.get(baseDir).toAbsolutePath().normalize() : null;
67+
if (this.baseDir != null) {
68+
logger.info("ReadFileTool initialized with base directory: {}", this.baseDir);
69+
} else {
70+
logger.info("ReadFileTool initialized without base directory restriction");
71+
}
72+
}
73+
74+
/**
75+
* View the file content in the specified range with line numbers.
76+
* If ranges is not provided, the entire file will be returned.
77+
*
78+
* @param filePath The target file path
79+
* @param ranges The range of lines to be viewed (e.g., lines 1 to 100: "1,100"),
80+
* inclusive. If not provided, the entire file will be returned.
81+
* To view the last 100 lines, use "-100,-1". Format: "start,end" or "[start,end]"
82+
* @return The file content with line numbers or an error message
83+
*/
84+
@Tool(
85+
name = "view_text_file",
86+
description =
87+
"View the file content in the specified range with line numbers. If ranges is"
88+
+ " not provided, the entire file will be returned. Use this to read and"
89+
+ " inspect file contents. Supports negative indices to view from the end"
90+
+ " (e.g., '-100,-1' for last 100 lines).")
91+
public Mono<ToolResultBlock> viewTextFile(
92+
@ToolParam(name = "file_path", description = "The target file path") String filePath,
93+
@ToolParam(
94+
name = "ranges",
95+
description =
96+
"The range of lines to be viewed (e.g., '1,100' or '[1,100]'),"
97+
+ " inclusive. If not provided, the entire file will be"
98+
+ " returned. To view the last 100 lines, use '-100,-1'.",
99+
required = false)
100+
String ranges) {
101+
102+
logger.debug("view_text_file called: filePath='{}', ranges='{}'", filePath, ranges);
103+
104+
return Mono.fromCallable(
105+
() -> {
106+
// Validate path is within base directory
107+
Path path;
108+
try {
109+
path = FileToolUtils.validatePath(filePath, baseDir);
110+
} catch (Exception e) {
111+
logger.warn(
112+
"Path validation failed for '{}': {}",
113+
filePath,
114+
e.getMessage());
115+
return ToolResultBlock.error(e.getMessage());
116+
}
117+
118+
// Check if file exists
119+
if (!Files.exists(path)) {
120+
logger.warn("File does not exist: {}", filePath);
121+
return ToolResultBlock.error(
122+
String.format("The file %s does not exist.", filePath));
123+
}
124+
125+
// Check if path is a file
126+
if (!Files.isRegularFile(path)) {
127+
logger.warn("Path is not a regular file: {}", filePath);
128+
return ToolResultBlock.error(
129+
String.format("The path %s is not a file.", filePath));
130+
}
131+
132+
// Read all lines
133+
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
134+
logger.debug("Read {} lines from file: {}", lines.size(), filePath);
135+
136+
// Parse ranges if provided
137+
if (ranges == null || ranges.trim().isEmpty()) {
138+
// Return entire file content
139+
logger.debug(
140+
"Returning entire file content ({} lines)", lines.size());
141+
String content = formatLinesWithNumbers(lines, 1, lines.size());
142+
return ToolResultBlock.text(
143+
String.format(
144+
"The content of %s:\n```\n%s```",
145+
filePath, content));
146+
}
147+
148+
// Parse the range
149+
int[] rangeArray = FileToolUtils.parseRanges(ranges);
150+
if (rangeArray == null) {
151+
logger.warn("Invalid range format: {}", ranges);
152+
return ToolResultBlock.error(
153+
String.format(
154+
"Invalid range format. Expected '[start,end]' or"
155+
+ " 'start,end', but got %s.",
156+
ranges));
157+
}
158+
159+
int start = rangeArray[0];
160+
int end = rangeArray[1];
161+
162+
// Handle negative indices (count from the end)
163+
if (start < 0) {
164+
start = lines.size() + start + 1;
165+
}
166+
if (end < 0) {
167+
end = lines.size() + end + 1;
168+
}
169+
170+
// Validate range
171+
if (start < 1) {
172+
start = 1;
173+
}
174+
if (end > lines.size()) {
175+
end = lines.size();
176+
}
177+
if (start > end) {
178+
logger.warn(
179+
"Invalid range: start {} > end {} for file with {} lines",
180+
start,
181+
end,
182+
lines.size());
183+
return ToolResultBlock.error(
184+
String.format(
185+
"Invalid range: start line %d is greater than end"
186+
+ " line %d.",
187+
start, end));
188+
}
189+
190+
logger.debug("Viewing lines {}-{} from file: {}", start, end, filePath);
191+
192+
// Extract the specified range
193+
String content = formatLinesWithNumbers(lines, start, end);
194+
195+
return ToolResultBlock.text(
196+
String.format(
197+
"The content of %s in lines [%d, %d]:\n```\n%s```",
198+
filePath, start, end, content));
199+
})
200+
.onErrorResume(
201+
e -> {
202+
logger.error(
203+
"Error viewing file '{}' with ranges '{}': {}",
204+
filePath,
205+
ranges,
206+
e.getMessage(),
207+
e);
208+
return Mono.just(ToolResultBlock.error("Error: " + e.getMessage()));
209+
});
210+
}
211+
212+
/**
213+
* Format lines with line numbers for display.
214+
*
215+
* @param lines All lines from the file
216+
* @param start Start line number (1-based, inclusive)
217+
* @param end End line number (1-based, inclusive)
218+
* @return Formatted string with line numbers
219+
*/
220+
private String formatLinesWithNumbers(List<String> lines, int start, int end) {
221+
StringBuilder result = new StringBuilder();
222+
223+
// Adjust to 0-based index
224+
int startIdx = start - 1;
225+
int endIdx = end - 1;
226+
227+
for (int i = startIdx; i <= endIdx && i < lines.size(); i++) {
228+
result.append(String.format("%d: %s\n", i + 1, lines.get(i)));
229+
}
230+
231+
return result.toString();
232+
}
233+
}

0 commit comments

Comments
 (0)