Skip to main content

agentmux_srv_core/backend/google/
gmail_write.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The `Gmail` tool's write actions (G3), named after Google's Gmail MCP tools
5//! (SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md §5, §6):
6//! `create_draft`, `update_draft`, `label_thread` (no prompt with a write grant),
7//! `send_draft` and `trash_thread` (always ask the person).
8//!
9//! There is no raw send: an agent writes a draft, and sending is `send_draft`, which shows the
10//! person the draft exactly as it will go. This module is the pure half, as [`super::gmail`] is for
11//! reads: the mail an agent describes as a message Google takes ([`outgoing`], [`rfc822`]), the
12//! requests, what the person is shown ([`DraftView`], [`send_question`]) and the check that what
13//! they approved is what is sent ([`DraftView::digest`]). The flow that asks and calls is
14//! [`super::gmail_flow`].
15
16use base64::Engine as _;
17use serde_json::{json, Value};
18use sha2::{Digest, Sha256};
19
20use super::gmail::{attachments, body_text, get, header, html_alternative, id_arg, line, s, tidy, url_of, GmailArgs};
21use super::gmail_thread::ThreadNote;
22use super::{clip, GoogleRequest};
23
24/// The write actions, in the order the tool lists them.
25pub const WRITE_ACTIONS: [&str; 5] = ["create_draft", "update_draft", "send_draft", "label_thread", "trash_thread"];
26
27/// Actions that always wait for the person (§6).
28pub fn always_asks(action: &str) -> bool {
29    matches!(action, "send_draft" | "trash_thread")
30}
31
32/// Most recipients, subject characters and body characters of one mail.
33const RECIPIENTS: usize = 50;
34const SUBJECT_CHARS: usize = 300;
35const BODY_CHARS: usize = 100_000;
36/// Label ids one `label_thread` adds or removes.
37const LABELS: usize = 10;
38/// How much of a mail's text the approval window shows.
39const SHOWN_BODY_CHARS: usize = 3000;
40
41/// The scopes an action can run with: any one is enough. A draft or a send is `gmail.compose`;
42/// labels and trash need `gmail.modify` (which includes compose).
43pub fn needs(action: &str) -> &'static [&'static str] {
44    match action {
45        "label_thread" | "trash_thread" => &["gmail.modify"],
46        _ => &["gmail.compose", "gmail.modify"],
47    }
48}
49
50/// Whether `granted` (full scope URLs, or bare names) covers the write `action`.
51pub fn granted_for(action: &str, granted: &[String]) -> bool {
52    needs(action).iter().any(|n| super::gmail::has_scope(granted, n))
53}
54
55/// One mail as an agent describes it, checked.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Outgoing {
58    pub to: Vec<String>,
59    pub cc: Vec<String>,
60    pub bcc: Vec<String>,
61    pub subject: String,
62    pub body: String,
63    /// A reply's `In-Reply-To` and `References` (Gmail threads a message by these, its subject and
64    /// its `threadId` together).
65    pub in_reply_to: Option<String>,
66    pub references: Option<String>,
67}
68
69/// An address an agent gave: `name@example.com`, or `Name <name@example.com>` with a plain name. No
70/// line break, no second address, nothing a mail header could be bent with.
71fn address(raw: &str) -> Result<String, String> {
72    let a = raw.trim();
73    let bad = || format!("\"{}\" isn't an address I can send to; write it as name@example.com", clip(&line(a, 80), 60));
74    if a.is_empty() || a.len() > 320 || a.chars().any(|c| c.is_control()) {
75        return Err(bad());
76    }
77    let (name, email) = match (a.rfind('<'), a.ends_with('>')) {
78        (Some(open), true) => (a[..open].trim(), &a[open + 1..a.len() - 1]),
79        _ => ("", a),
80    };
81    let plain_name = name.chars().all(|c| c.is_ascii_alphanumeric() || " .'-_".contains(c));
82    let (local, domain) = email.split_once('@').ok_or_else(bad)?;
83    let part_ok = |p: &str, extra: &str| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c));
84    if !plain_name || !part_ok(local, ".+-_") || !part_ok(domain, ".-") || !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.') || email.len() > 254 {
85        return Err(bad());
86    }
87    Ok(if name.is_empty() { email.to_string() } else { format!("{name} <{email}>") })
88}
89
90fn addresses(list: &Option<Vec<String>>) -> Result<Vec<String>, String> {
91    list.iter().flatten().filter(|s| !s.trim().is_empty()).map(|a| address(a)).collect()
92}
93
94/// The mail `args` describes. A draft needs a recipient only in the end: `create_draft` may leave
95/// `to` empty for the person to fill in, but nothing is sent without one.
96pub fn outgoing(args: &GmailArgs) -> Result<Outgoing, String> {
97    let (to, cc, bcc) = (addresses(&args.to)?, addresses(&args.cc)?, addresses(&args.bcc)?);
98    if to.len() + cc.len() + bcc.len() > RECIPIENTS {
99        return Err(format!("a mail goes to at most {RECIPIENTS} people"));
100    }
101    let subject = args.subject.as_deref().unwrap_or("").trim().to_string();
102    if subject.chars().any(|c| c.is_control()) {
103        return Err("the subject is a single line".to_string());
104    }
105    if subject.chars().count() > SUBJECT_CHARS {
106        return Err(format!("the subject is at most {SUBJECT_CHARS} characters"));
107    }
108    let body = args.body.as_deref().unwrap_or("").to_string();
109    if body.chars().count() > BODY_CHARS {
110        return Err(format!("the body is at most {BODY_CHARS} characters"));
111    }
112    if subject.is_empty() && body.trim().is_empty() && to.is_empty() {
113        return Err("a draft needs at least a recipient (to), a subject or a body".to_string());
114    }
115    Ok(Outgoing { to, cc, bcc, subject, body, in_reply_to: None, references: None })
116}
117
118fn b64_lines(bytes: &[u8]) -> String {
119    let all = base64::engine::general_purpose::STANDARD.encode(bytes);
120    all.as_bytes().chunks(76).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().join("\r\n")
121}
122
123/// A subject as a header value: as is when ASCII, else RFC 2047 encoded words.
124fn subject_header(subject: &str) -> String {
125    if subject.is_ascii() {
126        return subject.to_string();
127    }
128    let mut words = Vec::new();
129    let mut chunk = String::new();
130    for c in subject.chars() {
131        if chunk.len() + c.len_utf8() > 36 {
132            words.push(std::mem::take(&mut chunk));
133        }
134        chunk.push(c);
135    }
136    if !chunk.is_empty() {
137        words.push(chunk);
138    }
139    words.iter().map(|w| format!("=?UTF-8?B?{}?=", base64::engine::general_purpose::STANDARD.encode(w))).collect::<Vec<_>>().join("\r\n ")
140}
141
142/// The mail as RFC 5322 text, which Gmail takes (base64url) as a draft's `raw`. No `From`: Gmail
143/// writes the account's own address.
144pub fn rfc822(o: &Outgoing) -> String {
145    let mut out = String::from("MIME-Version: 1.0\r\n");
146    for (name, list) in [("To", &o.to), ("Cc", &o.cc), ("Bcc", &o.bcc)] {
147        if !list.is_empty() {
148            out.push_str(&format!("{name}: {}\r\n", list.join(", ")));
149        }
150    }
151    out.push_str(&format!("Subject: {}\r\n", subject_header(&o.subject)));
152    if let Some(id) = &o.in_reply_to {
153        out.push_str(&format!("In-Reply-To: {id}\r\n"));
154    }
155    if let Some(refs) = &o.references {
156        out.push_str(&format!("References: {refs}\r\n"));
157    }
158    out.push_str("Content-Type: text/plain; charset=\"UTF-8\"\r\nContent-Transfer-Encoding: base64\r\n\r\n");
159    out.push_str(&b64_lines(o.body.as_bytes()));
160    out.push_str("\r\n");
161    out
162}
163
164fn draft_body(o: &Outgoing, thread_id: Option<&str>) -> Value {
165    let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(rfc822(o));
166    let mut message = json!({ "raw": raw });
167    if let Some(t) = thread_id {
168        message["threadId"] = json!(t);
169    }
170    json!({ "message": message })
171}
172
173fn post(url: String, body: Value) -> GoogleRequest {
174    GoogleRequest { method: reqwest::Method::POST, url, query: Vec::new(), body: Some(body), text: false }
175}
176
177/// What a reply needs from the thread it answers.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Reply {
180    pub in_reply_to: String,
181    pub references: String,
182    pub subject: String,
183}
184
185/// The request for the headers of the thread a draft replies to.
186pub fn reply_fetch_plan(thread_id: &str) -> Result<GoogleRequest, String> {
187    let id = id_arg("thread_id", Some(thread_id))?;
188    let mut q = vec![("format", "metadata".to_string())];
189    for h in ["Message-ID", "References", "Subject"] {
190        q.push(("metadataHeaders", h.to_string()));
191    }
192    Ok(get(url_of(&["threads", &id])?, q))
193}
194
195/// A message id header value: `<local@host>`, one line.
196fn message_id(v: &str) -> Option<String> {
197    let v = v.trim();
198    (v.len() >= 3 && v.len() <= 998 && v.starts_with('<') && v.ends_with('>') && !v.chars().any(|c| c.is_control() || c.is_whitespace())).then(|| v.to_string())
199}
200
201/// The reply headers for an answer to the last message of `thread` (Google's `threads.get`, format
202/// metadata); `None` when it has no usable `Message-ID`.
203pub fn reply_of(thread: &Value) -> Option<Reply> {
204    let last = thread.get("messages").and_then(Value::as_array)?.last()?;
205    let p = last.get("payload")?;
206    let id = message_id(header(p, "Message-ID"))?;
207    // The thread's references, then this message: the last few, so the header stays short.
208    let mut refs: Vec<String> = header(p, "References").split_whitespace().filter_map(message_id).collect();
209    refs.push(id.clone());
210    let keep = refs.len().saturating_sub(10);
211    let subject = line(header(p, "Subject"), SUBJECT_CHARS);
212    Some(Reply { in_reply_to: id, references: refs[keep..].join(" "), subject })
213}
214
215/// `o` as a reply: its threading headers, and the original subject (with `Re: `) when it has none.
216pub fn with_reply(o: &mut Outgoing, r: &Reply) {
217    o.in_reply_to = Some(r.in_reply_to.clone());
218    o.references = Some(r.references.clone());
219    if o.subject.is_empty() && !r.subject.is_empty() {
220        o.subject = if r.subject.to_ascii_lowercase().starts_with("re:") { r.subject.clone() } else { format!("Re: {}", r.subject) };
221    }
222}
223
224/// The request for `create_draft` (or, with a draft id, `update_draft`). A `thread_id` makes the
225/// draft a reply in that thread: `reply` is that thread's last message (see [`reply_of`]), which a
226/// reply needs for Gmail to thread it.
227pub fn draft_plan(action: &str, args: &GmailArgs, reply: Option<&Reply>) -> Result<GoogleRequest, String> {
228    let mut o = outgoing(args)?;
229    if let Some(r) = reply {
230        with_reply(&mut o, r);
231    }
232    let thread = match args.thread_id.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
233        Some(t) => Some(id_arg("thread_id", Some(t))?),
234        None => None,
235    };
236    let body = draft_body(&o, thread.as_deref());
237    match action {
238        "create_draft" => Ok(post(url_of(&["drafts"])?, body)),
239        "update_draft" => {
240            let id = id_arg("draft_id", args.draft_id.as_deref())?;
241            Ok(GoogleRequest { method: reqwest::Method::PUT, url: url_of(&["drafts", &id])?, query: Vec::new(), body: Some(body), text: false })
242        }
243        other => Err(format!("{other} doesn't write a draft")),
244    }
245}
246
247/// The request for a draft as it is now, to show the person and to check before sending.
248pub fn draft_fetch_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
249    let id = id_arg("draft_id", args.draft_id.as_deref())?;
250    Ok(get(url_of(&["drafts", &id])?, vec![("format", "full".to_string())]))
251}
252
253/// The request for the draft's message as raw MIME: the snapshot that is sent.
254pub fn draft_raw_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
255    let id = id_arg("draft_id", args.draft_id.as_deref())?;
256    Ok(get(url_of(&["drafts", &id])?, vec![("format", "raw".to_string())]))
257}
258
259/// The request that sends the draft `id` with exactly the message `raw` (base64url MIME) that was
260/// checked, so a save made after the check cannot put other text, recipients or files in its place.
261pub fn send_plan(id: &str, raw: &str, thread_id: Option<&str>) -> Result<GoogleRequest, String> {
262    let id = id_arg("draft_id", Some(id))?;
263    let mut message = json!({ "raw": raw });
264    if let Some(t) = thread_id.filter(|t| !t.is_empty()) {
265        message["threadId"] = json!(t);
266    }
267    Ok(post(url_of(&["drafts", "send"])?, json!({ "id": id, "message": message })))
268}
269
270/// The request that moves a thread to the trash (it stays there for 30 days).
271pub fn trash_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
272    let id = id_arg("thread_id", args.thread_id.as_deref())?;
273    Ok(post(url_of(&["threads", &id, "trash"])?, json!({})))
274}
275
276fn label_ids(name: &str, list: &Option<Vec<String>>) -> Result<Vec<String>, String> {
277    let ids: Vec<String> = list.iter().flatten().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect();
278    if ids.len() > LABELS {
279        return Err(format!("{name} takes at most {LABELS} label ids"));
280    }
281    for id in &ids {
282        id_arg(name, Some(id)).map_err(|_| format!("\"{}\" isn't a label id; list_labels has them", clip(id, 40)))?;
283    }
284    Ok(ids)
285}
286
287/// The request for `label_thread`. Putting a thread in the trash takes `trash_thread`, which asks
288/// the person, so the trash label is not one this can add.
289pub fn label_plan(args: &GmailArgs) -> Result<GoogleRequest, String> {
290    let thread = id_arg("thread_id", args.thread_id.as_deref())?;
291    let add = label_ids("add_label_ids", &args.add_label_ids)?;
292    let remove = label_ids("remove_label_ids", &args.remove_label_ids)?;
293    if add.is_empty() && remove.is_empty() {
294        return Err("label_thread needs add_label_ids or remove_label_ids (ids from list_labels)".to_string());
295    }
296    if add.iter().any(|l| l == "TRASH") {
297        return Err("a thread goes to the trash with trash_thread, which asks the person first".to_string());
298    }
299    Ok(post(url_of(&["threads", &thread, "modify"])?, json!({ "addLabelIds": add, "removeLabelIds": remove })))
300}
301
302/// A draft as it is stored: what `send_draft` shows the person and checks again before sending.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct DraftView {
305    pub id: String,
306    pub to: String,
307    pub cc: String,
308    pub bcc: String,
309    pub subject: String,
310    pub body: String,
311    /// The HTML version's text, when the draft has one that reads differently from `body`: what most
312    /// recipients' mail programs show.
313    pub html: String,
314    /// The files attached, as `name (size)`.
315    pub attachments: Vec<String>,
316    /// The thread the draft replies into, empty for a mail that starts a new one. Not in the digest:
317    /// the window only says who is in it (see [`super::gmail_thread`]).
318    pub thread_id: String,
319    /// The stored message's id (Gmail makes a new one whenever a draft is saved) and a hash of its
320    /// whole payload without the attachment ids, which are not stable between reads.
321    version: String,
322}
323
324fn normalized(s: &str) -> String {
325    s.split_whitespace().collect::<Vec<_>>().join(" ")
326}
327
328/// The payload without its `attachmentId`s, which Google may change between reads of the same message.
329fn without_attachment_ids(v: &Value) -> Value {
330    match v {
331        Value::Object(m) => Value::Object(m.iter().filter(|(k, _)| k.as_str() != "attachmentId").map(|(k, v)| (k.clone(), without_attachment_ids(v))).collect()),
332        Value::Array(a) => Value::Array(a.iter().map(without_attachment_ids).collect()),
333        other => other.clone(),
334    }
335}
336
337impl DraftView {
338    /// From Google's `drafts.get` answer (format full), with any text it keeps outside the message
339    /// already loaded (see `gmail_flow`).
340    pub fn of(draft: &Value) -> DraftView {
341        let msg = draft.get("message").unwrap_or(&Value::Null);
342        let p = msg.get("payload").unwrap_or(&Value::Null);
343        let h = |name: &str| header(p, name).split_whitespace().collect::<Vec<_>>().join(" ");
344        let body = tidy(&body_text(p));
345        let html = tidy(&html_alternative(p));
346        let html = if html.is_empty() || normalized(&html) == normalized(&body) { String::new() } else { html };
347        let attachments = attachments(p)
348            .iter()
349            .map(|a| format!("{} ({} bytes)", s(a, "/filename"), a.get("size").and_then(Value::as_u64).unwrap_or(0)))
350            .collect();
351        let mut hash = Sha256::new();
352        hash.update(without_attachment_ids(p).to_string().as_bytes());
353        let version = format!("{}:{}", s(msg, "/id"), hash.finalize().iter().map(|b| format!("{b:02x}")).collect::<String>());
354        DraftView { id: s(draft, "/id").to_string(), to: h("To"), cc: h("Cc"), bcc: h("Bcc"), subject: h("Subject"), body, html, attachments, thread_id: s(msg, "/threadId").to_string(), version }
355    }
356
357    /// A fingerprint of everything that would be sent, not only of what the person is shown, so a
358    /// draft changed after they said yes (its other version, a file, anything) is not sent.
359    pub fn digest(&self) -> String {
360        let mut h = Sha256::new();
361        for part in [&self.to, &self.cc, &self.bcc, &self.subject, &self.body, &self.html, &self.attachments.join("\n"), &self.version] {
362            h.update((part.len() as u64).to_le_bytes());
363            h.update(part.as_bytes());
364        }
365        h.finalize().iter().map(|b| format!("{b:02x}")).collect()
366    }
367
368    /// Whether there is anyone to send it to.
369    pub fn has_recipient(&self) -> bool {
370        [&self.to, &self.cc, &self.bcc].iter().any(|r| !r.trim().is_empty())
371    }
372}
373
374/// The title and text of the window that asks the person to send `view`.
375pub fn send_question(agent: &str, account: &str, view: &DraftView) -> (String, String) {
376    send_question_in(agent, account, view, &ThreadNote::default())
377}
378
379/// [`send_question`] for a draft that replies into a thread: the warning first, the thread after
380/// the recipients.
381pub fn send_question_in(agent: &str, account: &str, view: &DraftView, note: &ThreadNote) -> (String, String) {
382    // With an HTML version that reads differently, both are shown, half the room each.
383    let room = if view.html.is_empty() { SHOWN_BODY_CHARS } else { SHOWN_BODY_CHARS / 2 };
384    let field = |name: &str, v: &str| if v.is_empty() { String::new() } else { format!("{name}: {v}\n") };
385    let files = if view.attachments.is_empty() { String::new() } else { format!("Attached: {}\n", view.attachments.join(", ")) };
386    let html = if view.html.is_empty() {
387        String::new()
388    } else {
389        format!("\n\nThis mail also has an HTML version, which most people's mail programs show instead of the text above. It reads:\n\n{}", clip(&view.html, room))
390    };
391    let warning = note.warning.as_ref().map(|w| format!("{w}\n\n")).unwrap_or_default();
392    let thread = note.line.as_ref().map(|l| format!("{l}\n")).unwrap_or_default();
393    let message = format!(
394        "{warning}{agent} wants to send this email from {account}. It can't be taken back once it is sent.\n\n{}{}{}{thread}{files}Subject: {}\n\n{}{html}",
395        field("To", &view.to),
396        field("Cc", &view.cc),
397        field("Bcc", &view.bcc),
398        if view.subject.is_empty() { "(none)" } else { &view.subject },
399        clip(&view.body, room),
400    );
401    (format!("{} wants to send an email", clip(&line(agent, 60), 60)), message)
402}
403
404/// The title and text of the window that asks the person to trash a thread. `summary` is the
405/// thread's headers as [`super::gmail::summary_plan`] asks for them.
406pub fn trash_question(agent: &str, account: &str, summary: &Value) -> (String, String) {
407    let first = summary.get("messages").and_then(Value::as_array).and_then(|m| m.first());
408    let p = first.and_then(|m| m.get("payload")).unwrap_or(&Value::Null);
409    let count = summary.get("messages").and_then(Value::as_array).map_or(0, Vec::len);
410    let message = format!(
411        "{agent} wants to move this email thread in {account} to the trash (Gmail keeps it there for 30 days).\n\nSubject: {}\nFrom: {}\nMessages: {count}",
412        clip(&line(header(p, "Subject"), 200), 200),
413        clip(&line(header(p, "From"), 200), 200),
414    );
415    (format!("{} wants to trash an email", clip(&line(agent, 60), 60)), message)
416}
417
418#[cfg(test)]
419#[path = "gmail_write_tests.rs"]
420mod tests;