Skip to main content

adk_sandbox/
error.rs

1//! Error types for sandbox execution.
2
3use std::time::Duration;
4use thiserror::Error;
5
6/// Errors that can occur during sandbox execution.
7///
8/// All variants include actionable context to help callers diagnose issues.
9///
10/// # Example
11///
12/// ```rust
13/// use adk_sandbox::SandboxError;
14/// use std::time::Duration;
15///
16/// let err = SandboxError::Timeout { timeout: Duration::from_secs(30) };
17/// assert!(err.to_string().contains("30s"));
18/// ```
19// Feature-gated variants (`workspace`) mean downstream crates cannot match exhaustively.
20#[derive(Debug, Clone, Error)]
21#[non_exhaustive]
22pub enum SandboxError {
23    /// Execution exceeded the configured timeout.
24    #[error("execution timed out after {timeout:?}")]
25    Timeout {
26        /// The timeout duration that was exceeded.
27        timeout: Duration,
28    },
29
30    /// Execution exceeded the configured memory limit (Wasm only).
31    #[error("memory limit exceeded: {limit_mb} MB")]
32    MemoryExceeded {
33        /// The memory limit in megabytes that was exceeded.
34        limit_mb: u32,
35    },
36
37    /// Execution failed due to an internal error (e.g., subprocess I/O failure).
38    #[error("execution failed: {0}")]
39    ExecutionFailed(String),
40
41    /// The request is invalid (e.g., unsupported language for this backend).
42    #[error("invalid request: {0}")]
43    InvalidRequest(String),
44
45    /// The backend is not available (e.g., missing runtime or feature not enabled).
46    #[error("backend unavailable: {0}")]
47    BackendUnavailable(String),
48
49    /// The sandbox enforcer failed to apply the profile.
50    #[error("enforcer '{enforcer}' failed: {message}")]
51    EnforcerFailed {
52        /// The enforcer name (e.g., "seatbelt", "bubblewrap", "restricted-token").
53        enforcer: String,
54        /// A descriptive message explaining what failed.
55        message: String,
56    },
57
58    /// The sandbox enforcer is not available on this system.
59    #[error("enforcer '{enforcer}' unavailable: {message}")]
60    EnforcerUnavailable {
61        /// The enforcer name.
62        enforcer: String,
63        /// A message explaining why the enforcer is not functional.
64        message: String,
65    },
66
67    /// A policy path or resource could not be resolved.
68    #[error("policy violation: {0}")]
69    PolicyViolation(String),
70
71    /// The enforcer cannot enforce part of the policy, so the command does not run.
72    #[error(
73        "enforcer '{enforcer}' cannot enforce {requirement}, so the command does not run with \
74         less confinement than its policy asks for; choose a mode the enforcer supports (see \
75         `SandboxEnforcer::network_support`) or an enforcer that supports this one"
76    )]
77    Unenforceable {
78        /// The enforcer name.
79        enforcer: String,
80        /// What it cannot enforce, such as `network access denied`.
81        requirement: String,
82    },
83
84    // ── Workspace lifecycle variants (behind `workspace` feature) ──────────
85    /// Workspace provisioning failed.
86    #[cfg(feature = "workspace")]
87    #[error("provisioning failed for '{resource}': {reason}. {suggestion}")]
88    ProvisionFailed {
89        /// The resource that failed to provision (e.g., manifest entry path).
90        resource: String,
91        /// A description of why provisioning failed.
92        reason: String,
93        /// An actionable suggestion for resolution.
94        suggestion: String,
95    },
96
97    /// Referenced session does not exist or has been stopped.
98    #[cfg(feature = "workspace")]
99    #[error("session '{handle}' not found. It may have been stopped or expired.")]
100    SessionNotFound {
101        /// The session handle that was not found.
102        handle: String,
103    },
104
105    /// Referenced snapshot does not exist.
106    #[cfg(feature = "workspace")]
107    #[error("snapshot '{id}' not found. It may have been deleted or expired.")]
108    SnapshotNotFound {
109        /// The snapshot ID that was not found.
110        id: String,
111    },
112
113    /// Path traversal attempt detected.
114    #[cfg(feature = "workspace")]
115    #[error("path traversal rejected: '{path}' escapes workspace root. Use relative paths only.")]
116    PathTraversal {
117        /// The offending path that attempted to escape the workspace root.
118        path: String,
119    },
120
121    /// Docker is not available on this host.
122    #[cfg(feature = "workspace")]
123    #[error("Docker unavailable: {reason}. Ensure Docker daemon is running and accessible.")]
124    DockerUnavailable {
125        /// A description of why Docker is unavailable.
126        reason: String,
127    },
128
129    /// Session exceeded its configured timeout.
130    #[cfg(feature = "workspace")]
131    #[error(
132        "session timed out after {timeout:?}. Consider increasing session_timeout in SandboxConfig."
133    )]
134    SessionTimeout {
135        /// The timeout duration that was exceeded.
136        timeout: Duration,
137    },
138
139    /// The sandbox client does not support the operation, such as `pause` on a provider
140    /// without suspended environments.
141    #[cfg(feature = "workspace")]
142    #[error(
143        "{provider} does not support {operation}; check `SandboxClient::capabilities` before \
144         calling it"
145    )]
146    Unsupported {
147        /// The client's provider name (`SandboxClient::provider`).
148        provider: String,
149        /// The operation that is not supported.
150        operation: String,
151    },
152
153    /// A remote sandbox provider refused or failed a request.
154    #[cfg(feature = "workspace")]
155    #[error("{provider} {operation} failed{}: {message}", status.map(|s| format!(" with HTTP {s}")).unwrap_or_default())]
156    Remote {
157        /// The provider name, such as `e2b`, `daytona` or `modal`.
158        provider: String,
159        /// The operation that failed, such as `create sandbox`.
160        operation: String,
161        /// The HTTP status the provider answered with, or for a gRPC provider such as Modal the
162        /// HTTP equivalent of its status code; `None` when no response arrived.
163        status: Option<u16>,
164        /// The provider's message, cut to a bounded length.
165        message: String,
166    },
167}
168
169impl From<std::io::Error> for SandboxError {
170    fn from(err: std::io::Error) -> Self {
171        SandboxError::ExecutionFailed(format!("I/O error: {err}"))
172    }
173}
174
175impl From<SandboxError> for adk_core::AdkError {
176    fn from(err: SandboxError) -> Self {
177        use adk_core::{ErrorCategory, ErrorComponent};
178        let (category, code) = match &err {
179            SandboxError::Timeout { .. } => (ErrorCategory::Timeout, "code.sandbox_timeout"),
180            SandboxError::MemoryExceeded { .. } => (ErrorCategory::Internal, "code.sandbox_memory"),
181            SandboxError::ExecutionFailed(_) => (ErrorCategory::Internal, "code.sandbox_execution"),
182            SandboxError::InvalidRequest(_) => {
183                (ErrorCategory::InvalidInput, "code.sandbox_invalid_request")
184            }
185            SandboxError::BackendUnavailable(_) => {
186                (ErrorCategory::Unavailable, "code.sandbox_unavailable")
187            }
188            SandboxError::EnforcerFailed { .. } => {
189                (ErrorCategory::Internal, "code.sandbox_enforcer_failed")
190            }
191            SandboxError::EnforcerUnavailable { .. } => {
192                (ErrorCategory::Unavailable, "code.sandbox_enforcer_unavailable")
193            }
194            SandboxError::PolicyViolation(_) => {
195                (ErrorCategory::InvalidInput, "code.sandbox_policy_violation")
196            }
197            SandboxError::Unenforceable { .. } => {
198                (ErrorCategory::Unsupported, "code.sandbox_unenforceable")
199            }
200            #[cfg(feature = "workspace")]
201            SandboxError::ProvisionFailed { .. } => {
202                (ErrorCategory::Internal, "code.sandbox_provision_failed")
203            }
204            #[cfg(feature = "workspace")]
205            SandboxError::SessionNotFound { .. } => {
206                (ErrorCategory::NotFound, "code.sandbox_session_not_found")
207            }
208            #[cfg(feature = "workspace")]
209            SandboxError::SnapshotNotFound { .. } => {
210                (ErrorCategory::NotFound, "code.sandbox_snapshot_not_found")
211            }
212            #[cfg(feature = "workspace")]
213            SandboxError::PathTraversal { .. } => {
214                (ErrorCategory::InvalidInput, "code.sandbox_path_traversal")
215            }
216            #[cfg(feature = "workspace")]
217            SandboxError::DockerUnavailable { .. } => {
218                (ErrorCategory::Unavailable, "code.sandbox_docker_unavailable")
219            }
220            #[cfg(feature = "workspace")]
221            SandboxError::SessionTimeout { .. } => {
222                (ErrorCategory::Timeout, "code.sandbox_session_timeout")
223            }
224            #[cfg(feature = "workspace")]
225            SandboxError::Unsupported { .. } => {
226                (ErrorCategory::Unsupported, "code.sandbox_unsupported")
227            }
228            #[cfg(feature = "workspace")]
229            SandboxError::Remote { status, .. } => {
230                let category = match status {
231                    Some(401) => ErrorCategory::Unauthorized,
232                    Some(403) => ErrorCategory::Forbidden,
233                    Some(404) => ErrorCategory::NotFound,
234                    Some(408 | 504) => ErrorCategory::Timeout,
235                    Some(409) => ErrorCategory::Conflict,
236                    Some(429) => ErrorCategory::RateLimited,
237                    Some(400..=499) => ErrorCategory::InvalidInput,
238                    Some(_) | None => ErrorCategory::Unavailable,
239                };
240                (category, "code.sandbox_remote")
241            }
242        };
243        #[cfg(feature = "workspace")]
244        let remote = match &err {
245            SandboxError::Remote { provider, status, .. } => Some((provider.clone(), *status)),
246            _ => None,
247        };
248        let error = adk_core::AdkError::new(ErrorComponent::Code, category, code, err.to_string())
249            .with_source(err);
250        #[cfg(feature = "workspace")]
251        let error = match remote {
252            Some((provider, Some(status))) => {
253                error.with_provider(provider).with_upstream_status(status)
254            }
255            Some((provider, None)) => error.with_provider(provider),
256            None => error,
257        };
258        error
259    }
260}