1use thiserror::Error;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum SessionBuildResource {
18 Capability,
19 MemoryStore,
20 MemoryMaintenance,
21 SessionStore,
22 Queue,
23 Mcp,
24 RlTrajectory,
25 WorkspaceRetrieval,
26}
27
28impl std::fmt::Display for SessionBuildResource {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(match self {
31 Self::Capability => "capability runtime",
32 Self::MemoryStore => "memory store",
33 Self::MemoryMaintenance => "memory maintenance",
34 Self::SessionStore => "session store",
35 Self::Queue => "session queue",
36 Self::Mcp => "MCP",
37 Self::RlTrajectory => "RL trajectory recorder",
38 Self::WorkspaceRetrieval => "workspace retrieval",
39 })
40 }
41}
42
43pub type Result<T> = std::result::Result<T, CodeError>;
45
46#[derive(Debug, Error)]
51pub enum CodeError {
52 #[error("Config error: {0}")]
54 Config(String),
55
56 #[error("LLM error: {0}")]
58 Llm(String),
59
60 #[error("Tool error: {tool}: {message}")]
62 Tool { tool: String, message: String },
63
64 #[error("Session error: {0}")]
66 Session(String),
67
68 #[error("Invalid session configuration for '{field}': {message}")]
70 SessionConfiguration {
71 field: &'static str,
72 message: String,
73 },
74
75 #[error("Failed to initialize {resource}: {message}")]
77 SessionInitialization {
78 resource: SessionBuildResource,
79 message: String,
80 },
81
82 #[error(
85 "{resource} requires asynchronous session construction; use Agent::session_builder(...).build().await"
86 )]
87 AsyncSessionBuildRequired { resource: SessionBuildResource },
88
89 #[error("Session '{session_id}' is closed")]
95 SessionClosed { session_id: String },
96
97 #[error("Session '{session_id}' already has an active operation")]
103 SessionBusy { session_id: String },
104
105 #[error("Task admission for session '{session_id}' was cancelled")]
107 TaskAdmissionCancelled { session_id: String },
108
109 #[error("Task scheduler is closed")]
111 TaskSchedulerClosed,
112
113 #[error("Run '{run_id}' is already bound to different immutable input")]
116 RunIdentityConflict { run_id: String },
117
118 #[error("Run control error: {0}")]
121 RunControl(#[from] crate::run_control::RunControlError),
122
123 #[error("Budget exhausted on '{resource}': {reason}")]
127 BudgetExhausted { resource: String, reason: String },
128
129 #[error("Security error: {0}")]
131 Security(String),
132
133 #[error("Context error: {0}")]
135 Context(String),
136
137 #[error("MCP error: {0}")]
139 Mcp(String),
140
141 #[error("Queue error: {0}")]
143 Queue(String),
144
145 #[error("Capability runtime error: {0}")]
147 Capability(#[from] crate::capability::CapabilityRuntimeError),
148
149 #[error("Flow error: {0}")]
151 Flow(#[from] a3s_flow::FlowError),
152
153 #[error("IO error: {0}")]
155 Io(#[from] std::io::Error),
156
157 #[error("Serialization error: {0}")]
159 Serialization(#[from] serde_json::Error),
160
161 #[error("{0:#}")]
167 Internal(#[from] anyhow::Error),
168}
169
170impl CodeError {
171 pub const fn code(&self) -> &'static str {
173 match self {
174 Self::Config(_) => "CONFIG_ERROR",
175 Self::Llm(_) => "LLM_ERROR",
176 Self::Tool { .. } => "TOOL_ERROR",
177 Self::Session(_) => "SESSION_ERROR",
178 Self::SessionConfiguration { .. } => "SESSION_CONFIGURATION_ERROR",
179 Self::SessionInitialization { .. } => "SESSION_INITIALIZATION_ERROR",
180 Self::AsyncSessionBuildRequired { .. } => "ASYNC_SESSION_BUILD_REQUIRED",
181 Self::SessionClosed { .. } => "SESSION_CLOSED",
182 Self::SessionBusy { .. } => "SESSION_BUSY",
183 Self::TaskAdmissionCancelled { .. } => "TASK_ADMISSION_CANCELLED",
184 Self::TaskSchedulerClosed => "TASK_SCHEDULER_CLOSED",
185 Self::RunIdentityConflict { .. } => "RUN_IDENTITY_CONFLICT",
186 Self::RunControl(error) => error.code(),
187 Self::BudgetExhausted { .. } => "BUDGET_EXHAUSTED",
188 Self::Security(_) => "SECURITY_ERROR",
189 Self::Context(_) => "CONTEXT_ERROR",
190 Self::Mcp(_) => "MCP_ERROR",
191 Self::Queue(_) => "QUEUE_ERROR",
192 Self::Capability(_) => "CAPABILITY_RUNTIME_ERROR",
193 Self::Flow(_) => "FLOW_ERROR",
194 Self::Io(_) => "IO_ERROR",
195 Self::Serialization(_) => "SERIALIZATION_ERROR",
196 Self::Internal(_) => "INTERNAL_ERROR",
197 }
198 }
199}
200
201pub(crate) fn read_or_recover<T>(lock: &std::sync::RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
211 lock.read().unwrap_or_else(|p| p.into_inner())
212}
213
214pub(crate) fn write_or_recover<T>(
218 lock: &std::sync::RwLock<T>,
219) -> std::sync::RwLockWriteGuard<'_, T> {
220 lock.write().unwrap_or_else(|p| p.into_inner())
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 #[test]
228 fn test_code_error_config() {
229 let err = CodeError::Config("missing API key".to_string());
230 assert!(err.to_string().contains("Config error"));
231 assert!(err.to_string().contains("missing API key"));
232 }
233
234 #[test]
235 fn test_code_error_llm() {
236 let err = CodeError::Llm("rate limited".to_string());
237 assert!(err.to_string().contains("LLM error"));
238 }
239
240 #[test]
241 fn test_code_error_tool() {
242 let err = CodeError::Tool {
243 tool: "bash".to_string(),
244 message: "command not found".to_string(),
245 };
246 let msg = err.to_string();
247 assert!(msg.contains("bash"));
248 assert!(msg.contains("command not found"));
249 }
250
251 #[test]
252 fn test_code_error_session() {
253 let err = CodeError::Session("not found".to_string());
254 assert!(err.to_string().contains("Session error"));
255 }
256
257 #[test]
258 fn test_code_error_session_configuration_keeps_field_identity() {
259 let err = CodeError::SessionConfiguration {
260 field: "session_id",
261 message: "must not be empty".to_string(),
262 };
263 assert!(err.to_string().contains("session_id"));
264 assert!(err.to_string().contains("must not be empty"));
265 }
266
267 #[test]
268 fn test_code_error_session_busy() {
269 let err = CodeError::SessionBusy {
270 session_id: "session-1".to_string(),
271 };
272 assert!(err.to_string().contains("session-1"));
273 assert!(err.to_string().contains("active operation"));
274 }
275
276 #[test]
277 fn test_code_error_security() {
278 let err = CodeError::Security("taint detected".to_string());
279 assert!(err.to_string().contains("Security error"));
280 }
281
282 #[test]
283 fn test_code_error_context() {
284 let err = CodeError::Context("provider failed".to_string());
285 assert!(err.to_string().contains("Context error"));
286 }
287
288 #[test]
289 fn test_code_error_mcp() {
290 let err = CodeError::Mcp("connection refused".to_string());
291 assert!(err.to_string().contains("MCP error"));
292 }
293
294 #[test]
295 fn test_code_error_queue() {
296 let err = CodeError::Queue("lane full".to_string());
297 assert!(err.to_string().contains("Queue error"));
298 }
299
300 #[test]
301 fn test_code_error_from_io() {
302 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
303 let err: CodeError = io_err.into();
304 assert!(matches!(err, CodeError::Io(_)));
305 assert!(err.to_string().contains("file missing"));
306 }
307
308 #[test]
309 fn test_code_error_from_serde_json() {
310 let json_err = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
311 let err: CodeError = json_err.into();
312 assert!(matches!(err, CodeError::Serialization(_)));
313 }
314
315 #[test]
316 fn test_code_error_from_anyhow() {
317 let anyhow_err = anyhow::anyhow!("something went wrong");
318 let err: CodeError = anyhow_err.into();
319 assert!(matches!(err, CodeError::Internal(_)));
320 assert!(err.to_string().contains("something went wrong"));
321 }
322
323 #[test]
324 fn stable_error_codes_cover_control_flow_variants() {
325 assert_eq!(
326 CodeError::SessionBusy {
327 session_id: "session-1".to_string(),
328 }
329 .code(),
330 "SESSION_BUSY"
331 );
332 assert_eq!(
333 CodeError::SessionClosed {
334 session_id: "session-1".to_string(),
335 }
336 .code(),
337 "SESSION_CLOSED"
338 );
339 assert_eq!(
340 CodeError::RunIdentityConflict {
341 run_id: "run-1".to_string(),
342 }
343 .code(),
344 "RUN_IDENTITY_CONFLICT"
345 );
346 assert_eq!(
347 CodeError::BudgetExhausted {
348 resource: "tokens".to_string(),
349 reason: "limit".to_string(),
350 }
351 .code(),
352 "BUDGET_EXHAUSTED"
353 );
354 assert_eq!(
355 CodeError::TaskAdmissionCancelled {
356 session_id: "session-1".to_string(),
357 }
358 .code(),
359 "TASK_ADMISSION_CANCELLED"
360 );
361 assert_eq!(
362 CodeError::TaskSchedulerClosed.code(),
363 "TASK_SCHEDULER_CLOSED"
364 );
365 }
366
367 #[test]
368 fn test_code_error_question_mark_from_anyhow() {
369 fn inner() -> anyhow::Result<()> {
370 anyhow::bail!("inner error")
371 }
372
373 fn outer() -> Result<()> {
374 inner()?; Ok(())
376 }
377
378 let result = outer();
379 assert!(result.is_err());
380 let err = result.unwrap_err();
381 assert!(matches!(err, CodeError::Internal(_)));
382 }
383
384 #[test]
385 fn test_read_or_recover_normal() {
386 let lock = std::sync::RwLock::new(42);
387 let guard = read_or_recover(&lock);
388 assert_eq!(*guard, 42);
389 }
390
391 #[test]
392 fn test_write_or_recover_normal() {
393 let lock = std::sync::RwLock::new(42);
394 let mut guard = write_or_recover(&lock);
395 *guard = 99;
396 drop(guard);
397 assert_eq!(*read_or_recover(&lock), 99);
398 }
399
400 #[test]
401 fn test_read_or_recover_poisoned() {
402 let lock = std::sync::RwLock::new(42);
403 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
405 let _guard = lock.write().unwrap();
406 panic!("intentional poison");
407 }));
408 let guard = read_or_recover(&lock);
410 assert_eq!(*guard, 42);
411 }
412
413 #[test]
414 fn test_write_or_recover_poisoned() {
415 let lock = std::sync::RwLock::new(42);
416 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
417 let _guard = lock.write().unwrap();
418 panic!("intentional poison");
419 }));
420 let mut guard = write_or_recover(&lock);
421 *guard = 100;
422 assert_eq!(*guard, 100);
423 }
424}