|
| 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