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 needs_confirmation(&self) -> bool {
27 true
28 }
29
30 fn description(&self) -> String {
31 include_str!("./bash_tool/description.md").to_string()
32 }
33
34 fn input_schema(&self) -> serde_json::Value {
35 let schema = schemars::schema_for!(BashToolInput);
36 serde_json::to_value(&schema).unwrap()
37 }
38
39 fn ui_text(&self, input: &serde_json::Value) -> String {
40 match serde_json::from_value::<BashToolInput>(input.clone()) {
41 Ok(input) => format!("`$ {}`", input.command),
42 Err(_) => "Run bash command".to_string(),
43 }
44 }
45
46 fn run(
47 self: Arc<Self>,
48 input: serde_json::Value,
49 _messages: &[LanguageModelRequestMessage],
50 project: Entity<Project>,
51 _action_log: Entity<ActionLog>,
52 cx: &mut App,
53 ) -> Task<Result<String>> {
54 let input: BashToolInput = match serde_json::from_value(input) {
55 Ok(input) => input,
56 Err(err) => return Task::ready(Err(anyhow!(err))),
57 };
58
59 let Some(worktree) = project.read(cx).worktree_for_root_name(&input.cd, cx) else {
60 return Task::ready(Err(anyhow!("Working directory not found in the project")));
61 };
62 let working_directory = worktree.read(cx).abs_path();
63
64 cx.spawn(async move |_| {
65 // Add 2>&1 to merge stderr into stdout for proper interleaving.
66 let command = format!("({}) 2>&1", input.command);
67
68 let output = new_smol_command("bash")
69 .arg("-c")
70 .arg(&command)
71 .current_dir(working_directory)
72 .output()
73 .await
74 .context("Failed to execute bash command")?;
75
76 let output_string = String::from_utf8_lossy(&output.stdout).to_string();
77
78 if output.status.success() {
79 if output_string.is_empty() {
80 Ok("Command executed successfully.".to_string())
81 } else {
82 Ok(output_string)
83 }
84 } else {
85 Ok(format!(
86 "Command failed with exit code {}\n{}",
87 output.status.code().unwrap_or(-1),
88 &output_string
89 ))
90 }
91 })
92 }
93}