Skip to main content

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    /// A handle's terminator is the exception, so that unwinding still closes
44    /// what the run had open and the run ends with a cancelled `RUN_FINISHED`.
45    #[error("the run was cancelled")]
46    Cancelled,
47
48    /// The consumer dropped the event stream, so there is nowhere left to emit.
49    #[error("the event stream was dropped by the consumer")]
50    Disconnected,
51
52    /// The configured event queue filled before the consumer could drain it.
53    /// The stream ends with an `EVENT_BUFFER_FULL` error; the rejected event
54    /// was not delivered. Reconnect/replay is the application's responsibility.
55    #[error("the event buffer reached its capacity of {capacity} events")]
56    EventBufferFull {
57        /// Maximum queued events, excluding the reserved overflow error.
58        capacity: usize,
59    },
60
61    /// The agent itself failed. Build one with [`Error::agent`].
62    #[error("agent error: {0}")]
63    Agent(Box<dyn std::error::Error + Send + Sync>),
64}
65
66impl Error {
67    /// Wraps an arbitrary agent-side error.
68    ///
69    /// ```
70    /// # use ag_ui::server::Error;
71    /// let err = Error::agent("the weather service is down");
72    /// assert_eq!(err.code(), "AGENT_ERROR");
73    /// ```
74    pub fn agent<E>(error: E) -> Self
75    where
76        E: Into<Box<dyn std::error::Error + Send + Sync>>,
77    {
78        Self::Agent(error.into())
79    }
80
81    /// The machine-readable code placed on the `RUN_ERROR` event.
82    pub const fn code(&self) -> &'static str {
83        match self {
84            Self::Protocol(_) => "PROTOCOL",
85            Self::Json(_) => "SERIALIZATION",
86            Self::Verification(_) => "PROTOCOL_VIOLATION",
87            Self::Cancelled => "CANCELLED",
88            Self::Disconnected => "DISCONNECTED",
89            Self::EventBufferFull { .. } => "EVENT_BUFFER_FULL",
90            Self::Agent(_) => "AGENT_ERROR",
91        }
92    }
93
94    /// Whether this error means the run was cancelled rather than that it
95    /// failed.
96    pub const fn is_cancelled(&self) -> bool {
97        matches!(self, Self::Cancelled)
98    }
99
100    /// Whether the consumer has gone away, making further emits pointless.
101    pub const fn is_disconnected(&self) -> bool {
102        matches!(self, Self::Disconnected)
103    }
104}
105
106/// The ordering rule an event broke.
107///
108/// Each variant is one check in the state machine described on
109/// [`verify`](crate::server::verify).
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111#[non_exhaustive]
112pub enum Rule {
113    /// No event may follow `RUN_FINISHED` or `RUN_ERROR`.
114    RunEnded,
115    /// A run starts exactly once.
116    DuplicateRunStarted,
117    /// A message, tool call, reasoning block or step was opened twice under the
118    /// same id.
119    DuplicateStart,
120    /// Content or a terminator arrived for something that is not open.
121    NotOpen,
122    /// An event referenced an id that was never introduced.
123    UnknownId,
124    /// `RUN_FINISHED` arrived while something was still open.
125    OpenAtFinish,
126    /// The event is legal but arrived in the wrong place — a tool result before
127    /// its `TOOL_CALL_END`, for instance.
128    OutOfOrder,
129    /// A continuation, terminator or re-open carried a `subagentRunId` that
130    /// disagrees with the subagent that opened the entity — or a tool call was
131    /// tagged with one subagent while its parent message belongs to another.
132    OwnerMismatch,
133    /// A `*_CHUNK` event cannot be read as the events it stands for: it names
134    /// no id and has no chunk stream to continue, it opens a tool call without
135    /// naming the tool, or it repeats a field its stream was opened with, with
136    /// another value.
137    MalformedChunk,
138    /// `RUN_FINISHED` carried an `interrupt` outcome with no interrupt in it.
139    InvalidOutcome,
140}
141
142impl Rule {
143    /// The rule's kebab-case name, as it appears in error messages.
144    pub const fn as_str(&self) -> &'static str {
145        match self {
146            Self::RunEnded => "run-ended",
147            Self::DuplicateRunStarted => "duplicate-run-started",
148            Self::DuplicateStart => "duplicate-start",
149            Self::NotOpen => "not-open",
150            Self::UnknownId => "unknown-id",
151            Self::OpenAtFinish => "open-at-finish",
152            Self::OutOfOrder => "out-of-order",
153            Self::OwnerMismatch => "owner-mismatch",
154            Self::MalformedChunk => "malformed-chunk",
155            Self::InvalidOutcome => "invalid-outcome",
156        }
157    }
158
159    /// The rule in one sentence, for humans reading a log.
160    pub const fn describe(&self) -> &'static str {
161        match self {
162            Self::RunEnded => "a run emits nothing after RUN_FINISHED or RUN_ERROR",
163            Self::DuplicateRunStarted => "a run emits RUN_STARTED exactly once",
164            Self::DuplicateStart => "an id may only be opened once",
165            Self::NotOpen => "content and terminators require a matching start",
166            Self::UnknownId => "an event may only reference an id it has seen",
167            Self::OpenAtFinish => "everything opened must be closed before RUN_FINISHED",
168            Self::OutOfOrder => "the event arrived before the event it depends on",
169            Self::OwnerMismatch => "an event names the subagent that opened its entity",
170            Self::MalformedChunk => {
171                "a chunk names the item it opens, and repeats only what opened it"
172            }
173            Self::InvalidOutcome => "an interrupt outcome names at least one interrupt",
174        }
175    }
176}
177
178impl fmt::Display for Rule {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.write_str(self.as_str())
181    }
182}
183
184/// One event rejected by the ordering verifier.
185///
186/// The message names the offending event, the rule it broke and the id
187/// involved. In debug builds it also carries a dump of everything still open,
188/// which is usually enough to spot the missing terminator:
189///
190/// ```text
191/// TEXT_MESSAGE_CONTENT breaks rule `not-open` (content and terminators require
192/// a matching start): message "msg-2" is not open [open: messages={"msg-1"}]
193/// ```
194///
195/// `#[non_exhaustive]`: a rejection can come to say more, such as the id it
196/// is about, without a breaking release. Build one with [`new`](Self::new).
197#[derive(Debug, Error)]
198#[error("{event} breaks rule `{rule}` ({}): {detail}", rule.describe())]
199#[non_exhaustive]
200pub struct VerificationError {
201    /// The event that was rejected.
202    pub event: EventType,
203    /// The rule it broke.
204    pub rule: Rule,
205    /// What specifically was wrong, plus — in debug builds — the open-entity
206    /// dump.
207    pub detail: String,
208}
209
210impl VerificationError {
211    /// Builds a rejection.
212    pub fn new(event: EventType, rule: Rule, detail: impl Into<String>) -> Self {
213        Self {
214            event,
215            rule,
216            detail: detail.into(),
217        }
218    }
219}