Skip to main content

rig_core/tool/
facts.rs

1//! Facts a tool call publishes about what it did, beside the text the model
2//! reads: the files it read ([`FilesRead`]), the files it changed
3//! ([`FilesChanged`]), how a process it ran ended ([`ExitStatus`]) and
4//! whether its output was cut to fit ([`OutputCut`]). A
5//! file's [`ContentHash`] says which content the tool saw or left, so a
6//! host can tell whether a file changed since without reading it again; a
7//! change's [`FileState`]s also give each side's size and lines.
8//! They are [`ContextValue`]s a tool publishes with
9//! [`ToolContext::insert_result`](super::ToolContext::insert_result), so
10//! they reach the host in the call's [`ToolResultContext`](super::ToolResultContext)
11//! and the effect log, whatever the tool: a built-in one, a plugin's, or an
12//! MCP server's adapter. A host reads them back with
13//! [`ToolResultContext::get`](super::ToolResultContext::get).
14//!
15//! ```
16//! use rig_core::tool::{
17//!     ExitStatus, FileChange, FileRead, FilesChanged, FilesRead, ToolContext, content_hash,
18//! };
19//!
20//! let mut context = ToolContext::new();
21//! let readme = FileRead::new("/work/README.md", content_hash(b"# Work\n"));
22//! context.insert_result(FilesRead(vec![readme]))?;
23//! context.insert_result(FilesChanged(vec![FileChange::modified("/work/src/lib.rs", 3, 1)]))?;
24//! context.insert_result(ExitStatus::Exited(0))?;
25//! let published = context.result_context();
26//! assert_eq!(published.get::<ExitStatus>()?.map(|status| status.success()), Some(true));
27//! let changed = published.get::<FilesChanged>()?.unwrap_or_default();
28//! assert_eq!(changed.paths().collect::<Vec<_>>(), ["/work/src/lib.rs"]);
29//! let read = published.get::<FilesRead>()?.unwrap_or_default();
30//! assert_eq!(read.paths().collect::<Vec<_>>(), ["/work/README.md"]);
31//! assert_eq!(read.0.first().map(|file| &file.hash), Some(&content_hash(b"# Work\n")));
32//! # Ok::<(), rig_core::tool::ToolContextError>(())
33//! ```
34
35use std::fmt::{self, Write as _};
36
37use serde::{Deserialize, Serialize};
38
39use super::ContextValue;
40
41/// The SHA-256 of a file's bytes, as lowercase hex: which content a tool
42/// read or left ([`content_hash`]).
43#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(transparent)]
45pub struct ContentHash(pub String);
46
47/// The [`ContentHash`] of `bytes`.
48///
49/// ```
50/// use rig_core::tool::content_hash;
51///
52/// assert_eq!(
53///     content_hash(b"").0,
54///     "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
55/// );
56/// ```
57pub fn content_hash(bytes: &[u8]) -> ContentHash {
58    use sha2::Digest as _;
59    let digest = sha2::Sha256::digest(bytes);
60    ContentHash(digest.iter().map(|byte| format!("{byte:02x}")).collect())
61}
62
63/// The files a tool call read, in the order it read them, each once: a
64/// file it showed the model, or one it found matches in.
65#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(transparent)]
67pub struct FilesRead(pub Vec<FileRead>);
68
69impl ContextValue for FilesRead {
70    const KEY: &'static str = "files_read";
71}
72
73impl FilesRead {
74    /// The read files' paths, in order.
75    pub fn paths(&self) -> impl Iterator<Item = &str> {
76        self.0.iter().map(|file| file.path.as_str())
77    }
78}
79
80/// One file a tool call read.
81#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
82pub struct FileRead {
83    /// The file, as [`FileChange::path`] spells it.
84    pub path: String,
85    /// The hash of the bytes the tool read.
86    pub hash: ContentHash,
87    /// Which of its lines the tool showed, when it showed some of them
88    /// rather than matches in it.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub lines: Option<LinesShown>,
91}
92
93impl FileRead {
94    /// `path` was read, and held the content `hash` names.
95    pub fn new(path: impl Into<String>, hash: ContentHash) -> Self {
96        Self {
97            path: path.into(),
98            hash,
99            lines: None,
100        }
101    }
102
103    /// This read, having shown `lines` of the file.
104    #[must_use]
105    pub fn with_lines(mut self, lines: LinesShown) -> Self {
106        self.lines = Some(lines);
107        self
108    }
109}
110
111/// The lines of a file a tool showed: `count` lines from line `first`, of
112/// the `total` it has.
113///
114/// ```
115/// use rig_core::tool::LinesShown;
116///
117/// assert!(LinesShown { first: 1, count: 3, total: 3 }.whole());
118/// assert!(!LinesShown { first: 2, count: 2, total: 3 }.whole());
119/// ```
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
121pub struct LinesShown {
122    /// The first line shown, counted from 1.
123    pub first: usize,
124    /// How many lines were shown.
125    pub count: usize,
126    /// How many lines the file has.
127    pub total: usize,
128}
129
130impl LinesShown {
131    /// Whether every line of the file was shown.
132    pub fn whole(&self) -> bool {
133        self.first <= 1 && self.count >= self.total
134    }
135}
136
137/// The files a tool call changed, in the order it changed them. The file
138/// tools publish it for what they write. A tool that does not publish it,
139/// such as `shell`, says nothing about the files it changed.
140#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(transparent)]
142pub struct FilesChanged(pub Vec<FileChange>);
143
144impl ContextValue for FilesChanged {
145    const KEY: &'static str = "files_changed";
146}
147
148impl FilesChanged {
149    /// The changed files' paths, in order.
150    pub fn paths(&self) -> impl Iterator<Item = &str> {
151        self.0.iter().map(|change| change.path.as_str())
152    }
153}
154
155/// One file a tool call changed.
156#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157pub struct FileChange {
158    /// The file: an absolute path when the tool knows the directory it ran
159    /// in, else as the call named it.
160    pub path: String,
161    /// What happened to it.
162    pub kind: ChangeKind,
163    /// Lines added.
164    pub added: usize,
165    /// Lines removed.
166    pub removed: usize,
167    /// The change as hunks, each line with its ending, with three lines of
168    /// context; none when the tool did not diff the file (such as one too
169    /// large to read). [`unified`](Self::unified) renders them as a diff.
170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171    pub hunks: Vec<Hunk>,
172    /// The file's text before the change, when the tool read it whole as
173    /// UTF-8 within its read limit; `None` for a created file.
174    /// [`after_text`](Self::after_text) is it with the hunks applied.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub before_text: Option<String>,
177    /// The file before the change, when the tool or a checkpoint around it
178    /// knows it; `None` for a created file.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub before: Option<FileState>,
181    /// The file the change left, when the tool knows it; `None` for a
182    /// deleted file.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub after: Option<FileState>,
185}
186
187/// A file on one side of a [`FileChange`]: as it was before the change, or
188/// as the change left it.
189///
190/// ```
191/// use rig_core::tool::{FileState, content_hash};
192///
193/// let state = FileState::of(b"one\ntwo");
194/// assert_eq!((state.bytes, state.lines), (7, Some(2)));
195/// assert_eq!(state.hash, Some(content_hash(b"one\ntwo")));
196/// ```
197#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
198pub struct FileState {
199    /// Its size in bytes.
200    pub bytes: u64,
201    /// Its lines, as [`str::lines`] counts them, when it was read (not
202    /// when it was too large to read).
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub lines: Option<usize>,
205    /// The hash of its bytes, when it was read.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub hash: Option<ContentHash>,
208}
209
210impl FileState {
211    /// A file that held `bytes`, read whole.
212    pub fn of(bytes: &[u8]) -> Self {
213        let breaks = bytes.iter().filter(|byte| **byte == b'\n').count();
214        let unended = !bytes.is_empty() && !bytes.ends_with(b"\n");
215        Self {
216            bytes: bytes.len() as u64,
217            lines: Some(breaks + usize::from(unended)),
218            hash: Some(content_hash(bytes)),
219        }
220    }
221
222    /// A file of `bytes` bytes that was not read, such as one too large to.
223    pub fn unread(bytes: u64) -> Self {
224        Self {
225            bytes,
226            lines: None,
227            hash: None,
228        }
229    }
230}
231
232impl FileChange {
233    fn new(path: impl Into<String>, kind: ChangeKind, added: usize, removed: usize) -> Self {
234        Self {
235            path: path.into(),
236            kind,
237            added,
238            removed,
239            hunks: Vec::new(),
240            before_text: None,
241            before: None,
242            after: None,
243        }
244    }
245
246    /// `path` was created with `lines` lines.
247    pub fn created(path: impl Into<String>, lines: usize) -> Self {
248        Self::new(path, ChangeKind::Created, lines, 0)
249    }
250
251    /// `path` was changed: `added` lines added and `removed` removed.
252    pub fn modified(path: impl Into<String>, added: usize, removed: usize) -> Self {
253        Self::new(path, ChangeKind::Modified, added, removed)
254    }
255
256    /// `path`, which had `lines` lines, was deleted.
257    pub fn deleted(path: impl Into<String>, lines: usize) -> Self {
258        Self::new(path, ChangeKind::Deleted, 0, lines)
259    }
260
261    /// This change, made by `hunks`.
262    #[must_use]
263    pub fn with_hunks(mut self, hunks: Vec<Hunk>) -> Self {
264        self.hunks = hunks;
265        self
266    }
267
268    /// This change, made to a file that held `text`.
269    #[must_use]
270    pub fn with_before_text(mut self, text: impl Into<String>) -> Self {
271        self.before_text = Some(text.into());
272        self
273    }
274
275    /// The change as a unified diff, its hunks under a `---`/`+++` header
276    /// naming the path (`/dev/null` on the side with no file); empty when
277    /// it has no hunks.
278    ///
279    /// ```
280    /// use rig_core::tool::{FileChange, Hunk, HunkLine, Lines};
281    ///
282    /// let change = FileChange::modified("a.rs", 1, 1).with_hunks(vec![Hunk {
283    ///     old: Lines { start: 1, count: 2 },
284    ///     new: Lines { start: 1, count: 2 },
285    ///     lines: vec![
286    ///         HunkLine::Same("one\n".into()),
287    ///         HunkLine::Removed("two\n".into()),
288    ///         HunkLine::Added("2".into()),
289    ///     ],
290    /// }]);
291    /// assert_eq!(
292    ///     change.unified(),
293    ///     "--- a.rs\n+++ a.rs\n@@ -1,2 +1,2 @@\n one\n-two\n+2\n\\ No newline at end of file\n"
294    /// );
295    /// ```
296    pub fn unified(&self) -> String {
297        if self.hunks.is_empty() {
298            return String::new();
299        }
300        let side = |gone| {
301            if self.kind == gone {
302                "/dev/null"
303            } else {
304                self.path.as_str()
305            }
306        };
307        let mut out = format!(
308            "--- {}\n+++ {}\n",
309            side(ChangeKind::Created),
310            side(ChangeKind::Deleted)
311        );
312        for hunk in &self.hunks {
313            let _ = writeln!(out, "@@ -{} +{} @@", hunk.old, hunk.new);
314            for line in &hunk.lines {
315                out.push(line.sign());
316                out.push_str(line.text());
317                if !line.text().ends_with(['\r', '\n']) {
318                    out.push_str("\n\\ No newline at end of file\n");
319                }
320            }
321        }
322        out
323    }
324
325    /// The file's text after the change: [`before_text`](Self::before_text)
326    /// (empty for a created file) with the hunks applied. `None` for a
327    /// deleted file, when the text before is not known, or when the hunks
328    /// do not make the whole change (they do not count the lines
329    /// [`added`](Self::added) and [`removed`](Self::removed), or do not fit
330    /// the text before).
331    ///
332    /// ```
333    /// use rig_core::tool::{FileChange, Hunk, HunkLine, Lines};
334    ///
335    /// let change = FileChange::modified("a.rs", 1, 1)
336    ///     .with_before_text("one\ntwo\n")
337    ///     .with_hunks(vec![Hunk {
338    ///         old: Lines { start: 2, count: 1 },
339    ///         new: Lines { start: 2, count: 1 },
340    ///         lines: vec![HunkLine::Removed("two\n".into()), HunkLine::Added("2\n".into())],
341    ///     }]);
342    /// assert_eq!(change.after_text().as_deref(), Some("one\n2\n"));
343    /// assert_eq!(change.changed_lines().collect::<Vec<_>>(), [2]);
344    /// ```
345    pub fn after_text(&self) -> Option<String> {
346        let before = match self.kind {
347            ChangeKind::Deleted => return None,
348            ChangeKind::Created => "",
349            ChangeKind::Modified => self.before_text.as_deref()?,
350        };
351        let lines = self.hunks.iter().flat_map(|hunk| &hunk.lines);
352        let counted = |sign| lines.clone().filter(|line| line.sign() == sign).count();
353        if (counted('+'), counted('-')) != (self.added, self.removed) {
354            return None;
355        }
356        let mut old = text_lines(before);
357        let mut next = 1;
358        let mut out = String::with_capacity(before.len());
359        for hunk in &self.hunks {
360            while next < hunk.old.start {
361                out.push_str(old.next()?);
362                next += 1;
363            }
364            for line in &hunk.lines {
365                if let HunkLine::Added(text) = line {
366                    out.push_str(text);
367                    continue;
368                }
369                if old.next()? != line.text() {
370                    return None;
371                }
372                next += 1;
373                if let HunkLine::Same(text) = line {
374                    out.push_str(text);
375                }
376            }
377        }
378        out.extend(old);
379        Some(out)
380    }
381
382    /// The lines the change added or rewrote, counted from 1 in the file
383    /// after it.
384    pub fn changed_lines(&self) -> impl Iterator<Item = usize> + '_ {
385        self.hunks.iter().flat_map(|hunk| {
386            let new = hunk.lines.iter().filter(|line| line.sign() != '-');
387            new.zip(hunk.new.start..)
388                .filter_map(|(line, at)| matches!(line, HunkLine::Added(_)).then_some(at))
389        })
390    }
391
392    /// This change, made to the file `before`.
393    #[must_use]
394    pub fn with_before(mut self, before: FileState) -> Self {
395        self.before = Some(before);
396        self
397    }
398
399    /// This change, leaving the file `after`.
400    #[must_use]
401    pub fn with_after(mut self, after: FileState) -> Self {
402        self.after = Some(after);
403        self
404    }
405}
406
407/// One run of a [`FileChange`]: the lines it removed and added, between
408/// the lines around them it kept.
409#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
410pub struct Hunk {
411    /// The lines of the file before the change that it spans.
412    pub old: Lines,
413    /// The lines of the file after the change that it spans.
414    pub new: Lines,
415    /// Its lines in order, each with its line ending (`\n`, `\r\n` or a
416    /// lone `\r`; none on a last line that has none).
417    pub lines: Vec<HunkLine>,
418}
419
420/// Lines of a file that a [`Hunk`] spans: `count` lines from line `start`,
421/// counted from 1. An empty span starts at the line it comes before. Shown
422/// as a unified diff's range (`3,2`; `3`; `2,0` for an empty one before
423/// line 3).
424#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
425pub struct Lines {
426    /// The first line.
427    pub start: usize,
428    /// How many lines.
429    pub count: usize,
430}
431
432impl fmt::Display for Lines {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        match self.count {
435            1 => write!(f, "{}", self.start),
436            0 => write!(f, "{},0", self.start.saturating_sub(1)),
437            count => write!(f, "{},{count}", self.start),
438        }
439    }
440}
441
442/// A line of a [`Hunk`], with its ending. Its wire form is the line as a
443/// unified diff shows it: its sign (` `, `-` or `+`), then its text.
444#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
445#[serde(into = "String", try_from = "String")]
446pub enum HunkLine {
447    /// A line the change kept, around those it changed.
448    Same(String),
449    /// A line of the file before that the change removed.
450    Removed(String),
451    /// A line of the file after that the change added.
452    Added(String),
453}
454
455impl HunkLine {
456    /// The line's text, with its ending.
457    pub fn text(&self) -> &str {
458        match self {
459            Self::Same(text) | Self::Removed(text) | Self::Added(text) => text,
460        }
461    }
462
463    /// Its sign in a unified diff: ` `, `-` or `+`.
464    pub fn sign(&self) -> char {
465        match self {
466            Self::Same(_) => ' ',
467            Self::Removed(_) => '-',
468            Self::Added(_) => '+',
469        }
470    }
471}
472
473impl From<HunkLine> for String {
474    fn from(line: HunkLine) -> Self {
475        let sign = line.sign();
476        let (HunkLine::Same(mut text) | HunkLine::Removed(mut text) | HunkLine::Added(mut text)) =
477            line;
478        text.insert(0, sign);
479        text
480    }
481}
482
483impl TryFrom<String> for HunkLine {
484    type Error = String;
485
486    fn try_from(mut line: String) -> Result<Self, Self::Error> {
487        let make = match line.chars().next() {
488            Some(' ') => Self::Same,
489            Some('-') => Self::Removed,
490            Some('+') => Self::Added,
491            _ => return Err(format!("a hunk line starts with ' ', '-' or '+': {line:?}")),
492        };
493        line.remove(0);
494        Ok(make(line))
495    }
496}
497
498/// `text`'s lines, each with its ending: `\n`, `\r\n` or a lone `\r`, as
499/// hunks count them.
500fn text_lines(mut text: &str) -> impl Iterator<Item = &str> {
501    std::iter::from_fn(move || {
502        let end = match text.find(['\r', '\n']) {
503            Some(at) if text.get(at..).is_some_and(|rest| rest.starts_with("\r\n")) => at + 2,
504            Some(at) => at + 1,
505            None => text.len(),
506        };
507        let (line, rest) = text.split_at_checked(end)?;
508        text = rest;
509        (!line.is_empty()).then_some(line)
510    })
511}
512
513/// What a tool call did to a file.
514#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
515#[serde(rename_all = "snake_case")]
516pub enum ChangeKind {
517    /// It did not exist before.
518    Created,
519    /// It existed and was changed.
520    Modified,
521    /// It existed and is gone.
522    Deleted,
523}
524
525/// A tool's output was cut to fit: the model's text keeps one end, or both
526/// ends and some lines from between, and says so in a line of its own. A
527/// front reads this fact, not that line's wording, to draw and count the
528/// cut.
529///
530/// ```
531/// use rig_core::tool::{KeptEnd, OutputCut};
532///
533/// let cut = OutputCut { kept: KeptEnd::Ends, kept_lines: 2000, total_lines: 5120, spill: None };
534/// assert_eq!(cut.cut_lines(), 3120);
535/// ```
536#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
537pub struct OutputCut {
538    /// Which end of the output the text keeps.
539    pub kept: KeptEnd,
540    /// How many lines of the output the text keeps, not counting the lines
541    /// that say what was cut.
542    pub kept_lines: usize,
543    /// How many lines the whole output had.
544    pub total_lines: usize,
545    /// The file that holds all of the output, when the tool kept it.
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub spill: Option<String>,
548}
549
550impl ContextValue for OutputCut {
551    const KEY: &'static str = "output_cut";
552}
553
554impl OutputCut {
555    /// How many lines of the output the text leaves out.
556    pub fn cut_lines(&self) -> usize {
557        self.total_lines.saturating_sub(self.kept_lines)
558    }
559}
560
561/// Which part of a cut output a tool kept ([`OutputCut::kept`]).
562#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
563#[serde(rename_all = "snake_case")]
564pub enum KeptEnd {
565    /// Its first lines, such as a long file read from the top. The line
566    /// that says so comes last.
567    Start,
568    /// Its first and last lines, and lines from between, such as a
569    /// command's output with the errors from its middle. The line that says
570    /// so comes first.
571    Ends,
572}
573
574/// How a process a tool call ran ended.
575#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
576#[serde(rename_all = "snake_case")]
577pub enum ExitStatus {
578    /// It exited with this code.
579    Exited(i32),
580    /// A signal it did not expect ended it.
581    Signaled,
582    /// It ran past its time limit and was killed.
583    TimedOut,
584    /// The tool killed it for another reason, such as the call being
585    /// cancelled.
586    Killed,
587}
588
589impl ContextValue for ExitStatus {
590    const KEY: &'static str = "exit_status";
591}
592
593impl ExitStatus {
594    /// Whether it exited with code 0.
595    pub fn success(&self) -> bool {
596        matches!(self, Self::Exited(0))
597    }
598
599    /// The code it exited with, if it exited.
600    pub fn code(&self) -> Option<i32> {
601        match self {
602            Self::Exited(code) => Some(*code),
603            Self::Signaled | Self::TimedOut | Self::Killed => None,
604        }
605    }
606}
607
608#[cfg(test)]
609mod tests;