Skip to main content

rig_tools/
lib.rs

1#![deny(missing_docs)]
2//! Coding tools for Rig agents: [`Read`], [`Write`], [`Edit`], [`Search`], [`List`],
3//! [`Shell`], [`Delete`] and [`Move`].
4//!
5//! - Each says in its description when to pick it, and what it may touch
6//!   ([`footprint`](rig_core::tool::Tool::footprint)): `read`, `search` and `list` read the
7//!   path they name, the other file tools write theirs, and `shell` may change anything, so a
8//!   host runs calls on different files side by side.
9//! - Each publishes what it did beside its text: files read
10//!   ([`FilesRead`](rig_core::tool::FilesRead)), [`SearchHits`], [`FilesListed`], files changed
11//!   with their diffs ([`FilesChanged`](rig_core::tool::FilesChanged)), how a command ended
12//!   ([`ExitStatus`](rig_core::tool::ExitStatus)).
13//! - Each acts on a [`Workspace`](workspace::Workspace): this machine
14//!   ([`Local`](workspace::Local), the default) or another. The file tools resolve paths from an
15//!   optional base directory they can be confined to. A path whose first component is `~` is in
16//!   the home directory; `./~` is a folder named `~`.
17//! - `shell` reports its output as it comes to a [`Live`]. Arguments are plain data with public
18//!   fields.
19//!
20//! Also the pieces they are made of, for tools of your own:
21//! - [`edit::apply`]: what `edit` makes of a file's text, without the file,
22//!   and [`ReadArgs::show`]: what `read` shows of it;
23//! - [`workspace`]: the disk and the commands the tools act on,
24//!   [`overlay`]: one that keeps the tools' writes from the disk, to
25//!   preview them, and [`remote`]: another machine reached through a
26//!   transport such as `ssh`, and paths written `HOST:PATH` that reach it;
27//! - [`attach`]: the files a message names as `@path`, read to go with it;
28//! - [`checkpoint`]: the files under a root at one moment, what changed by
29//!   a later one, and a handler that reports what any call changed;
30//! - [`clipboard`]: the system clipboard's text and images;
31//! - [`fs`]: an atomic file write and capped text reads on this machine;
32//! - [`show_lines`]: some lines of a text, the way `read` shows a file;
33//! - [`Spill`]: where output a tool cut is kept whole, and [`OutputLimit`]: how
34//!   much of a long output is kept;
35//! - [`process`]: child processes in a process group of their own, the
36//!   [`Launcher`](process::Launcher) that says how tools start them, and
37//!   the [`Process`](process::Process) it spawns: input in, output line by
38//!   line, stopped gently or killed with its group;
39//! - [`blocking`]: blocking work on a thread of its own, so no async
40//!   executor thread blocks.
41//!
42//! Native only: the tools use the file system and processes.
43
44use unicode_width::{UnicodeWidthChar as _, UnicodeWidthStr as _};
45
46pub mod attach;
47mod blocking;
48pub mod checkpoint;
49pub mod clipboard;
50mod delete;
51pub mod edit;
52pub mod fs;
53mod list;
54mod live;
55mod move_file;
56pub mod overlay;
57pub mod process;
58mod read;
59pub mod remote;
60mod search;
61mod shell;
62mod spill;
63mod watch;
64pub mod workspace;
65mod write;
66
67pub use blocking::blocking;
68pub use delete::{Delete, DeleteArgs};
69pub use edit::{Edit, EditArgs, Replacement};
70pub use list::{FilesListed, List, ListArgs};
71pub use live::Live;
72pub use move_file::{Move, MoveArgs};
73pub use read::{Read, ReadArgs, Seen, show_lines};
74pub use search::{
75    Found, Hit, MAX_FILES, MAX_MATCHES, Search, SearchArgs, SearchHits, find, render,
76};
77pub use shell::{Shell, ShellArgs, ShellRun, split_status};
78pub use spill::Spill;
79pub use write::{Write, WriteArgs};
80
81/// Most lines a tool returns.
82pub const MAX_LINES: usize = 2000;
83/// Most bytes a tool returns.
84pub const MAX_BYTES: usize = 50 * 1024;
85/// The largest file `read` and `edit` load whole, and `search` scans.
86pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
87/// Characters of one line `read` and `shell` show; the rest of a longer
88/// line is cut.
89const MAX_LINE_CHARS: usize = 2000;
90/// What marks a line that was cut.
91const CUT_MARK: &str = " […]";
92
93/// How much of a long output a tool keeps: at most `lines` lines and
94/// `bytes` bytes, of whole lines. [`tail`](Self::tail) keeps the last ones;
95/// [`Shell`] keeps a quarter for the first lines, a quarter for the errors
96/// and failures from between, and the rest for the last lines.
97///
98/// ```
99/// use rig_tools::OutputLimit;
100///
101/// let cut = OutputLimit { lines: 2, bytes: 1024 };
102/// assert_eq!(cut.tail("one\ntwo\nthree\n"), ("two\nthree\n", 1));
103/// let narrow = OutputLimit { lines: 10, bytes: 7 };
104/// assert_eq!(narrow.tail("one\ntwo\nthree\n"), ("three\n", 2));
105/// ```
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub struct OutputLimit {
108    /// Most lines kept.
109    pub lines: usize,
110    /// Most bytes kept.
111    pub bytes: usize,
112}
113
114impl Default for OutputLimit {
115    /// [`MAX_LINES`] lines or [`MAX_BYTES`] bytes.
116    fn default() -> Self {
117        Self {
118            lines: MAX_LINES,
119            bytes: MAX_BYTES,
120        }
121    }
122}
123
124impl OutputLimit {
125    /// The end of `text` this keeps, starting at a line, and how many lines
126    /// before it were left out. When even the last line is longer than
127    /// [`bytes`](Self::bytes), nothing is kept.
128    pub fn tail<'t>(&self, text: &'t str) -> (&'t str, usize) {
129        let starts: Vec<usize> = std::iter::once(0)
130            .chain(text.match_indices('\n').map(|(at, _)| at + 1))
131            .filter(|start| *start < text.len())
132            .collect();
133        let first = starts.len().saturating_sub(self.lines);
134        let kept = starts
135            .iter()
136            .enumerate()
137            .skip(first)
138            .find(|(_, start)| text.len() - **start <= self.bytes);
139        match kept {
140            Some((dropped, start)) => (text.get(*start..).unwrap_or_default(), dropped),
141            None => ("", starts.len()),
142        }
143    }
144}
145
146/// `line` cut to its first `limit` characters.
147pub fn clip(line: &str, limit: usize) -> &str {
148    match line.char_indices().nth(limit) {
149        Some((end, _)) => line.get(..end).unwrap_or(line),
150        None => line,
151    }
152}
153
154/// `text` quoted for `sh`.
155pub(crate) fn quote(text: &str) -> String {
156    format!("'{}'", text.replace('\'', "'\\''"))
157}
158
159/// `path`, a path a file tool resolved, quoted for a command in `shell`:
160/// `None` when it is not absolute for `sh`, such as a remote `~/` path, a
161/// `HOST:PATH` or a Windows path, which `shell` would not find as written.
162pub(crate) fn shell_path(path: &str) -> Option<String> {
163    path.starts_with('/').then(|| quote(path))
164}
165
166/// `text` cut to fit in `width` terminal columns, ending in `…` when cut:
167/// a wide character, such as most CJK ones, takes two columns.
168///
169/// ```
170/// use rig_tools::shorten;
171///
172/// assert_eq!(shorten("a short label", 20), "a short label");
173/// assert_eq!(shorten("a longer label", 9), "a longer…");
174/// assert_eq!(shorten("日本語のラベル", 7), "日本語…");
175/// ```
176pub fn shorten(text: &str, width: usize) -> String {
177    if text.width() <= width {
178        return text.to_owned();
179    }
180    let room = width.saturating_sub(1);
181    let mut used = 0;
182    let end = text
183        .char_indices()
184        .find(|(_, character)| {
185            used += character.width().unwrap_or(0);
186            used > room
187        })
188        .map_or(text.len(), |(at, _)| at);
189    match width {
190        0 => String::new(),
191        _ => format!("{}…", text.get(..end).unwrap_or_default()),
192    }
193}
194
195/// How long ago `elapsed` was, roughly, for a list a person reads:
196/// `just now`, `3m ago`, `5h ago`, `2d ago`.
197///
198/// ```
199/// use std::time::Duration;
200/// use rig_tools::ago;
201///
202/// assert_eq!(ago(Duration::from_secs(30)), "just now");
203/// assert_eq!(ago(Duration::from_secs(5 * 3600 + 59)), "5h ago");
204/// ```
205pub fn ago(elapsed: std::time::Duration) -> String {
206    let seconds = elapsed.as_secs();
207    match seconds {
208        0..60 => "just now".to_owned(),
209        60..3600 => format!("{}m ago", seconds / 60),
210        3600..86_400 => format!("{}h ago", seconds / 3600),
211        _ => format!("{}d ago", seconds / 86_400),
212    }
213}
214
215#[cfg(test)]
216mod tests;