| 898 | } |
| 899 | |
| 900 | fn exec_read_file(&self, args: &serde_json::Value) -> Result<String, String> { |
| 901 | let path_str = args["path"] |
| 902 | .as_str() |
| 903 | .ok_or("missing required parameter: path")?; |
| 904 | |
| 905 | // Prevent path traversal. |
| 906 | if path_str.contains("..") { |
| 907 | return Err("path must not contain '..'".into()); |
| 908 | } |
| 909 | |
| 910 | let full_path = self.root.join(path_str); |
| 911 | let content = std::fs::read_to_string(&full_path) |
| 912 | .map_err(|e| format!("cannot read {path_str}: {e}"))?; |
| 913 | |
| 914 | // Optionally slice by line range. |
| 915 | let start_line = args["start_line"].as_u64().map(|n| n as usize); |
| 916 | let end_line = args["end_line"].as_u64().map(|n| n as usize); |
| 917 | |
| 918 | let has_line_range = start_line.is_some() || end_line.is_some(); |
| 919 | let total_lines = content.lines().count(); |
| 920 | |
| 921 | // If no line range and file is large, return a structured outline. |
| 922 | // The LLM should use list_entities or code_search to find the |
| 923 | // right line range first. |
| 924 | if !has_line_range && content.len() > READ_FILE_PREVIEW_THRESHOLD { |
| 925 | return Ok(build_file_outline(path_str, &content, total_lines)); |
| 926 | } |
| 927 | |
| 928 | let output = match (start_line, end_line) { |
| 929 | (Some(s), Some(e)) => { |
| 930 | let s = s.saturating_sub(1); // 1-based to 0-based |
| 931 | content |
| 932 | .lines() |
| 933 | .skip(s) |
| 934 | .take(e.saturating_sub(s)) |
| 935 | .collect::<Vec<_>>() |
| 936 | .join("\n") |
| 937 | } |
| 938 | (Some(s), None) => { |
| 939 | let s = s.saturating_sub(1); |
| 940 | content |
| 941 | .lines() |
| 942 | .skip(s) |
| 943 | .take(200) // cap open-ended reads at 200 lines |
| 944 | .collect::<Vec<_>>() |
| 945 | .join("\n") |
| 946 | } |
| 947 | (None, Some(e)) => content.lines().take(e).collect::<Vec<_>>().join("\n"), |
| 948 | (None, None) => content, |
| 949 | }; |
| 950 | |
| 951 | // Final cap on output size. |
| 952 | if output.len() > MAX_READ_FILE_BYTES { |
| 953 | Ok(format!( |
| 954 | "{}\n\n... truncated ({} bytes total)", |
| 955 | &output[..MAX_READ_FILE_BYTES], |
| 956 | output.len() |
| 957 | )) |