Skip to main content

ag_ui/client/
error.rs

1//! Errors this crate can produce.
2
3use thiserror::Error;
4
5/// Everything that can go wrong while consuming an AG-UI stream.
6///
7/// The variant list is `#[non_exhaustive]`: new transports and validation rules
8/// are expected to add variants without a breaking release.
9#[derive(Debug, Error)]
10#[non_exhaustive]
11pub enum Error {
12    /// A local request failed before dispatch.
13    #[error("request rejected: {0}")]
14    Request(String),
15
16    /// A saved local conversation is invalid or unsupported.
17    #[error("invalid thread snapshot: {0}")]
18    Snapshot(String),
19
20    /// A frame's payload was not valid JSON, or not a valid [`Event`].
21    ///
22    /// [`Event`]: https://kimsoungryoul.github.io/ag-ui-rust/api/ag_ui/event/enum.Event.html
23    #[error("JSON error: {0}")]
24    Json(#[from] serde_json::Error),
25
26    /// An error raised by the core protocol types.
27    ///
28    /// Core's *protocol* violations do not arrive here: they are flattened into
29    /// [`Error::Protocol`] so that every rule a stream can break has one shape.
30    #[error(transparent)]
31    Core(crate::Error),
32
33    /// The bytes were not well-formed `text/event-stream`.
34    #[error("SSE decode error: {0}")]
35    Decode(String),
36
37    /// The stream parsed, but broke a rule the protocol requires — a content
38    /// event with no open message, a chunk with no id to attach to, events
39    /// after the run finished.
40    #[error("protocol violation: {0}")]
41    Protocol(String),
42
43    /// An RFC 6902 patch could not be applied.
44    ///
45    /// The target document is left exactly as it was: [`json_patch::patch`]
46    /// rolls back the operations it had already applied, so a rejected patch
47    /// never leaves half-mutated state behind.
48    #[error("{target} patch failed: {message}")]
49    Patch {
50        /// What the patch targeted — `"state"`, or `"activity <message id>"`.
51        target: String,
52        /// Why it was rejected, as reported by the patch engine.
53        message: String,
54    },
55
56    /// The application state did not deserialize into the caller's type.
57    ///
58    /// The raw JSON state is still updated and correct; only the typed view is
59    /// unavailable.
60    #[error("state does not match the expected type: {0}")]
61    State(#[source] serde_json::Error),
62
63    /// The agent reported `RUN_ERROR`.
64    #[error("run failed: {message}")]
65    Run {
66        /// What went wrong, for a human.
67        message: String,
68        /// The machine-readable code, when the agent sent one.
69        code: Option<String>,
70    },
71
72    /// The server answered with a status outside 2xx.
73    #[error("HTTP {status}: {body}")]
74    Http {
75        /// The status code.
76        status: u16,
77        /// Up to 2 KiB of response bytes, decoded as UTF-8 with invalid sequences
78        /// replaced. The response is dropped once the byte limit is reached.
79        body: String,
80    },
81
82    /// The transport failed — a connection reset, a DNS failure, a closed
83    /// channel. Carries the underlying error.
84    #[error("transport error: {0}")]
85    Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
86
87    /// A transport was configured with something it cannot use: an unparseable
88    /// URL, an invalid header name.
89    #[error("invalid client configuration: {0}")]
90    Config(String),
91}
92
93impl From<crate::Error> for Error {
94    fn from(error: crate::Error) -> Self {
95        match error {
96            // A rule broken by the stream is a protocol violation whichever
97            // crate noticed it; a caller matching on `Protocol` should not have
98            // to know that `RunOutcome::validate` lives in core.
99            crate::Error::Protocol(message) => Self::Protocol(message),
100            other => Self::Core(other),
101        }
102    }
103}
104
105impl Error {
106    /// Wraps any error as a [`Error::Transport`].
107    ///
108    /// Transports for exotic runtimes have their own error types; this is how
109    /// they enter this crate's error enum without a variant of their own.
110    pub fn transport(error: impl std::error::Error + Send + Sync + 'static) -> Self {
111        Self::Transport(Box::new(error))
112    }
113
114    /// Builds a [`Error::Protocol`] from anything printable.
115    pub(crate) fn protocol(message: impl Into<String>) -> Self {
116        Self::Protocol(message.into())
117    }
118
119    /// Builds a [`Error::Decode`] from anything printable.
120    pub(crate) fn decode(message: impl Into<String>) -> Self {
121        Self::Decode(message.into())
122    }
123}
124
125/// Result alias used throughout this crate.
126pub type Result<T, E = Error> = core::result::Result<T, E>;