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