1use std::path::PathBuf;
4use std::time::Duration;
5
6use adk_core::{AdkError, ErrorCategory, ErrorComponent, RetryHint};
7
8use crate::digest::Digest;
9
10#[derive(Debug, thiserror::Error)]
29#[non_exhaustive]
30pub enum VisionError {
31 #[error(
33 "unsupported image format {detected}; accepted formats are PNG, JPEG, WebP and the first frame of a GIF"
34 )]
35 UnsupportedFormat {
36 detected: String,
38 },
39
40 #[error(
42 "the image is {actual} bytes, over the {limit}-byte cap; downscale or recompress it before handing it over"
43 )]
44 TooManyBytes {
45 limit: u64,
47 actual: u64,
49 },
50
51 #[error(
53 "the image has {actual} pixels, over the {limit}-pixel cap; downscale it before handing it over"
54 )]
55 TooManyPixels {
56 limit: u64,
58 actual: u64,
60 },
61
62 #[error("the image could not be decoded: {0}")]
64 Decode(String),
65
66 #[error(
68 "backend `{backend}` accepts at most {limit}; the image is {actual}. Crop or downscale it first"
69 )]
70 InputTooLarge {
71 backend: String,
73 limit: String,
75 actual: String,
77 },
78
79 #[error(
81 "backend `{backend}` is remote and only takes images released by the egress gate; configure an `EgressGate` on the runtime"
82 )]
83 NotReleased {
84 backend: String,
86 },
87
88 #[error("the image was not released to {host}: {reason}")]
90 EgressRefused {
91 host: String,
93 reason: String,
95 },
96
97 #[error(
99 "sending image {egress} to {host} as `{data_class}` needs a person's approval; approve that digest and retry"
100 )]
101 EgressHeld {
102 host: String,
104 data_class: String,
106 egress: Digest,
108 },
109
110 #[error(
112 "the egress policy requires `{class}` redaction and no redactor for it is installed; add one to the egress gate or remove the class from the policy"
113 )]
114 RedactionUnavailable {
115 class: String,
117 },
118
119 #[error(
121 "licence acceptance required for model `{model}`: read {licence_url}, then run `adk-rust vision models accept {model}`"
122 )]
123 LicenceAcceptanceRequired {
124 model: String,
126 licence_url: String,
128 },
129
130 #[error(
132 "model `{model}` is licensed {class} ({licence_url}); name it in the licence policy to allow it"
133 )]
134 LicenceNotAllowed {
135 model: String,
137 class: String,
139 licence_url: String,
141 },
142
143 #[error(
145 "model file {path} does not match its manifest: expected {expected}, found {actual}; delete it and fetch again"
146 )]
147 DigestMismatch {
148 path: PathBuf,
150 expected: Digest,
152 actual: Digest,
154 },
155
156 #[error(
158 "model file {path} is {actual} bytes, but its manifest pins {expected}; delete it and fetch again"
159 )]
160 SizeMismatch {
161 path: PathBuf,
163 expected: u64,
165 actual: u64,
167 },
168
169 #[error(
171 "`{file}` of model `{model}` is not in the cache and HF_HUB_OFFLINE is set; fetch it once with network access"
172 )]
173 Offline {
174 model: String,
176 file: String,
178 },
179
180 #[error("fetching `{file}` of model `{model}` failed: {message}")]
182 Fetch {
183 model: String,
185 file: String,
187 message: String,
189 },
190
191 #[error("model manifest `{id}` is invalid: {reason}")]
193 Manifest {
194 id: String,
196 reason: String,
198 },
199
200 #[error("backend `{backend}` is rate limited; retry later")]
202 RateLimited {
203 backend: String,
205 retry_after: Option<Duration>,
207 },
208
209 #[error("backend `{backend}` timed out")]
211 Timeout {
212 backend: String,
214 },
215
216 #[error("the vision call was cancelled")]
218 Cancelled,
219
220 #[error("backend `{backend}` is unavailable: {message}")]
222 Unavailable {
223 backend: String,
225 message: String,
227 },
228
229 #[error("unsupported: {0}")]
231 Unsupported(String),
232
233 #[error("invalid input: {0}")]
235 InvalidInput(String),
236
237 #[error("no vision backend `{0}` is registered for this task")]
239 BackendNotFound(String),
240
241 #[error("backend `{backend}` returned output that could not be parsed: {message}")]
243 Parse {
244 backend: String,
246 message: String,
248 },
249
250 #[error("backend `{backend}` failed: {message}")]
252 Backend {
253 backend: String,
255 message: String,
257 },
258
259 #[error("{action} {path}: {source}")]
261 Io {
262 action: &'static str,
264 path: PathBuf,
266 #[source]
268 source: std::io::Error,
269 },
270
271 #[error(
274 "collection `{collection}` holds vectors of embedding space {recorded}, not {offered}; \
275 re-index into a new collection with this embedder, or use the embedder the collection \
276 was built with"
277 )]
278 SpaceMismatch {
279 collection: String,
281 recorded: String,
283 offered: String,
285 },
286
287 #[error(transparent)]
289 Core(#[from] AdkError),
290}
291
292impl VisionError {
293 pub fn code(&self) -> &'static str {
295 match self {
296 Self::UnsupportedFormat { .. } => "vision.unsupported_format",
297 Self::TooManyBytes { .. } => "vision.too_many_bytes",
298 Self::TooManyPixels { .. } => "vision.too_many_pixels",
299 Self::Decode(_) => "vision.decode",
300 Self::InputTooLarge { .. } => "vision.input_too_large",
301 Self::NotReleased { .. } => "vision.not_released",
302 Self::EgressRefused { .. } => "vision.egress.refused",
303 Self::EgressHeld { .. } => "vision.egress.held",
304 Self::RedactionUnavailable { .. } => "vision.egress.redaction_unavailable",
305 Self::LicenceAcceptanceRequired { .. } => "vision.model.licence_acceptance_required",
306 Self::LicenceNotAllowed { .. } => "vision.model.licence_not_allowed",
307 Self::DigestMismatch { .. } => "vision.model.digest_mismatch",
308 Self::SizeMismatch { .. } => "vision.model.size_mismatch",
309 Self::Offline { .. } => "vision.model.offline",
310 Self::Fetch { .. } => "vision.model.fetch",
311 Self::Manifest { .. } => "vision.model.manifest",
312 Self::RateLimited { .. } => "vision.rate_limited",
313 Self::Timeout { .. } => "vision.timeout",
314 Self::Cancelled => "vision.cancelled",
315 Self::Unavailable { .. } => "vision.unavailable",
316 Self::Unsupported(_) => "vision.unsupported",
317 Self::InvalidInput(_) => "vision.invalid_input",
318 Self::BackendNotFound(_) => "vision.backend_not_found",
319 Self::Parse { .. } => "vision.parse",
320 Self::Backend { .. } => "vision.backend",
321 Self::Io { .. } => "vision.io",
322 Self::SpaceMismatch { .. } => "vision.memory.space_mismatch",
323 Self::Core(_) => "vision.core",
324 }
325 }
326
327 pub fn category(&self) -> ErrorCategory {
329 match self {
330 Self::UnsupportedFormat { .. }
331 | Self::TooManyBytes { .. }
332 | Self::TooManyPixels { .. }
333 | Self::Decode(_)
334 | Self::InputTooLarge { .. }
335 | Self::Manifest { .. }
336 | Self::SpaceMismatch { .. }
337 | Self::InvalidInput(_) => ErrorCategory::InvalidInput,
338 Self::NotReleased { .. }
339 | Self::EgressRefused { .. }
340 | Self::EgressHeld { .. }
341 | Self::RedactionUnavailable { .. }
342 | Self::LicenceNotAllowed { .. }
343 | Self::DigestMismatch { .. }
344 | Self::SizeMismatch { .. } => ErrorCategory::Forbidden,
345 Self::LicenceAcceptanceRequired { .. } => ErrorCategory::Unauthorized,
346 Self::Offline { .. } | Self::BackendNotFound(_) => ErrorCategory::NotFound,
347 Self::Fetch { .. } | Self::Unavailable { .. } => ErrorCategory::Unavailable,
348 Self::RateLimited { .. } => ErrorCategory::RateLimited,
349 Self::Timeout { .. } => ErrorCategory::Timeout,
350 Self::Cancelled => ErrorCategory::Cancelled,
351 Self::Unsupported(_) => ErrorCategory::Unsupported,
352 Self::Parse { .. } | Self::Backend { .. } | Self::Io { .. } => ErrorCategory::Internal,
353 Self::Core(err) => err.category,
354 }
355 }
356
357 pub(crate) fn io(
358 action: &'static str,
359 path: impl Into<PathBuf>,
360 source: std::io::Error,
361 ) -> Self {
362 Self::Io { action, path: path.into(), source }
363 }
364}
365
366impl From<VisionError> for AdkError {
367 fn from(err: VisionError) -> Self {
368 let code = err.code();
369 let category = err.category();
370 match err {
371 VisionError::Core(inner) => inner,
372 VisionError::RateLimited { ref backend, retry_after } => {
373 let mut retry = RetryHint::for_category(category);
374 if let Some(after) = retry_after {
375 retry = retry.with_retry_after(after);
376 }
377 let provider = backend.clone();
378 AdkError::new(ErrorComponent::Tool, category, code, err.to_string())
379 .with_retry(retry)
380 .with_provider(provider)
381 }
382 other => AdkError::new(ErrorComponent::Tool, category, code, other.to_string()),
383 }
384 }
385}
386
387pub type Result<T, E = VisionError> = std::result::Result<T, E>;
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 #[test]
395 fn rate_limits_carry_the_retry_hint() {
396 let err: AdkError = VisionError::RateLimited {
397 backend: "sam-3.1".into(),
398 retry_after: Some(Duration::from_secs(3)),
399 }
400 .into();
401 assert_eq!(err.category, ErrorCategory::RateLimited);
402 assert_eq!(err.code, "vision.rate_limited");
403 assert_eq!(err.retry.retry_after(), Some(Duration::from_secs(3)));
404 assert!(err.retry.should_retry);
405 }
406
407 #[test]
408 fn licence_gate_names_the_url_and_the_command() {
409 let err: AdkError = VisionError::LicenceAcceptanceRequired {
410 model: "sam3-local".into(),
411 licence_url: "https://example.org/sam-license".into(),
412 }
413 .into();
414 assert_eq!(err.category, ErrorCategory::Unauthorized);
415 assert!(err.message.contains("licence acceptance required"));
416 assert!(err.message.contains("https://example.org/sam-license"));
417 assert!(err.message.contains("adk-rust vision models accept sam3-local"));
418 }
419
420 #[test]
421 fn unreleased_images_are_forbidden() {
422 let err: AdkError = VisionError::NotReleased { backend: "gemini".into() }.into();
423 assert_eq!(err.category, ErrorCategory::Forbidden);
424 }
425
426 #[test]
427 fn platform_errors_pass_through_unchanged() {
428 let inner = AdkError::new(
429 ErrorComponent::Model,
430 ErrorCategory::ResourceExhausted,
431 "budget.exceeded",
432 "over budget",
433 );
434 let err: AdkError = VisionError::Core(inner).into();
435 assert_eq!(err.code, "budget.exceeded");
436 assert_eq!(err.category, ErrorCategory::ResourceExhausted);
437 }
438}