create_directory_tool.rs

 1use agent_client_protocol::ToolKind;
 2use anyhow::{Context as _, Result, anyhow};
 3use gpui::{App, Entity, SharedString, Task};
 4use project::Project;
 5use schemars::JsonSchema;
 6use serde::{Deserialize, Serialize};
 7use std::sync::Arc;
 8use util::markdown::MarkdownInlineCode;
 9
10use crate::{AgentTool, ToolCallEventStream};
11
12/// Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.
13///
14/// This tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.
15#[derive(Debug, Serialize, Deserialize, JsonSchema)]
16pub struct CreateDirectoryToolInput {
17    /// The path of the new directory.
18    ///
19    /// <example>
20    /// If the project has the following structure:
21    ///
22    /// - directory1/
23    /// - directory2/
24    ///
25    /// You can create a new directory by providing a path of "directory1/new_directory"
26    /// </example>
27    pub path: String,
28}
29
30pub struct CreateDirectoryTool {
31    project: Entity<Project>,
32}
33
34impl CreateDirectoryTool {
35    pub const fn new(project: Entity<Project>) -> Self {
36        Self { project }
37    }
38}
39
40impl AgentTool for CreateDirectoryTool {
41    type Input = CreateDirectoryToolInput;
42    type Output = String;
43
44    fn name() -> &'static str {
45        "create_directory"
46    }
47
48    fn kind() -> ToolKind {
49        ToolKind::Read
50    }
51
52    fn initial_title(
53        &self,
54        input: Result<Self::Input, serde_json::Value>,
55        _cx: &mut App,
56    ) -> SharedString {
57        if let Ok(input) = input {
58            format!("Create directory {}", MarkdownInlineCode(&input.path)).into()
59        } else {
60            "Create directory".into()
61        }
62    }
63
64    fn run(
65        self: Arc<Self>,
66        input: Self::Input,
67        _event_stream: ToolCallEventStream,
68        cx: &mut App,
69    ) -> Task<Result<Self::Output>> {
70        let project_path = match self.project.read(cx).find_project_path(&input.path, cx) {
71            Some(project_path) => project_path,
72            None => {
73                return Task::ready(Err(anyhow!("Path to create was outside the project")));
74            }
75        };
76        let destination_path: Arc<str> = input.path.as_str().into();
77
78        let create_entry = self.project.update(cx, |project, cx| {
79            project.create_entry(project_path.clone(), true, cx)
80        });
81
82        cx.spawn(async move |_cx| {
83            create_entry
84                .await
85                .with_context(|| format!("Creating directory {destination_path}"))?;
86
87            Ok(format!("Created directory {destination_path}"))
88        })
89    }
90}