Cotton code
300 lines · 10.8 KB · RustRaw
//! The generic verbs' writes to the mailbox and the chats — `email`,//! `email_thread` and `thread` — each through the engine tool the app and an//! assistant already call, so a write here means exactly what theirs does.//!//! - **`email`** — `unread`, `starred` and `in_inbox` through `update_email`//!   on the one message (`read` is the tool's word, the opposite of//!   `unread`). Everything else on a message is what arrived with it.//! - **`email_thread`** — `summary` through `update_summary` (kind//!   `email_thread`). A conversation's read, starred and inbox state is//!   folded from its messages, so it is written on them.//! - **`thread`** (a chat, `cotton_msg_threads`) — `pinned_at` through//!   `set_thread_pinned` (a day pins it, now; null takes the pin off),//!   `muted_until` through `set_thread_muted`, `summary` through//!   `update_summary` (kind `thread`), and the archive through//!   `set_thread_archived` as the adapter's delete and restore.//!//! - **`message`** — the one write out of the archive: the owner's app//!   creates a WhatsApp or Instagram text (`thread_id`, `body`, `reply_to_id`) as a//!   `queued` row the serving Mac sends, and sets a failed one's//!   `send_state` back to `queued` to send it again; a failed one goes in the//!   bin as the adapter's delete. Nothing else on a message is written here.//!//! A patch naming several columns calls each tool it needs in one fixed//! order, every refusal first, so a bad column never leaves half a write.use cotton_core::definitions::TableDefinition;use cotton_core::records::Data;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use super::builtin::{self, cannot_clear, set_by_cotton};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::chat::threads;use crate::mcp::handlers::common::{now_iso, Valid};use crate::mcp::handlers::emails::state;use crate::mcp::handlers::summaries;use crate::mcp::protocol::ToolFailure;/// A summary as `update_summary` takes it: a blank one is refused by the tool/// with a sentence about null, so blank and null both clear.fn summary_arg(value: &Value) -> Value {    match value.as_str() {        Some(text) if text.trim().is_empty() => Value::Null,        _ => value.clone(),    }}fn write_summary(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    kind: &str,    id: &str,    summary: &Value,) -> Valid<()> {    builtin::call(        ctx,        definition,        "update_summary",        summaries::update_summary,        json!({ "kind": kind, "id": id, "summary": summary_arg(summary) }),    )    .map(|_| ())}// ── email ───────────────────────────────────────────────────────────────────/// `update_record` on one message: its read, starred and inbox marks, all in/// one `update_email`. A mark is true or false; it has no "unset".pub(super) fn email_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    args.insert("id".into(), Value::from(id));    for (key, value) in patch {        let arg = match key.as_str() {            "unread" => "read",            "starred" => "starred",            "in_inbox" => "inbox",            other => return Err(set_by_cotton(definition, other)),        };        if value.is_null() {            return Err(cannot_clear(definition, key));        }        // Refused here, by the column's own name: the tool would name its        // own argument, which for `unread` is the opposite word.        let Some(on) = value.as_bool() else {            return Err(ToolFailure::new(format!("{key} is true or false")));        };        args.insert(arg.into(), Value::Bool(if key == "unread" { !on } else { on }));    }    builtin::call(        ctx,        definition,        "update_email",        state::update_email,        Value::Object(args),    )    .map(|_| ())}// ── email thread ────────────────────────────────────────────────────────────/// `update_record` on a conversation: its summary, which the summaries engine/// writes and stamps. Null (or blank) clears it.pub(super) fn email_thread_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    if let Some(other) = patch.keys().find(|key| key.as_str() != "summary") {        return Err(set_by_cotton(definition, other));    }    match patch.get("summary") {        Some(summary) => write_summary(ctx, definition, "email_thread", id, summary),        None => Ok(()),    }}// ── chat thread ─────────────────────────────────────────────────────────────/// `update_record` on a chat: its pin, its mute and its summary, each through/// its own tool, in that order. A pin's day is the engine's — any day pins/// it now, so an undo re-pins rather than restoring the old moment.pub(super) fn thread_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    if let Some(other) = patch        .keys()        .find(|key| !matches!(key.as_str(), "pinned_at" | "muted_until" | "summary"))    {        return Err(set_by_cotton(definition, other));    }    if let Some(until) = patch.get("muted_until") {        if !until.is_null() && !until.is_string() {            return Err(ToolFailure::new("muted_until is a time, or null to unmute"));        }    }    if let Some(summary) = patch.get("summary") {        if !summary.is_null() && !summary.is_string() {            return Err(ToolFailure::new("summary is a paragraph, or null to clear it"));        }    }    if let Some(pinned) = patch.get("pinned_at") {        builtin::call(            ctx,            definition,            "set_thread_pinned",            threads::set_thread_pinned,            json!({ "threadId": id, "pinned": !pinned.is_null() }),        )?;    }    if let Some(until) = patch.get("muted_until") {        builtin::call(            ctx,            definition,            "set_thread_muted",            threads::set_thread_muted,            json!({ "threadId": id, "until": until }),        )?;    }    if let Some(summary) = patch.get("summary") {        write_summary(ctx, definition, "thread", id, summary)?;    }    Ok(())}/// A chat put away: `set_thread_archived` — the adapter's delete.pub(super) fn thread_archive(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Valid<()> {    builtin::call(        ctx,        definition,        "set_thread_archived",        threads::set_thread_archived,        json!({ "threadId": id, "archived": true }),    )    .map(|_| ())}/// A chat brought back: `set_thread_archived` — the adapter's restore.pub(super) fn thread_unarchive(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Valid<()> {    builtin::call(        ctx,        definition,        "set_thread_archived",        threads::set_thread_archived,        json!({ "threadId": id, "archived": false }),    )    .map(|_| ())}/// `email_thread`'s delete: the conversation goes to the bin with its emails,/// through `update_email`, exactly as the mailbox's own Bin — the generic/// Delete asks first, says "Moved <subject> to the bin" and offers Undo/// (walk 3c SEV 1: the Swift-only "Bin" asked nothing and had no Undo).pub(super) fn email_thread_trash(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Valid<()> {    email_thread_binned(ctx, definition, id, true)}/// The Undo of [`email_thread_trash`]: every email out of the bin again.pub(super) fn email_thread_untrash(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Valid<()> {    email_thread_binned(ctx, definition, id, false)}fn email_thread_binned(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    bin: bool,) -> Valid<()> {    builtin::call(        ctx,        definition,        "update_email",        state::update_email,        json!({ "threadId": id, "bin": bin }),    )    .map(|_| ())}// ── chat message ────────────────────────────────────────────────────────────const MESSAGES: &str = "cotton_msg_messages";/// Only the person's own app writes a text out; an assistant never does.fn owner_sends(ctx: &Ctx<'_>) -> Valid<()> {    if ctx.is_owner_app() {        Ok(())    } else {        Err(ToolFailure::new("Only your own app sends a message; an assistant never writes one into a chat"))    }}fn stored_message(ctx: &Ctx<'_>, id: &str) -> Valid<cotton_store::Row> {    ctx.db()        .get(            "SELECT thread_id, direction, channel, meta, send_state, send_attempts, trashed_at FROM cotton_msg_messages WHERE id = ?",            &[SqlValue::Text(id.to_string())],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .ok_or_else(|| ToolFailure::new("That message is not here"))}/// Whether a message may go in the bin: only a text of the owner's that/// failed to send. `message_extras` answers it as `can_delete`.pub(super) fn binnable(direction: Option<&str>, send_state: Option<&str>) -> bool {    direction == Some("out") && send_state == Some("failed")}/// `delete_record` on a message: a failed text of the owner's goes in the/// bin, still failed and never sent. Every other message stays: what arrived/// is what was written, and leaves this copy only with Delete from my copy.pub(super) fn message_bin(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> {    owner_sends(ctx)?;    let row = stored_message(ctx, id)?;    if !binnable(row.text("direction"), row.text("send_state")) {        return Err(ToolFailure::new(            "Only a text of yours that failed to send goes in the bin; any other message leaves your copy with Delete from my copy",        ));    }    let mut binned = Map::new();    binned.insert("trashed_at".into(), Value::from(now_iso(ctx)));    ctx.writer()?.upsert(MESSAGES, id, binned);    ctx.commit()}/// A binned text back out of the bin, as the bin's own restore takes it out:/// still failed, sent again only by its Retry.pub(super) fn message_unbin(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    builtin::call(        ctx,        definition,        "restore_from_bin",        crate::mcp::handlers::bin::restore_from_bin,        json!({ "kind": "message", "id": id }),    )    .map(|_| ())}