Skip to main content

rig_tools/
list.rs

1//! The `list` tool.
2
3use std::collections::BTreeSet;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use rig_core::completion::ToolAnnotations;
8use rig_core::tool::{
9    ContextValue, KeptEnd, OutputCut, Scope, Tool, ToolContext, ToolExecutionError, Touches,
10    args_schema,
11};
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14
15use crate::fs::{listed, shown};
16use crate::workspace::{Listing, Local, Workspace};
17use crate::{MAX_BYTES, MAX_LINES, blocking};
18
19/// Lists the files under a directory, as far down as asked, honouring
20/// `.gitignore` ([`Listing::Visible`], or [`Listing::Hidden`] when asked or
21/// when the glob names a hidden path): one path per line below the listed directory, and each
22/// directory deeper than the listing goes once, as `dir/`. Publishes what
23/// it listed ([`FilesListed`]) and, when the list was cut, [`OutputCut`].
24#[derive(Clone, Debug)]
25pub struct List {
26    /// Where the files are listed.
27    pub workspace: Arc<dyn Workspace>,
28    /// The directory a relative path is listed from; `None` is the
29    /// workspace's working directory.
30    pub base: Option<PathBuf>,
31    /// Whether a path that resolves outside `base` is refused, before
32    /// anything is listed.
33    pub confine: bool,
34}
35
36impl Default for List {
37    /// Lists this machine's files, from this process's working directory.
38    fn default() -> Self {
39        Self {
40            workspace: Arc::new(Local),
41            base: None,
42            confine: false,
43        }
44    }
45}
46
47/// Arguments of [`List`].
48#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, JsonSchema)]
49#[serde(deny_unknown_fields)]
50pub struct ListArgs {
51    /// The directory to list; default the current directory.
52    pub path: Option<String>,
53    /// How many levels down to list: 1 lists the directory's own entries;
54    /// default every level.
55    pub depth: Option<usize>,
56    /// Only files matching this glob, such as `*.rs`.
57    pub glob: Option<String>,
58    /// Also hidden files and directories (named with a leading `.`), such
59    /// as `.github/`; files git ignores stay out.
60    #[serde(default)]
61    pub hidden: bool,
62}
63
64impl ListArgs {
65    /// List `path`.
66    pub fn new(path: impl Into<String>) -> Self {
67        Self {
68            path: Some(path.into()),
69            ..Self::default()
70        }
71    }
72
73    /// The same listing, `depth` levels down.
74    pub fn depth(mut self, depth: usize) -> Self {
75        self.depth = Some(depth);
76        self
77    }
78
79    /// The same listing, only of files matching `glob`.
80    pub fn glob(mut self, glob: impl Into<String>) -> Self {
81        self.glob = Some(glob.into());
82        self
83    }
84
85    /// The same listing, hidden files included.
86    pub fn hidden(mut self) -> Self {
87        self.hidden = true;
88        self
89    }
90
91    /// Which files it lists.
92    pub fn listing(&self) -> Listing {
93        Listing::from_options(self.hidden, self.glob.as_deref())
94    }
95}
96
97/// What a [`List`] call listed, as it published it beside the text.
98#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99pub struct FilesListed {
100    /// The listed directory, [resolved](Workspace).
101    pub root: String,
102    /// The entries shown, below `root`, in order: files, and directories
103    /// deeper than the listing with a trailing `/`. One starting with a
104    /// folder named `~` starts with `./~`.
105    pub entries: Vec<String>,
106}
107
108impl ContextValue for FilesListed {
109    const KEY: &'static str = "files_listed";
110}
111
112impl Tool for List {
113    const NAME: &'static str = "list";
114    type Args = ListArgs;
115    type Output = String;
116    type Error = ToolExecutionError;
117
118    fn description(&self) -> String {
119        format!(
120            "List the files under a directory, sorted, one path per line below it. Skips files \
121             ignored by git, target directories and, unless hidden is set or the glob names \
122             one, hidden files. With depth, directories below that depth are listed once as \
123             `dir/`. At most {MAX_LINES} lines or {} KB. Use it to see what files a directory \
124             holds, not `ls` or `find` in `shell`.",
125            MAX_BYTES / 1024
126        )
127    }
128
129    fn parameters(&self) -> serde_json::Value {
130        args_schema::<ListArgs>()
131    }
132
133    fn annotations(&self) -> ToolAnnotations {
134        ToolAnnotations::default()
135            .with_read_only(true)
136            .with_open_world(false)
137    }
138
139    fn footprint(&self, args: &ListArgs) -> Touches {
140        Touches::Reads(Scope::Paths(vec![
141            self.workspace
142                .resolve(self.base.as_deref(), args.path.as_deref().unwrap_or(".")),
143        ]))
144    }
145
146    async fn call(
147        &self,
148        context: &mut ToolContext,
149        args: ListArgs,
150    ) -> Result<String, ToolExecutionError> {
151        let root = self.workspace.place(
152            self.base.as_deref(),
153            self.confine,
154            args.path.as_deref().unwrap_or("."),
155        )?;
156        let workspace = self.workspace.clone();
157        let (text, listed, cut) = blocking(move || list(&*workspace, &root, &args)).await?;
158        context.insert_result(listed)?;
159        if let Some(cut) = cut {
160            context.insert_result(cut)?;
161        }
162        Ok(text)
163    }
164}
165
166/// Lists `root` in `workspace` as [`List`] does: the text, what it shows,
167/// and how it was cut.
168fn list(
169    workspace: &dyn Workspace,
170    root: &Path,
171    args: &ListArgs,
172) -> Result<(String, FilesListed, Option<OutputCut>), ToolExecutionError> {
173    let files = listed(workspace, root, args.glob.as_deref(), args.listing())?;
174    let depth = args.depth.unwrap_or(usize::MAX).max(1);
175    let entries: BTreeSet<String> = files
176        .iter()
177        .filter_map(|file| {
178            let below = file.strip_prefix(root).ok()?;
179            let parts: Vec<_> = below.iter().collect();
180            Some(match parts.get(..depth) {
181                Some(kept) if kept.len() < parts.len() => {
182                    format!("{}/", shown(&kept.iter().collect::<PathBuf>()).display())
183                }
184                _ if below.as_os_str().is_empty() => file.to_string_lossy().into_owned(),
185                _ => shown(below).to_string_lossy().into_owned(),
186            })
187        })
188        .collect();
189    let total = entries.len();
190    let mut text = String::new();
191    let mut kept = Vec::new();
192    for entry in entries {
193        if kept.len() == MAX_LINES || text.len() + entry.len() + 1 > MAX_BYTES {
194            break;
195        }
196        text.push_str(&entry);
197        text.push('\n');
198        kept.push(entry);
199    }
200    let cut = (kept.len() < total).then(|| {
201        text.push_str(&format!(
202            "[{} more entries; narrow the listing with path, depth or glob]\n",
203            total - kept.len()
204        ));
205        OutputCut {
206            kept: KeptEnd::Start,
207            kept_lines: kept.len(),
208            total_lines: total,
209            spill: None,
210        }
211    });
212    if total == 0 {
213        text.push_str("No files.\n");
214    }
215    let listed = FilesListed {
216        root: root.to_string_lossy().into_owned(),
217        entries: kept,
218    };
219    Ok((text, listed, cut))
220}
221
222#[cfg(test)]
223mod tests;