1use std::error::Error as StdError;
4use std::fmt;
5use std::sync::Arc;
6
7use super::tool::ToolOutcome;
8use crate::error::BoxError;
9use crate::interrupt::InterruptError;
10use crate::types::{ToolResultBlock, ToolResultContent, ToolResultError};
11
12pub struct ToolError {
34 repr: Box<Repr>,
35}
36
37enum Repr {
38 Error(ToolResultError),
39 Interrupt(InterruptError),
40}
41
42#[derive(Debug)]
43struct MessageError(String);
44
45impl fmt::Display for MessageError {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.write_str(&self.0)
48 }
49}
50
51impl StdError for MessageError {}
52
53impl ToolError {
54 pub fn msg(message: impl fmt::Display) -> Self {
56 Self::new(MessageError(message.to_string()))
57 }
58
59 pub fn new(error: impl StdError + Send + Sync + 'static) -> Self {
61 Self::from_boxed(Box::new(error))
62 }
63
64 #[must_use]
84 pub fn from_boxed(error: BoxError) -> Self {
85 let repr = match error.downcast::<InterruptError>() {
86 Ok(interrupt) => Repr::Interrupt(*interrupt),
87 Err(error) => Repr::Error(Arc::from(error)),
88 };
89 Self { repr: Box::new(repr) }
90 }
91
92 #[must_use]
94 pub fn is_interrupt(&self) -> bool {
95 matches!(*self.repr, Repr::Interrupt(_))
96 }
97
98 #[must_use]
100 pub fn as_interrupt(&self) -> Option<&InterruptError> {
101 match &*self.repr {
102 Repr::Interrupt(interrupt) => Some(interrupt),
103 Repr::Error(_) => None,
104 }
105 }
106
107 #[must_use]
109 pub fn as_error(&self) -> Option<&(dyn StdError + Send + Sync + 'static)> {
110 match &*self.repr {
111 Repr::Error(error) => Some(error.as_ref()),
112 Repr::Interrupt(_) => None,
113 }
114 }
115
116 #[must_use]
119 pub fn into_outcome(self, tool_use_id: impl Into<String>) -> ToolOutcome {
120 match *self.repr {
121 Repr::Interrupt(interrupt) => ToolOutcome::Interrupt(interrupt),
122 Repr::Error(error) => {
123 let text = format!("Error: {error}");
124 let mut result = ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(text)]);
125 result.error = Some(error);
126 ToolOutcome::Result(result)
127 }
128 }
129 }
130}
131
132impl<E: StdError + Send + Sync + 'static> From<E> for ToolError {
133 fn from(error: E) -> Self {
134 Self::new(error)
135 }
136}
137
138impl fmt::Display for ToolError {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 match &*self.repr {
141 Repr::Error(error) => fmt::Display::fmt(error, f),
142 Repr::Interrupt(interrupt) => fmt::Display::fmt(interrupt, f),
143 }
144 }
145}
146
147impl fmt::Debug for ToolError {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 match &*self.repr {
150 Repr::Error(error) => fmt::Debug::fmt(error, f),
151 Repr::Interrupt(interrupt) => f.debug_tuple("Interrupt").field(interrupt).finish(),
152 }
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use serde_json::json;
159
160 use super::*;
161 use crate::Error;
162 use crate::interrupt::Interrupt;
163
164 #[test]
165 fn failures_become_error_results_with_the_error_kept() {
166 let error: ToolError = Error::other("city not found").into();
167 assert!(!error.is_interrupt());
168 let ToolOutcome::Result(result) = error.into_outcome("t-1") else {
169 panic!("expected a result");
170 };
171 assert_eq!(
172 serde_json::to_value(&result).unwrap(),
173 json!({"toolUseId": "t-1", "status": "error", "content": [{"text": "Error: city not found"}]})
174 );
175 assert_eq!(result.error.unwrap().to_string(), "city not found");
176 }
177
178 #[test]
179 fn interrupts_stay_interrupts() {
180 let interrupt = InterruptError::from(Interrupt::new("tool:t-1:confirm", "confirm"));
181 let error = ToolError::from(interrupt.clone());
182 assert_eq!(error.to_string(), "Interrupt raised: confirm");
183 assert_eq!(error.as_interrupt(), Some(&interrupt));
184 assert!(error.as_error().is_none());
185 assert_eq!(error.into_outcome("t-1"), ToolOutcome::Interrupt(interrupt));
186 }
187
188 #[test]
189 fn interrupts_survive_a_box_error() {
190 let interrupts = InterruptError::new([Interrupt::new("a", "a"), Interrupt::new("b", "b")]);
191 let boxed: BoxError = Box::new(interrupts.clone());
192 let error = ToolError::from_boxed(boxed);
193 assert_eq!(error.to_string(), "2 interrupts raised: a, b");
194 assert_eq!(error.into_outcome("t-1"), ToolOutcome::Interrupt(interrupts));
195 let failure = ToolError::from_boxed("plain".into());
196 assert!(!failure.is_interrupt());
197 assert_eq!(failure.to_string(), "plain");
198 }
199
200 #[test]
201 fn tool_error_is_one_pointer() {
202 assert_eq!(std::mem::size_of::<ToolError>(), std::mem::size_of::<usize>());
203 }
204}