terminal_tool.rs

  1use crate::schema::json_schema_for;
  2use anyhow::{Context as _, Result, anyhow};
  3use assistant_tool::{ActionLog, Tool};
  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) -> 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    ) -> Task<Result<String>> {
 83        let input: TerminalToolInput = match serde_json::from_value(input) {
 84            Ok(input) => input,
 85            Err(err) => return Task::ready(Err(anyhow!(err))),
 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 => return Task::ready(Err(anyhow!("No worktrees found in the project"))),
 97            };
 98
 99            if worktrees.next().is_some() {
100                return Task::ready(Err(anyhow!(
101                    "'.' is ambiguous in multi-root workspaces. Please specify a root directory explicitly."
102                )));
103            }
104
105            only_worktree.read(cx).abs_path()
106        } else if input_path.is_absolute() {
107            // Absolute paths are allowed, but only if they're in one of the project's worktrees.
108            if !project
109                .worktrees(cx)
110                .any(|worktree| input_path.starts_with(&worktree.read(cx).abs_path()))
111            {
112                return Task::ready(Err(anyhow!(
113                    "The absolute path must be within one of the project's worktrees"
114                )));
115            }
116
117            input_path.into()
118        } else {
119            let Some(worktree) = project.worktree_for_root_name(&input.cd, cx) else {
120                return Task::ready(Err(anyhow!(
121                    "`cd` directory {} not found in the project",
122                    &input.cd
123                )));
124            };
125
126            worktree.read(cx).abs_path()
127        };
128
129        cx.background_spawn(run_command_limited(working_dir, input.command))
130    }
131}
132
133const LIMIT: usize = 16 * 1024;
134
135async fn run_command_limited(working_dir: Arc<Path>, command: String) -> Result<String> {
136    let shell = get_system_shell();
137
138    let mut cmd = new_smol_command(&shell)
139        .arg("-c")
140        .arg(&command)
141        .current_dir(working_dir)
142        .stdout(std::process::Stdio::piped())
143        .stderr(std::process::Stdio::piped())
144        .spawn()
145        .context("Failed to execute terminal command")?;
146
147    let mut combined_buffer = String::with_capacity(LIMIT + 1);
148
149    let mut out_reader = BufReader::new(cmd.stdout.take().context("Failed to get stdout")?);
150    let mut out_tmp_buffer = String::with_capacity(512);
151    let mut err_reader = BufReader::new(cmd.stderr.take().context("Failed to get stderr")?);
152    let mut err_tmp_buffer = String::with_capacity(512);
153
154    let mut out_line = Box::pin(
155        out_reader
156            .read_line(&mut out_tmp_buffer)
157            .left_future()
158            .fuse(),
159    );
160    let mut err_line = Box::pin(
161        err_reader
162            .read_line(&mut err_tmp_buffer)
163            .left_future()
164            .fuse(),
165    );
166
167    let mut has_stdout = true;
168    let mut has_stderr = true;
169    while (has_stdout || has_stderr) && combined_buffer.len() < LIMIT + 1 {
170        futures::select_biased! {
171            read = out_line => {
172                drop(out_line);
173                combined_buffer.extend(out_tmp_buffer.drain(..));
174                if read? == 0 {
175                    out_line = Box::pin(future::pending().right_future().fuse());
176                    has_stdout = false;
177                } else {
178                    out_line = Box::pin(out_reader.read_line(&mut out_tmp_buffer).left_future().fuse());
179                }
180            }
181            read = err_line => {
182                drop(err_line);
183                combined_buffer.extend(err_tmp_buffer.drain(..));
184                if read? == 0 {
185                    err_line = Box::pin(future::pending().right_future().fuse());
186                    has_stderr = false;
187                } else {
188                    err_line = Box::pin(err_reader.read_line(&mut err_tmp_buffer).left_future().fuse());
189                }
190            }
191        };
192    }
193
194    drop((out_line, err_line));
195
196    let truncated = combined_buffer.len() > LIMIT;
197    combined_buffer.truncate(LIMIT);
198
199    consume_reader(out_reader, truncated).await?;
200    consume_reader(err_reader, truncated).await?;
201
202    let status = cmd.status().await.context("Failed to get command status")?;
203
204    let output_string = if truncated {
205        // Valid to find `\n` in UTF-8 since 0-127 ASCII characters are not used in
206        // multi-byte characters.
207        let last_line_ix = combined_buffer.bytes().rposition(|b| b == b'\n');
208        let combined_buffer = &combined_buffer[..last_line_ix.unwrap_or(combined_buffer.len())];
209
210        format!(
211            "Command output too long. The first {} bytes:\n\n{}",
212            combined_buffer.len(),
213            output_block(&combined_buffer),
214        )
215    } else {
216        output_block(&combined_buffer)
217    };
218
219    let output_with_status = if status.success() {
220        if output_string.is_empty() {
221            "Command executed successfully.".to_string()
222        } else {
223            output_string.to_string()
224        }
225    } else {
226        format!(
227            "Command failed with exit code {} (shell: {}).\n\n{}",
228            status.code().unwrap_or(-1),
229            shell,
230            output_string,
231        )
232    };
233
234    Ok(output_with_status)
235}
236
237async fn consume_reader<T: AsyncReadExt + Unpin>(
238    mut reader: BufReader<T>,
239    truncated: bool,
240) -> Result<(), std::io::Error> {
241    loop {
242        let skipped_bytes = reader.fill_buf().await?;
243        if skipped_bytes.is_empty() {
244            break;
245        }
246        let skipped_bytes_len = skipped_bytes.len();
247        reader.consume_unpin(skipped_bytes_len);
248
249        // Should only skip if we went over the limit
250        debug_assert!(truncated);
251    }
252    Ok(())
253}
254
255fn output_block(output: &str) -> String {
256    format!(
257        "```\n{}{}```",
258        output,
259        if output.ends_with('\n') { "" } else { "\n" }
260    )
261}
262
263#[cfg(test)]
264#[cfg(not(windows))]
265mod tests {
266    use gpui::TestAppContext;
267
268    use super::*;
269
270    #[gpui::test(iterations = 10)]
271    async fn test_run_command_simple(cx: &mut TestAppContext) {
272        cx.executor().allow_parking();
273
274        let result =
275            run_command_limited(Path::new(".").into(), "echo 'Hello, World!'".to_string()).await;
276
277        assert!(result.is_ok());
278        assert_eq!(result.unwrap(), "```\nHello, World!\n```");
279    }
280
281    #[gpui::test(iterations = 10)]
282    async fn test_interleaved_stdout_stderr(cx: &mut TestAppContext) {
283        cx.executor().allow_parking();
284
285        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";
286        let result = run_command_limited(Path::new(".").into(), command.to_string()).await;
287
288        assert!(result.is_ok());
289        assert_eq!(
290            result.unwrap(),
291            "```\nstdout 1\nstderr 1\nstdout 2\nstderr 2\n```"
292        );
293    }
294
295    #[gpui::test(iterations = 10)]
296    async fn test_multiple_output_reads(cx: &mut TestAppContext) {
297        cx.executor().allow_parking();
298
299        // Command with multiple outputs that might require multiple reads
300        let result = run_command_limited(
301            Path::new(".").into(),
302            "echo '1'; sleep 0.01; echo '2'; sleep 0.01; echo '3'".to_string(),
303        )
304        .await;
305
306        assert!(result.is_ok());
307        assert_eq!(result.unwrap(), "```\n1\n2\n3\n```");
308    }
309
310    #[gpui::test(iterations = 10)]
311    async fn test_output_truncation_single_line(cx: &mut TestAppContext) {
312        cx.executor().allow_parking();
313
314        let cmd = format!("echo '{}'; sleep 0.01;", "X".repeat(LIMIT * 2));
315
316        let result = run_command_limited(Path::new(".").into(), cmd).await;
317
318        assert!(result.is_ok());
319        let output = result.unwrap();
320
321        let content_start = output.find("```\n").map(|i| i + 4).unwrap_or(0);
322        let content_end = output.rfind("\n```").unwrap_or(output.len());
323        let content_length = content_end - content_start;
324
325        // Output should be exactly the limit
326        assert_eq!(content_length, LIMIT);
327    }
328
329    #[gpui::test(iterations = 10)]
330    async fn test_output_truncation_multiline(cx: &mut TestAppContext) {
331        cx.executor().allow_parking();
332
333        let cmd = format!("echo '{}'; ", "X".repeat(120)).repeat(160);
334        let result = run_command_limited(Path::new(".").into(), cmd).await;
335
336        assert!(result.is_ok());
337        let output = result.unwrap();
338
339        assert!(output.starts_with("Command output too long. The first 16334 bytes:\n\n"));
340
341        let content_start = output.find("```\n").map(|i| i + 4).unwrap_or(0);
342        let content_end = output.rfind("\n```").unwrap_or(output.len());
343        let content_length = content_end - content_start;
344
345        assert!(content_length <= LIMIT);
346    }
347
348    #[gpui::test(iterations = 10)]
349    async fn test_command_failure(cx: &mut TestAppContext) {
350        cx.executor().allow_parking();
351
352        let result = run_command_limited(Path::new(".").into(), "exit 42".to_string()).await;
353
354        assert!(result.is_ok());
355        let output = result.unwrap();
356
357        // Extract the shell name from path for cleaner test output
358        let shell_path = std::env::var("SHELL").unwrap_or("bash".to_string());
359
360        let expected_output = format!(
361            "Command failed with exit code 42 (shell: {}).\n\n```\n\n```",
362            shell_path
363        );
364        assert_eq!(output, expected_output);
365    }
366}