| 1 | //! Turning a local image file into a wire-ready image content block. |
| 2 | //! |
| 3 | //! CodeWhale's message model has been multimodal for a long time — |
| 4 | //! [`ContentBlock::ImageUrl`] round-trips |
| 5 | //! through session persistence, compaction and all three wire builders. What it |
| 6 | //! never had was a *faucet*: nothing outside `#[cfg(any(test, feature = "test-support"))]` ever constructed |
| 7 | //! one, so a user who attached a screenshot got the literal text |
| 8 | //! `[Attached image: /path/to/shot.png]` and a model that correctly concluded it |
| 9 | //! could not see the picture. |
| 10 | //! |
| 11 | //! This module is that faucet. It reads a file, proves it is an image the |
| 12 | //! providers actually accept, holds it to a size budget, and emits a |
| 13 | //! `data:` URL. |
| 14 | //! |
| 15 | //! # Two stages, because the two failure kinds differ |
| 16 | //! |
| 17 | //! [`expand_attachment_blocks`] runs when the message is built and decides the |
| 18 | //! *permanent* questions: does this file exist, is it really an image, is it |
| 19 | //! small enough. Those answers cannot change, so they are baked into history. |
| 20 | //! |
| 21 | //! [`strip_images_when_unsupported`] runs per outbound request and decides the |
| 22 | //! one *contingent* question: can the model this request is going to actually |
| 23 | //! see images. Routes change mid-session, so answering that at build time |
| 24 | //! would mean attaching a screenshot under a text-only model and losing it |
| 25 | //! permanently, even after switching to a vision model. History keeps the |
| 26 | //! image; each request is normalized against its own route. |
| 27 | //! |
| 28 | //! # Provider neutrality |
| 29 | //! |
| 30 | //! There is exactly one internal representation — a `data:<media-type>;base64,…` |
| 31 | //! URL on `ContentBlock::ImageUrl` — and each wire builder projects it: |
| 32 | //! |
| 33 | //! | wire format | shape | |
| 34 | //! |---|---| |
| 35 | //! | Chat Completions | `{"type":"image_url","image_url":{"url":"data:…"}}` | |
| 36 | //! | Responses | `{"type":"input_image","image_url":"data:…"}` | |
| 37 | //! | Anthropic Messages | `{"type":"image","source":{"type":"base64","media_type":…,"data":…}}` | |
| 38 | //! |
| 39 | //! The Anthropic split lives in [`parse_data_url`], which |
| 40 | //! `client::anthropic` calls. Anthropic is the reason the accepted-format list |
| 41 | //! below is not simply "whatever the `image` crate can decode": it accepts only |
| 42 | //! PNG/JPEG/GIF/WebP, and so, therefore, do we. Refusing a BMP here with a |
| 43 | //! readable message beats letting one through to a provider-side 400. |
| 44 | |
| 45 | use anyhow::{Result, bail}; |
| 46 | use codewhale_app_server_protocol::runtime::{ |
| 47 | MAX_RUNTIME_IMAGE_BYTES, MAX_RUNTIME_IMAGE_TOTAL_BYTES, MAX_RUNTIME_IMAGES, RuntimeImageInput, |
| 48 | }; |
| 49 | use image::codecs::jpeg::JpegEncoder; |
| 50 | use image::codecs::png::{CompressionType, FilterType as PngFilter, PngEncoder}; |
| 51 | use image::imageops::FilterType; |
| 52 | use image::{DynamicImage, ExtendedColorType, GenericImageView, ImageEncoder, ImageReader, Limits}; |
| 53 | use std::io::Cursor; |
| 54 | use std::path::{Path, PathBuf}; |
| 55 | |
| 56 | use base64::{Engine as _, engine::general_purpose::STANDARD}; |
| 57 | |
| 58 | use crate::model_profile::SupportState; |
| 59 | use codewhale_models::image_window::{parse_data_url, tool_result_text_with_omission}; |
| 60 | use codewhale_models::{ContentBlock, ImageUrlContent}; |
| 61 | |
| 62 | /// Largest source image accepted, in bytes, before base64 expansion. |
| 63 | /// |
| 64 | /// Base64 inflates by 4/3, so this admits roughly 6.7 MB of request body per |
| 65 | /// image. The number is Anthropic's documented per-image ceiling; keeping the |
| 66 | /// tightest provider limit as the shared limit is what makes a "CodeWhale |
| 67 | /// accepted it" verdict portable across routes. |
| 68 | pub const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024; |
| 69 | |
| 70 | /// Maximum width or height admitted for an input image (8192 px). |
| 71 | pub const MAX_IMAGE_DIMENSION: u32 = 8192; |
| 72 | |
| 73 | /// Maximum total pixels admitted before decoding is aborted (~33.5 megapixels). |
| 74 | pub const MAX_IMAGE_PIXELS: u64 = 33_554_432; |
| 75 | |
| 76 | /// Memory allocation limit for image decoding (64 MiB). |
| 77 | pub const MAX_DECODE_ALLOC_BYTES: u64 = 64 * 1024 * 1024; |
| 78 | pub const MAX_TOOL_RESULT_IMAGES: usize = 1; |
| 79 | pub const ACCEPTED_IMAGE_MEDIA_TYPES: &[&str] = |
| 80 | &["image/png", "image/jpeg", "image/webp", "image/gif"]; |
| 81 | |
| 82 | pub(crate) fn decode_limits() -> Limits { |
| 83 | let mut limits = Limits::default(); |
| 84 | limits.max_alloc = Some(MAX_DECODE_ALLOC_BYTES); |
| 85 | limits.max_image_width = Some(MAX_IMAGE_DIMENSION); |
| 86 | limits.max_image_height = Some(MAX_IMAGE_DIMENSION); |
| 87 | limits |
| 88 | } |
| 89 | |
| 90 | pub fn decode_and_guard_image(bytes: &[u8]) -> Result<(DynamicImage, u32, u32)> { |
| 91 | let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format()?; |
| 92 | reader.limits(decode_limits()); |
| 93 | let (width, height) = reader |
| 94 | .into_dimensions() |
| 95 | .map_err(|_| anyhow::anyhow!("invalid image header or decompression bomb guard"))?; |
| 96 | if u64::from(width) * u64::from(height) > MAX_IMAGE_PIXELS |
| 97 | || width > MAX_IMAGE_DIMENSION |
| 98 | || height > MAX_IMAGE_DIMENSION |
| 99 | { |
| 100 | bail!("image dimensions exceed the decompression bomb guard; downscale or crop first"); |
| 101 | } |
| 102 | let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format()?; |
| 103 | reader.limits(decode_limits()); |
| 104 | let decoded = reader |
| 105 | .decode() |
| 106 | .map_err(|_| anyhow::anyhow!("invalid image content or decode allocation limit"))?; |
| 107 | Ok((decoded, width, height)) |
| 108 | } |
| 109 | |
| 110 | /// Validate untrusted inline input before route selection or durable admission. |
| 111 | /// Return the existing provider-neutral history representation; no file is opened. |
| 112 | pub fn prepare_runtime_images(images: &[RuntimeImageInput]) -> Result<Vec<ContentBlock>> { |
| 113 | if images.len() > MAX_RUNTIME_IMAGES { |
| 114 | bail!("images exceed the {MAX_RUNTIME_IMAGES} attachment limit"); |
| 115 | } |
| 116 | prepare_images_with_limit( |
| 117 | images, |
| 118 | MAX_RUNTIME_IMAGE_BYTES, |
| 119 | Some(MAX_RUNTIME_IMAGE_TOTAL_BYTES), |
| 120 | ) |
| 121 | } |
| 122 | |
| 123 | /// Internal Engine/history input retains the established local 5 MiB ceiling. |
| 124 | /// Network callers must first pass `prepare_runtime_images` (4 MiB per image, |
| 125 | /// 10 images and 5 MiB total). Local history never had those aggregate/count |
| 126 | /// limits; impose only its existing per-image bound and bounded full decode. |
| 127 | pub fn prepare_stored_images(images: &[RuntimeImageInput]) -> Result<Vec<ContentBlock>> { |
| 128 | prepare_images_with_limit(images, MAX_IMAGE_BYTES, None) |
| 129 | } |
| 130 | |
| 131 | fn prepare_images_with_limit( |
| 132 | images: &[RuntimeImageInput], |
| 133 | per_image_limit: usize, |
| 134 | total_limit: Option<usize>, |
| 135 | ) -> Result<Vec<ContentBlock>> { |
| 136 | let mut total = 0usize; |
| 137 | images |
| 138 | .iter() |
| 139 | .enumerate() |
| 140 | .map(|(index, image)| { |
| 141 | if image.data_base64.len() > per_image_limit.div_ceil(3) * 4 { |
| 142 | bail!( |
| 143 | "image {} exceeds the {} MiB limit", |
| 144 | index + 1, |
| 145 | per_image_limit / (1024 * 1024) |
| 146 | ); |
| 147 | } |
| 148 | let bytes = STANDARD |
| 149 | .decode(&image.data_base64) |
| 150 | .map_err(|_| anyhow::anyhow!("image {} has invalid base64", index + 1))?; |
| 151 | if bytes.len() > per_image_limit { |
| 152 | bail!( |
| 153 | "image {} exceeds the {} MiB limit", |
| 154 | index + 1, |
| 155 | per_image_limit / (1024 * 1024) |
| 156 | ); |
| 157 | } |
| 158 | total = total.saturating_add(bytes.len()); |
| 159 | if total_limit.is_some_and(|limit| total > limit) { |
| 160 | bail!("images exceed the 5 MiB total limit"); |
| 161 | } |
| 162 | let attached = encode_image_bytes(&bytes, &format!("image {}", index + 1))?; |
| 163 | if image.mime != attached.media_type { |
| 164 | bail!("image {} MIME does not match its content", index + 1); |
| 165 | } |
| 166 | decode_and_guard_image(&bytes)?; |
| 167 | // Standard padded base64 is the one replay representation. |
| 168 | if STANDARD.encode(&bytes) != image.data_base64 { |
| 169 | bail!("image {} base64 is not canonical", index + 1); |
| 170 | } |
| 171 | Ok(attached.content_block()) |
| 172 | }) |
| 173 | .collect() |
| 174 | } |
| 175 | |
| 176 | /// Reuse durable canonical bytes for retry, never reread a path or URL. |
| 177 | pub fn runtime_images_from_blocks(blocks: &[ContentBlock]) -> Result<Vec<RuntimeImageInput>> { |
| 178 | let mut images = Vec::new(); |
| 179 | for block in blocks { |
| 180 | if let ContentBlock::ImageUrl { image_url } = block { |
| 181 | if image_url.url.len() > MAX_IMAGE_BYTES.div_ceil(3) * 4 + 32 { |
| 182 | bail!("stored image exceeds the attachment limit"); |
| 183 | } |
| 184 | let (mime, data) = parse_data_url(&image_url.url) |
| 185 | .ok_or_else(|| anyhow::anyhow!("stored image requires canonical inline content"))?; |
| 186 | images.push(RuntimeImageInput { |
| 187 | mime: mime.to_string(), |
| 188 | data_base64: data.to_string(), |
| 189 | }); |
| 190 | } |
| 191 | } |
| 192 | prepare_stored_images(&images)?; |
| 193 | Ok(images) |
| 194 | } |
| 195 | |
| 196 | /// Validate new image-bearing durable records without rewriting their block order. |
| 197 | /// Legacy schema 2 history continues to use its original interpretation. |
| 198 | pub fn validate_stored_image_content(blocks: &[ContentBlock]) -> Result<()> { |
| 199 | if blocks.iter().any(|block| { |
| 200 | !matches!( |
| 201 | block, |
| 202 | ContentBlock::Text { .. } | ContentBlock::ImageUrl { .. } |
| 203 | ) |
| 204 | }) { |
| 205 | bail!("invalid persisted user image content kind"); |
| 206 | } |
| 207 | if runtime_images_from_blocks(blocks)?.is_empty() { |
| 208 | bail!("persisted image input must contain an image"); |
| 209 | } |
| 210 | Ok(()) |
| 211 | } |
| 212 | |
| 213 | /// Why a file could not be attached as an image. |
| 214 | /// |
| 215 | /// Every variant renders to a sentence naming the file and the reason. These |
| 216 | /// strings reach both the user (as a command error) and the model (as an |
| 217 | /// in-band notice), so they say what to do next rather than only what failed. |
| 218 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 219 | pub enum ImageAttachError { |
| 220 | /// The file could not be read at all. |
| 221 | Unreadable { path: String, reason: String }, |
| 222 | /// The file is zero bytes. |
| 223 | Empty { path: String }, |
| 224 | /// Over `limit` bytes: [`MAX_IMAGE_BYTES`] for already-encoded bytes, the |
| 225 | /// larger source bound when attach-time downscaling applies. |
| 226 | TooLarge { |
| 227 | path: String, |
| 228 | bytes: usize, |
| 229 | limit: usize, |
| 230 | }, |
| 231 | /// Magic bytes identify a format no provider in the set accepts. |
| 232 | UnsupportedFormat { path: String, detected: String }, |
| 233 | /// Magic bytes match nothing we recognize as an image. |
| 234 | NotAnImage { path: String }, |
| 235 | } |
| 236 | |
| 237 | impl std::fmt::Display for ImageAttachError { |
| 238 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 239 | match self { |
| 240 | Self::Unreadable { path, reason } => { |
| 241 | write!(f, "Cannot attach {path}: {reason}") |
| 242 | } |
| 243 | Self::Empty { path } => { |
| 244 | write!(f, "Cannot attach {path}: the file is empty") |
| 245 | } |
| 246 | Self::TooLarge { path, bytes, limit } => write!( |
| 247 | f, |
| 248 | "Cannot attach {path}: {} exceeds the {} per-image limit. \ |
| 249 | Downscale or crop it first.", |
| 250 | human_bytes(*bytes), |
| 251 | human_bytes(*limit), |
| 252 | ), |
| 253 | Self::UnsupportedFormat { path, detected } => write!( |
| 254 | f, |
| 255 | "Cannot attach {path}: {detected} is not accepted by vision \ |
| 256 | models. Convert it to PNG, JPEG, GIF or WebP.", |
| 257 | ), |
| 258 | Self::NotAnImage { path } => write!( |
| 259 | f, |
| 260 | "Cannot attach {path}: the file is not a PNG, JPEG, GIF or \ |
| 261 | WebP image (its contents do not match any of those formats).", |
| 262 | ), |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | impl std::error::Error for ImageAttachError {} |
| 268 | |
| 269 | pub fn human_bytes(bytes: usize) -> String { |
| 270 | if bytes >= 1024 * 1024 { |
| 271 | format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)) |
| 272 | } else if bytes >= 1024 { |
| 273 | format!("{:.1} KB", bytes as f64 / 1024.0) |
| 274 | } else { |
| 275 | format!("{bytes} bytes") |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// An image that is ready to go on the wire. |
| 280 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 281 | pub struct AttachedImage { |
| 282 | /// e.g. `"image/png"`. |
| 283 | pub media_type: &'static str, |
| 284 | /// `data:<media_type>;base64,<payload>`. |
| 285 | pub data_url: String, |
| 286 | /// Size of the source file, before base64. |
| 287 | pub source_bytes: usize, |
| 288 | } |
| 289 | |
| 290 | /// Validated image content returned by lowercase `read`. |
| 291 | pub struct PreparedToolImage { |
| 292 | pub block: Option<codewhale_tools::ToolResultContentBlock>, |
| 293 | pub note: String, |
| 294 | } |
| 295 | |
| 296 | /// Prepare one provider-neutral tool-result image using Codewhale's existing |
| 297 | /// cross-provider format and size policy. Failure is a visible text receipt, |
| 298 | /// not a failed file read. |
| 299 | #[must_use] |
| 300 | pub fn prepare_tool_image_bytes(bytes: &[u8], mime_type: &str) -> PreparedToolImage { |
| 301 | let mime_type = mime_type.split(';').next().unwrap_or(mime_type).trim(); |
| 302 | let budget = crate::tools::read_media::READ_IMAGE_BYTE_BUDGET; |
| 303 | if bytes.len() <= crate::tools::read_media::MAX_SOURCE_IMAGE_BYTES |
| 304 | && sniff_media_type(bytes) == Some(mime_type) |
| 305 | && decode_and_guard_image(bytes).is_ok() |
| 306 | && let Ok(fitted) = fit_image_bytes(bytes, Path::new("image"), budget) |
| 307 | && let Some((fitted_mime, payload)) = parse_data_url(&fitted.data_url) |
| 308 | { |
| 309 | let note = if fitted.source_bytes == bytes.len() && fitted_mime == mime_type { |
| 310 | format!("Read image file [{mime_type}]") |
| 311 | } else { |
| 312 | format!( |
| 313 | "Read image file [{mime_type}] (re-encoded from {} to a {} {fitted_mime} within the {} default delivery budget)", |
| 314 | human_bytes(bytes.len()), |
| 315 | human_bytes(fitted.source_bytes), |
| 316 | human_bytes(budget), |
| 317 | ) |
| 318 | }; |
| 319 | return PreparedToolImage { |
| 320 | block: Some(codewhale_tools::ToolResultContentBlock::Image { |
| 321 | mime_type: fitted_mime.to_string(), |
| 322 | data: payload.to_string(), |
| 323 | }), |
| 324 | note, |
| 325 | }; |
| 326 | } |
| 327 | PreparedToolImage { |
| 328 | block: None, |
| 329 | note: format!( |
| 330 | "Read image file [{mime_type}]\n[Image omitted: unsupported, invalid, above the source limit, or unable to fit the {} default delivery budget. Use read_media with a crop or higher detail if needed.]", |
| 331 | human_bytes(budget), |
| 332 | ), |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | fn valid_tool_image(mime_type: &str, data: &str) -> bool { |
| 337 | ACCEPTED_IMAGE_MEDIA_TYPES.contains(&mime_type) |
| 338 | && data.len() <= MAX_IMAGE_BYTES.div_ceil(3) * 4 |
| 339 | && STANDARD.decode(data).is_ok_and(|bytes| { |
| 340 | bytes.len() <= MAX_IMAGE_BYTES |
| 341 | && sniff_media_type(&bytes) == Some(mime_type) |
| 342 | && decode_and_guard_image(&bytes).is_ok() |
| 343 | }) |
| 344 | } |
| 345 | |
| 346 | /// Enforce the same one-image limit at the tool execution boundary so plugin |
| 347 | /// or future rich tools cannot create unbounded history. |
| 348 | #[must_use] |
| 349 | pub fn bound_rich_tool_result( |
| 350 | mut rich: crate::tools::spec::RichToolResult, |
| 351 | ) -> crate::tools::spec::RichToolResult { |
| 352 | let mut kept = Vec::with_capacity(1); |
| 353 | let mut omitted = 0usize; |
| 354 | for block in rich.content_blocks.drain(..) { |
| 355 | let codewhale_tools::ToolResultContentBlock::Image { mime_type, data } = █ |
| 356 | if kept.len() < MAX_TOOL_RESULT_IMAGES && valid_tool_image(mime_type, data) { |
| 357 | kept.push(block); |
| 358 | } else { |
| 359 | omitted += 1; |
| 360 | } |
| 361 | } |
| 362 | rich.result.content = tool_result_text_with_omission(&rich.result.content, omitted); |
| 363 | rich.content_blocks = kept; |
| 364 | rich |
| 365 | } |
| 366 | |
| 367 | /// Borrow the first valid inline image and count everything omitted. |
| 368 | #[must_use] |
| 369 | pub fn provider_tool_result_image_refs( |
| 370 | blocks: Option<&[serde_json::Value]>, |
| 371 | ) -> (Option<(&str, &str)>, usize) { |
| 372 | let mut image = None; |
| 373 | let mut omitted = 0usize; |
| 374 | for block in blocks.unwrap_or_default() { |
| 375 | let fields = block |
| 376 | .get("type") |
| 377 | .and_then(serde_json::Value::as_str) |
| 378 | .filter(|kind| *kind == "image") |
| 379 | .and_then(|_| { |
| 380 | block |
| 381 | .get("mime_type") |
| 382 | .and_then(serde_json::Value::as_str) |
| 383 | .zip(block.get("data").and_then(serde_json::Value::as_str)) |
| 384 | }); |
| 385 | if image.is_none() |
| 386 | && let Some((mime_type, data)) = fields |
| 387 | && valid_tool_image(mime_type, data) |
| 388 | { |
| 389 | image = Some((mime_type, data)); |
| 390 | } else { |
| 391 | omitted += 1; |
| 392 | } |
| 393 | } |
| 394 | (image, omitted) |
| 395 | } |
| 396 | |
| 397 | /// Copy/export projection that retains metadata but never inline base64. |
| 398 | #[must_use] |
| 399 | pub fn safe_tool_result_content_blocks( |
| 400 | blocks: Option<&[serde_json::Value]>, |
| 401 | ) -> Option<Vec<serde_json::Value>> { |
| 402 | blocks.map(|blocks| { |
| 403 | blocks |
| 404 | .iter() |
| 405 | .map(|block| { |
| 406 | if block.get("type").and_then(serde_json::Value::as_str) == Some("image") { |
| 407 | serde_json::json!({ |
| 408 | "type": "image", |
| 409 | "mime_type": block.get("mime_type").and_then(serde_json::Value::as_str).unwrap_or("application/octet-stream"), |
| 410 | "omission_code": "inline_or_local_image_payload", |
| 411 | "omitted_base64_bytes": block.get("data").and_then(serde_json::Value::as_str).map_or(0, str::len), |
| 412 | }) |
| 413 | } else { |
| 414 | block.clone() |
| 415 | } |
| 416 | }) |
| 417 | .collect() |
| 418 | }) |
| 419 | } |
| 420 | |
| 421 | #[must_use] |
| 422 | pub fn safe_tool_result_message_projection( |
| 423 | messages: &[codewhale_models::Message], |
| 424 | ) -> Vec<codewhale_models::Message> { |
| 425 | let mut projected = messages.to_vec(); |
| 426 | for message in &mut projected { |
| 427 | for block in &mut message.content { |
| 428 | if let ContentBlock::ToolResult { content_blocks, .. } = block { |
| 429 | *content_blocks = safe_tool_result_content_blocks(content_blocks.as_deref()); |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | projected |
| 434 | } |
| 435 | |
| 436 | impl AttachedImage { |
| 437 | /// The content block this image becomes in a message. |
| 438 | #[must_use] |
| 439 | pub fn content_block(&self) -> ContentBlock { |
| 440 | ContentBlock::ImageUrl { |
| 441 | image_url: ImageUrlContent { |
| 442 | url: self.data_url.clone(), |
| 443 | }, |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | /// Identify an image format from its leading bytes. |
| 449 | /// |
| 450 | /// Extension sniffing is not enough here: the extension is attacker- and |
| 451 | /// typo-controlled, while what the provider validates is the payload. A |
| 452 | /// `.png` holding JPEG bytes must be declared `image/jpeg` or the request is |
| 453 | /// rejected with a media-type mismatch that reads like a CodeWhale bug. |
| 454 | /// |
| 455 | /// Returns `None` for anything that is not one of the four accepted formats; |
| 456 | /// [`detect_rejected_format`] names the near-misses so the error can be |
| 457 | /// specific. |
| 458 | #[must_use] |
| 459 | pub fn sniff_media_type(bytes: &[u8]) -> Option<&'static str> { |
| 460 | if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { |
| 461 | return Some("image/png"); |
| 462 | } |
| 463 | if bytes.starts_with(b"\xff\xd8\xff") { |
| 464 | return Some("image/jpeg"); |
| 465 | } |
| 466 | if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { |
| 467 | return Some("image/gif"); |
| 468 | } |
| 469 | if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { |
| 470 | return Some("image/webp"); |
| 471 | } |
| 472 | None |
| 473 | } |
| 474 | |
| 475 | /// Name a format we can recognize but deliberately refuse. |
| 476 | /// |
| 477 | /// These are real images, so `NotAnImage` would be a lie and would send the |
| 478 | /// user looking for a corrupt file. Naming the format points at the fix |
| 479 | /// (convert it) instead. |
| 480 | #[must_use] |
| 481 | pub fn detect_rejected_format(bytes: &[u8]) -> Option<&'static str> { |
| 482 | if bytes.starts_with(b"BM") { |
| 483 | return Some("BMP"); |
| 484 | } |
| 485 | if bytes.starts_with(b"II\x2a\x00") || bytes.starts_with(b"MM\x00\x2a") { |
| 486 | return Some("TIFF"); |
| 487 | } |
| 488 | if bytes.len() >= 12 && bytes.starts_with(b"\0\0\0") && &bytes[4..8] == b"ftyp" { |
| 489 | return Some("HEIC/AVIF"); |
| 490 | } |
| 491 | if bytes.starts_with(b"<svg") || bytes.starts_with(b"<?xml") { |
| 492 | return Some("SVG"); |
| 493 | } |
| 494 | if bytes.starts_with(b"%PDF") { |
| 495 | return Some("PDF"); |
| 496 | } |
| 497 | None |
| 498 | } |
| 499 | |
| 500 | /// Validate and encode raw bytes that were read from `path`. |
| 501 | /// |
| 502 | /// Split from [`attach_image_from_path`] so the whole policy — order of |
| 503 | /// checks, limits, format verdicts — is testable without touching a |
| 504 | /// filesystem. |
| 505 | pub fn encode_image_bytes(bytes: &[u8], path: &str) -> Result<AttachedImage, ImageAttachError> { |
| 506 | if bytes.is_empty() { |
| 507 | return Err(ImageAttachError::Empty { |
| 508 | path: path.to_string(), |
| 509 | }); |
| 510 | } |
| 511 | // Size is checked before format so a huge file is rejected on the cheap |
| 512 | // fact rather than after we have decided what it is. |
| 513 | if bytes.len() > MAX_IMAGE_BYTES { |
| 514 | return Err(ImageAttachError::TooLarge { |
| 515 | path: path.to_string(), |
| 516 | bytes: bytes.len(), |
| 517 | limit: MAX_IMAGE_BYTES, |
| 518 | }); |
| 519 | } |
| 520 | let Some(media_type) = sniff_media_type(bytes) else { |
| 521 | return Err(format_error(bytes, path)); |
| 522 | }; |
| 523 | let payload = STANDARD.encode(bytes); |
| 524 | Ok(AttachedImage { |
| 525 | media_type, |
| 526 | data_url: format!("data:{media_type};base64,{payload}"), |
| 527 | source_bytes: bytes.len(), |
| 528 | }) |
| 529 | } |
| 530 | |
| 531 | fn format_error(bytes: &[u8], path: &str) -> ImageAttachError { |
| 532 | match detect_rejected_format(bytes) { |
| 533 | Some(detected) => ImageAttachError::UnsupportedFormat { |
| 534 | path: path.to_string(), |
| 535 | detected: detected.to_string(), |
| 536 | }, |
| 537 | None => ImageAttachError::NotAnImage { |
| 538 | path: path.to_string(), |
| 539 | }, |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | /// Longest edge an attached image is sent at. A Retina screenshot is 3–6k px |
| 544 | /// and often over [`MAX_IMAGE_BYTES`] as PNG; larger images are downscaled |
| 545 | /// and re-encoded when attached rather than refused. |
| 546 | pub const ATTACH_MAX_EDGE_PX: u32 = 2048; |
| 547 | |
| 548 | /// Read, validate and encode an image file. |
| 549 | /// |
| 550 | /// Images over [`ATTACH_MAX_EDGE_PX`] or [`MAX_IMAGE_BYTES`] are decoded under |
| 551 | /// the decompression-bomb guard, fitted to the edge and re-encoded on |
| 552 | /// `read_media`'s budget ladder (PNG for flat or alpha content, JPEG for |
| 553 | /// photos). Known limit: an animated GIF that needs downscaling keeps only |
| 554 | /// its first frame. Sources above `read_media`'s source bound are refused. |
| 555 | pub fn attach_image_from_path(path: &Path) -> Result<AttachedImage, ImageAttachError> { |
| 556 | let display = path.display().to_string(); |
| 557 | let source_limit = crate::tools::read_media::MAX_SOURCE_IMAGE_BYTES; |
| 558 | // Check the size from metadata first so a multi-gigabyte file is refused |
| 559 | // without being read into memory. |
| 560 | if let Ok(meta) = std::fs::metadata(path) { |
| 561 | let len = meta.len(); |
| 562 | if len > source_limit as u64 { |
| 563 | return Err(ImageAttachError::TooLarge { |
| 564 | path: display, |
| 565 | bytes: usize::try_from(len).unwrap_or(usize::MAX), |
| 566 | limit: source_limit, |
| 567 | }); |
| 568 | } |
| 569 | } |
| 570 | let bytes = std::fs::read(path).map_err(|error| ImageAttachError::Unreadable { |
| 571 | path: display.clone(), |
| 572 | reason: error.to_string(), |
| 573 | })?; |
| 574 | if bytes.len() > source_limit { |
| 575 | return Err(ImageAttachError::TooLarge { |
| 576 | path: display, |
| 577 | bytes: bytes.len(), |
| 578 | limit: source_limit, |
| 579 | }); |
| 580 | } |
| 581 | fit_image_bytes(&bytes, path, MAX_IMAGE_BYTES) |
| 582 | } |
| 583 | |
| 584 | fn fit_image_bytes( |
| 585 | bytes: &[u8], |
| 586 | path: &Path, |
| 587 | byte_budget: usize, |
| 588 | ) -> Result<AttachedImage, ImageAttachError> { |
| 589 | let display = path.display().to_string(); |
| 590 | let oversized_edge = ImageReader::new(Cursor::new(bytes)) |
| 591 | .with_guessed_format() |
| 592 | .ok() |
| 593 | .and_then(|reader| reader.into_dimensions().ok()) |
| 594 | .is_some_and(|(width, height)| width.max(height) > ATTACH_MAX_EDGE_PX); |
| 595 | if bytes.len() <= byte_budget && !oversized_edge { |
| 596 | return encode_image_bytes(bytes, &display); |
| 597 | } |
| 598 | if sniff_media_type(bytes).is_none() { |
| 599 | return Err(format_error(bytes, &display)); |
| 600 | } |
| 601 | let unreadable = |reason: String| ImageAttachError::Unreadable { |
| 602 | path: display.clone(), |
| 603 | reason, |
| 604 | }; |
| 605 | let (image, _, _) = |
| 606 | decode_and_guard_image(bytes).map_err(|error| unreadable(error.to_string()))?; |
| 607 | let (encoded, _) = |
| 608 | crate::tools::read_media::fit_and_encode(&image, ATTACH_MAX_EDGE_PX, byte_budget, path) |
| 609 | .map_err(|error| unreadable(error.to_string()))?; |
| 610 | encode_image_bytes(&encoded, &display) |
| 611 | } |
| 612 | |
| 613 | /// Upper bound on a paste considered as a list of dropped file paths. |
| 614 | const MAX_PASTED_PATHS_BYTES: usize = 16 * 1024; |
| 615 | |
| 616 | /// The local image files a pasted string names, or `None` when the paste is |
| 617 | /// anything else and belongs in the composer as text. |
| 618 | /// |
| 619 | /// Terminals deliver a drag-and-drop as a paste of the file's path, in |
| 620 | /// whatever spelling the terminal prefers: Terminal.app and iTerm2 |
| 621 | /// shell-escape (`/var/folders/…/Screenshot\ 2026-10-04\ at\ 22.25.47.png`), |
| 622 | /// others quote, some hand over a `file://` URL, and several files arrive as |
| 623 | /// one space-separated line. Without this, that path reached the model as |
| 624 | /// prose and the model had no way to look at the picture. |
| 625 | /// |
| 626 | /// The paste converts only when *every* path in it is absolute and names an |
| 627 | /// existing file whose bytes are PNG, JPEG, GIF or WebP, so a sentence that |
| 628 | /// merely mentions a path, a relative name, or a pasted non-image stays text. |
| 629 | /// |
| 630 | /// Known limits: a path typed or pasted inside prose is not converted (the |
| 631 | /// drop is the gesture, not the mention); on Windows a paste is read as one |
| 632 | /// path verbatim, without shell unescaping. |
| 633 | #[must_use] |
| 634 | pub fn pasted_image_paths(text: &str) -> Option<Vec<PathBuf>> { |
| 635 | pasted_paths_matching(text, |path| sniff_image_file(path).is_some()) |
| 636 | } |
| 637 | |
| 638 | /// A local image path leading a submitted message, and the text after it. |
| 639 | /// |
| 640 | /// The paste-time check ([`pasted_image_paths`]) only sees a paste that is |
| 641 | /// nothing but paths. A drop can still reach the composer as typed keys, or |
| 642 | /// be followed by the question on the same line before Enter. So at submit a |
| 643 | /// message that *starts* with an existing image path (escaped, quoted, a |
| 644 | /// `file://` URL, or unescaped with spaces) attaches it and keeps the rest as |
| 645 | /// the prompt — the same rule Hermes Agent's `_detect_file_drop` applies. |
| 646 | #[must_use] |
| 647 | pub fn leading_dropped_image(text: &str) -> Option<(PathBuf, String)> { |
| 648 | leading_path_matching(text, |path| sniff_image_file(path).is_some()) |
| 649 | } |
| 650 | |
| 651 | fn leading_path_matching( |
| 652 | text: &str, |
| 653 | is_image: impl Fn(&Path) -> bool, |
| 654 | ) -> Option<(PathBuf, String)> { |
| 655 | let text = text.trim_start(); |
| 656 | let (line, after) = text.split_once('\n').unwrap_or((text, "")); |
| 657 | let line = line.trim_end(); |
| 658 | if line.is_empty() || line.len() > MAX_PASTED_PATHS_BYTES { |
| 659 | return None; |
| 660 | } |
| 661 | let bare = line.trim_start_matches(['"', '\'']); |
| 662 | if !(bare.starts_with('/') || bare.starts_with("file://") || Path::new(bare).is_absolute()) { |
| 663 | return None; |
| 664 | } |
| 665 | let accept = |raw: &str, unescape: bool| { |
| 666 | let path = pasted_path(raw, unescape); |
| 667 | (path.is_absolute() && is_image(&path)).then_some(path) |
| 668 | }; |
| 669 | let found = (|| { |
| 670 | // A quoted path ends at its closing quote. |
| 671 | if let Some(quote) = line.chars().next().filter(|c| *c == '"' || *c == '\'') |
| 672 | && let Some(end) = line[1..].find(quote) |
| 673 | { |
| 674 | let end = end + 2; |
| 675 | return accept(&line[..end], false).map(|path| (path, end)); |
| 676 | } |
| 677 | // A shell-escaped path ends at its first unescaped space. |
| 678 | let mut escaped = false; |
| 679 | let token_end = line |
| 680 | .char_indices() |
| 681 | .find(|&(_, ch)| { |
| 682 | let stop = ch == ' ' && !escaped; |
| 683 | escaped = ch == '\\' && !escaped; |
| 684 | stop |
| 685 | }) |
| 686 | .map_or(line.len(), |(index, _)| index); |
| 687 | if let Some(path) = accept(&line[..token_end], true) { |
| 688 | return Some((path, token_end)); |
| 689 | } |
| 690 | // An unescaped path with spaces: the longest prefix that is a file. |
| 691 | let mut cuts: Vec<usize> = line.match_indices(' ').map(|(index, _)| index).collect(); |
| 692 | cuts.push(line.len()); |
| 693 | cuts.into_iter() |
| 694 | .rev() |
| 695 | .filter(|&cut| cut > token_end) |
| 696 | .find_map(|cut| accept(&line[..cut], false).map(|path| (path, cut))) |
| 697 | })()?; |
| 698 | let (path, end) = found; |
| 699 | let rest = format!("{}\n{after}", &line[end..]); |
| 700 | Some((path, rest.trim().to_string())) |
| 701 | } |
| 702 | |
| 703 | fn pasted_paths_matching(text: &str, is_image: impl Fn(&Path) -> bool) -> Option<Vec<PathBuf>> { |
| 704 | let text = text.trim(); |
| 705 | if text.is_empty() || text.len() > MAX_PASTED_PATHS_BYTES { |
| 706 | return None; |
| 707 | } |
| 708 | let accept = |path: PathBuf| (path.is_absolute() && is_image(&path)).then_some(path); |
| 709 | // The whole paste as one path first: a dropped file whose name has |
| 710 | // spaces is one path even when the terminal did not escape it. |
| 711 | if let Some(path) = accept(pasted_path(text, true)) { |
| 712 | return Some(vec![path]); |
| 713 | } |
| 714 | if cfg!(windows) { |
| 715 | return None; |
| 716 | } |
| 717 | // Several dropped files: shlex has already removed quotes and escapes. |
| 718 | let paths = shlex::split(text)? |
| 719 | .iter() |
| 720 | .map(|token| accept(pasted_path(token, false))) |
| 721 | .collect::<Option<Vec<_>>>()?; |
| 722 | (!paths.is_empty()).then_some(paths) |
| 723 | } |
| 724 | |
| 725 | /// One pasted path spelling (quoted, shell-escaped, or a `file://` URL) as |
| 726 | /// a filesystem path. `unescape` is false for a token shlex already split. |
| 727 | fn pasted_path(raw: &str, unescape: bool) -> PathBuf { |
| 728 | let unquoted = ['"', '\''] |
| 729 | .iter() |
| 730 | .find_map(|quote| { |
| 731 | raw.strip_prefix(*quote) |
| 732 | .and_then(|rest| rest.strip_suffix(*quote)) |
| 733 | }) |
| 734 | .unwrap_or(raw); |
| 735 | if let Ok(url) = url::Url::parse(unquoted) |
| 736 | && url.scheme() == "file" |
| 737 | && let Ok(path) = url.to_file_path() |
| 738 | { |
| 739 | return path; |
| 740 | } |
| 741 | if cfg!(windows) || !unescape { |
| 742 | return PathBuf::from(unquoted); |
| 743 | } |
| 744 | let mut unescaped = String::with_capacity(unquoted.len()); |
| 745 | let mut chars = unquoted.chars(); |
| 746 | while let Some(ch) = chars.next() { |
| 747 | if ch == '\\' |
| 748 | && let Some(next) = chars.next() |
| 749 | { |
| 750 | unescaped.push(next); |
| 751 | } else { |
| 752 | unescaped.push(ch); |
| 753 | } |
| 754 | } |
| 755 | PathBuf::from(unescaped) |
| 756 | } |
| 757 | |
| 758 | /// The accepted image format of a regular file, judged by its leading bytes. |
| 759 | fn sniff_image_file(path: &Path) -> Option<&'static str> { |
| 760 | use std::io::Read as _; |
| 761 | // stat before open: opening a FIFO (or other special file) a paste named |
| 762 | // blocks until a writer appears, which would freeze the composer. |
| 763 | if !std::fs::metadata(path).ok()?.is_file() { |
| 764 | return None; |
| 765 | } |
| 766 | let file = std::fs::File::open(path).ok()?; |
| 767 | if !file.metadata().ok()?.is_file() { |
| 768 | return None; |
| 769 | } |
| 770 | let mut head = Vec::with_capacity(16); |
| 771 | file.take(16).read_to_end(&mut head).ok()?; |
| 772 | sniff_media_type(&head) |
| 773 | } |
| 774 | |
| 775 | /// Paths of the images the user attached in this session's own prompts. |
| 776 | /// |
| 777 | /// Reads only `[Attached image: …]` lines in user-role text — the logged |
| 778 | /// record of what the user put in the composer — and never tool output or |
| 779 | /// model text, so a tool result cannot widen what a read may open. Pure |
| 780 | /// string work; [`resolve_user_attached_image`] does the filesystem half. |
| 781 | #[must_use] |
| 782 | pub fn user_attached_image_references(messages: &[codewhale_models::Message]) -> Vec<String> { |
| 783 | messages |
| 784 | .iter() |
| 785 | .filter(|message| message.role == codewhale_models::Role::User) |
| 786 | .flat_map(|message| &message.content) |
| 787 | .filter_map(|block| match block { |
| 788 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 789 | _ => None, |
| 790 | }) |
| 791 | .flat_map(codewhale_core::media_attachment_references) |
| 792 | .filter(|reference| reference.kind == "image") |
| 793 | .map(|reference| reference.path) |
| 794 | .collect() |
| 795 | } |
| 796 | |
| 797 | /// Admit `raw` for a read-only image tool when it is exactly a file the user |
| 798 | /// attached (see [`user_attached_image_references`]). |
| 799 | /// |
| 800 | /// The workspace boundary keeps the model from wandering the disk; a |
| 801 | /// screenshot the user dropped into the composer from a temp directory is not |
| 802 | /// wandering, and refusing it is what sent a model to OCR and computer-use |
| 803 | /// screenshots instead of looking. Admission stays narrow: the exact file |
| 804 | /// (compared after canonicalization, so `/var` and `/private/var` agree), not |
| 805 | /// its directory, and only while its bytes are an accepted image format. |
| 806 | /// Callers still apply the credential and read deny-list checks. |
| 807 | #[must_use] |
| 808 | pub fn resolve_user_attached_image(references: &[String], raw: &str) -> Option<PathBuf> { |
| 809 | let requested = Path::new(raw); |
| 810 | if !requested.is_absolute() { |
| 811 | return None; |
| 812 | } |
| 813 | let requested = std::fs::canonicalize(requested).ok()?; |
| 814 | let attached = references |
| 815 | .iter() |
| 816 | .any(|reference| std::fs::canonicalize(reference).is_ok_and(|path| path == requested)); |
| 817 | (attached && sniff_image_file(&requested).is_some()).then_some(requested) |
| 818 | } |
| 819 | |
| 820 | /// Image blocks sent from the latest user prompt onward: this turn's |
| 821 | /// attachments and tool-result images, not ones replayed from history. |
| 822 | #[must_use] |
| 823 | pub fn images_since_last_user_prompt(messages: &[codewhale_models::Message]) -> usize { |
| 824 | let is_prompt = |message: &codewhale_models::Message| { |
| 825 | message.role == codewhale_models::Role::User |
| 826 | && message.content.iter().any(|block| { |
| 827 | matches!( |
| 828 | block, |
| 829 | ContentBlock::Text { .. } | ContentBlock::ImageUrl { .. } |
| 830 | ) |
| 831 | }) |
| 832 | }; |
| 833 | let start = messages.iter().rposition(is_prompt).unwrap_or(0); |
| 834 | messages[start..] |
| 835 | .iter() |
| 836 | .flat_map(|message| &message.content) |
| 837 | .map(|block| match block { |
| 838 | ContentBlock::ImageUrl { .. } => 1, |
| 839 | ContentBlock::ToolResult { content_blocks, .. } => { |
| 840 | content_blocks.as_ref().map_or(0, Vec::len) |
| 841 | } |
| 842 | _ => 0, |
| 843 | }) |
| 844 | .sum() |
| 845 | } |
| 846 | |
| 847 | /// The outcome of expanding a user turn's attachment placeholders. |
| 848 | #[derive(Debug, Clone, Default, PartialEq)] |
| 849 | pub struct ExpandedAttachments { |
| 850 | /// Image blocks to append to the user message, in placeholder order. |
| 851 | pub blocks: Vec<ContentBlock>, |
| 852 | /// One line per attachment that could not be sent. These are shown to the |
| 853 | /// user and also handed to the model, because a model that is not told an |
| 854 | /// image was dropped will confidently discuss it from the filename. |
| 855 | pub notices: Vec<String>, |
| 856 | } |
| 857 | |
| 858 | /// Build the image blocks for a user turn from its `[Attached image: …]` lines. |
| 859 | /// |
| 860 | /// This is the ingest half of the composer's placeholder design: the buffer |
| 861 | /// holds a path-bearing text line (which survives editing, history and session |
| 862 | /// reload for free), and the bytes are read here, once, as the message is |
| 863 | /// built. |
| 864 | /// |
| 865 | /// Only *permanent* failures are decided here — a file that is missing, |
| 866 | /// oversized, or not an image will still be all of those things next turn, so |
| 867 | /// baking the verdict into history costs nothing. Whether the *model* can see |
| 868 | /// images is deliberately not decided here; that is contingent on the active |
| 869 | /// route and is re-decided per request by |
| 870 | /// [`strip_images_when_unsupported`]. |
| 871 | /// |
| 872 | /// Each image is bracketed by text tags naming its path. Without them a turn |
| 873 | /// carrying three screenshots gives the model three anonymous images in a row |
| 874 | /// and no way to say which is which. |
| 875 | /// |
| 876 | /// Never returns an error: a turn with one bad attachment should still be |
| 877 | /// sent, with the failure stated in-band rather than swallowed. |
| 878 | #[must_use] |
| 879 | pub fn expand_attachment_blocks(text: &str) -> ExpandedAttachments { |
| 880 | let references = codewhale_core::media_attachment_references(text); |
| 881 | let mut out = ExpandedAttachments::default(); |
| 882 | for reference in references { |
| 883 | if reference.kind != "image" { |
| 884 | // Video and any future kind: left as the text reference it |
| 885 | // already was. Silently ignoring it here is not a drop — the |
| 886 | // path is still in the prompt, exactly as before this module |
| 887 | // existed. |
| 888 | continue; |
| 889 | } |
| 890 | match attach_image_from_path(Path::new(&reference.path)) { |
| 891 | Ok(image) => { |
| 892 | out.blocks |
| 893 | .push(tag_block(&format!("<image path=\"{}\">", reference.path))); |
| 894 | out.blocks.push(image.content_block()); |
| 895 | out.blocks.push(tag_block("</image>")); |
| 896 | } |
| 897 | Err(error) => out.notices.push(error.to_string()), |
| 898 | } |
| 899 | } |
| 900 | out |
| 901 | } |
| 902 | |
| 903 | fn tag_block(text: &str) -> ContentBlock { |
| 904 | ContentBlock::Text { |
| 905 | text: text.to_string(), |
| 906 | cache_control: None, |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | /// True for the `<image path="…">` / `</image>` text blocks that |
| 911 | /// [`expand_attachment_blocks`] brackets an attachment with. |
| 912 | /// |
| 913 | /// They exist so the model can tell three screenshots apart, not because a |
| 914 | /// person typed them: the turn record keeps the prompt block that named |
| 915 | /// `[Attached image: …]` and nothing else. Readers that rebuild "what the user |
| 916 | /// said" from a saved transcript skip them, so a prompt that carried a |
| 917 | /// screenshot still matches the turn that recorded it. |
| 918 | #[must_use] |
| 919 | pub fn is_attachment_tag_block(block: &ContentBlock) -> bool { |
| 920 | let ContentBlock::Text { text, .. } = block else { |
| 921 | return false; |
| 922 | }; |
| 923 | let text = text.trim(); |
| 924 | text == "</image>" || (text.starts_with("<image path=\"") && text.ends_with("\">")) |
| 925 | } |
| 926 | |
| 927 | /// Replace every image in a request with text when the route cannot see them. |
| 928 | /// |
| 929 | /// Capability is a property of the *route*, not of the attachment, and the |
| 930 | /// route changes freely mid-session. Deciding this when the message is built |
| 931 | /// would burn the answer into history: attach a screenshot while a text-only |
| 932 | /// model is selected, switch to a vision model, and the image would be gone |
| 933 | /// for good. So history always keeps the real image and each outbound request |
| 934 | /// is normalized against the model it is actually going to. |
| 935 | /// |
| 936 | /// Only a known `Unsupported` strips. Most routes report `Unknown` because |
| 937 | /// models.dev has no modality data for them, and treating unknown as "no" |
| 938 | /// would make the feature dead on arrival for exactly the self-hosted and |
| 939 | /// custom routes that most need it — so `Unknown` sends the image and lets the |
| 940 | /// provider be the authority. |
| 941 | /// |
| 942 | /// The image is replaced in place rather than removed, so the model is told |
| 943 | /// why it is looking at a gap instead of being left to invent one. |
| 944 | pub fn strip_images_when_unsupported( |
| 945 | messages: &mut [codewhale_models::Message], |
| 946 | vision: SupportState, |
| 947 | model: &str, |
| 948 | ) -> usize { |
| 949 | if vision != SupportState::Unsupported { |
| 950 | return 0; |
| 951 | } |
| 952 | let mut stripped = 0; |
| 953 | for message in messages.iter_mut() { |
| 954 | for block in &mut message.content { |
| 955 | match block { |
| 956 | ContentBlock::ImageUrl { .. } => { |
| 957 | *block = ContentBlock::Text { |
| 958 | text: format!( |
| 959 | "[image content omitted: the active model ({model}) does \ |
| 960 | not accept image input. Use the image_ocr tool to read \ |
| 961 | text from it, or switch to a vision-capable model with \ |
| 962 | /model.]" |
| 963 | ), |
| 964 | cache_control: None, |
| 965 | }; |
| 966 | stripped += 1; |
| 967 | } |
| 968 | ContentBlock::ToolResult { |
| 969 | content, |
| 970 | content_blocks, |
| 971 | .. |
| 972 | } => { |
| 973 | let count = content_blocks.as_ref().map_or(0, Vec::len); |
| 974 | if count > 0 { |
| 975 | *content_blocks = None; |
| 976 | *content = format!( |
| 977 | "{content}\n[{count} image block(s) omitted: the active model ({model}) does not accept image input. Use the image_ocr tool to read text from it, or switch to a vision-capable model with /model.]" |
| 978 | ); |
| 979 | stripped += count; |
| 980 | } |
| 981 | } |
| 982 | _ => {} |
| 983 | } |
| 984 | } |
| 985 | } |
| 986 | stripped |
| 987 | } |
| 988 | |
| 989 | /// Total inline-image byte budget for one compaction retry that follows a |
| 990 | /// provider body-size rejection. |
| 991 | /// |
| 992 | /// An HTTP 413 boundary caps the request *body*, and the token-side context |
| 993 | /// budget that governs compaction cannot see it: an image that costs a flat |
| 994 | /// token estimate can still spend megabytes of base64. Nothing consults this |
| 995 | /// budget on the happy path — it exists only to recover a summary call that |
| 996 | /// has already been refused, where the cheapest useful move is to re-encode |
| 997 | /// the inline images under a cap at or below the smallest provider body limits |
| 998 | /// seen in practice and retry. |
| 999 | pub const COMPACTION_IMAGE_TOTAL_BUDGET_BYTES: usize = 2 * 1024 * 1024; |
| 1000 | |
| 1001 | /// Smallest per-image share of that budget, so an image-heavy session still |
| 1002 | /// re-encodes each image instead of dividing the budget down to nothing. |
| 1003 | const COMPACTION_IMAGE_MIN_BUDGET_BYTES: usize = 96 * 1024; |
| 1004 | |
| 1005 | /// Longest edge a re-encoded inline image keeps, in pixels. |
| 1006 | const COMPACTION_IMAGE_MAX_EDGE: u32 = 1024; |
| 1007 | |
| 1008 | /// Longest edge the shrink ladder descends to before giving up on an image. |
| 1009 | const COMPACTION_IMAGE_MIN_EDGE: u32 = 128; |
| 1010 | |
| 1011 | /// JPEG quality for re-encoded images that carry no meaningful alpha. |
| 1012 | const COMPACTION_IMAGE_JPEG_QUALITY: u8 = 80; |
| 1013 | |
| 1014 | /// What one inline-image shrink pass changed. |
| 1015 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] |
| 1016 | pub struct ShrunkInlineImages { |
| 1017 | /// Images that were re-encoded smaller. |
| 1018 | pub images: usize, |
| 1019 | /// Inline images the request carried, rewritten or not. |
| 1020 | /// |
| 1021 | /// `images == 0` alone cannot tell "nothing to do because every image |
| 1022 | /// already fits" from "there were no images"; a request-size ladder must |
| 1023 | /// not conflate the two, because only the second makes the next rung |
| 1024 | /// pointless. |
| 1025 | pub images_seen: usize, |
| 1026 | /// Decoded bytes of those images before the pass. |
| 1027 | pub bytes_before: usize, |
| 1028 | /// Decoded bytes of those images after the pass. |
| 1029 | pub bytes_after: usize, |
| 1030 | } |
| 1031 | |
| 1032 | /// Re-encode every inline image in `messages` under a total byte budget. |
| 1033 | /// |
| 1034 | /// Covers both carriers an outbound request can hold: an `image_url` block, |
| 1035 | /// and the stored tool-result shape (`{"type":"image","mime_type","data"}`) |
| 1036 | /// that the wire projection reads back out via |
| 1037 | /// [`provider_tool_result_image_refs`]. |
| 1038 | /// |
| 1039 | /// `images == 0` means nothing was rewritten — either there were no inline |
| 1040 | /// images, or each was already under its share of the budget. Check |
| 1041 | /// [`ShrunkInlineImages::images_seen`] to tell those apart: a caller that is |
| 1042 | /// still looking at a body-size rejection must climb to the next rung rather |
| 1043 | /// than resend the same bytes, and when images are present but nothing was |
| 1044 | /// rewritten, the next rung is the only one that can still change the payload. |
| 1045 | pub fn shrink_images_for_request(messages: &mut [codewhale_models::Message]) -> ShrunkInlineImages { |
| 1046 | shrink_images_for_request_with_budget(messages, COMPACTION_IMAGE_TOTAL_BUDGET_BYTES) |
| 1047 | } |
| 1048 | |
| 1049 | /// Budget-parameterized core of [`shrink_images_for_request`], kept separate |
| 1050 | /// so tests can drive it with small budgets and small images. |
| 1051 | pub fn shrink_images_for_request_with_budget( |
| 1052 | messages: &mut [codewhale_models::Message], |
| 1053 | budget: usize, |
| 1054 | ) -> ShrunkInlineImages { |
| 1055 | let sizes = inline_image_sizes(messages); |
| 1056 | let total: usize = sizes.iter().sum(); |
| 1057 | let images_seen = sizes.len(); |
| 1058 | if total <= budget { |
| 1059 | // Images may be present and simply already fit: report them as seen |
| 1060 | // without rewriting, so a caller can tell "nothing to shrink" from |
| 1061 | // "nothing there". |
| 1062 | return ShrunkInlineImages { |
| 1063 | images_seen, |
| 1064 | ..ShrunkInlineImages::default() |
| 1065 | }; |
| 1066 | } |
| 1067 | // A share of the budget per image, floored so a few large images still come |
| 1068 | // back readable. With many images the floor can push the total past |
| 1069 | // `budget`; the caller's next rung (replace with notes) covers that case, |
| 1070 | // not a tighter share here. |
| 1071 | let per_image = (budget / sizes.len()).max(COMPACTION_IMAGE_MIN_BUDGET_BYTES); |
| 1072 | let mut outcome = ShrunkInlineImages::default(); |
| 1073 | for message in messages.iter_mut() { |
| 1074 | for block in &mut message.content { |
| 1075 | match block { |
| 1076 | ContentBlock::ImageUrl { image_url } => { |
| 1077 | if let Some((url, shrunk)) = shrink_data_url(&image_url.url, per_image) { |
| 1078 | image_url.url = url; |
| 1079 | outcome.images += 1; |
| 1080 | outcome.bytes_before += shrunk.before; |
| 1081 | outcome.bytes_after += shrunk.after; |
| 1082 | } |
| 1083 | } |
| 1084 | ContentBlock::ToolResult { content_blocks, .. } => { |
| 1085 | let Some(blocks) = content_blocks.as_mut() else { |
| 1086 | continue; |
| 1087 | }; |
| 1088 | for value in blocks.iter_mut() { |
| 1089 | if let Some(shrunk) = shrink_stored_tool_image(value, per_image) { |
| 1090 | outcome.images += 1; |
| 1091 | outcome.bytes_before += shrunk.before; |
| 1092 | outcome.bytes_after += shrunk.after; |
| 1093 | } |
| 1094 | } |
| 1095 | } |
| 1096 | _ => {} |
| 1097 | } |
| 1098 | } |
| 1099 | } |
| 1100 | outcome.images_seen = images_seen; |
| 1101 | outcome |
| 1102 | } |
| 1103 | |
| 1104 | /// Replace every inline image with a text note that keeps the image's |
| 1105 | /// existence visible without its bytes. |
| 1106 | /// |
| 1107 | /// This is the last rung of the request-size ladder. A summary pass that still |
| 1108 | /// exceeds the provider's body cap after re-encoding has nothing left to give |
| 1109 | /// but the pixels; the note keeps the fact that a tool or the user supplied an |
| 1110 | /// image — and how large it was — so the handoff can still say so instead of |
| 1111 | /// silently dropping the detail. Session history keeps the real image; this |
| 1112 | /// only rewrites the outbound copy. |
| 1113 | /// |
| 1114 | /// Returns the number of images replaced. |
| 1115 | pub fn replace_images_with_placeholders( |
| 1116 | messages: &mut [codewhale_models::Message], |
| 1117 | reason: &str, |
| 1118 | ) -> usize { |
| 1119 | let mut replaced = 0; |
| 1120 | for message in messages.iter_mut() { |
| 1121 | for block in &mut message.content { |
| 1122 | match block { |
| 1123 | ContentBlock::ImageUrl { image_url } => { |
| 1124 | let bytes = parse_data_url(&image_url.url) |
| 1125 | .map(|(_, payload)| decoded_len_estimate(payload)); |
| 1126 | *block = ContentBlock::Text { |
| 1127 | text: image_placeholder_note(1, bytes, reason), |
| 1128 | cache_control: None, |
| 1129 | }; |
| 1130 | replaced += 1; |
| 1131 | } |
| 1132 | ContentBlock::ToolResult { |
| 1133 | content, |
| 1134 | content_blocks, |
| 1135 | .. |
| 1136 | } => { |
| 1137 | let Some(blocks) = content_blocks.as_ref() else { |
| 1138 | continue; |
| 1139 | }; |
| 1140 | let mut count = 0usize; |
| 1141 | let mut bytes = 0usize; |
| 1142 | for value in blocks { |
| 1143 | if let Some((_, payload)) = stored_tool_image_payload(value) { |
| 1144 | count += 1; |
| 1145 | bytes += decoded_len_estimate(payload); |
| 1146 | } |
| 1147 | } |
| 1148 | if count == 0 { |
| 1149 | continue; |
| 1150 | } |
| 1151 | // Same shape as `strip_images_when_unsupported`: the |
| 1152 | // wire projection reads tool images back out of |
| 1153 | // `content_blocks` and would count a text block placed |
| 1154 | // there as an omitted image. |
| 1155 | *content_blocks = None; |
| 1156 | *content = format!( |
| 1157 | "{content}\n{}", |
| 1158 | image_placeholder_note(count, Some(bytes), reason) |
| 1159 | ); |
| 1160 | replaced += count; |
| 1161 | } |
| 1162 | _ => {} |
| 1163 | } |
| 1164 | } |
| 1165 | } |
| 1166 | replaced |
| 1167 | } |
| 1168 | |
| 1169 | /// The in-band note that replaces an inline image byte payload for one |
| 1170 | /// summary pass. It tells the summarizer what was there and what to do |
| 1171 | /// about it (refer to it as an image; never invent its contents), rather than |
| 1172 | /// leaving a silent gap. |
| 1173 | fn image_placeholder_note(count: usize, bytes: Option<usize>, reason: &str) -> String { |
| 1174 | let size = bytes.map_or(String::new(), |bytes| format!(" (~{})", human_bytes(bytes))); |
| 1175 | format!( |
| 1176 | "[{count} image(s){size} omitted from this summary pass: {reason}. \ |
| 1177 | The image(s) remain in the session. Refer to them only as images the \ |
| 1178 | conversation included; do not describe or guess what they showed.]" |
| 1179 | ) |
| 1180 | } |
| 1181 | |
| 1182 | /// Base64 length to decoded length: four characters carry three bytes. |
| 1183 | fn decoded_len_estimate(payload: &str) -> usize { |
| 1184 | payload.len() / 4 * 3 |
| 1185 | } |
| 1186 | |
| 1187 | /// Decoded-size estimates for every inline image, in request order. |
| 1188 | fn inline_image_sizes(messages: &[codewhale_models::Message]) -> Vec<usize> { |
| 1189 | let mut sizes = Vec::new(); |
| 1190 | for message in messages { |
| 1191 | for block in &message.content { |
| 1192 | match block { |
| 1193 | ContentBlock::ImageUrl { image_url } => { |
| 1194 | if let Some((_, payload)) = parse_data_url(&image_url.url) { |
| 1195 | sizes.push(decoded_len_estimate(payload)); |
| 1196 | } |
| 1197 | } |
| 1198 | ContentBlock::ToolResult { content_blocks, .. } => { |
| 1199 | if let Some(blocks) = content_blocks.as_ref() { |
| 1200 | for value in blocks { |
| 1201 | if let Some((_, payload)) = stored_tool_image_payload(value) { |
| 1202 | sizes.push(decoded_len_estimate(payload)); |
| 1203 | } |
| 1204 | } |
| 1205 | } |
| 1206 | } |
| 1207 | _ => {} |
| 1208 | } |
| 1209 | } |
| 1210 | } |
| 1211 | sizes |
| 1212 | } |
| 1213 | |
| 1214 | /// The `(mime_type, data)` pair of a stored tool-result image block, if the |
| 1215 | /// block is one. |
| 1216 | pub(crate) fn stored_tool_image_payload(value: &serde_json::Value) -> Option<(&str, &str)> { |
| 1217 | if value.get("type").and_then(serde_json::Value::as_str) != Some("image") { |
| 1218 | return None; |
| 1219 | } |
| 1220 | let mime_type = value.get("mime_type").and_then(serde_json::Value::as_str)?; |
| 1221 | let data = value.get("data").and_then(serde_json::Value::as_str)?; |
| 1222 | Some((mime_type, data)) |
| 1223 | } |
| 1224 | |
| 1225 | /// One rewritten image, in decoded bytes. |
| 1226 | #[derive(Debug, Clone, Copy)] |
| 1227 | struct ShrunkPayload { |
| 1228 | before: usize, |
| 1229 | after: usize, |
| 1230 | } |
| 1231 | |
| 1232 | /// Re-encode a `data:` URL image under `budget`, returning the replacement |
| 1233 | /// URL plus the byte delta. |
| 1234 | fn shrink_data_url(url: &str, budget: usize) -> Option<(String, ShrunkPayload)> { |
| 1235 | let (_, payload) = parse_data_url(url)?; |
| 1236 | let (mime, data, shrunk) = shrink_base64_image(payload, budget)?; |
| 1237 | Some((format!("data:{mime};base64,{data}"), shrunk)) |
| 1238 | } |
| 1239 | |
| 1240 | /// Re-encode one stored tool-result image block in place. |
| 1241 | fn shrink_stored_tool_image(value: &mut serde_json::Value, budget: usize) -> Option<ShrunkPayload> { |
| 1242 | let (_, payload) = stored_tool_image_payload(value)?; |
| 1243 | let (mime, data, shrunk) = shrink_base64_image(payload, budget)?; |
| 1244 | let object = value.as_object_mut()?; |
| 1245 | object.insert("mime_type".to_string(), serde_json::Value::String(mime)); |
| 1246 | object.insert("data".to_string(), serde_json::Value::String(data)); |
| 1247 | Some(shrunk) |
| 1248 | } |
| 1249 | |
| 1250 | /// Re-encode one base64 inline image to fit `budget` decoded bytes. |
| 1251 | /// |
| 1252 | /// `None` means the image already fits, cannot be decoded, or the re-encode |
| 1253 | /// came back no smaller — so a caller's "did anything change" tally stays |
| 1254 | /// honest about what a retry would actually send. |
| 1255 | fn shrink_base64_image(data: &str, budget: usize) -> Option<(String, String, ShrunkPayload)> { |
| 1256 | let bytes = STANDARD.decode(data).ok()?; |
| 1257 | if bytes.len() <= budget { |
| 1258 | return None; |
| 1259 | } |
| 1260 | let (decoded, _, _) = decode_and_guard_image(&bytes).ok()?; |
| 1261 | let (mime, encoded) = reencode_within_budget(decoded, budget)?; |
| 1262 | if encoded.len() >= bytes.len() { |
| 1263 | return None; |
| 1264 | } |
| 1265 | Some(( |
| 1266 | mime.to_string(), |
| 1267 | STANDARD.encode(&encoded), |
| 1268 | ShrunkPayload { |
| 1269 | before: bytes.len(), |
| 1270 | after: encoded.len(), |
| 1271 | }, |
| 1272 | )) |
| 1273 | } |
| 1274 | |
| 1275 | /// Encode `image` down a short ladder until it fits `budget`. |
| 1276 | /// |
| 1277 | /// Rung order: longest edge capped at [`COMPACTION_IMAGE_MAX_EDGE`], then |
| 1278 | /// halved until [`COMPACTION_IMAGE_MIN_EDGE`]. Alpha-bearing images stay PNG |
| 1279 | /// (JPEG would flatten transparency); everything else becomes JPEG, which is |
| 1280 | /// what actually makes screenshots and artwork small. The smallest rung wins |
| 1281 | /// even when nothing fits `budget`, because a smaller-than-before payload is |
| 1282 | /// still progress for the retry. |
| 1283 | fn reencode_within_budget(image: DynamicImage, budget: usize) -> Option<(&'static str, Vec<u8>)> { |
| 1284 | let mut current = image; |
| 1285 | let (mut width, mut height) = current.dimensions(); |
| 1286 | if width.max(height) > COMPACTION_IMAGE_MAX_EDGE { |
| 1287 | let scale = f64::from(COMPACTION_IMAGE_MAX_EDGE) / f64::from(width.max(height)); |
| 1288 | let scaled_width = ((f64::from(width) * scale).round() as u32).max(1); |
| 1289 | let scaled_height = ((f64::from(height) * scale).round() as u32).max(1); |
| 1290 | current = current.resize(scaled_width, scaled_height, FilterType::Lanczos3); |
| 1291 | (width, height) = current.dimensions(); |
| 1292 | } |
| 1293 | let mut smallest: Option<(&'static str, Vec<u8>)> = None; |
| 1294 | loop { |
| 1295 | if let Some(candidate) = encode_inline_image(¤t) |
| 1296 | && smallest |
| 1297 | .as_ref() |
| 1298 | .is_none_or(|(_, best)| candidate.1.len() < best.len()) |
| 1299 | { |
| 1300 | smallest = Some(candidate); |
| 1301 | } |
| 1302 | if smallest |
| 1303 | .as_ref() |
| 1304 | .is_some_and(|(_, bytes)| bytes.len() <= budget) |
| 1305 | { |
| 1306 | break; |
| 1307 | } |
| 1308 | if width.max(height) <= COMPACTION_IMAGE_MIN_EDGE { |
| 1309 | break; |
| 1310 | } |
| 1311 | (width, height) = ((width / 2).max(1), (height / 2).max(1)); |
| 1312 | current = current.resize(width, height, FilterType::Lanczos3); |
| 1313 | } |
| 1314 | smallest |
| 1315 | } |
| 1316 | |
| 1317 | /// One encoder pass: PNG when alpha matters, JPEG otherwise. |
| 1318 | fn encode_inline_image(image: &DynamicImage) -> Option<(&'static str, Vec<u8>)> { |
| 1319 | let (width, height) = image.dimensions(); |
| 1320 | let mut bytes = Vec::new(); |
| 1321 | if image.color().has_alpha() { |
| 1322 | let rgba = image.to_rgba8(); |
| 1323 | PngEncoder::new_with_quality(&mut bytes, CompressionType::Best, PngFilter::Adaptive) |
| 1324 | .write_image(rgba.as_raw(), width, height, ExtendedColorType::Rgba8) |
| 1325 | .ok()?; |
| 1326 | Some(("image/png", bytes)) |
| 1327 | } else { |
| 1328 | let rgb = image.to_rgb8(); |
| 1329 | JpegEncoder::new_with_quality(&mut bytes, COMPACTION_IMAGE_JPEG_QUALITY) |
| 1330 | .write_image(rgb.as_raw(), width, height, ExtendedColorType::Rgb8) |
| 1331 | .ok()?; |
| 1332 | Some(("image/jpeg", bytes)) |
| 1333 | } |
| 1334 | } |
| 1335 | |
| 1336 | /// Render dropped-attachment notices as a block the model will read. |
| 1337 | /// |
| 1338 | /// Wrapped in a tag rather than appended as bare prose so the model can tell |
| 1339 | /// the difference between the user saying something and the harness reporting |
| 1340 | /// on itself. |
| 1341 | #[must_use] |
| 1342 | pub fn notice_block(notices: &[String]) -> Option<ContentBlock> { |
| 1343 | if notices.is_empty() { |
| 1344 | return None; |
| 1345 | } |
| 1346 | let body = notices.join("\n"); |
| 1347 | Some(ContentBlock::Text { |
| 1348 | text: format!( |
| 1349 | "<attachment_notice>\n{body}\nDo not describe these images from \ |
| 1350 | memory or from their filenames; ask the user to re-share them.\n\ |
| 1351 | </attachment_notice>" |
| 1352 | ), |
| 1353 | cache_control: None, |
| 1354 | }) |
| 1355 | } |
| 1356 | |
| 1357 | #[cfg(any(test, feature = "test-support"))] |
| 1358 | pub mod test_support; |
| 1359 | #[cfg(test)] |
| 1360 | #[path = "image_attach/tests.rs"] |
| 1361 | mod tests; |
| 1362 |