1use anyhow::{anyhow, Context as _, Result};
2use assistant_tool::{ActionLog, Tool};
3use gpui::{App, Entity, Task};
4use language_model::LanguageModelRequestMessage;
5use project::Project;
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use std::sync::Arc;
9use util::command::new_smol_command;
10
11#[derive(Debug, Serialize, Deserialize, JsonSchema)]
12pub struct BashToolInput {
13 /// The bash command to execute as a one-liner.
14 command: String,
15 /// Working directory for the command. This must be one of the root directories of the project.
16 cd: String,
17}
18
19pub struct BashTool;
20
21impl Tool for BashTool {
22 fn name(&self) -> String {
23 "bash".to_string()
24 }
25
26 fn description(&self) -> String {
27 include_str!("./bash_tool/description.md").to_string()
28 }
29
30 fn input_schema(&self) -> serde_json::Value {
31 let schema = schemars::schema_for!(BashToolInput);
32 serde_json::to_value(&schema).unwrap()
33 }
34
35 fn run(
36 self: Arc<Self>,
37 input: serde_json::Value,
38 _messages: &[LanguageModelRequestMessage],
39 project: Entity<Project>,
40 _action_log: Entity<ActionLog>,
41 cx: &mut App,
42 ) -> Task<Result<String>> {
43 let input: BashToolInput = match serde_json::from_value(input) {
44 Ok(input) => input,
45 Err(err) => return Task::ready(Err(anyhow!(err))),
46 };
47
48 let Some(worktree) = project.read(cx).worktree_for_root_name(&input.cd, cx) else {
49 return Task::ready(Err(anyhow!("Working directory not found in the project")));
50 };
51 let working_directory = worktree.read(cx).abs_path();
52
53 cx.spawn(async move |_| {
54 // Add 2>&1 to merge stderr into stdout for proper interleaving.
55 let command = format!("({}) 2>&1", input.command);
56
57 let output = new_smol_command("bash")
58 .arg("-c")
59 .arg(&command)
60 .current_dir(working_directory)
61 .output()
62 .await
63 .context("Failed to execute bash command")?;
64
65 let output_string = String::from_utf8_lossy(&output.stdout).to_string();
66
67 if output.status.success() {
68 if output_string.is_empty() {
69 Ok("Command executed successfully.".to_string())
70 } else {
71 Ok(output_string)
72 }
73 } else {
74 Ok(format!(
75 "Command failed with exit code {}\n{}",
76 output.status.code().unwrap_or(-1),
77 &output_string
78 ))
79 }
80 })
81 }
82}