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`]: crate::event::Event
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    /// A patch document is structurally invalid, before application is attempted.
57    ///
58    /// A malformed JSON Pointer is a producer protocol error; unlike a valid
59    /// operation targeting missing state, it cannot be retried against another
60    /// state value.
61    #[error("{target} patch document is invalid: {message}")]
62    InvalidPatchDocument {
63        /// What the patch targeted — `"state"`, or `"activity <message id>"`.
64        target: String,
65        /// Why the document could not be parsed.
66        message: String,
67    },
68
69    /// The application state did not deserialize into the caller's type.
70    ///
71    /// The raw JSON state is still updated and correct; only the typed view is
72    /// unavailable.
73    #[error("state does not match the expected type: {0}")]
74    State(#[source] serde_json::Error),
75
76    /// The agent reported `RUN_ERROR`.
77    #[error("run failed: {message}")]
78    Run {
79        /// What went wrong, for a human.
80        message: String,
81        /// The machine-readable code, when the agent sent one.
82        code: Option<String>,
83    },
84
85    /// The server answered with a status outside 2xx.
86    #[error("HTTP {status}: {body}")]
87    Http {
88        /// The status code.
89        status: u16,
90        /// Up to 2 KiB of response bytes, decoded as UTF-8 with invalid sequences
91        /// replaced. The response is dropped once the byte limit is reached.
92        body: String,
93    },
94
95    /// A successful HTTP response chose a format this transport cannot decode.
96    #[error("HTTP response Content-Type must be text/event-stream; received {0}")]
97    UnexpectedContentType(String),
98
99    /// The transport failed — a connection reset, a DNS failure, a closed
100    /// channel. Carries the underlying error.
101    #[error("transport error: {0}")]
102    Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
103
104    /// A transport was configured with something it cannot use: an unparseable
105    /// URL, an invalid header name.
106    #[error("invalid client configuration: {0}")]
107    Config(String),
108}
109
110impl From<crate::Error> for Error {
111    fn from(error: crate::Error) -> Self {
112        match error {
113            // A rule broken by the stream is a protocol violation whichever
114            // crate noticed it; a caller matching on `Protocol` should not have
115            // to know that `RunOutcome::validate` lives in core.
116            crate::Error::Protocol(message) => Self::Protocol(message),
117            other => Self::Core(other),
118        }
119    }
120}
121
122impl Error {
123    /// Wraps any error as a [`Error::Transport`].
124    ///
125    /// Transports for exotic runtimes have their own error types; this is how
126    /// they enter this crate's error enum without a variant of their own.
127    pub fn transport(error: impl std::error::Error + Send + Sync + 'static) -> Self {
128        Self::Transport(Box::new(error))
129    }
130
131    /// Builds a [`Error::Protocol`] from anything printable.
132    pub(crate) fn protocol(message: impl Into<String>) -> Self {
133        Self::Protocol(message.into())
134    }
135
136    /// Builds a [`Error::Decode`] from anything printable.
137    pub(crate) fn decode(message: impl Into<String>) -> Self {
138        Self::Decode(message.into())
139    }
140}
141
142/// Result alias used throughout this crate.
143pub type Result<T, E = Error> = core::result::Result<T, E>;