terminal_tool.rs

  1use crate::schema::json_schema_for;
  2use anyhow::{Context as _, Result, anyhow};
  3use assistant_tool::{ActionLog, Tool, ToolResult};
  4use futures::io::BufReader;
  5use futures::{AsyncBufReadExt, AsyncReadExt, FutureExt};
  6use gpui::{App, AppContext, Entity, Task};
  7use language_model::{LanguageModelRequestMessage, LanguageModelToolSchemaFormat};
  8use project::Project;
  9use schemars::JsonSchema;
 10use serde::{Deserialize, Serialize};
 11use std::future;
 12use util::get_system_shell;
 13
 14use std::path::Path;
 15use std::sync::Arc;
 16use ui::IconName;
 17use util::command::new_smol_command;
 18use util::markdown::MarkdownString;
 19
 20#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 21pub struct TerminalToolInput {
 22    /// The one-liner command to execute.
 23    command: String,
 24    /// Working directory for the command. This must be one of the root directories of the project.
 25    cd: String,
 26}
 27
 28pub struct TerminalTool;
 29
 30impl Tool for TerminalTool {
 31    fn name(&self) -> String {
 32        "terminal".to_string()
 33    }
 34
 35    fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
 36        true
 37    }
 38
 39    fn description(&self) -> String {
 40        include_str!("./terminal_tool/description.md").to_string()
 41    }
 42
 43    fn icon(&self) -> IconName {
 44        IconName::Terminal
 45    }
 46
 47    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
 48        json_schema_for::<TerminalToolInput>(format)
 49    }
 50
 51    fn ui_text(&self, input: &serde_json::Value) -> String {
 52        match serde_json::from_value::<TerminalToolInput>(input.clone()) {
 53            Ok(input) => {
 54                let mut lines = input.command.lines();
 55                let first_line = lines.next().unwrap_or_default();
 56                let remaining_line_count = lines.count();
 57                match remaining_line_count {
 58                    0 => MarkdownString::inline_code(&first_line).0,
 59                    1 => {
 60                        MarkdownString::inline_code(&format!(
 61                            "{} - {} more line",
 62                            first_line, remaining_line_count
 63                        ))
 64                        .0
 65                    }
 66                    n => {
 67                        MarkdownString::inline_code(&format!("{} - {} more lines", first_line, n)).0
 68                    }
 69                }
 70            }
 71            Err(_) => "Run terminal command".to_string(),
 72        }
 73    }
 74
 75    fn run(
 76        self: Arc<Self>,
 77        input: serde_json::Value,
 78        _messages: &[LanguageModelRequestMessage],
 79        project: Entity<Project>,
 80        _action_log: Entity<ActionLog>,
 81        cx: &mut App,
 82    ) -> ToolResult {
 83        let input: TerminalToolInput = match serde_json::from_value(input) {
 84            Ok(input) => input,
 85            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
 86        };
 87
 88        let project = project.read(cx);
 89        let input_path = Path::new(&input.cd);
 90        let working_dir = if input.cd == "." {
 91            // Accept "." as meaning "the one worktree" if we only have one worktree.
 92            let mut worktrees = project.worktrees(cx);
 93
 94            let only_worktree = match worktrees.next() {
 95                Some(worktree) => worktree,
 96                None => {
 97                    return Task::ready(Err(anyhow!("No worktrees found in the project"))).into();
 98                }
 99            };
100
101            if worktrees.next().is_some() {
102                return Task::ready(Err(anyhow!(
103                    "'.' is ambiguous in multi-root workspaces. Please specify a root directory explicitly."
104                ))).into();
105            }
106
107            only_worktree.read(cx).abs_path()
108        } else if input_path.is_absolute() {
109            // Absolute paths are allowed, but only if they're in one of the project's worktrees.
110            if !project
111                .worktrees(cx)
112                .any(|worktree| input_path.starts_with(&worktree.read(cx).abs_path()))
113            {
114                return Task::ready(Err(anyhow!(
115                    "The absolute path must be within one of the project's worktrees"
116                )))
117                .into();
118            }
119
120            input_path.into()
121        } else {
122            let Some(worktree) = project.worktree_for_root_name(&input.cd, cx) else {
123                return Task::ready(Err(anyhow!(
124                    "`cd` directory {} not found in the project",
125                    &input.cd
126                )))
127                .into();
128            };
129
130            worktree.read(cx).abs_path()
131        };
132
133        cx.background_spawn(run_command_limited(working_dir, input.command))
134            .into()
135    }
136}
137
138const LIMIT: usize = 16 * 1024;
139
140async fn run_command_limited(working_dir: Arc<Path>, command: String) -> Result<String> {
141    let shell = get_system_shell();
142
143    let mut cmd = new_smol_command(&shell)
144        .arg("-c")
145        .arg(&command)
146        .current_dir(working_dir)
147        .stdout(std::process::Stdio::piped())
148        .stderr(std::process::Stdio::piped())
149        .spawn()
150        .context("Failed to execute terminal command")?;
151
152    let mut combined_buffer = String::with_capacity(LIMIT + 1);
153
154    let mut out_reader = BufReader::new(cmd.stdout.take().context("Failed to get stdout")?);
155    let mut out_tmp_buffer = String::with_capacity(512);
156    let mut err_reader = BufReader::new(cmd.stderr.take().context("Failed to get stderr")?);
157    let mut err_tmp_buffer = String::with_capacity(512);
158
159    let mut out_line = Box::pin(
160        out_reader
161            .read_line(&mut out_tmp_buffer)
162            .left_future()
163            .fuse(),
164    );
165    let mut err_line = Box::pin(
166        err_reader
167            .read_line(&mut err_tmp_buffer)
168            .left_future()
169            .fuse(),
170    );
171
172    let mut has_stdout = true;
173    let mut has_stderr = true;
174    while (has_stdout || has_stderr) && combined_buffer.len() < LIMIT + 1 {
175        futures::select_biased! {
176            read = out_line => {
177                drop(out_line);
178                combined_buffer.extend(out_tmp_buffer.drain(..));
179                if read? == 0 {
180                    out_line = Box::pin(future::pending().right_future().fuse());
181                    has_stdout = false;
182                } else {
183                    out_line = Box::pin(out_reader.read_line(&mut out_tmp_buffer).left_future().fuse());
184                }
185            }
186            read = err_line => {
187                drop(err_line);
188                combined_buffer.extend(err_tmp_buffer.drain(..));
189                if read? == 0 {
190                    err_line = Box::pin(future::pending().right_future().fuse());
191                    has_stderr = false;
192                } else {
193                    err_line = Box::pin(err_reader.read_line(&mut err_tmp_buffer).left_future().fuse());
194                }
195            }
196        };
197    }
198
199    drop((out_line, err_line));
200
201    let truncated = combined_buffer.len() > LIMIT;
202    combined_buffer.truncate(LIMIT);
203
204    consume_reader(out_reader, truncated).await?;
205    consume_reader(err_reader, truncated).await?;
206
207    let status = cmd.status().await.context("Failed to get command status")?;
208
209    let output_string = if truncated {
210        // Valid to find `\n` in UTF-8 since 0-127 ASCII characters are not used in
211        // multi-byte characters.
212        let last_line_ix = combined_buffer.bytes().rposition(|b| b == b'\n');
213        let combined_buffer = &combined_buffer[..last_line_ix.unwrap_or(combined_buffer.len())];
214
215        format!(
216            "Command output too long. The first {} bytes:\n\n{}",
217            combined_buffer.len(),
218            output_block(&combined_buffer),
219        )
220    } else {
221        output_block(&combined_buffer)
222    };
223
224    let output_with_status = if status.success() {
225        if output_string.is_empty() {
226            "Command executed successfully.".to_string()
227        } else {
228            output_string.to_string()
229        }
230    } else {
231        format!(
232            "Command failed with exit code {} (shell: {}).\n\n{}",
233            status.code().unwrap_or(-1),
234            shell,
235            output_string,
236        )
237    };
238
239    Ok(output_with_status)
240}
241
242async fn consume_reader<T: AsyncReadExt + Unpin>(
243    mut reader: BufReader<T>,
244    truncated: bool,
245) -> Result<(), std::io::Error> {
246    loop {
247        let skipped_bytes = reader.fill_buf().await?;
248        if skipped_bytes.is_empty() {
249            break;
250        }
251        let skipped_bytes_len = skipped_bytes.len();
252        reader.consume_unpin(skipped_bytes_len);
253
254        // Should only skip if we went over the limit
255        debug_assert!(truncated);
256    }
257    Ok(())
258}
259
260fn output_block(output: &str) -> String {
261    format!(
262        "```\n{}{}```",
263        output,
264        if output.ends_with('\n') { "" } else { "\n" }
265    )
266}
267
268#[cfg(test)]
269#[cfg(not(windows))]
270mod tests {
271    use gpui::TestAppContext;
272
273    use super::*;
274
275    #[gpui::test(iterations = 10)]
276    async fn test_run_command_simple(cx: &mut TestAppContext) {
277        cx.executor().allow_parking();
278
279        let result =
280            run_command_limited(Path::new(".").into(), "echo 'Hello, World!'".to_string()).await;
281
282        assert!(result.is_ok());
283        assert_eq!(result.unwrap(), "```\nHello, World!\n```");
284    }
285
286    #[gpui::test(iterations = 10)]
287    async fn test_interleaved_stdout_stderr(cx: &mut TestAppContext) {
288        cx.executor().allow_parking();
289
290        let command = "echo 'stdout 1' && sleep 0.01 && echo 'stderr 1' >&2 && sleep 0.01 && echo 'stdout 2' && sleep 0.01 && echo 'stderr 2' >&2";
291        let result = run_command_limited(Path::new(".").into(), command.to_string()).await;
292
293        assert!(result.is_ok());
294        assert_eq!(
295            result.unwrap(),
296            "```\nstdout 1\nstderr 1\nstdout 2\nstderr 2\n```"
297        );
298    }
299
300    #[gpui::test(iterations = 10)]
301    async fn test_multiple_output_reads(cx: &mut TestAppContext) {
302        cx.executor().allow_parking();
303
304        // Command with multiple outputs that might require multiple reads
305        let result = run_command_limited(
306            Path::new(".").into(),
307            "echo '1'; sleep 0.01; echo '2'; sleep 0.01; echo '3'".to_string(),
308        )
309        .await;
310
311        assert!(result.is_ok());
312        assert_eq!(result.unwrap(), "```\n1\n2\n3\n```");
313    }
314
315    #[gpui::test(iterations = 10)]
316    async fn test_output_truncation_single_line(cx: &mut TestAppContext) {
317        cx.executor().allow_parking();
318
319        let cmd = format!("echo '{}'; sleep 0.01;", "X".repeat(LIMIT * 2));
320
321        let result = run_command_limited(Path::new(".").into(), cmd).await;
322
323        assert!(result.is_ok());
324        let output = result.unwrap();
325
326        let content_start = output.find("```\n").map(|i| i + 4).unwrap_or(0);
327        let content_end = output.rfind("\n```").unwrap_or(output.len());
328        let content_length = content_end - content_start;
329
330        // Output should be exactly the limit
331        assert_eq!(content_length, LIMIT);
332    }
333
334    #[gpui::test(iterations = 10)]
335    async fn test_output_truncation_multiline(cx: &mut TestAppContext) {
336        cx.executor().allow_parking();
337
338        let cmd = format!("echo '{}'; ", "X".repeat(120)).repeat(160);
339        let result = run_command_limited(Path::new(".").into(), cmd).await;
340
341        assert!(result.is_ok());
342        let output = result.unwrap();
343
344        assert!(output.starts_with("Command output too long. The first 16334 bytes:\n\n"));
345
346        let content_start = output.find("```\n").map(|i| i + 4).unwrap_or(0);
347        let content_end = output.rfind("\n```").unwrap_or(output.len());
348        let content_length = content_end - content_start;
349
350        assert!(content_length <= LIMIT);
351    }
352
353    #[gpui::test(iterations = 10)]
354    async fn test_command_failure(cx: &mut TestAppContext) {
355        cx.executor().allow_parking();
356
357        let result = run_command_limited(Path::new(".").into(), "exit 42".to_string()).await;
358
359        assert!(result.is_ok());
360        let output = result.unwrap();
361
362        // Extract the shell name from path for cleaner test output
363        let shell_path = std::env::var("SHELL").unwrap_or("bash".to_string());
364
365        let expected_output = format!(
366            "Command failed with exit code 42 (shell: {}).\n\n```\n\n```",
367            shell_path
368        );
369        assert_eq!(output, expected_output);
370    }
371}