Cotton code
234 lines · 9.7 KB · RustRaw
//! The photo tools (schema v31): `list_photos`, `get_photo`, `get_photo_bytes`,//! `update_photo`, `remove_photo`.//!//! The machinery is [`super::media_tools`] — one implementation shared with//! videos, as D1 promised. What lives HERE is the one thing a photo has that a//! video does not: the picture itself can travel inside a tool result, so an//! assistant can look at it. That is `get_photo_bytes`, and it is the//! `get_document_bytes` shape down to the cap, because it is the same road —//! base64 through the protocol is what works from a sandboxed client with no//! network.//!//! There is deliberately NO create verb. A photo enters as bytes — the app's//! picker or share sheet, or a chat — and assistants describe and file what//! exists (D8).use base64::engine::general_purpose::STANDARD;use base64::Engine;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::media_tools::{    get_media, list_media, media_row, remove_media, require_media_id, rint, rtext, rtext_any,    update_media, validate_list_media, validate_update_media, PHOTO_SPEC,};use crate::mcp::protocol::{tool_content, ToolFailure};pub fn handlers() -> HandlerGroup {    &[        ("list_photos", list_photos),        ("get_photo", get_photo),        ("get_photo_bytes", get_photo_bytes),        ("update_photo", update_photo),        ("add_photo", add_photo),        ("remove_photo", remove_photo),    ]}/// The most a picture may weigh to travel INSIDE a tool result.////// `get_document_bytes`'s number, deliberately the same one: the constraint is/// the protocol and the client's context window, not what kind of file it is,/// and two caps would be two numbers to explain.pub const BYTES_TOOL_MAX: usize = 2 * 1024 * 1024;pub fn list_photos(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_list_media(args)?;    list_media(ctx, PHOTO_SPEC, &args)}pub fn get_photo(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_media_id(args, "photo")?;    Ok(Value::Object(get_media(ctx, PHOTO_SPEC, &id)?))}/// The most a picture sent whole may weigh, before its base64.pub const ADD_PHOTO_MAX: usize = 12 * 1024 * 1024;/// A picture `add_photo` was sent, as its bytes say it is — `None` for/// arguments that carry none, which the handler refuses by name. Read here/// and before the file (`BeforeTheFile::StorePhoto`) alike.pub fn sent_photo(args: &Map<String, Value>) -> Option<crate::tool_pictures::ToolPhoto> {    let encoded = args.get("bytes")?.as_str()?;    if encoded.len() > ADD_PHOTO_MAX / 3 * 4 + 4 {        return None;    }    crate::tool_pictures::uploaded(STANDARD.decode(encoded).ok()?)}/// Put a picture into this database: its bytes, stored by the server before/// the file was taken, and its photo record, answered by id — the/// `photo:<sha256>` a photo column holds, with its create change as every add/// answers one where Photos draws the table. A picture already here is/// answered as it is, never written twice.pub fn add_photo(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let caption = match args.get("caption") {        None | Some(Value::Null) => None,        Some(Value::String(caption)) if caption.chars().count() <= 500 => Some(caption.trim()).filter(|caption| !caption.is_empty()),        Some(_) => return Err(ToolFailure::new("caption is at most 500 characters of text")),    };    let Some(photo) = sent_photo(args) else {        return Err(ToolFailure::new(format!(            "bytes must be a PNG, JPEG or WebP picture of at most {} MB, as standard base64",            ADD_PHOTO_MAX / 1024 / 1024        )));    };    let id = photo.id();    let held = ctx        .db()        .get("SELECT id FROM cotton_photos WHERE workspace_id = ? AND id = ?", &[ctx.workspace_id.to_string().into(), id.clone().into()])        .map_err(|error| ToolFailure::new(error.to_string()))?        .is_some();    if held {        return Ok(serde_json::json!({"id": id, "added": false}));    }    match &ctx.services.stored_photos {        None => return Err(ToolFailure::new("this database keeps no picture bytes here, so no picture can be added to it")),        Some(stored) if !stored.contains(&photo.sha256) => {            return Err(ToolFailure::new("the picture's bytes could not be stored — send it again"))        }        Some(_) => {}    }    let file_name = args        .get("fileName")        .and_then(Value::as_str)        .map(str::trim)        .filter(|name| !name.is_empty() && name.chars().count() <= 200)        .map_or_else(|| format!("{}.{}", photo.sha256, photo.ext), str::to_string);    // In a database no Photos tool draws (a business's), the picture is only    // what a photo column names: no record a person sees, so no add to undo.    let drawn = super::tables::definition(ctx, "photo").is_ok();    crate::tool_pictures::write_upload(ctx, &photo, &file_name, caption)?;    if !drawn {        ctx.commit()?;        return Ok(serde_json::json!({"id": id, "added": true}));    }    let change = super::tables::record_added(ctx, "photo", &id)?;    Ok(serde_json::json!({"id": id, "added": true, "change": change}))}pub fn update_photo(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_update_media(args, "photo")?;    update_media(ctx, PHOTO_SPEC, &args)}pub fn remove_photo(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_media_id(args, "photo")?;    remove_media(ctx, PHOTO_SPEC, &id)}/// `Number.prototype.toLocaleString("en-GB")` for a non-negative integer:/// groups of three from the right, separated by commas. The sentence a person/// reads carries the separator, and the number in it must track the constant/// rather than be typed out beside it.fn en_gb_thousands(value: u64) -> String {    let digits = value.to_string();    let mut out = String::with_capacity(digits.len() + digits.len() / 3);    for (index, digit) in digits.chars().enumerate() {        if index > 0 && (digits.len() - index).is_multiple_of(3) {            out.push(',');        }        out.push(digit);    }    out}pub fn get_photo_bytes(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_media_id(args, "photo")?;    let row = media_row(ctx, PHOTO_SPEC, &id)?;    let Some(store) = ctx.services.media_get.clone() else {        return Err(ToolFailure::new(            "this server cannot reach the pictures themselves: no object store is configured. \             Everything Cotton knows about this photo still answers through get_photo.",        ));    };    // The row's own size FIRST, so an oversized picture is refused before its    // bytes are pulled through a process capped at 2 GB. A row that never    // learned its size (an imported chat archive records 0) is checked again    // below, against what was actually read.    let size_bytes = rint(&row, "size_bytes").unwrap_or(0);    if size_bytes > BYTES_TOOL_MAX as i64 {        return Err(ToolFailure::new(format!(            "this picture is {} bytes — over the {}-byte limit for carrying bytes in a tool \             result. get_photo answers everything else about it.",            en_gb_thousands(size_bytes.max(0) as u64),            en_gb_thousands(BYTES_TOOL_MAX as u64)        )));    }    let key = rtext(&row, "key").unwrap_or_default();    let Some(bytes) = store(&key).map_err(ToolFailure::new)? else {        // THE ROW ARRIVES BEFORE THE BYTES, and that is not a fault —        // offline-first means the phone queues the upload for whatever network        // it walks into next. Said plainly, so an assistant reports it rather        // than retrying.        return Err(ToolFailure::new(            "this photo's bytes have not reached the server yet — the record is here and the \             picture is still on the owner's phone, waiting to upload. Try again later.",        ));    };    if bytes.len() > BYTES_TOOL_MAX {        return Err(ToolFailure::new(format!(            "this picture is {} bytes — over the {}-byte limit for carrying bytes in a tool \             result.",            en_gb_thousands(bytes.len() as u64),            en_gb_thousands(BYTES_TOOL_MAX as u64)        )));    }    let mut facts = Map::new();    facts.insert("id".to_string(), Value::from(id));    facts.insert(        "caption".to_string(),        rtext_any(&row, "caption").map_or(Value::Null, Value::from),    );    facts.insert(        "description".to_string(),        rtext_any(&row, "summary").map_or(Value::Null, Value::from),    );    facts.insert(        "takenAt".to_string(),        rtext_any(&row, "taken_at").map_or(Value::Null, Value::from),    );    facts.insert("byteSize".to_string(), Value::from(bytes.len()));    facts.insert(        "mime".to_string(),        rtext_any(&row, "content_type").map_or(Value::Null, Value::from),    );    facts.insert(        "sha256".to_string(),        rtext_any(&row, "sha256").map_or(Value::Null, Value::from),    );    let mut image = Map::new();    // The protocol's own image block: clients render those directly, which is    // the whole reason this tool exists rather than a link.    image.insert("type".to_string(), Value::from("image"));    image.insert("data".to_string(), Value::from(STANDARD.encode(&bytes)));    image.insert(        "mimeType".to_string(),        rtext_any(&row, "content_type").map_or(Value::Null, Value::from),    );    let mut text_block = Map::new();    text_block.insert("type".to_string(), Value::from("text"));    text_block.insert(        "text".to_string(),        Value::from(Value::Object(facts).to_string()),    );    Ok(tool_content(vec![        Value::Object(image),        Value::Object(text_block),    ]))}