ag_ui/server/error.rs
1//! Errors raised while hosting a run.
2//!
3//! Everything an agent can fail with funnels through [`enum@Error`]. The run driver
4//! turns whatever escapes [`Agent::run`](crate::server::Agent::run) into a `RUN_ERROR`
5//! event, so an error is never a panic and never a silently truncated stream.
6
7use std::fmt;
8
9use crate::EventType;
10use thiserror::Error;
11
12/// Result alias used throughout this crate.
13pub type Result<T, E = Error> = core::result::Result<T, E>;
14
15/// Everything that can go wrong while hosting an AG-UI run.
16///
17/// The variant list is `#[non_exhaustive]`: new emitters and verification rules
18/// are expected to add variants without a breaking release.
19#[derive(Debug, Error)]
20#[non_exhaustive]
21pub enum Error {
22 /// A core protocol type rejected a value — for example an `interrupt`
23 /// outcome carrying no interrupts.
24 #[error(transparent)]
25 Protocol(#[from] crate::Error),
26
27 /// State, tool arguments or a tool result could not be converted to or from
28 /// JSON.
29 #[error("JSON conversion failed: {0}")]
30 Json(#[from] serde_json::Error),
31
32 /// The emitted event stream broke the protocol's ordering rules.
33 ///
34 /// Detailed ordering checks use the `verify` feature. The producer's
35 /// requirement to explicitly close announced subagents is always enforced.
36 #[error(transparent)]
37 Verification(#[from] VerificationError),
38
39 /// The run was cancelled — usually because the client disconnected.
40 ///
41 /// Every emit after cancellation fails with this, so an agent that uses `?`
42 /// on its emits unwinds promptly without any cancellation code of its own.
43 #[error("the run was cancelled")]
44 Cancelled,
45
46 /// The consumer dropped the event stream, so there is nowhere left to emit.
47 #[error("the event stream was dropped by the consumer")]
48 Disconnected,
49
50 /// The configured event queue filled before the consumer could drain it.
51 /// The stream ends with an `EVENT_BUFFER_FULL` error; the rejected event
52 /// was not delivered. Reconnect/replay is the application's responsibility.
53 #[error("the event buffer reached its capacity of {capacity} events")]
54 EventBufferFull {
55 /// Maximum queued events, excluding the reserved overflow error.
56 capacity: usize,
57 },
58
59 /// The agent itself failed. Build one with [`Error::agent`].
60 #[error("agent error: {0}")]
61 Agent(Box<dyn std::error::Error + Send + Sync>),
62}
63
64impl Error {
65 /// Wraps an arbitrary agent-side error.
66 ///
67 /// ```
68 /// # use ag_ui::server::Error;
69 /// let err = Error::agent("the weather service is down");
70 /// assert_eq!(err.code(), "AGENT_ERROR");
71 /// ```
72 pub fn agent<E>(error: E) -> Self
73 where
74 E: Into<Box<dyn std::error::Error + Send + Sync>>,
75 {
76 Self::Agent(error.into())
77 }
78
79 /// The machine-readable code placed on the `RUN_ERROR` event.
80 pub const fn code(&self) -> &'static str {
81 match self {
82 Self::Protocol(_) => "PROTOCOL",
83 Self::Json(_) => "SERIALIZATION",
84 Self::Verification(_) => "PROTOCOL_VIOLATION",
85 Self::Cancelled => "CANCELLED",
86 Self::Disconnected => "DISCONNECTED",
87 Self::EventBufferFull { .. } => "EVENT_BUFFER_FULL",
88 Self::Agent(_) => "AGENT_ERROR",
89 }
90 }
91
92 /// Whether this error means the run was cancelled rather than that it
93 /// failed.
94 pub const fn is_cancelled(&self) -> bool {
95 matches!(self, Self::Cancelled)
96 }
97
98 /// Whether the consumer has gone away, making further emits pointless.
99 pub const fn is_disconnected(&self) -> bool {
100 matches!(self, Self::Disconnected)
101 }
102}
103
104/// The ordering rule an event broke.
105///
106/// Each variant is one check in the state machine described on
107/// [`verify`](crate::server::verify).
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
109#[non_exhaustive]
110pub enum Rule {
111 /// No event may follow `RUN_FINISHED` or `RUN_ERROR`.
112 RunEnded,
113 /// A run starts exactly once.
114 DuplicateRunStarted,
115 /// A message, tool call, reasoning block or step was opened twice under the
116 /// same id.
117 DuplicateStart,
118 /// Content or a terminator arrived for something that is not open.
119 NotOpen,
120 /// An event referenced an id that was never introduced.
121 UnknownId,
122 /// `RUN_FINISHED` arrived while something was still open.
123 OpenAtFinish,
124 /// The event is legal but arrived in the wrong place — a tool result before
125 /// its `TOOL_CALL_END`, for instance.
126 OutOfOrder,
127 /// A continuation, terminator or re-open carried a `subagentRunId` that
128 /// disagrees with the subagent that opened the entity — or a tool call was
129 /// tagged with one subagent while its parent message belongs to another.
130 OwnerMismatch,
131}
132
133impl Rule {
134 /// The rule's kebab-case name, as it appears in error messages.
135 pub const fn as_str(&self) -> &'static str {
136 match self {
137 Self::RunEnded => "run-ended",
138 Self::DuplicateRunStarted => "duplicate-run-started",
139 Self::DuplicateStart => "duplicate-start",
140 Self::NotOpen => "not-open",
141 Self::UnknownId => "unknown-id",
142 Self::OpenAtFinish => "open-at-finish",
143 Self::OutOfOrder => "out-of-order",
144 Self::OwnerMismatch => "owner-mismatch",
145 }
146 }
147
148 /// The rule in one sentence, for humans reading a log.
149 pub const fn describe(&self) -> &'static str {
150 match self {
151 Self::RunEnded => "a run emits nothing after RUN_FINISHED or RUN_ERROR",
152 Self::DuplicateRunStarted => "a run emits RUN_STARTED exactly once",
153 Self::DuplicateStart => "an id may only be opened once",
154 Self::NotOpen => "content and terminators require a matching start",
155 Self::UnknownId => "an event may only reference an id it has seen",
156 Self::OpenAtFinish => "everything opened must be closed before RUN_FINISHED",
157 Self::OutOfOrder => "the event arrived before the event it depends on",
158 Self::OwnerMismatch => "an event names the subagent that opened its entity",
159 }
160 }
161}
162
163impl fmt::Display for Rule {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 f.write_str(self.as_str())
166 }
167}
168
169/// One event rejected by the ordering verifier.
170///
171/// The message names the offending event, the rule it broke and the id
172/// involved. In debug builds it also carries a dump of everything still open,
173/// which is usually enough to spot the missing terminator:
174///
175/// ```text
176/// TEXT_MESSAGE_CONTENT breaks rule `not-open` (content and terminators require
177/// a matching start): message "msg-2" is not open [open: messages={"msg-1"}]
178/// ```
179#[derive(Debug, Error)]
180#[error("{event} breaks rule `{rule}` ({}): {detail}", rule.describe())]
181pub struct VerificationError {
182 /// The event that was rejected.
183 pub event: EventType,
184 /// The rule it broke.
185 pub rule: Rule,
186 /// What specifically was wrong, plus — in debug builds — the open-entity
187 /// dump.
188 pub detail: String,
189}
190
191impl VerificationError {
192 /// Builds a rejection.
193 pub fn new(event: EventType, rule: Rule, detail: impl Into<String>) -> Self {
194 Self {
195 event,
196 rule,
197 detail: detail.into(),
198 }
199 }
200}