Skip to main content

adk_devtools/
error.rs

1//! Error type for developer-tool operations.
2
3/// Errors produced by the developer tools.
4#[derive(Debug, thiserror::Error)]
5pub enum DevToolError {
6    /// The requested path resolves outside the workspace root.
7    #[error("path '{0}' escapes the workspace root")]
8    PathEscape(String),
9
10    /// A mutating operation was attempted on a read-only workspace.
11    #[error("workspace is read-only; '{0}' is not permitted")]
12    ReadOnly(&'static str),
13
14    /// `bash` execution is disabled for this workspace.
15    #[error("bash execution is disabled for this workspace")]
16    BashDisabled,
17
18    /// `edit_file` was called on a file that has not been read in this session.
19    #[error("file '{0}' must be read with read_file before it can be edited")]
20    NotRead(String),
21
22    /// The file changed since this session and agent read it, or since the decision that
23    /// approved the write was shown: the write did not happen (spec 3.1 §7.26, I66).
24    ///
25    /// Maps to an [`AdkError`](adk_core::AdkError) with category `Conflict` and code
26    /// `devtools.stale`, whose message the model sees.
27    #[error("'{path}' changed since it was read: {detail}. Read it again, then make the change")]
28    Stale {
29        /// The file path.
30        path: String,
31        /// What differs.
32        detail: String,
33    },
34
35    /// `old_string` was not found in the target file.
36    #[error("no occurrence of the target string was found in '{0}'")]
37    NoMatch(String),
38
39    /// `old_string` matched more than once and `replace_all` was not set.
40    #[error(
41        "the target string occurs {count} times in '{path}'; pass replace_all=true \
42         or provide a more specific string"
43    )]
44    Ambiguous {
45        /// The file path.
46        path: String,
47        /// Number of occurrences found.
48        count: usize,
49    },
50
51    /// The path matches one of the workspace's exclusion patterns, which by default
52    /// name secret files such as `.env` and private keys.
53    ///
54    /// Maps to an [`AdkError`](adk_core::AdkError) with category `Forbidden` and code
55    /// `devtools.path_excluded`, so a caller can ask for approval and read the file
56    /// through a workspace that does not exclude it. Implements spec 3.1 §10 D5.
57    #[error(
58        "'{0}' matches an excluded pattern (secret files such as .env and private keys are \
59         not read by default); ask the operator to approve reading it"
60    )]
61    Excluded(String),
62
63    /// A bash command exceeded its timeout.
64    #[error("command timed out after {0:?}")]
65    Timeout(std::time::Duration),
66
67    /// An underlying I/O error.
68    #[error(transparent)]
69    Io(#[from] std::io::Error),
70
71    /// Any other error (e.g. invalid arguments, bad regex).
72    #[error("{0}")]
73    Other(String),
74}
75
76/// The category, code and whether the model sees the message, for each error the model can
77/// act on (spec 3.1 §7.33 fix 6, §10 D9): a rejection's message reaches the model, so it
78/// learns to read before editing or to give a more specific string; an I/O failure other
79/// than a missing file stays internal and hidden.
80impl From<DevToolError> for adk_core::AdkError {
81    fn from(e: DevToolError) -> Self {
82        use adk_core::ErrorCategory::{
83            Conflict, Forbidden, Internal, InvalidInput, NotFound, Timeout,
84        };
85        let (category, code) = match &e {
86            DevToolError::Excluded(_) => (Forbidden, "devtools.path_excluded"),
87            DevToolError::NotRead(_) => (Conflict, "devtools.not_read"),
88            DevToolError::Stale { .. } => (Conflict, "devtools.stale"),
89            DevToolError::NoMatch(_) => (InvalidInput, "devtools.no_match"),
90            DevToolError::Ambiguous { .. } => (InvalidInput, "devtools.ambiguous"),
91            DevToolError::PathEscape(_) => (Forbidden, "devtools.path_escape"),
92            DevToolError::ReadOnly(_) => (Forbidden, "devtools.read_only"),
93            DevToolError::BashDisabled => (Forbidden, "devtools.bash_disabled"),
94            DevToolError::Timeout(_) => (Timeout, "devtools.timeout"),
95            DevToolError::Io(io) if io.kind() == std::io::ErrorKind::NotFound => {
96                (NotFound, "devtools.not_found")
97            }
98            DevToolError::Io(_) => (Internal, "devtools.io"),
99            DevToolError::Other(_) => (InvalidInput, "devtools.invalid_argument"),
100        };
101        adk_core::AdkError::new(adk_core::ErrorComponent::Tool, category, code, e.to_string())
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::DevToolError;
108    use adk_core::{AdkError, ErrorCategory, tool_error_response};
109
110    fn mapped(error: DevToolError) -> (ErrorCategory, String, String) {
111        let error: AdkError = error.into();
112        let seen = tool_error_response("edit_file", &error, false)["error"]
113            .as_str()
114            .unwrap_or_default()
115            .to_string();
116        (error.category, error.code.to_string(), seen)
117    }
118
119    #[test]
120    fn each_error_the_model_can_act_on_reaches_it_with_its_code() {
121        let cases = [
122            (
123                DevToolError::NotRead("src/lib.rs".into()),
124                ErrorCategory::Conflict,
125                "devtools.not_read",
126            ),
127            (
128                DevToolError::Stale {
129                    path: "src/lib.rs".into(),
130                    detail: "it no longer exists".into(),
131                },
132                ErrorCategory::Conflict,
133                "devtools.stale",
134            ),
135            (
136                DevToolError::NoMatch("src/lib.rs".into()),
137                ErrorCategory::InvalidInput,
138                "devtools.no_match",
139            ),
140            (
141                DevToolError::Ambiguous { path: "src/lib.rs".into(), count: 2 },
142                ErrorCategory::InvalidInput,
143                "devtools.ambiguous",
144            ),
145            (
146                DevToolError::PathEscape("../x".into()),
147                ErrorCategory::Forbidden,
148                "devtools.path_escape",
149            ),
150            (DevToolError::ReadOnly("write_file"), ErrorCategory::Forbidden, "devtools.read_only"),
151            (DevToolError::BashDisabled, ErrorCategory::Forbidden, "devtools.bash_disabled"),
152            (
153                DevToolError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "no such file")),
154                ErrorCategory::NotFound,
155                "devtools.not_found",
156            ),
157            (
158                DevToolError::Other("bad pattern".into()),
159                ErrorCategory::InvalidInput,
160                "devtools.invalid_argument",
161            ),
162            (
163                DevToolError::Excluded(".env".into()),
164                ErrorCategory::Forbidden,
165                "devtools.path_excluded",
166            ),
167        ];
168        for (error, category, code) in cases {
169            let message = error.to_string();
170            let (got_category, got_code, seen) = mapped(error);
171            assert_eq!((got_category, got_code.as_str()), (category, code));
172            assert!(seen.contains(&message), "the model sees why: {seen}");
173            assert!(seen.contains(code), "{seen}");
174        }
175    }
176
177    #[test]
178    fn the_not_read_message_tells_the_model_what_to_do() {
179        let (_, _, seen) = mapped(DevToolError::NotRead("src/lib.rs".into()));
180        assert_eq!(
181            seen,
182            "tool 'edit_file' failed: tool.conflict (devtools.not_read): file 'src/lib.rs' must be \
183             read with read_file before it can be edited"
184        );
185    }
186
187    #[test]
188    fn other_io_failures_and_timeouts_stay_hidden() {
189        let (category, code, seen) =
190            mapped(DevToolError::Io(std::io::Error::other("disk at /secret")));
191        assert_eq!((category, code.as_str()), (ErrorCategory::Internal, "devtools.io"));
192        assert!(!seen.contains("/secret"), "{seen}");
193        let (category, _, seen) = mapped(DevToolError::Timeout(std::time::Duration::from_secs(5)));
194        assert_eq!(category, ErrorCategory::Timeout);
195        assert!(seen.contains("devtools.timeout"), "{seen}");
196    }
197}