use futures::stream::BoxStream;
use gadk_model::ModelError;
use gadk_session::compaction::CompactionError;
use gadk_session::{Event, SessionError};
pub type EventStream = BoxStream<'static, Result<Event, AgentError>>;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum AgentError {
#[error(transparent)]
Model(#[from] ModelError),
#[error(transparent)]
Session(#[from] SessionError),
#[error(transparent)]
Artifact(#[from] gadk_artifact::ArtifactError),
#[error(transparent)]
Memory(#[from] gadk_memory::MemoryError),
#[error("error tool {} {source}", crate::go_fmt::go_quote(.tool))]
Tool {
tool: String,
#[source]
source: ToolError,
},
#[error(transparent)]
Workflow(Box<dyn std::error::Error + Send + Sync>),
#[error("max number of llm calls exceeded: limit is {limit}")]
LlmCallsLimitExceeded {
limit: i32,
},
#[error("context canceled")]
Cancelled,
#[error("context deadline exceeded")]
DeadlineExceeded,
#[error("{0}")]
Config(String),
#[error(transparent)]
Compaction(CompactionError),
#[error("{0}")]
Other(Box<dyn std::error::Error + Send + Sync>),
}
impl AgentError {
pub fn other(msg: impl Into<String>) -> Self {
AgentError::Other(msg.into().into())
}
pub fn is_compaction(&self) -> bool {
chain_any(self, &|e| {
e.is::<CompactionError>()
|| matches!(
e.downcast_ref::<AgentError>(),
Some(AgentError::Compaction(_))
)
})
}
}
pub(crate) fn chain_any(
err: &AgentError,
pred: &dyn Fn(&(dyn std::error::Error + 'static)) -> bool,
) -> bool {
let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(e) = cur {
if pred(e) {
return true;
}
match e.downcast_ref::<AgentError>() {
Some(AgentError::Other(inner) | AgentError::Workflow(inner)) => {
cur = Some(&**inner);
continue;
}
Some(AgentError::Tool {
source: ToolError::Execution(inner),
..
}) => {
cur = Some(&**inner);
continue;
}
_ => {}
}
if let Some(ToolError::Execution(inner)) = e.downcast_ref::<ToolError>() {
cur = Some(&**inner);
continue;
}
cur = e.source();
}
false
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
#[error("requires confirmation, please approve or reject")]
ConfirmationRequired,
#[error("call is rejected")]
ConfirmationRejected,
#[error("{0}")]
InvalidArgument(String),
#[error("{0}")]
Panic(String),
#[error(transparent)]
Execution(Box<dyn std::error::Error + Send + Sync>),
}
#[derive(Debug, Clone)]
pub struct SharedToolError(pub std::sync::Arc<ToolError>);
impl std::fmt::Display for SharedToolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&*self.0, f)
}
}
impl std::error::Error for SharedToolError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
std::error::Error::source(&*self.0)
}
}
#[derive(Debug)]
pub(crate) struct Wrapped {
msg: String,
source: AgentError,
}
impl std::fmt::Display for Wrapped {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.msg, self.source)
}
}
impl std::error::Error for Wrapped {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
pub(crate) fn wrap(msg: impl Into<String>, source: AgentError) -> AgentError {
AgentError::Other(Box::new(Wrapped {
msg: msg.into(),
source,
}))
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use gadk_session::compaction::CompactionError;
use super::*;
#[test]
fn compaction_error_displays_go_text_and_is_compaction() {
let e = AgentError::Compaction(CompactionError::new("post-invocation: boom"));
assert_eq!(
e.to_string(),
"context compaction failed: post-invocation: boom"
);
assert!(e.to_string().starts_with("context compaction failed: "));
assert!(e.is_compaction());
}
#[test]
fn shared_tool_error_is_display_transparent_and_keeps_the_arc() {
use std::error::Error as _;
use std::sync::Arc;
let plain = Arc::new(ToolError::InvalidArgument("bad args".into()));
let shared = SharedToolError(plain.clone());
assert_eq!(shared.to_string(), "bad args");
assert!(shared.source().is_none(), "InvalidArgument has no source");
let inner = Wrapped {
msg: "outer".into(),
source: AgentError::other("root cause"),
};
let exec = Arc::new(ToolError::Execution(Box::new(inner)));
let shared_exec = SharedToolError(exec.clone());
assert_eq!(shared_exec.to_string(), "outer: root cause");
assert_eq!(
shared_exec.source().map(|s| s.to_string()).as_deref(),
Some("root cause")
);
let agent_err = AgentError::Other(Box::new(SharedToolError(plain.clone())));
assert_eq!(agent_err.to_string(), "bad args");
let AgentError::Other(boxed) = &agent_err else {
panic!("not Other: {agent_err:?}")
};
let got = boxed.downcast_ref::<SharedToolError>().unwrap();
assert!(Arc::ptr_eq(&got.0, &plain));
assert!(!Arc::ptr_eq(&got.0, &exec));
let cloned = shared.clone();
assert!(Arc::ptr_eq(&cloned.0, &shared.0));
}
#[test]
fn is_compaction_walks_the_chain() {
let wrapped = wrap("outer", AgentError::Compaction(CompactionError::new("x")));
assert!(wrapped.is_compaction());
assert!(AgentError::Other(Box::new(CompactionError::new("x"))).is_compaction());
assert!(AgentError::Workflow(Box::new(CompactionError::new("x"))).is_compaction());
assert!(!AgentError::other("context compaction failed: lookalike").is_compaction());
assert!(!AgentError::Cancelled.is_compaction());
assert!(!wrap("outer", AgentError::Cancelled).is_compaction());
}
}