rig_core/tool/footprint.rs
1//! What a tool call may read and change ([`Touches`]), so a host runs the
2//! calls of one reply that touch different things side by side, and holds
3//! back only those that conflict.
4//!
5//! ```
6//! use std::path::PathBuf;
7//! use rig_core::tool::{Scope, Touches};
8//!
9//! let paths = |path: &str| Scope::Paths(vec![PathBuf::from(path)]);
10//! let edit = Touches::Writes(paths("/work/src/a.rs"));
11//! assert!(!edit.conflicts_with(&Touches::Reads(paths("/work/src/b.rs"))));
12//! assert!(edit.conflicts_with(&Touches::Reads(paths("/work/src"))));
13//! assert!(edit.conflicts_with(&Touches::Independent));
14//! assert!(!Touches::Reads(Scope::Anything).conflicts_with(&Touches::Independent));
15//! ```
16
17use std::path::{Component, PathBuf};
18
19use serde::{Deserialize, Serialize};
20
21use crate::completion::ToolAnnotations;
22
23/// What a tool call may read and change, so calls that touch different
24/// things run side by side.
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum Touches {
28 /// Reads what the scope names and changes nothing: run again after a
29 /// restart.
30 Reads(Scope),
31 /// Reads and may change what the scope names.
32 Writes(Scope),
33 /// Changes nothing the other calls of its reply see, such as handing
34 /// work to another agent. It may read anything, so it waits behind an
35 /// earlier writer; it is never run again after a restart.
36 Independent,
37}
38
39/// What a footprint names: these paths (absolute; a directory covers what
40/// is under it), or anything at all. A guard compares paths as they are,
41/// so a host makes a footprint [`normalized`](Touches::normalized) before
42/// any guard sees it, for every tool call.
43///
44/// Normalizing folds `.` and `..` by the text alone and follows no link,
45/// so a tool declares canonical paths: the files it will open once links
46/// are resolved. A guard that must not be fooled by a link a tool did not
47/// resolve canonicalizes the paths it compares itself.
48#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Scope {
51 /// These files and directories, canonical and absolute.
52 Paths(Vec<PathBuf>),
53 /// Anything at all.
54 Anything,
55}
56
57impl Scope {
58 /// Whether the two name something in common: a path is, or is under, a
59 /// path of the other, compared component by component; `Anything`
60 /// meets everything.
61 pub fn overlaps(&self, other: &Scope) -> bool {
62 match (self, other) {
63 (Self::Paths(ours), Self::Paths(theirs)) => ours.iter().any(|ours| {
64 theirs
65 .iter()
66 .any(|theirs| ours.starts_with(theirs) || theirs.starts_with(ours))
67 }),
68 (Self::Anything, _) | (_, Self::Anything) => true,
69 }
70 }
71
72 /// The scope with each path's `.` and `..` folded away, by the path's
73 /// text alone, so `/work/src/../../etc` names `/etc`, as a guard
74 /// comparing paths must see it. A relative path names no place a guard
75 /// can check, so a scope with one is [`Anything`](Self::Anything).
76 pub fn normalized(self) -> Scope {
77 match self {
78 Self::Paths(paths) => paths
79 .into_iter()
80 .map(normal)
81 .collect::<Option<Vec<_>>>()
82 .map_or(Self::Anything, Self::Paths),
83 Self::Anything => Self::Anything,
84 }
85 }
86}
87
88/// `path` with its `.` and `..` folded away, or `None` when it is relative.
89/// `..` at the root stays at the root.
90fn normal(path: PathBuf) -> Option<PathBuf> {
91 if !path.is_absolute() {
92 return None;
93 }
94 let mut normal = PathBuf::new();
95 for component in path.components() {
96 match component {
97 Component::ParentDir => {
98 normal.pop();
99 }
100 Component::CurDir => {}
101 Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
102 normal.push(component);
103 }
104 }
105 }
106 Some(normal)
107}
108
109impl Default for Touches {
110 /// `Writes(Anything)`: a tool that declares nothing may change
111 /// anything, so its calls wait for, and hold back, every other.
112 fn default() -> Self {
113 Self::Writes(Scope::Anything)
114 }
115}
116
117impl Touches {
118 /// Whether a call touching `self` must not run beside one touching
119 /// `other`: one of them writes what the other reads or writes.
120 /// [`Independent`](Self::Independent) counts as `Reads(Anything)` here.
121 pub fn conflicts_with(&self, other: &Touches) -> bool {
122 let (ours, we_write) = self.parts();
123 let (theirs, they_write) = other.parts();
124 (we_write || they_write) && ours.overlaps(theirs)
125 }
126
127 /// Whether a call touching `self` waits, before it starts, for any of
128 /// `earlier`: the calls before it in its reply that are not settled,
129 /// held ones included, so a call is never overtaken by one it
130 /// conflicts with. A call that declared nothing counts as
131 /// [`Touches::default`].
132 pub fn must_wait<'a>(&self, earlier: impl IntoIterator<Item = &'a Touches>) -> bool {
133 earlier
134 .into_iter()
135 .any(|before| self.conflicts_with(before))
136 }
137
138 /// Whether it only reads: [`Reads`](Self::Reads), and nothing else.
139 pub fn reads_only(&self) -> bool {
140 matches!(self, Self::Reads(_))
141 }
142
143 /// The footprint with its scope [`normalized`](Scope::normalized).
144 pub fn normalized(self) -> Touches {
145 match self {
146 Self::Reads(scope) => Self::Reads(scope.normalized()),
147 Self::Writes(scope) => Self::Writes(scope.normalized()),
148 Self::Independent => Self::Independent,
149 }
150 }
151
152 /// From the annotations a tool's own code declares, such as a
153 /// [`Tool`](super::Tool)'s: `Reads(Anything)` when it says it only
154 /// reads, else `Writes(Anything)`. For annotations from elsewhere, such
155 /// as an MCP server's, [`from_hints`](Self::from_hints).
156 pub fn from_annotations(annotations: &ToolAnnotations) -> Self {
157 match annotations.read_only() {
158 true => Self::Reads(Scope::Anything),
159 false => Self::default(),
160 }
161 }
162
163 /// From annotations rig cannot check, such as those an MCP server
164 /// sends: a tool that says it only reads is
165 /// [`Independent`](Self::Independent), so its calls still run beside
166 /// readers but are never run again after a restart; any other is
167 /// `Writes(Anything)`. Only a local declaration makes a call
168 /// [`Reads`](Self::Reads).
169 pub fn from_hints(annotations: &ToolAnnotations) -> Self {
170 match annotations.read_only() {
171 true => Self::Independent,
172 false => Self::default(),
173 }
174 }
175
176 /// What it names, and whether it writes there.
177 fn parts(&self) -> (&Scope, bool) {
178 match self {
179 Self::Reads(scope) => (scope, false),
180 Self::Writes(scope) => (scope, true),
181 Self::Independent => (&Scope::Anything, false),
182 }
183 }
184}
185
186#[cfg(test)]
187mod tests;