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("Budget exhausted on '{resource}': {reason}")]
122 BudgetExhausted { resource: String, reason: String },
123
124 #[error("Security error: {0}")]
126 Security(String),
127
128 #[error("Context error: {0}")]
130 Context(String),
131
132 #[error("MCP error: {0}")]
134 Mcp(String),
135
136 #[error("Queue error: {0}")]
138 Queue(String),
139
140 #[error("Capability runtime error: {0}")]
142 Capability(#[from] crate::capability::CapabilityRuntimeError),
143
144 #[error("Flow error: {0}")]
146 Flow(#[from] a3s_flow::FlowError),
147
148 #[error("IO error: {0}")]
150 Io(#[from] std::io::Error),
151
152 #[error("Serialization error: {0}")]
154 Serialization(#[from] serde_json::Error),
155
156 #[error("{0:#}")]
162 Internal(#[from] anyhow::Error),
163}
164
165impl CodeError {
166 pub const fn code(&self) -> &'static str {
168 match self {
169 Self::Config(_) => "CONFIG_ERROR",
170 Self::Llm(_) => "LLM_ERROR",
171 Self::Tool { .. } => "TOOL_ERROR",
172 Self::Session(_) => "SESSION_ERROR",
173 Self::SessionConfiguration { .. } => "SESSION_CONFIGURATION_ERROR",
174 Self::SessionInitialization { .. } => "SESSION_INITIALIZATION_ERROR",
175 Self::AsyncSessionBuildRequired { .. } => "ASYNC_SESSION_BUILD_REQUIRED",
176 Self::SessionClosed { .. } => "SESSION_CLOSED",
177 Self::SessionBusy { .. } => "SESSION_BUSY",
178 Self::TaskAdmissionCancelled { .. } => "TASK_ADMISSION_CANCELLED",
179 Self::TaskSchedulerClosed => "TASK_SCHEDULER_CLOSED",
180 Self::RunIdentityConflict { .. } => "RUN_IDENTITY_CONFLICT",
181 Self::BudgetExhausted { .. } => "BUDGET_EXHAUSTED",
182 Self::Security(_) => "SECURITY_ERROR",
183 Self::Context(_) => "CONTEXT_ERROR",
184 Self::Mcp(_) => "MCP_ERROR",
185 Self::Queue(_) => "QUEUE_ERROR",
186 Self::Capability(_) => "CAPABILITY_RUNTIME_ERROR",
187 Self::Flow(_) => "FLOW_ERROR",
188 Self::Io(_) => "IO_ERROR",
189 Self::Serialization(_) => "SERIALIZATION_ERROR",
190 Self::Internal(_) => "INTERNAL_ERROR",
191 }
192 }
193}
194
195pub(crate) fn read_or_recover<T>(lock: &std::sync::RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
205 lock.read().unwrap_or_else(|p| p.into_inner())
206}
207
208pub(crate) fn write_or_recover<T>(
212 lock: &std::sync::RwLock<T>,
213) -> std::sync::RwLockWriteGuard<'_, T> {
214 lock.write().unwrap_or_else(|p| p.into_inner())
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
222 fn test_code_error_config() {
223 let err = CodeError::Config("missing API key".to_string());
224 assert!(err.to_string().contains("Config error"));
225 assert!(err.to_string().contains("missing API key"));
226 }
227
228 #[test]
229 fn test_code_error_llm() {
230 let err = CodeError::Llm("rate limited".to_string());
231 assert!(err.to_string().contains("LLM error"));
232 }
233
234 #[test]
235 fn test_code_error_tool() {
236 let err = CodeError::Tool {
237 tool: "bash".to_string(),
238 message: "command not found".to_string(),
239 };
240 let msg = err.to_string();
241 assert!(msg.contains("bash"));
242 assert!(msg.contains("command not found"));
243 }
244
245 #[test]
246 fn test_code_error_session() {
247 let err = CodeError::Session("not found".to_string());
248 assert!(err.to_string().contains("Session error"));
249 }
250
251 #[test]
252 fn test_code_error_session_configuration_keeps_field_identity() {
253 let err = CodeError::SessionConfiguration {
254 field: "session_id",
255 message: "must not be empty".to_string(),
256 };
257 assert!(err.to_string().contains("session_id"));
258 assert!(err.to_string().contains("must not be empty"));
259 }
260
261 #[test]
262 fn test_code_error_session_busy() {
263 let err = CodeError::SessionBusy {
264 session_id: "session-1".to_string(),
265 };
266 assert!(err.to_string().contains("session-1"));
267 assert!(err.to_string().contains("active operation"));
268 }
269
270 #[test]
271 fn test_code_error_security() {
272 let err = CodeError::Security("taint detected".to_string());
273 assert!(err.to_string().contains("Security error"));
274 }
275
276 #[test]
277 fn test_code_error_context() {
278 let err = CodeError::Context("provider failed".to_string());
279 assert!(err.to_string().contains("Context error"));
280 }
281
282 #[test]
283 fn test_code_error_mcp() {
284 let err = CodeError::Mcp("connection refused".to_string());
285 assert!(err.to_string().contains("MCP error"));
286 }
287
288 #[test]
289 fn test_code_error_queue() {
290 let err = CodeError::Queue("lane full".to_string());
291 assert!(err.to_string().contains("Queue error"));
292 }
293
294 #[test]
295 fn test_code_error_from_io() {
296 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
297 let err: CodeError = io_err.into();
298 assert!(matches!(err, CodeError::Io(_)));
299 assert!(err.to_string().contains("file missing"));
300 }
301
302 #[test]
303 fn test_code_error_from_serde_json() {
304 let json_err = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
305 let err: CodeError = json_err.into();
306 assert!(matches!(err, CodeError::Serialization(_)));
307 }
308
309 #[test]
310 fn test_code_error_from_anyhow() {
311 let anyhow_err = anyhow::anyhow!("something went wrong");
312 let err: CodeError = anyhow_err.into();
313 assert!(matches!(err, CodeError::Internal(_)));
314 assert!(err.to_string().contains("something went wrong"));
315 }
316
317 #[test]
318 fn stable_error_codes_cover_control_flow_variants() {
319 assert_eq!(
320 CodeError::SessionBusy {
321 session_id: "session-1".to_string(),
322 }
323 .code(),
324 "SESSION_BUSY"
325 );
326 assert_eq!(
327 CodeError::SessionClosed {
328 session_id: "session-1".to_string(),
329 }
330 .code(),
331 "SESSION_CLOSED"
332 );
333 assert_eq!(
334 CodeError::RunIdentityConflict {
335 run_id: "run-1".to_string(),
336 }
337 .code(),
338 "RUN_IDENTITY_CONFLICT"
339 );
340 assert_eq!(
341 CodeError::BudgetExhausted {
342 resource: "tokens".to_string(),
343 reason: "limit".to_string(),
344 }
345 .code(),
346 "BUDGET_EXHAUSTED"
347 );
348 assert_eq!(
349 CodeError::TaskAdmissionCancelled {
350 session_id: "session-1".to_string(),
351 }
352 .code(),
353 "TASK_ADMISSION_CANCELLED"
354 );
355 assert_eq!(
356 CodeError::TaskSchedulerClosed.code(),
357 "TASK_SCHEDULER_CLOSED"
358 );
359 }
360
361 #[test]
362 fn test_code_error_question_mark_from_anyhow() {
363 fn inner() -> anyhow::Result<()> {
364 anyhow::bail!("inner error")
365 }
366
367 fn outer() -> Result<()> {
368 inner()?; Ok(())
370 }
371
372 let result = outer();
373 assert!(result.is_err());
374 let err = result.unwrap_err();
375 assert!(matches!(err, CodeError::Internal(_)));
376 }
377
378 #[test]
379 fn test_read_or_recover_normal() {
380 let lock = std::sync::RwLock::new(42);
381 let guard = read_or_recover(&lock);
382 assert_eq!(*guard, 42);
383 }
384
385 #[test]
386 fn test_write_or_recover_normal() {
387 let lock = std::sync::RwLock::new(42);
388 let mut guard = write_or_recover(&lock);
389 *guard = 99;
390 drop(guard);
391 assert_eq!(*read_or_recover(&lock), 99);
392 }
393
394 #[test]
395 fn test_read_or_recover_poisoned() {
396 let lock = std::sync::RwLock::new(42);
397 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
399 let _guard = lock.write().unwrap();
400 panic!("intentional poison");
401 }));
402 let guard = read_or_recover(&lock);
404 assert_eq!(*guard, 42);
405 }
406
407 #[test]
408 fn test_write_or_recover_poisoned() {
409 let lock = std::sync::RwLock::new(42);
410 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
411 let _guard = lock.write().unwrap();
412 panic!("intentional poison");
413 }));
414 let mut guard = write_or_recover(&lock);
415 *guard = 100;
416 assert_eq!(*guard, 100);
417 }
418}