1use super::VmValue;
2
3#[derive(Debug, Clone)]
4pub enum VmError {
5 StackUnderflow,
6 StackOverflow,
7 UndefinedVariable(String),
8 UndefinedBuiltin(String),
9 ImmutableAssignment(String),
10 TypeError(String),
11 Runtime(String),
12 DivisionByZero,
13 Thrown(VmValue),
14 CategorizedError {
16 message: String,
17 category: ErrorCategory,
18 },
19 DaemonQueueFull {
20 daemon_id: String,
21 capacity: usize,
22 },
23 Return(VmValue),
24 InvalidInstruction(u8),
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum ErrorCategory {
30 Timeout,
32 Auth,
34 RateLimit,
36 Overloaded,
40 ServerError,
42 TransientNetwork,
45 SchemaValidation,
47 ToolError,
49 ToolRejected,
51 EgressBlocked,
53 Cancelled,
55 NotFound,
57 CircuitOpen,
59 Generic,
61}
62
63impl ErrorCategory {
64 pub fn as_str(&self) -> &'static str {
65 match self {
66 ErrorCategory::Timeout => "timeout",
67 ErrorCategory::Auth => "auth",
68 ErrorCategory::RateLimit => "rate_limit",
69 ErrorCategory::Overloaded => "overloaded",
70 ErrorCategory::ServerError => "server_error",
71 ErrorCategory::TransientNetwork => "transient_network",
72 ErrorCategory::SchemaValidation => "schema_validation",
73 ErrorCategory::ToolError => "tool_error",
74 ErrorCategory::ToolRejected => "tool_rejected",
75 ErrorCategory::EgressBlocked => "egress_blocked",
76 ErrorCategory::Cancelled => "cancelled",
77 ErrorCategory::NotFound => "not_found",
78 ErrorCategory::CircuitOpen => "circuit_open",
79 ErrorCategory::Generic => "generic",
80 }
81 }
82
83 pub fn parse(s: &str) -> Self {
84 match s {
85 "timeout" => ErrorCategory::Timeout,
86 "auth" => ErrorCategory::Auth,
87 "rate_limit" => ErrorCategory::RateLimit,
88 "overloaded" => ErrorCategory::Overloaded,
89 "server_error" => ErrorCategory::ServerError,
90 "transient_network" => ErrorCategory::TransientNetwork,
91 "schema_validation" => ErrorCategory::SchemaValidation,
92 "tool_error" => ErrorCategory::ToolError,
93 "tool_rejected" => ErrorCategory::ToolRejected,
94 "egress_blocked" => ErrorCategory::EgressBlocked,
95 "cancelled" => ErrorCategory::Cancelled,
96 "not_found" => ErrorCategory::NotFound,
97 "circuit_open" => ErrorCategory::CircuitOpen,
98 _ => ErrorCategory::Generic,
99 }
100 }
101
102 pub fn is_transient(&self) -> bool {
106 matches!(
107 self,
108 ErrorCategory::Timeout
109 | ErrorCategory::RateLimit
110 | ErrorCategory::Overloaded
111 | ErrorCategory::ServerError
112 | ErrorCategory::TransientNetwork
113 )
114 }
115}
116
117pub fn categorized_error(message: impl Into<String>, category: ErrorCategory) -> VmError {
119 VmError::CategorizedError {
120 message: message.into(),
121 category,
122 }
123}
124
125pub fn error_to_category(err: &VmError) -> ErrorCategory {
134 match err {
135 VmError::CategorizedError { category, .. } => category.clone(),
136 VmError::Thrown(VmValue::Dict(d)) => d
137 .get("category")
138 .map(|v| ErrorCategory::parse(&v.display()))
139 .unwrap_or(ErrorCategory::Generic),
140 VmError::Thrown(VmValue::String(s)) => classify_error_message(s),
141 VmError::Runtime(msg) => classify_error_message(msg),
142 _ => ErrorCategory::Generic,
143 }
144}
145
146pub fn classify_error_message(msg: &str) -> ErrorCategory {
149 if let Some(cat) = classify_by_http_status(msg) {
151 return cat;
152 }
153 if msg.contains("Deadline exceeded") || msg.contains("context deadline exceeded") {
156 return ErrorCategory::Timeout;
157 }
158 if msg.contains("overloaded_error") {
159 return ErrorCategory::Overloaded;
161 }
162 if msg.contains("api_error") {
163 return ErrorCategory::ServerError;
165 }
166 if msg.contains("insufficient_quota") || msg.contains("billing_hard_limit_reached") {
167 return ErrorCategory::RateLimit;
169 }
170 if msg.contains("invalid_api_key") || msg.contains("authentication_error") {
171 return ErrorCategory::Auth;
172 }
173 if msg.contains("not_found_error") || msg.contains("model_not_found") {
174 return ErrorCategory::NotFound;
175 }
176 if msg.contains("circuit_open") {
177 return ErrorCategory::CircuitOpen;
178 }
179 let lower = msg.to_lowercase();
181 if lower.contains("connection reset")
182 || lower.contains("connection refused")
183 || lower.contains("connection closed")
184 || lower.contains("broken pipe")
185 || lower.contains("dns error")
186 || lower.contains("stream error")
187 || lower.contains("unexpected eof")
188 {
189 return ErrorCategory::TransientNetwork;
190 }
191 ErrorCategory::Generic
192}
193
194fn classify_by_http_status(msg: &str) -> Option<ErrorCategory> {
198 for code in extract_http_status_codes(msg) {
201 return Some(match code {
202 401 | 403 => ErrorCategory::Auth,
203 404 | 410 => ErrorCategory::NotFound,
204 408 | 504 | 522 | 524 => ErrorCategory::Timeout,
205 429 => ErrorCategory::RateLimit,
206 503 | 529 => ErrorCategory::Overloaded,
207 500 | 502 => ErrorCategory::ServerError,
208 _ => continue,
209 });
210 }
211 None
212}
213
214fn extract_http_status_codes(msg: &str) -> Vec<u16> {
216 let mut codes = Vec::new();
217 let bytes = msg.as_bytes();
218 for i in 0..bytes.len().saturating_sub(2) {
219 if bytes[i].is_ascii_digit()
221 && bytes[i + 1].is_ascii_digit()
222 && bytes[i + 2].is_ascii_digit()
223 {
224 let before_ok = i == 0 || !bytes[i - 1].is_ascii_digit();
226 let after_ok = i + 3 >= bytes.len() || !bytes[i + 3].is_ascii_digit();
227 if before_ok && after_ok {
228 if let Ok(code) = msg[i..i + 3].parse::<u16>() {
229 if (400..=599).contains(&code) {
230 codes.push(code);
231 }
232 }
233 }
234 }
235 }
236 codes
237}
238
239impl std::fmt::Display for VmError {
240 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241 match self {
242 VmError::StackUnderflow => write!(f, "Stack underflow"),
243 VmError::StackOverflow => write!(f, "Stack overflow: too many nested calls"),
244 VmError::UndefinedVariable(n) => write!(f, "Undefined variable: {n}"),
245 VmError::UndefinedBuiltin(n) => write!(f, "Undefined builtin: {n}"),
246 VmError::ImmutableAssignment(n) => {
247 write!(f, "Cannot assign to immutable binding: {n}")
248 }
249 VmError::TypeError(msg) => write!(f, "Type error: {msg}"),
250 VmError::Runtime(msg) => write!(f, "Runtime error: {msg}"),
251 VmError::DivisionByZero => write!(f, "Division by zero"),
252 VmError::Thrown(v) => write!(f, "Thrown: {}", v.display()),
253 VmError::CategorizedError { message, category } => {
254 write!(f, "Error [{}]: {}", category.as_str(), message)
255 }
256 VmError::DaemonQueueFull {
257 daemon_id,
258 capacity,
259 } => write!(
260 f,
261 "Daemon queue full: daemon '{daemon_id}' reached its event_queue_capacity of {capacity}"
262 ),
263 VmError::Return(_) => write!(f, "Return from function"),
264 VmError::InvalidInstruction(op) => write!(f, "Invalid instruction: 0x{op:02x}"),
265 }
266 }
267}
268
269impl std::error::Error for VmError {}