1use std::time::Duration;
7use thiserror::Error;
8
9#[derive(Error, Debug)]
14pub enum RegulaError {
15 #[error("Node '{0}' already exists in graph")]
20 DuplicateNode(String),
21
22 #[error("Node '{0}' not found in graph")]
24 NodeNotFound(String),
25
26 #[error("Invalid edge: source node '{0}' does not exist")]
28 InvalidEdgeSource(String),
29
30 #[error("Invalid edge: target node '{0}' does not exist")]
32 InvalidEdgeTarget(String),
33
34 #[error("Graph has no entry point (no edge from START)")]
36 NoEntryPoint,
37
38 #[error("Graph contains a cycle without exit condition: {0}")]
40 InvalidCycle(String),
41
42 #[error("Unreachable node: '{0}' has no incoming edges")]
44 UnreachableNode(String),
45
46 #[error("Ambiguous routing: node '{0}' has multiple outgoing edges without conditional routing")]
48 AmbiguousRouting(String),
49
50 #[error("Conditional edge from '{0}' has no valid targets")]
52 NoConditionalTargets(String),
53
54 #[error("Node '{node}' execution failed: {message}")]
59 NodeExecution {
60 node: String,
62 message: String,
64 #[source]
66 source: Option<Box<dyn std::error::Error + Send + Sync>>,
67 },
68
69 #[error("Router for node '{0}' returned invalid target: '{1}'")]
71 InvalidRouteTarget(String, String),
72
73 #[error("Maximum iterations ({0}) exceeded - possible infinite loop")]
75 MaxIterationsExceeded(usize),
76
77 #[error("Graph execution was interrupted at node '{0}'")]
79 Interrupted(String),
80
81 #[error("Graph execution was cancelled")]
83 Cancelled,
84
85 #[error("Graph has already completed execution")]
87 AlreadyCompleted,
88
89 #[error("No pending tasks to execute")]
91 NoPendingTasks,
92
93 #[error("Channel '{0}' is empty (no value set)")]
98 EmptyChannel(String),
99
100 #[error("Channel '{channel}' type mismatch: expected {expected}, got {actual}")]
102 ChannelTypeMismatch {
103 channel: String,
105 expected: String,
107 actual: String,
109 },
110
111 #[error("Failed to apply reducer on channel '{channel}': {message}")]
113 ReducerFailed {
114 channel: String,
116 message: String,
118 },
119
120 #[error("State serialization failed: {0}")]
122 StateSerialization(#[from] serde_json::Error),
123
124 #[error("Required state field '{0}' is missing")]
126 MissingStateField(String),
127
128 #[error("Unknown field in state update: '{0}'")]
130 UnknownStateField(String),
131
132 #[error("Checkpoint not found for thread '{0}'")]
137 CheckpointNotFound(String),
138
139 #[error("Checkpoint storage error: {0}")]
141 CheckpointStorage(String),
142
143 #[error("Checkpoint deserialization failed: {0}")]
145 CheckpointDeserialization(String),
146
147 #[error("Checkpoint version mismatch: expected {expected}, got {actual}")]
149 CheckpointVersionMismatch {
150 expected: String,
152 actual: String,
154 },
155
156 #[error("No checkpointer configured")]
158 NoCheckpointer,
159
160 #[error("LLM API request failed: {0}")]
165 LlmRequest(String),
166
167 #[error("LLM API error (status {status}): {message}")]
169 LlmApiError {
170 status: u16,
172 message: String,
174 },
175
176 #[error("LLM response parsing failed: {0}")]
178 LlmResponseParse(String),
179
180 #[error("LLM rate limited, retry after {retry_after:?}")]
182 LlmRateLimited {
183 retry_after: Option<Duration>,
185 },
186
187 #[error("LLM streaming error: {0}")]
189 LlmStreaming(String),
190
191 #[error("LLM API key is missing or invalid")]
193 LlmApiKeyMissing,
194
195 #[error("LLM request timed out after {0:?}")]
197 LlmTimeout(Duration),
198
199 #[error("Invalid configuration: {0}")]
204 InvalidConfig(String),
205
206 #[error("Missing required configuration: {0}")]
208 MissingConfig(String),
209
210 #[error("Configuration key '{0}' not found in context")]
212 ConfigKeyNotFound(String),
213
214 #[error("Configuration key '{key}' type mismatch: expected {expected}")]
216 ConfigTypeMismatch {
217 key: String,
219 expected: String,
221 },
222
223 #[error("Internal error: {0}")]
228 Internal(String),
229
230 #[error("Failed to acquire lock: {0}")]
232 LockError(String),
233
234 #[error("I/O error: {0}")]
236 Io(#[from] std::io::Error),
237
238 #[error(transparent)]
240 Other(#[from] anyhow::Error),
241}
242
243impl RegulaError {
244 pub fn node_execution(
246 node: impl Into<String>,
247 source: impl std::error::Error + Send + Sync + 'static,
248 ) -> Self {
249 let message = source.to_string();
250 Self::NodeExecution {
251 node: node.into(),
252 message,
253 source: Some(Box::new(source)),
254 }
255 }
256
257 pub fn node_execution_msg(node: impl Into<String>, message: impl Into<String>) -> Self {
259 Self::NodeExecution {
260 node: node.into(),
261 message: message.into(),
262 source: None,
263 }
264 }
265
266 pub fn is_retryable(&self) -> bool {
268 matches!(
269 self,
270 Self::LlmRateLimited { .. }
271 | Self::LlmTimeout(_)
272 | Self::LlmRequest(_)
273 | Self::LockError(_)
274 )
275 }
276
277 pub fn is_cancelled(&self) -> bool {
279 matches!(self, Self::Cancelled | Self::Interrupted(_))
280 }
281}
282
283pub type Result<T> = std::result::Result<T, RegulaError>;
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn test_error_display() {
292 let err = RegulaError::DuplicateNode("agent".to_string());
293 assert_eq!(err.to_string(), "Node 'agent' already exists in graph");
294 }
295
296 #[test]
297 fn test_node_execution_error() {
298 let err = RegulaError::node_execution_msg("agent", "connection refused");
299 assert!(err.to_string().contains("agent"));
300 assert!(err.to_string().contains("connection refused"));
301 }
302
303 #[test]
304 fn test_is_retryable() {
305 assert!(RegulaError::LlmRateLimited { retry_after: None }.is_retryable());
306 assert!(RegulaError::LlmTimeout(Duration::from_secs(30)).is_retryable());
307 assert!(!RegulaError::Cancelled.is_retryable());
308 }
309}