1use std::path::PathBuf;
4
5use async_trait::async_trait;
6use serde::Deserialize;
7use serde_json::{json, Value};
8use tokio_util::sync::CancellationToken;
9
10use crate::agent::tool::{AgentTool, ToolResult};
11use crate::tools::truncate::{format_size, truncate_head, DEFAULT_MAX_BYTES};
12use crate::tools::util::{display_path, resolve_to_cwd};
13
14const DEFAULT_ENTRY_LIMIT: usize = 500;
15
16pub struct LsTool {
17 pub cwd: PathBuf,
18}
19
20#[derive(Debug, Deserialize)]
21struct LsInput {
22 #[serde(default)]
23 path: Option<String>,
24 #[serde(default)]
25 limit: Option<usize>,
26}
27
28#[async_trait]
29impl AgentTool for LsTool {
30 fn name(&self) -> &str {
31 "ls"
32 }
33 fn description(&self) -> &str {
34 "List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to 500 entries or 50KB (whichever is hit first)."
35 }
36 fn input_schema(&self) -> Value {
37 json!({
38 "type": "object",
39 "properties": {
40 "path": { "type": "string", "description": "Directory to list (default: current directory)" },
41 "limit": { "type": "number", "description": "Maximum number of entries to return (default: 500)" }
42 }
43 })
44 }
45
46 async fn execute(&self, args: Value, _cancel: CancellationToken) -> anyhow::Result<ToolResult> {
47 let input: LsInput = serde_json::from_value(args)?;
48 let dir = resolve_to_cwd(input.path.as_deref().unwrap_or("."), &self.cwd);
49 let effective_limit = input.limit.unwrap_or(DEFAULT_ENTRY_LIMIT).max(1);
52 let display = display_path(input.path.as_deref().unwrap_or("."), &self.cwd);
53
54 if !dir.exists() {
55 anyhow::bail!("Path not found: {display}");
56 }
57 if !dir.is_dir() {
58 anyhow::bail!("Not a directory: {display}");
59 }
60
61 let mut entries: Vec<(String, bool)> = std::fs::read_dir(&dir)
62 .map_err(|e| anyhow::anyhow!("Cannot read directory: {e}"))?
63 .filter_map(Result::ok)
64 .map(|e| {
65 let name = e.file_name().to_string_lossy().to_string();
66 let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
67 (name, is_dir)
68 })
69 .collect();
70 entries.sort_by_key(|a| a.0.to_ascii_lowercase());
71
72 let mut results: Vec<String> = Vec::new();
73 let mut limit_reached = false;
74 for (name, is_dir) in entries {
75 if results.len() >= effective_limit {
76 limit_reached = true;
77 break;
78 }
79 results.push(if is_dir { format!("{name}/") } else { name });
80 }
81
82 if results.is_empty() {
83 return Ok(ToolResult::text("(empty directory)"));
84 }
85
86 let raw = results.join("\n");
87 let trunc = truncate_head(&raw, Some(usize::MAX), None);
89 let mut output = trunc.content;
90 let mut notices: Vec<String> = Vec::new();
91 if limit_reached {
92 notices.push(format!("{effective_limit} entries limit reached. Use limit={} for more", effective_limit * 2));
93 }
94 if trunc.truncated {
95 notices.push(format!("{} limit reached", format_size(DEFAULT_MAX_BYTES)));
96 }
97 if !notices.is_empty() {
98 output.push_str(&format!("\n\n[{}]", notices.join(". ")));
99 }
100 Ok(ToolResult::text(output))
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107 use crate::agent::tool::AgentTool;
108 use tokio_util::sync::CancellationToken;
109
110 fn scratch_dir(label: &str) -> PathBuf {
111 let dir = std::env::temp_dir()
112 .join(format!("pi-ls-test-{label}-{}", uuid::Uuid::new_v4()));
113 std::fs::create_dir_all(&dir).unwrap();
114 dir
115 }
116
117 async fn run_ls(cwd: PathBuf, args: serde_json::Value) -> String {
118 let tool = LsTool { cwd };
119 let res = tool.execute(args, CancellationToken::new()).await.unwrap();
120 match res.content.into_iter().next() {
121 Some(crate::ai::types::ToolResultContent::Text { text }) => text,
122 _ => panic!("expected text tool result"),
123 }
124 }
125
126 #[tokio::test]
127 async fn limit_zero_is_clamped_to_one_not_reported_empty() {
128 let dir = scratch_dir("zero-limit");
131 std::fs::write(dir.join("a.txt"), "x").unwrap();
132 std::fs::write(dir.join("b.txt"), "x").unwrap();
133
134 let out = run_ls(
135 dir.clone(),
136 serde_json::json!({ "path": dir.to_string_lossy(), "limit": 0 }),
137 )
138 .await;
139
140 assert!(
141 out.contains("a.txt"),
142 "limit:0 should be clamped to 1 and show an entry, got: {out}"
143 );
144 assert!(
145 !out.contains("empty directory"),
146 "limit:0 must not report '(empty directory)' when entries exist: {out}"
147 );
148
149 let _ = std::fs::remove_dir_all(&dir);
150 }
151}