use rig::tool::{Tool, ToolContext};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{path::PathBuf, sync::Arc};
use tokio::sync::Mutex;
use crate::llm::package_resolver::PackageResolver;
#[derive(Deserialize, Serialize)]
pub struct ListDirArgs {
path: PathBuf,
#[serde(default)]
start: Option<usize>,
#[serde(default)]
root: Option<String>,
}
pub struct ListDir {
package_resolver: Arc<Mutex<PackageResolver>>,
max_results: Option<usize>,
has_pacmans: bool, }
impl ListDir {
pub async fn new(resolver: Arc<Mutex<PackageResolver>>, max_results: Option<usize>) -> Self {
let has_pacmans = !resolver.lock().await.list_pacmans().is_empty();
Self {
package_resolver: resolver,
max_results,
has_pacmans,
}
}
}
impl Tool for ListDir {
const NAME: &'static str = "list_dir";
type Error = super::ToolError;
type Args = ListDirArgs;
type Output = super::DirectoryListing;
async fn call(
&self,
_context: &mut ToolContext,
args: Self::Args,
) -> Result<Self::Output, Self::Error> {
let package_resolver = self.package_resolver.lock().await;
let base_dir = package_resolver.base_directory(args.root.as_deref())?;
let path = super::allowed_canonical_path(&args.path, std::path::Path::new(&base_dir))?;
let mut result = super::list_dir(&path, false)?;
result.total_entries = result.entries.len();
if let Some(max_results) = self.max_results
&& result.entries.len() > max_results
{
result.entries.truncate(max_results);
result.truncated = true;
}
Ok(result)
}
fn description(&self) -> String {
if !self.has_pacmans {
format!(
"List the files and directories in the given directory (relative to given root), \
returning {} entries. Use an empty string \"\" for the root. \
Results include both files and subdirectories with their types.",
match self.max_results {
Some(val) => format!("at most {}", val),
None => "all".to_string(),
}
)
} else {
format!(
"List the files and directories in the given directory (relative to workspace root), \
returning {} entries. Use an empty string \"\" for the workspace root. \
Results include both files and subdirectories with their types.",
match self.max_results {
Some(val) => format!("at most {}", val),
None => "all".to_string(),
}
)
}
}
fn parameters(&self) -> serde_json::Value {
let path_description = format!(
"Path to the directory relative to {} root directory. \
Use an empty string for the root directory.",
if self.has_pacmans {
"the given"
} else {
"workspace"
}
);
let mut params = json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": path_description
},
},
"required": ["path"]
});
if self.has_pacmans {
if let Some(props) = params["properties"].as_object_mut() {
props.insert(
"root".to_string(),
json!({
"type": "string",
"description": "Optional package/dependency identifier to use as the root \
directory instead of the workspace root. \
If not provided, the workspace root is used."
}),
);
}
}
params
}
fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
rig::tool::ToolExecutionError::from_error(error)
}
}