1use anyhow::{anyhow, 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 ui::IconName;
10use util::markdown::MarkdownString;
11
12#[derive(Debug, Serialize, Deserialize, JsonSchema)]
13pub struct CreateDirectoryToolInput {
14 /// The path of the new directory.
15 ///
16 /// <example>
17 /// If the project has the following structure:
18 ///
19 /// - directory1/
20 /// - directory2/
21 ///
22 /// You can create a new directory by providing a path of "directory1/new_directory"
23 /// </example>
24 pub path: String,
25}
26
27pub struct CreateDirectoryTool;
28
29impl Tool for CreateDirectoryTool {
30 fn name(&self) -> String {
31 "create-directory".into()
32 }
33
34 fn needs_confirmation(&self) -> bool {
35 true
36 }
37
38 fn description(&self) -> String {
39 include_str!("./create_directory_tool/description.md").into()
40 }
41
42 fn icon(&self) -> IconName {
43 IconName::Folder
44 }
45
46 fn input_schema(&self) -> serde_json::Value {
47 let schema = schemars::schema_for!(CreateDirectoryToolInput);
48 serde_json::to_value(&schema).unwrap()
49 }
50
51 fn ui_text(&self, input: &serde_json::Value) -> String {
52 match serde_json::from_value::<CreateDirectoryToolInput>(input.clone()) {
53 Ok(input) => {
54 format!(
55 "Create directory {}",
56 MarkdownString::inline_code(&input.path)
57 )
58 }
59 Err(_) => "Create directory".to_string(),
60 }
61 }
62
63 fn run(
64 self: Arc<Self>,
65 input: serde_json::Value,
66 _messages: &[LanguageModelRequestMessage],
67 project: Entity<Project>,
68 _action_log: Entity<ActionLog>,
69 cx: &mut App,
70 ) -> Task<Result<String>> {
71 let input = match serde_json::from_value::<CreateDirectoryToolInput>(input) {
72 Ok(input) => input,
73 Err(err) => return Task::ready(Err(anyhow!(err))),
74 };
75 let project_path = match project.read(cx).find_project_path(&input.path, cx) {
76 Some(project_path) => project_path,
77 None => return Task::ready(Err(anyhow!("Path to create was outside the project"))),
78 };
79 let destination_path: Arc<str> = input.path.as_str().into();
80
81 cx.spawn(async move |cx| {
82 project
83 .update(cx, |project, cx| {
84 project.create_entry(project_path.clone(), true, cx)
85 })?
86 .await
87 .map_err(|err| anyhow!("Unable to create directory {destination_path}: {err}"))?;
88
89 Ok(format!("Created directory {destination_path}"))
90 })
91 }
92}