| 1 | use std::io::Cursor; |
| 2 | use std::path::Path; |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | use base64::Engine as _; |
| 6 | use base64::engine::general_purpose::STANDARD; |
| 7 | use codewhale_models::image_window::parse_data_url; |
| 8 | use codewhale_models::{ContentBlock, Message}; |
| 9 | use codewhale_runtime::hashing::sha256_hex; |
| 10 | use image::{DynamicImage, GenericImageView, ImageError, ImageReader}; |
| 11 | use serde::Deserialize; |
| 12 | use serde_json::{Value, json}; |
| 13 | |
| 14 | use super::core_call::HeldImage; |
| 15 | use super::dsh_broker::{ |
| 16 | BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode, |
| 17 | }; |
| 18 | use super::protocol::DshService; |
| 19 | use crate::image_attach::{ |
| 20 | ACCEPTED_IMAGE_MEDIA_TYPES, ATTACH_MAX_EDGE_PX, MAX_IMAGE_BYTES, MAX_IMAGE_DIMENSION, |
| 21 | MAX_IMAGE_PIXELS, decode_and_guard_image, decode_limits, detect_rejected_format, |
| 22 | prepare_tool_image_bytes, sniff_media_type, stored_tool_image_payload, |
| 23 | }; |
| 24 | use crate::tools::read_media::fit_and_encode; |
| 25 | |
| 26 | const MAX_ATTACHMENT_ID_LEN: usize = 7 + 64; |
| 27 | const MAX_NAME_LEN: usize = 128; |
| 28 | |
| 29 | #[derive(Deserialize)] |
| 30 | #[serde(tag = "method", content = "input", rename_all = "snake_case")] |
| 31 | enum AttachmentsMethod { |
| 32 | Validate(ImageBytesInput), |
| 33 | Save(ImageBytesInput), |
| 34 | Read(ReadInput), |
| 35 | ReadRequest(ReadRequestInput), |
| 36 | } |
| 37 | |
| 38 | impl BrokerMethods for AttachmentsMethod { |
| 39 | const NAMES: &'static [&'static str] = &["validate", "save", "read", "read_request"]; |
| 40 | } |
| 41 | |
| 42 | #[derive(Deserialize)] |
| 43 | #[serde(deny_unknown_fields)] |
| 44 | struct ImageBytesInput { |
| 45 | data_base64: String, |
| 46 | media_type: String, |
| 47 | name: Option<String>, |
| 48 | } |
| 49 | |
| 50 | #[derive(Deserialize)] |
| 51 | #[serde(deny_unknown_fields)] |
| 52 | struct AttachmentRefWire { |
| 53 | attachment_id: String, |
| 54 | media_type: Option<String>, |
| 55 | bytes: Option<u64>, |
| 56 | width: Option<u32>, |
| 57 | height: Option<u32>, |
| 58 | } |
| 59 | |
| 60 | #[derive(Deserialize)] |
| 61 | #[serde(deny_unknown_fields)] |
| 62 | struct ReadInput { |
| 63 | attachment: AttachmentRefWire, |
| 64 | } |
| 65 | |
| 66 | #[derive(Deserialize)] |
| 67 | #[serde(deny_unknown_fields)] |
| 68 | struct ReadRequestInput { |
| 69 | attachment: AttachmentRefWire, |
| 70 | width: Option<u32>, |
| 71 | height: Option<u32>, |
| 72 | max_bytes: Option<usize>, |
| 73 | } |
| 74 | |
| 75 | struct StoredImage { |
| 76 | attachment_id: String, |
| 77 | media_type: String, |
| 78 | bytes: Vec<u8>, |
| 79 | width: u32, |
| 80 | height: u32, |
| 81 | } |
| 82 | |
| 83 | struct ValidatedImage { |
| 84 | bytes: Vec<u8>, |
| 85 | media_type: &'static str, |
| 86 | width: u32, |
| 87 | height: u32, |
| 88 | } |
| 89 | |
| 90 | struct CodedError { |
| 91 | code: &'static str, |
| 92 | message: String, |
| 93 | } |
| 94 | |
| 95 | fn refuse(code: &str, message: impl std::fmt::Display) -> BrokerRefusal { |
| 96 | BrokerRefusal::Refused { |
| 97 | service: DshService::Attachments, |
| 98 | message: format!("[{code}] {message}"), |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | fn invalid_input(message: impl Into<String>) -> BrokerRefusal { |
| 103 | BrokerRefusal::InvalidInput { |
| 104 | service: DshService::Attachments, |
| 105 | message: message.into(), |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn refused_with_record( |
| 110 | call: &BrokerCall, |
| 111 | method: &str, |
| 112 | code: &str, |
| 113 | message: impl std::fmt::Display, |
| 114 | ) -> BrokerRefusal { |
| 115 | let _ = call.context.record(json!({ |
| 116 | "method": method, |
| 117 | "outcome": "refused", |
| 118 | "reason": code, |
| 119 | })); |
| 120 | refuse(code, message) |
| 121 | } |
| 122 | |
| 123 | fn valid_attachment_id(id: &str) -> bool { |
| 124 | id.len() == MAX_ATTACHMENT_ID_LEN |
| 125 | && id.strip_prefix("sha256:").is_some_and(|hex| { |
| 126 | hex.len() == 64 |
| 127 | && hex |
| 128 | .bytes() |
| 129 | .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | fn check_name(name: Option<&str>) -> Result<Option<String>, BrokerRefusal> { |
| 134 | let Some(name) = name else { |
| 135 | return Ok(None); |
| 136 | }; |
| 137 | if name.is_empty() |
| 138 | || name.len() > MAX_NAME_LEN |
| 139 | || name.starts_with('.') |
| 140 | || name.contains('/') |
| 141 | || name.contains('\\') |
| 142 | || name.contains("..") |
| 143 | || name.contains(':') |
| 144 | || name.chars().any(|ch| ch.is_control()) |
| 145 | { |
| 146 | return Err(invalid_input( |
| 147 | "attachment name must be a non-empty basename with no path separators or control characters", |
| 148 | )); |
| 149 | } |
| 150 | Ok(Some(name.to_string())) |
| 151 | } |
| 152 | |
| 153 | fn accepted_media_type(raw: &str) -> Option<&'static str> { |
| 154 | ACCEPTED_IMAGE_MEDIA_TYPES |
| 155 | .iter() |
| 156 | .copied() |
| 157 | .find(|&candidate| candidate == raw) |
| 158 | } |
| 159 | |
| 160 | fn validate_raw_image( |
| 161 | data_base64: &str, |
| 162 | declared_media_type: &str, |
| 163 | ) -> Result<ValidatedImage, CodedError> { |
| 164 | let Some(declared) = accepted_media_type(declared_media_type) else { |
| 165 | return Err(CodedError { |
| 166 | code: "UNSUPPORTED_IMAGE_TYPE", |
| 167 | message: format!("unsupported image media type: {declared_media_type}"), |
| 168 | }); |
| 169 | }; |
| 170 | let max_b64 = MAX_IMAGE_BYTES.div_ceil(3) * 4; |
| 171 | if data_base64.len() > max_b64 { |
| 172 | return Err(CodedError { |
| 173 | code: "IMAGE_TOO_LARGE", |
| 174 | message: format!("image exceeds the {MAX_IMAGE_BYTES} byte limit"), |
| 175 | }); |
| 176 | } |
| 177 | let bytes = STANDARD.decode(data_base64).map_err(|_| CodedError { |
| 178 | code: "INVALID_IMAGE_BASE64", |
| 179 | message: "invalid base64 image payload".to_string(), |
| 180 | })?; |
| 181 | if bytes.is_empty() { |
| 182 | return Err(CodedError { |
| 183 | code: "INVALID_IMAGE", |
| 184 | message: "image payload is empty".to_string(), |
| 185 | }); |
| 186 | } |
| 187 | if bytes.len() > MAX_IMAGE_BYTES { |
| 188 | return Err(CodedError { |
| 189 | code: "IMAGE_TOO_LARGE", |
| 190 | message: format!("image exceeds the {MAX_IMAGE_BYTES} byte limit"), |
| 191 | }); |
| 192 | } |
| 193 | if let Some(rejected) = detect_rejected_format(&bytes) { |
| 194 | return Err(CodedError { |
| 195 | code: "UNSUPPORTED_IMAGE_TYPE", |
| 196 | message: format!("{rejected} is not supported; use PNG, JPEG, GIF, or WebP"), |
| 197 | }); |
| 198 | } |
| 199 | let Some(sniffed) = sniff_media_type(&bytes) else { |
| 200 | return Err(CodedError { |
| 201 | code: "INVALID_IMAGE", |
| 202 | message: "image bytes do not match PNG, JPEG, GIF, or WebP".to_string(), |
| 203 | }); |
| 204 | }; |
| 205 | if sniffed != declared { |
| 206 | return Err(CodedError { |
| 207 | code: "IMAGE_TYPE_MISMATCH", |
| 208 | message: format!( |
| 209 | "declared mediaType {declared} does not match image content {sniffed}" |
| 210 | ), |
| 211 | }); |
| 212 | } |
| 213 | let mut reader = ImageReader::new(Cursor::new(&bytes)) |
| 214 | .with_guessed_format() |
| 215 | .map_err(|_| CodedError { |
| 216 | code: "INVALID_IMAGE", |
| 217 | message: "could not inspect image header".to_string(), |
| 218 | })?; |
| 219 | reader.limits(decode_limits()); |
| 220 | let (width, height) = reader.into_dimensions().map_err(|error| match error { |
| 221 | ImageError::Limits(_) => CodedError { |
| 222 | code: "IMAGE_DIMENSION_TOO_LARGE", |
| 223 | message: format!("image dimensions exceed the {MAX_IMAGE_DIMENSION}px limit"), |
| 224 | }, |
| 225 | _ => CodedError { |
| 226 | code: "INVALID_IMAGE", |
| 227 | message: "corrupt or truncated image header".to_string(), |
| 228 | }, |
| 229 | })?; |
| 230 | if width == 0 || height == 0 { |
| 231 | return Err(CodedError { |
| 232 | code: "INVALID_IMAGE", |
| 233 | message: "image has zero width or height".to_string(), |
| 234 | }); |
| 235 | } |
| 236 | if width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION { |
| 237 | return Err(CodedError { |
| 238 | code: "IMAGE_DIMENSION_TOO_LARGE", |
| 239 | message: format!( |
| 240 | "image dimensions {width}x{height} exceed the {MAX_IMAGE_DIMENSION}px limit" |
| 241 | ), |
| 242 | }); |
| 243 | } |
| 244 | if u64::from(width) * u64::from(height) > MAX_IMAGE_PIXELS { |
| 245 | return Err(CodedError { |
| 246 | code: "IMAGE_TOO_MANY_PIXELS", |
| 247 | message: format!("image pixels exceed the {MAX_IMAGE_PIXELS} pixel limit"), |
| 248 | }); |
| 249 | } |
| 250 | let (decoded, dec_width, dec_height) = |
| 251 | decode_and_guard_image(&bytes).map_err(|_| CodedError { |
| 252 | code: "INVALID_IMAGE", |
| 253 | message: "invalid or corrupted image payload".to_string(), |
| 254 | })?; |
| 255 | let (actual_width, actual_height) = decoded.dimensions(); |
| 256 | if dec_width == 0 |
| 257 | || dec_height == 0 |
| 258 | || actual_width == 0 |
| 259 | || actual_height == 0 |
| 260 | || actual_width > MAX_IMAGE_DIMENSION |
| 261 | || actual_height > MAX_IMAGE_DIMENSION |
| 262 | { |
| 263 | return Err(CodedError { |
| 264 | code: "IMAGE_DIMENSION_TOO_LARGE", |
| 265 | message: format!("image dimensions exceed the {MAX_IMAGE_DIMENSION}px limit"), |
| 266 | }); |
| 267 | } |
| 268 | if u64::from(actual_width) * u64::from(actual_height) > MAX_IMAGE_PIXELS { |
| 269 | return Err(CodedError { |
| 270 | code: "IMAGE_TOO_MANY_PIXELS", |
| 271 | message: format!("image pixels exceed the {MAX_IMAGE_PIXELS} pixel limit"), |
| 272 | }); |
| 273 | } |
| 274 | Ok(ValidatedImage { |
| 275 | bytes, |
| 276 | media_type: sniffed, |
| 277 | width: actual_width, |
| 278 | height: actual_height, |
| 279 | }) |
| 280 | } |
| 281 | |
| 282 | fn prepare_for_save( |
| 283 | data_base64: &str, |
| 284 | declared_media_type: &str, |
| 285 | ) -> Result<(Vec<u8>, &'static str, u32, u32, String), CodedError> { |
| 286 | let validated = validate_raw_image(data_base64, declared_media_type)?; |
| 287 | let prepared = prepare_tool_image_bytes(&validated.bytes, validated.media_type); |
| 288 | let Some(codewhale_tools::ToolResultContentBlock::Image { mime_type, data }) = prepared.block |
| 289 | else { |
| 290 | return Err(CodedError { |
| 291 | code: "IMAGE_TOO_LARGE", |
| 292 | message: "image could not fit the cross-provider tool delivery budget".to_string(), |
| 293 | }); |
| 294 | }; |
| 295 | let stored_bytes = STANDARD.decode(&data).map_err(|_| CodedError { |
| 296 | code: "INVALID_IMAGE", |
| 297 | message: "prepared image encoding failed".to_string(), |
| 298 | })?; |
| 299 | if stored_bytes.len() > MAX_IMAGE_BYTES { |
| 300 | return Err(CodedError { |
| 301 | code: "IMAGE_TOO_LARGE", |
| 302 | message: format!("prepared image exceeds the {MAX_IMAGE_BYTES} byte limit"), |
| 303 | }); |
| 304 | } |
| 305 | let Some(stored_mime) = accepted_media_type(&mime_type) else { |
| 306 | return Err(CodedError { |
| 307 | code: "UNSUPPORTED_IMAGE_TYPE", |
| 308 | message: format!("prepared image type {mime_type} is unsupported"), |
| 309 | }); |
| 310 | }; |
| 311 | if sniff_media_type(&stored_bytes) != Some(stored_mime) { |
| 312 | return Err(CodedError { |
| 313 | code: "INVALID_IMAGE", |
| 314 | message: "prepared image bytes failed media verification".to_string(), |
| 315 | }); |
| 316 | } |
| 317 | let (decoded, _, _) = decode_and_guard_image(&stored_bytes).map_err(|_| CodedError { |
| 318 | code: "INVALID_IMAGE", |
| 319 | message: "prepared image failed decode verification".to_string(), |
| 320 | })?; |
| 321 | let (width, height) = decoded.dimensions(); |
| 322 | if width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION { |
| 323 | return Err(CodedError { |
| 324 | code: "IMAGE_DIMENSION_TOO_LARGE", |
| 325 | message: format!("prepared image dimensions exceed the {MAX_IMAGE_DIMENSION}px limit"), |
| 326 | }); |
| 327 | } |
| 328 | if u64::from(width) * u64::from(height) > MAX_IMAGE_PIXELS { |
| 329 | return Err(CodedError { |
| 330 | code: "IMAGE_TOO_MANY_PIXELS", |
| 331 | message: format!("prepared image pixels exceed the {MAX_IMAGE_PIXELS} pixel limit"), |
| 332 | }); |
| 333 | } |
| 334 | Ok((stored_bytes, stored_mime, width, height, data)) |
| 335 | } |
| 336 | |
| 337 | fn verify_stored_bytes(attachment_id: String, b64: &str) -> Option<(StoredImage, DynamicImage)> { |
| 338 | if b64.len() > MAX_IMAGE_BYTES.div_ceil(3) * 4 + 4 { |
| 339 | return None; |
| 340 | } |
| 341 | let bytes = STANDARD.decode(b64).ok()?; |
| 342 | if bytes.is_empty() || bytes.len() > MAX_IMAGE_BYTES { |
| 343 | return None; |
| 344 | } |
| 345 | let id = format!("sha256:{}", sha256_hex(&bytes)); |
| 346 | if id != attachment_id { |
| 347 | return None; |
| 348 | } |
| 349 | let media_type = sniff_media_type(&bytes)?; |
| 350 | let (decoded, _, _) = decode_and_guard_image(&bytes).ok()?; |
| 351 | let (width, height) = decoded.dimensions(); |
| 352 | Some(( |
| 353 | StoredImage { |
| 354 | attachment_id: id, |
| 355 | media_type: media_type.to_string(), |
| 356 | bytes, |
| 357 | width, |
| 358 | height, |
| 359 | }, |
| 360 | decoded, |
| 361 | )) |
| 362 | } |
| 363 | |
| 364 | fn resolve_from_conversation_blocking( |
| 365 | held: Option<HeldImage>, |
| 366 | messages: Option<&[Message]>, |
| 367 | attachment_id: &str, |
| 368 | ) -> Option<(StoredImage, DynamicImage)> { |
| 369 | if let Some(held) = held |
| 370 | && let Some(found) = verify_stored_bytes(held.attachment_id, &held.data_base64) |
| 371 | { |
| 372 | return Some(found); |
| 373 | } |
| 374 | let messages = messages?; |
| 375 | for message in messages { |
| 376 | for block in &message.content { |
| 377 | match block { |
| 378 | ContentBlock::ImageUrl { image_url } => { |
| 379 | if let Some((_, payload)) = parse_data_url(&image_url.url) |
| 380 | && let Some(found) = verify_stored_bytes(attachment_id.to_string(), payload) |
| 381 | { |
| 382 | return Some(found); |
| 383 | } |
| 384 | } |
| 385 | ContentBlock::ToolResult { |
| 386 | content_blocks: Some(blocks), |
| 387 | .. |
| 388 | } => { |
| 389 | for value in blocks { |
| 390 | if let Some((_, payload)) = stored_tool_image_payload(value) |
| 391 | && let Some(found) = |
| 392 | verify_stored_bytes(attachment_id.to_string(), payload) |
| 393 | { |
| 394 | return Some(found); |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | _ => {} |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | None |
| 403 | } |
| 404 | |
| 405 | fn check_ref_fields(wire: &AttachmentRefWire, stored: &StoredImage) -> Result<(), CodedError> { |
| 406 | if let Some(ref media_type) = wire.media_type |
| 407 | && media_type != &stored.media_type |
| 408 | { |
| 409 | return Err(CodedError { |
| 410 | code: "INVALID_ATTACHMENT_REF", |
| 411 | message: "attachment reference mediaType does not match stored image".to_string(), |
| 412 | }); |
| 413 | } |
| 414 | if let Some(bytes) = wire.bytes |
| 415 | && bytes != stored.bytes.len() as u64 |
| 416 | { |
| 417 | return Err(CodedError { |
| 418 | code: "INVALID_ATTACHMENT_REF", |
| 419 | message: "attachment reference byte size does not match stored image".to_string(), |
| 420 | }); |
| 421 | } |
| 422 | if let Some(width) = wire.width |
| 423 | && width != stored.width |
| 424 | { |
| 425 | return Err(CodedError { |
| 426 | code: "INVALID_ATTACHMENT_REF", |
| 427 | message: "attachment reference width does not match stored image".to_string(), |
| 428 | }); |
| 429 | } |
| 430 | if let Some(height) = wire.height |
| 431 | && height != stored.height |
| 432 | { |
| 433 | return Err(CodedError { |
| 434 | code: "INVALID_ATTACHMENT_REF", |
| 435 | message: "attachment reference height does not match stored image".to_string(), |
| 436 | }); |
| 437 | } |
| 438 | Ok(()) |
| 439 | } |
| 440 | |
| 441 | fn ref_json(stored: &StoredImage) -> Value { |
| 442 | json!({ |
| 443 | "attachment_id": stored.attachment_id, |
| 444 | "media_type": stored.media_type, |
| 445 | "bytes": stored.bytes.len(), |
| 446 | "width": stored.width, |
| 447 | "height": stored.height, |
| 448 | }) |
| 449 | } |
| 450 | |
| 451 | fn target_edge_for_box( |
| 452 | orig_w: u32, |
| 453 | orig_h: u32, |
| 454 | wanted_w: Option<u32>, |
| 455 | wanted_h: Option<u32>, |
| 456 | ) -> u32 { |
| 457 | let edge_for_w = |tw: u32| { |
| 458 | if orig_w <= orig_h { |
| 459 | (u64::from(tw) * u64::from(orig_h) / u64::from(orig_w).max(1)) |
| 460 | .clamp(1, u64::from(MAX_IMAGE_DIMENSION)) as u32 |
| 461 | } else { |
| 462 | tw |
| 463 | } |
| 464 | }; |
| 465 | let edge_for_h = |th: u32| { |
| 466 | if orig_h < orig_w { |
| 467 | (u64::from(th) * u64::from(orig_w) / u64::from(orig_h).max(1)) |
| 468 | .clamp(1, u64::from(MAX_IMAGE_DIMENSION)) as u32 |
| 469 | } else { |
| 470 | th |
| 471 | } |
| 472 | }; |
| 473 | match (wanted_w, wanted_h) { |
| 474 | (Some(tw), Some(th)) => edge_for_w(tw).min(edge_for_h(th)), |
| 475 | (Some(tw), None) => { |
| 476 | if orig_w <= tw { |
| 477 | orig_w.max(orig_h) |
| 478 | } else { |
| 479 | edge_for_w(tw) |
| 480 | } |
| 481 | } |
| 482 | (None, Some(th)) => { |
| 483 | if orig_h <= th { |
| 484 | orig_w.max(orig_h) |
| 485 | } else { |
| 486 | edge_for_h(th) |
| 487 | } |
| 488 | } |
| 489 | (None, None) => orig_w.max(orig_h).min(ATTACH_MAX_EDGE_PX), |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | async fn handle_validate( |
| 494 | call: &BrokerCall, |
| 495 | input: ImageBytesInput, |
| 496 | ) -> Result<Value, BrokerRefusal> { |
| 497 | check_name(input.name.as_deref())?; |
| 498 | let target = accepted_media_type(&input.media_type); |
| 499 | call.context |
| 500 | .act("validate", BrokerEffect::Read, target) |
| 501 | .await?; |
| 502 | if call.context.cancel().is_cancelled() { |
| 503 | return Err(refuse( |
| 504 | "CANCELLED", |
| 505 | "the attachments broker call was cancelled", |
| 506 | )); |
| 507 | } |
| 508 | let validated = tokio::task::spawn_blocking(move || { |
| 509 | validate_raw_image(&input.data_base64, &input.media_type) |
| 510 | }) |
| 511 | .await |
| 512 | .map_err(|_| refuse("ATTACHMENT_READ_FAILED", "image validation task ended"))?; |
| 513 | if call.context.cancel().is_cancelled() { |
| 514 | return Err(refuse( |
| 515 | "CANCELLED", |
| 516 | "the attachments broker call was cancelled", |
| 517 | )); |
| 518 | } |
| 519 | match validated { |
| 520 | Ok(image) => { |
| 521 | let _ = call.context.record(json!({ |
| 522 | "method": "validate", |
| 523 | "outcome": "valid", |
| 524 | "media_type": image.media_type, |
| 525 | "bytes": image.bytes.len(), |
| 526 | "width": image.width, |
| 527 | "height": image.height, |
| 528 | })); |
| 529 | Ok(json!({ |
| 530 | "ok": true, |
| 531 | "media_type": image.media_type, |
| 532 | "bytes": image.bytes.len(), |
| 533 | "width": image.width, |
| 534 | "height": image.height, |
| 535 | })) |
| 536 | } |
| 537 | Err(error) => Err(refused_with_record( |
| 538 | call, |
| 539 | "validate", |
| 540 | error.code, |
| 541 | error.message, |
| 542 | )), |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | async fn handle_save(call: &BrokerCall, input: ImageBytesInput) -> Result<Value, BrokerRefusal> { |
| 547 | check_name(input.name.as_deref())?; |
| 548 | let target = accepted_media_type(&input.media_type); |
| 549 | call.context.act("save", BrokerEffect::Read, target).await?; |
| 550 | if call.context.cancel().is_cancelled() { |
| 551 | return Err(refuse( |
| 552 | "CANCELLED", |
| 553 | "the attachments broker call was cancelled", |
| 554 | )); |
| 555 | } |
| 556 | if let Err(sealed) = call.context.can_hold_image() { |
| 557 | if sealed { |
| 558 | return Err(refused_with_record( |
| 559 | call, |
| 560 | "save", |
| 561 | "CANCELLED", |
| 562 | "tool invocation has already ended", |
| 563 | )); |
| 564 | } |
| 565 | return Err(refused_with_record( |
| 566 | call, |
| 567 | "save", |
| 568 | "TOO_MANY_IMAGES", |
| 569 | "this Codewhale keeps one image per tool result", |
| 570 | )); |
| 571 | } |
| 572 | let prepared = tokio::task::spawn_blocking(move || { |
| 573 | prepare_for_save(&input.data_base64, &input.media_type) |
| 574 | }) |
| 575 | .await |
| 576 | .map_err(|_| refuse("ATTACHMENT_READ_FAILED", "image save preparation failed"))?; |
| 577 | if call.context.cancel().is_cancelled() { |
| 578 | return Err(refuse( |
| 579 | "CANCELLED", |
| 580 | "the attachments broker call was cancelled", |
| 581 | )); |
| 582 | } |
| 583 | let (stored_bytes, stored_mime, width, height, stored_b64) = match prepared { |
| 584 | Ok(parts) => parts, |
| 585 | Err(error) => { |
| 586 | return Err(refused_with_record(call, "save", error.code, error.message)); |
| 587 | } |
| 588 | }; |
| 589 | let attachment_id = format!("sha256:{}", sha256_hex(&stored_bytes)); |
| 590 | let held = HeldImage { |
| 591 | attachment_id: attachment_id.clone(), |
| 592 | media_type: stored_mime.to_string(), |
| 593 | bytes: stored_bytes.len(), |
| 594 | width, |
| 595 | height, |
| 596 | data_base64: stored_b64, |
| 597 | }; |
| 598 | if let Err(sealed) = call.context.hold_image(held) { |
| 599 | if sealed { |
| 600 | return Err(refused_with_record( |
| 601 | call, |
| 602 | "save", |
| 603 | "CANCELLED", |
| 604 | "tool invocation has already ended", |
| 605 | )); |
| 606 | } |
| 607 | return Err(refused_with_record( |
| 608 | call, |
| 609 | "save", |
| 610 | "TOO_MANY_IMAGES", |
| 611 | "this Codewhale keeps one image per tool result", |
| 612 | )); |
| 613 | } |
| 614 | let _ = call.context.record(json!({ |
| 615 | "method": "save", |
| 616 | "outcome": "held", |
| 617 | "attachment_id": attachment_id, |
| 618 | "media_type": stored_mime, |
| 619 | "bytes": stored_bytes.len(), |
| 620 | "width": width, |
| 621 | "height": height, |
| 622 | })); |
| 623 | Ok(json!({ |
| 624 | "attachment": { |
| 625 | "attachment_id": attachment_id, |
| 626 | "media_type": stored_mime, |
| 627 | "bytes": stored_bytes.len(), |
| 628 | "width": width, |
| 629 | "height": height, |
| 630 | } |
| 631 | })) |
| 632 | } |
| 633 | |
| 634 | async fn handle_read(call: &BrokerCall, input: ReadInput) -> Result<Value, BrokerRefusal> { |
| 635 | if !valid_attachment_id(&input.attachment.attachment_id) { |
| 636 | return Err(refuse("INVALID_ATTACHMENT_REF", "invalid attachment id")); |
| 637 | } |
| 638 | call.context |
| 639 | .act( |
| 640 | "read", |
| 641 | BrokerEffect::Read, |
| 642 | Some(&input.attachment.attachment_id), |
| 643 | ) |
| 644 | .await?; |
| 645 | if call.context.cancel().is_cancelled() { |
| 646 | return Err(refuse( |
| 647 | "CANCELLED", |
| 648 | "the attachments broker call was cancelled", |
| 649 | )); |
| 650 | } |
| 651 | let held = call.context.held_image(&input.attachment.attachment_id); |
| 652 | let messages = call |
| 653 | .context |
| 654 | .tool() |
| 655 | .execution |
| 656 | .session_objects |
| 657 | .as_ref() |
| 658 | .map(|snapshot| Arc::clone(&snapshot.messages)); |
| 659 | let attachment_ref = input.attachment; |
| 660 | let resolved = tokio::task::spawn_blocking(move || { |
| 661 | let (stored, _) = resolve_from_conversation_blocking( |
| 662 | held, |
| 663 | messages.as_deref().map(Vec::as_slice), |
| 664 | &attachment_ref.attachment_id, |
| 665 | ) |
| 666 | .ok_or_else(|| CodedError { |
| 667 | code: "ATTACHMENT_NOT_FOUND", |
| 668 | message: "attachment not found in this conversation".to_string(), |
| 669 | })?; |
| 670 | check_ref_fields(&attachment_ref, &stored)?; |
| 671 | let data_base64 = STANDARD.encode(&stored.bytes); |
| 672 | Ok::<_, CodedError>((stored, data_base64)) |
| 673 | }) |
| 674 | .await |
| 675 | .map_err(|_| refuse("ATTACHMENT_READ_FAILED", "attachment read task ended"))?; |
| 676 | if call.context.cancel().is_cancelled() { |
| 677 | return Err(refuse( |
| 678 | "CANCELLED", |
| 679 | "the attachments broker call was cancelled", |
| 680 | )); |
| 681 | } |
| 682 | let (stored, data_base64) = match resolved { |
| 683 | Ok(resolved) => resolved, |
| 684 | Err(error) => { |
| 685 | return Err(refused_with_record(call, "read", error.code, error.message)); |
| 686 | } |
| 687 | }; |
| 688 | let _ = call.context.record(json!({ |
| 689 | "method": "read", |
| 690 | "outcome": "read", |
| 691 | "attachment_id": stored.attachment_id, |
| 692 | "media_type": stored.media_type, |
| 693 | "bytes": stored.bytes.len(), |
| 694 | "width": stored.width, |
| 695 | "height": stored.height, |
| 696 | })); |
| 697 | Ok(json!({ |
| 698 | "data_base64": data_base64, |
| 699 | "attachment": ref_json(&stored), |
| 700 | })) |
| 701 | } |
| 702 | |
| 703 | async fn handle_read_request( |
| 704 | call: &BrokerCall, |
| 705 | input: ReadRequestInput, |
| 706 | ) -> Result<Value, BrokerRefusal> { |
| 707 | if !valid_attachment_id(&input.attachment.attachment_id) { |
| 708 | return Err(refuse("INVALID_ATTACHMENT_REF", "invalid attachment id")); |
| 709 | } |
| 710 | if input |
| 711 | .width |
| 712 | .is_some_and(|w| w == 0 || w > MAX_IMAGE_DIMENSION) |
| 713 | || input |
| 714 | .height |
| 715 | .is_some_and(|h| h == 0 || h > MAX_IMAGE_DIMENSION) |
| 716 | { |
| 717 | return Err(refuse( |
| 718 | "IMAGE_DIMENSION_TOO_LARGE", |
| 719 | format!("requested dimensions must be between 1 and {MAX_IMAGE_DIMENSION}"), |
| 720 | )); |
| 721 | } |
| 722 | if input |
| 723 | .max_bytes |
| 724 | .is_some_and(|max| max == 0 || max > MAX_IMAGE_BYTES) |
| 725 | { |
| 726 | return Err(refuse( |
| 727 | "IMAGE_TOO_LARGE", |
| 728 | format!("requested maxBytes must be between 1 and {MAX_IMAGE_BYTES}"), |
| 729 | )); |
| 730 | } |
| 731 | call.context |
| 732 | .act( |
| 733 | "read_request", |
| 734 | BrokerEffect::Read, |
| 735 | Some(&input.attachment.attachment_id), |
| 736 | ) |
| 737 | .await?; |
| 738 | if call.context.cancel().is_cancelled() { |
| 739 | return Err(refuse( |
| 740 | "CANCELLED", |
| 741 | "the attachments broker call was cancelled", |
| 742 | )); |
| 743 | } |
| 744 | let held = call.context.held_image(&input.attachment.attachment_id); |
| 745 | let messages = call |
| 746 | .context |
| 747 | .tool() |
| 748 | .execution |
| 749 | .session_objects |
| 750 | .as_ref() |
| 751 | .map(|snapshot| Arc::clone(&snapshot.messages)); |
| 752 | let budget = input.max_bytes.unwrap_or(MAX_IMAGE_BYTES); |
| 753 | let wanted_w = input.width; |
| 754 | let wanted_h = input.height; |
| 755 | let attachment_ref = input.attachment; |
| 756 | let fitted = tokio::task::spawn_blocking(move || { |
| 757 | let (stored, decoded) = resolve_from_conversation_blocking( |
| 758 | held, |
| 759 | messages.as_deref().map(Vec::as_slice), |
| 760 | &attachment_ref.attachment_id, |
| 761 | ) |
| 762 | .ok_or_else(|| CodedError { |
| 763 | code: "ATTACHMENT_NOT_FOUND", |
| 764 | message: "attachment not found in this conversation".to_string(), |
| 765 | })?; |
| 766 | check_ref_fields(&attachment_ref, &stored)?; |
| 767 | let max_edge = target_edge_for_box(stored.width, stored.height, wanted_w, wanted_h); |
| 768 | let (encoded, mime) = fit_and_encode(&decoded, max_edge, budget, Path::new("attachment")) |
| 769 | .map_err(|_| CodedError { |
| 770 | code: "IMAGE_TOO_LARGE", |
| 771 | message: "image could not fit the requested size budget".to_string(), |
| 772 | })?; |
| 773 | let mut reader = ImageReader::new(Cursor::new(&encoded)) |
| 774 | .with_guessed_format() |
| 775 | .map_err(|_| CodedError { |
| 776 | code: "ATTACHMENT_READ_FAILED", |
| 777 | message: "fitted image header could not be inspected".to_string(), |
| 778 | })?; |
| 779 | reader.limits(decode_limits()); |
| 780 | let (out_w, out_h) = reader.into_dimensions().map_err(|_| CodedError { |
| 781 | code: "ATTACHMENT_READ_FAILED", |
| 782 | message: "fitted image header could not be inspected".to_string(), |
| 783 | })?; |
| 784 | let variant_id = format!("sha256:{}", sha256_hex(&encoded)); |
| 785 | let data_base64 = STANDARD.encode(&encoded); |
| 786 | Ok::<_, CodedError>(( |
| 787 | stored.attachment_id, |
| 788 | variant_id, |
| 789 | data_base64, |
| 790 | mime, |
| 791 | encoded.len(), |
| 792 | out_w, |
| 793 | out_h, |
| 794 | )) |
| 795 | }) |
| 796 | .await |
| 797 | .map_err(|_| refuse("ATTACHMENT_READ_FAILED", "image resize task ended"))?; |
| 798 | if call.context.cancel().is_cancelled() { |
| 799 | return Err(refuse( |
| 800 | "CANCELLED", |
| 801 | "the attachments broker call was cancelled", |
| 802 | )); |
| 803 | } |
| 804 | let (attachment_id, variant_id, data_base64, mime, byte_len, out_w, out_h) = match fitted { |
| 805 | Ok(result) => result, |
| 806 | Err(error) => { |
| 807 | return Err(refused_with_record( |
| 808 | call, |
| 809 | "read_request", |
| 810 | error.code, |
| 811 | error.message, |
| 812 | )); |
| 813 | } |
| 814 | }; |
| 815 | let _ = call.context.record(json!({ |
| 816 | "method": "read_request", |
| 817 | "outcome": "served", |
| 818 | "attachment_id": attachment_id, |
| 819 | "variant_id": variant_id, |
| 820 | "media_type": mime, |
| 821 | "bytes": byte_len, |
| 822 | "width": out_w, |
| 823 | "height": out_h, |
| 824 | })); |
| 825 | Ok(json!({ |
| 826 | "variant_id": variant_id, |
| 827 | "data_base64": data_base64, |
| 828 | "media_type": mime, |
| 829 | })) |
| 830 | } |
| 831 | |
| 832 | pub fn serve(call: BrokerCall) -> BrokerFuture { |
| 833 | Box::pin(async move { |
| 834 | if call.context.cancel().is_cancelled() { |
| 835 | return Err(refuse( |
| 836 | "CANCELLED", |
| 837 | "the attachments broker call was cancelled", |
| 838 | )); |
| 839 | } |
| 840 | let method = decode::<AttachmentsMethod>(&call)?; |
| 841 | match method { |
| 842 | AttachmentsMethod::Validate(input) => handle_validate(&call, input).await, |
| 843 | AttachmentsMethod::Save(input) => handle_save(&call, input).await, |
| 844 | AttachmentsMethod::Read(input) => handle_read(&call, input).await, |
| 845 | AttachmentsMethod::ReadRequest(input) => handle_read_request(&call, input).await, |
| 846 | } |
| 847 | }) |
| 848 | } |
| 849 | |
| 850 | #[cfg(test)] |
| 851 | #[path = "dsh_attachments_tests.rs"] |
| 852 | mod tests; |
| 853 |