use std::fmt;
pub type ToolResult<T> = Result<T, ToolError>;
#[derive(Debug)]
pub enum ToolError {
Denied {
reason: String,
},
NotFound {
name: String,
},
Budget,
Generation,
Exec(std::io::Error),
Other(anyhow::Error),
}
impl ToolError {
pub fn denied(reason: impl Into<String>) -> Self {
Self::Denied {
reason: reason.into(),
}
}
pub fn not_found(name: impl Into<String>) -> Self {
Self::NotFound { name: name.into() }
}
}
impl fmt::Display for ToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Denied { reason } => write!(f, "denied: {reason}"),
Self::NotFound { name } => write!(f, "no such tool: {name}"),
Self::Budget => write!(f, "denied: call budget (max_calls) exhausted"),
Self::Generation => {
write!(f, "denied: grant is not valid for the gate's generation")
}
Self::Exec(e) => write!(f, "tool execution failed: {e}"),
Self::Other(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for ToolError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Exec(e) => Some(e),
Self::Other(e) => e.source(),
_ => None,
}
}
}
impl From<std::io::Error> for ToolError {
fn from(e: std::io::Error) -> Self {
Self::Exec(e)
}
}
impl From<anyhow::Error> for ToolError {
fn from(e: anyhow::Error) -> Self {
Self::Other(e)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_is_stable_and_safe() {
assert_eq!(
ToolError::denied("nope").to_string(),
"denied: nope".to_string()
);
assert_eq!(
ToolError::Budget.to_string(),
"denied: call budget (max_calls) exhausted"
);
assert!(ToolError::not_found("shell").to_string().contains("shell"));
}
}