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 run was refused before dispatch because these tool calls have no
17 /// answer in the transcript, in call order.
18 ///
19 /// Answer each with a tool message, or give it up with
20 /// [`Thread::abandon_tool_call`](crate::client::Thread::abandon_tool_call).
21 #[error(
22 "request rejected: unanswered tool calls must be answered with tool messages, or abandoned, before another run: {}",
23 .0.iter().map(crate::ToolCallId::as_str).collect::<Vec<_>>().join(", ")
24 )]
25 UnansweredToolCalls(Vec<crate::ToolCallId>),
26
27 /// A run that answers no interrupt was refused before dispatch because
28 /// the thread is paused on the interrupts with these ids.
29 ///
30 /// Answer them with [`Thread::resume`](crate::client::Thread::resume),
31 /// [`decline`](crate::client::Thread::decline) or
32 /// [`resume_many`](crate::client::Thread::resume_many).
33 #[error("request rejected: pending interrupts must be answered with resume_many")]
34 PendingInterrupts(Vec<String>),
35
36 /// A saved local conversation is invalid or unsupported.
37 #[error("invalid thread snapshot: {0}")]
38 Snapshot(String),
39
40 /// [`Thread::merge_messages_from`](crate::client::Thread::merge_messages_from)
41 /// refused to merge two threads, and changed neither: they are different
42 /// conversations, one of them still owes an answer or has a request in
43 /// flight, a tool call has a result on each, or the receiving thread gave
44 /// up a call the other holds a result for.
45 #[error("threads not merged: {0}")]
46 Merge(String),
47
48 /// A frame's payload was not valid JSON, or not a valid [`Event`].
49 ///
50 /// [`Event`]: crate::event::Event
51 #[error("JSON error: {0}")]
52 Json(#[from] serde_json::Error),
53
54 /// An error raised by the core protocol types.
55 ///
56 /// Core's *protocol* violations do not arrive here: they are flattened into
57 /// [`Error::Protocol`] so that every rule a stream can break has one shape.
58 #[error(transparent)]
59 Core(crate::Error),
60
61 /// The bytes were not well-formed `text/event-stream`.
62 #[error("SSE decode error: {0}")]
63 Decode(String),
64
65 /// The stream parsed, but broke a rule the protocol requires — a content
66 /// event with no open message, a chunk with no id to attach to, events
67 /// after the run finished.
68 #[error("protocol violation: {0}")]
69 Protocol(String),
70
71 /// An [`Applier`](crate::client::Applier) was handed a `*_CHUNK` or
72 /// `THINKING_*` event, which it applies only in their explicit form.
73 #[error("not supported by this client: {0}")]
74 Unsupported(String),
75
76 /// An RFC 6902 patch could not be applied.
77 ///
78 /// The client applies patches to a copy and commits the new document only
79 /// after every operation succeeds.
80 #[error("{target} patch failed: {message}")]
81 Patch {
82 /// What the patch targeted — `"state"`, or `"activity <message id>"`.
83 target: String,
84 /// Why it was rejected, as reported by the patch engine.
85 message: String,
86 },
87
88 /// A patch document is structurally invalid, before application is attempted.
89 ///
90 /// A malformed JSON Pointer is a producer protocol error; unlike a valid
91 /// operation targeting missing state, it cannot be retried against another
92 /// state value.
93 #[error("{target} patch document is invalid: {message}")]
94 InvalidPatchDocument {
95 /// What the patch targeted — `"state"`, or `"activity <message id>"`.
96 target: String,
97 /// Why the document could not be parsed.
98 message: String,
99 },
100
101 /// The application state did not deserialize into the caller's type.
102 ///
103 /// The raw JSON state is still updated and correct; only the typed view is
104 /// unavailable.
105 #[error("state does not match the expected type: {0}")]
106 State(#[source] serde_json::Error),
107
108 /// The agent reported `RUN_ERROR`.
109 #[error("run failed: {message}")]
110 Run {
111 /// What went wrong, for a human.
112 message: String,
113 /// The machine-readable code, when the agent sent one.
114 code: Option<String>,
115 },
116
117 /// The server answered with a status outside 2xx.
118 #[error("HTTP {status}: {body}")]
119 Http {
120 /// The status code.
121 status: u16,
122 /// Up to 2 KiB of response bytes, decoded as UTF-8 with invalid sequences
123 /// replaced. Reading stops after one second or when the byte limit is reached.
124 body: String,
125 },
126
127 /// A successful HTTP response chose a format this transport cannot decode.
128 #[error("HTTP response Content-Type must be text/event-stream; received {0}")]
129 UnexpectedContentType(String),
130
131 /// The transport failed — a connection reset, a DNS failure, a closed
132 /// channel. Carries the underlying error.
133 #[error("transport error: {0}")]
134 Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
135
136 /// A transport was configured with something it cannot use: an unparseable
137 /// URL, an invalid header name.
138 #[error("invalid client configuration: {0}")]
139 Config(String),
140}
141
142impl From<crate::Error> for Error {
143 fn from(error: crate::Error) -> Self {
144 match error {
145 // A rule broken by the stream is a protocol violation whichever
146 // crate noticed it; a caller matching on `Protocol` should not have
147 // to know that `RunOutcome::validate` lives in core.
148 crate::Error::Protocol(message) => Self::Protocol(message),
149 other => Self::Core(other),
150 }
151 }
152}
153
154impl Error {
155 /// Wraps any error as a [`Error::Transport`].
156 ///
157 /// Transports for exotic runtimes have their own error types; this is how
158 /// they enter this crate's error enum without a variant of their own.
159 pub fn transport(error: impl std::error::Error + Send + Sync + 'static) -> Self {
160 Self::Transport(Box::new(error))
161 }
162
163 /// Builds a [`Error::Protocol`] from anything printable.
164 pub(crate) fn protocol(message: impl Into<String>) -> Self {
165 Self::Protocol(message.into())
166 }
167
168 /// Builds a [`Error::Decode`] from anything printable.
169 pub(crate) fn decode(message: impl Into<String>) -> Self {
170 Self::Decode(message.into())
171 }
172}
173
174/// Result alias used throughout this crate.
175pub type Result<T, E = Error> = core::result::Result<T, E>;