1use std::path::Path;
2use std::sync::Arc;
3
4use crate::schema::json_schema_for;
5use anyhow::{Result, anyhow};
6use assistant_tool::{ActionLog, Tool};
7use gpui::{App, Entity, Task};
8use itertools::Itertools;
9use language_model::{LanguageModelRequestMessage, LanguageModelToolSchemaFormat};
10use project::Project;
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13use ui::IconName;
14use util::markdown::MarkdownString;
15
16#[derive(Debug, Serialize, Deserialize, JsonSchema)]
17pub struct ReadFileToolInput {
18 /// The relative path of the file to read.
19 ///
20 /// This path should never be absolute, and the first component
21 /// of the path should always be a root directory in a project.
22 ///
23 /// <example>
24 /// If the project has the following root directories:
25 ///
26 /// - directory1
27 /// - directory2
28 ///
29 /// If you wanna access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
30 /// If you wanna access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
31 /// </example>
32 pub path: Arc<Path>,
33
34 /// Optional line number to start reading on (1-based index)
35 #[serde(default)]
36 pub start_line: Option<usize>,
37
38 /// Optional line number to end reading on (1-based index)
39 #[serde(default)]
40 pub end_line: Option<usize>,
41}
42
43pub struct ReadFileTool;
44
45impl Tool for ReadFileTool {
46 fn name(&self) -> String {
47 "read_file".into()
48 }
49
50 fn needs_confirmation(&self) -> bool {
51 false
52 }
53
54 fn description(&self) -> String {
55 include_str!("./read_file_tool/description.md").into()
56 }
57
58 fn icon(&self) -> IconName {
59 IconName::FileSearch
60 }
61
62 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> serde_json::Value {
63 json_schema_for::<ReadFileToolInput>(format)
64 }
65
66 fn ui_text(&self, input: &serde_json::Value) -> String {
67 match serde_json::from_value::<ReadFileToolInput>(input.clone()) {
68 Ok(input) => {
69 let path = MarkdownString::inline_code(&input.path.display().to_string());
70 format!("Read file {path}")
71 }
72 Err(_) => "Read file".to_string(),
73 }
74 }
75
76 fn run(
77 self: Arc<Self>,
78 input: serde_json::Value,
79 _messages: &[LanguageModelRequestMessage],
80 project: Entity<Project>,
81 action_log: Entity<ActionLog>,
82 cx: &mut App,
83 ) -> Task<Result<String>> {
84 let input = match serde_json::from_value::<ReadFileToolInput>(input) {
85 Ok(input) => input,
86 Err(err) => return Task::ready(Err(anyhow!(err))),
87 };
88
89 let Some(project_path) = project.read(cx).find_project_path(&input.path, cx) else {
90 return Task::ready(Err(anyhow!(
91 "Path {} not found in project",
92 &input.path.display()
93 )));
94 };
95
96 cx.spawn(async move |cx| {
97 let buffer = cx
98 .update(|cx| {
99 project.update(cx, |project, cx| project.open_buffer(project_path, cx))
100 })?
101 .await?;
102
103 let result = buffer.read_with(cx, |buffer, _cx| {
104 let text = buffer.text();
105 if input.start_line.is_some() || input.end_line.is_some() {
106 let start = input.start_line.unwrap_or(1);
107 let lines = text.split('\n').skip(start - 1);
108 if let Some(end) = input.end_line {
109 let count = end.saturating_sub(start);
110 Itertools::intersperse(lines.take(count), "\n").collect()
111 } else {
112 Itertools::intersperse(lines, "\n").collect()
113 }
114 } else {
115 text
116 }
117 })?;
118
119 action_log.update(cx, |log, cx| {
120 log.buffer_read(buffer, cx);
121 })?;
122
123 anyhow::Ok(result)
124 })
125 }
126}