Skip to main content

agentmux_srv_core/backend/google/
gmail_flow.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! One `Gmail` write call end to end (G3): whose account and whether the agent may write
5//! ([`super::access`]), whether the token covers the action, the person's yes for what can't be taken
6//! back (`send_draft`, `trash_thread`: SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md §6),
7//! the call, and a line in the account's log however it ends.
8//!
9//! The yes comes from [`Approver`], which in srv is the host's approval window: a window an agent
10//! can neither click nor forge. A send is checked twice: the draft is read and shown, and read
11//! again after the yes, and a draft that changed in between is not sent.
12
13use std::future::Future;
14
15use chrono::{DateTime, Utc};
16use serde_json::{json, Value};
17
18use crate::backend::storage::google_grants::{CallsCounted, GrantLevel};
19use crate::backend::storage::store::AgentDefinition;
20use crate::identity::oauth_tokens::{access_token_for, HttpReply, OAuthHttp, TokenSecrets};
21
22use super::access::{access_for, Access};
23use super::calls::{load_external_text, log_call, CallDeps};
24use super::gmail::{self, GmailArgs};
25use super::gmail_thread::{self as thread, ThreadNote};
26use super::gmail_write::{self as write, DraftView};
27use super::{google_error, GoogleHttp, Service};
28
29/// What the person answered.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Answer {
32    Yes,
33    No,
34    /// The window closed, timed out or could not be opened.
35    Unanswered,
36}
37
38/// Asks the person a yes or no about what `def` wants to do.
39pub trait Approver: Sync {
40    fn ask(&self, def: &AgentDefinition, title: String, message: String, yes: &str, no: &str) -> impl Future<Output = Result<Answer, String>> + Send;
41}
42
43/// What a failure after the person's yes begins with. The log's hourly count of questions
44/// (`CallsCounted::Asked`) takes the lines that begin `error: the person `, so it takes these.
45const ANSWERED_YES: &str = "the person said yes, but ";
46
47/// Sends an agent can complete in a day, and questions it can put in an hour: a backstop in case a
48/// tricked agent asks over and over (§6).
49const SENDS_PER_DAY: usize = 20;
50const ASKS_PER_HOUR: usize = 10;
51
52/// A `Gmail` write action for agent `def`.
53pub async fn gmail_write<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets, A: Approver>(
54    deps: &CallDeps<'_, G, O, S>,
55    approver: &A,
56    def: &AgentDefinition,
57    action: &str,
58    args: &GmailArgs,
59    account: Option<&str>,
60    now: DateTime<Utc>,
61) -> Result<Value, String> {
62    if !write::WRITE_ACTIONS.contains(&action) {
63        return Err(format!("Gmail has no write action \"{action}\"; one of {}", write::WRITE_ACTIONS.join(", ")));
64    }
65    let access = access_for(deps.mstore, deps.id_store, deps.identity_store, def, Service::Gmail, account)?;
66    let ids = logged_ids(action, args);
67    // A call that puts a question to the person takes its place among the questions in flight here,
68    // and keeps it until its line is in the log: until then it is in neither count.
69    let asking = if write::always_asks(action) { reserve(deps, &access, def, now, action == "send_draft") } else { Ok(Asking(None)) };
70    let result = match &asking {
71        Ok(_) => write_with(deps, approver, &access, def, action, args, now).await,
72        Err(e) => Err(e.clone()),
73    };
74    log_call(deps, &access, def, Service::Gmail, action, ids, &result, now);
75    drop(asking);
76    result.map(|r| json!({ "account": access.email(), "result": r }))
77}
78
79/// The ids a write touched, for the account's log (D7): never the mail.
80fn logged_ids(action: &str, args: &GmailArgs) -> String {
81    let t = |v: &Option<String>| v.as_deref().map(str::trim).unwrap_or("").to_string();
82    match action {
83        "label_thread" | "trash_thread" => t(&args.thread_id),
84        _ => t(&args.draft_id),
85    }
86}
87
88async fn write_with<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets, A: Approver>(
89    deps: &CallDeps<'_, G, O, S>,
90    approver: &A,
91    access: &Access,
92    def: &AgentDefinition,
93    action: &str,
94    args: &GmailArgs,
95    now: DateTime<Utc>,
96) -> Result<Value, String> {
97    if access.level < GrantLevel::Write {
98        return Err(format!(
99            "{} lets you read Gmail but not write it. The person can allow drafts, labels and sending for you in Connectors > Accounts > {} > Gmail",
100            access.email(),
101            access.email()
102        ));
103    }
104    if !write::granted_for(action, &access.granted_scopes()) {
105        return Err(format!(
106            "{} hasn't granted the Gmail permission {action} needs. The person can turn Gmail writes on again for the account in Connectors",
107            access.email()
108        ));
109    }
110    // Plans are built before anything is asked or sent, so a bad argument costs the person nothing.
111    match action {
112        "create_draft" | "update_draft" => {
113            // A reply needs the thread's last message for its threading headers (Gmail threads by
114            // them, the subject and the thread id together).
115            let thread = args.thread_id.as_deref().map(str::trim).filter(|t| !t.is_empty());
116            let reply = match thread {
117                Some(t) => {
118                    let headers = send(deps, access, &write::reply_fetch_plan(t)?).await?.body;
119                    Some(write::reply_of(&headers).ok_or("that thread's last message has no Message-ID to reply to")?)
120                }
121                None => None,
122            };
123            let req = write::draft_plan(action, args, reply.as_ref())?;
124            let reply = send(deps, access, &req).await?;
125            Ok(shape_draft(&reply.body))
126        }
127        "label_thread" => {
128            let req = write::label_plan(args)?;
129            let reply = send(deps, access, &req).await?;
130            Ok(json!({ "thread_id": reply.body.get("id").and_then(Value::as_str).unwrap_or(""), "done": true }))
131        }
132        "send_draft" => send_draft(deps, approver, access, def, args, now).await,
133        "trash_thread" => trash_thread(deps, approver, access, def, args, now).await,
134        _ => unreachable!("checked against WRITE_ACTIONS"),
135    }
136}
137
138/// One request to Google with the account's token (refreshed in srv); a refusal is a sentence.
139async fn send<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
140    deps: &CallDeps<'_, G, O, S>,
141    access: &Access,
142    req: &super::GoogleRequest,
143) -> Result<HttpReply, String> {
144    // Asked just before each request: a grant turned off while the person was deciding stops a send.
145    access.still_held(deps.id_store, deps.identity_store, GrantLevel::Write)?;
146    let token = access_token_for(deps.oauth, deps.secrets, deps.id_store, deps.identity_store, &access.account, None).await?;
147    let reply = deps.google.send(req, &token).await?;
148    if (200..300).contains(&reply.status) {
149        Ok(reply)
150    } else {
151        Err(error_of(&reply))
152    }
153}
154
155fn error_of(reply: &HttpReply) -> String {
156    match reply.status {
157        404 => "Google found no such draft or thread for this account (the id may be from another account, or it was deleted)".to_string(),
158        403 if reply.body.pointer("/error/message").and_then(Value::as_str).is_some_and(|m| m.contains("has not been used") || m.contains("is disabled")) => {
159            "the Gmail API isn't turned on in the Google Cloud project of this account's OAuth client: the person can enable it in the Google Cloud console (APIs & Services)".to_string()
160        }
161        _ => google_error(reply),
162    }
163}
164
165fn shape_draft(body: &Value) -> Value {
166    json!({
167        "draft_id": body.get("id").and_then(Value::as_str).unwrap_or(""),
168        "thread_id": body.pointer("/message/threadId").and_then(Value::as_str).unwrap_or(""),
169        "note": "The draft is in the person's Gmail Drafts. Sending it is send_draft, which asks the person first.",
170    })
171}
172
173/// Questions in flight, per account and agent: a call is logged only when it ends, so calls made at
174/// once would all pass the limits before any was counted.
175fn in_flight() -> std::sync::MutexGuard<'static, std::collections::HashMap<(usize, String, String), usize>> {
176    use std::sync::{Mutex, OnceLock};
177    static PENDING: OnceLock<Mutex<std::collections::HashMap<(usize, String, String), usize>>> = OnceLock::new();
178    PENDING.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
179}
180
181/// A question counted while it is being asked.
182struct Asking(Option<(usize, String, String)>);
183
184impl Drop for Asking {
185    fn drop(&mut self) {
186        if let Some(key) = self.0.take() {
187            let mut m = in_flight();
188            if let Some(n) = m.get_mut(&key) {
189                *n = n.saturating_sub(1);
190                if *n == 0 {
191                    m.remove(&key);
192                }
193            }
194        }
195    }
196}
197
198/// Take the limits' check and, if it passes, a place among the questions in flight until the
199/// returned guard is dropped. `send` is whether the call is a `send_draft`. The logged questions of
200/// the last hour and mails sent in the last day come from the store, for this agent and this
201/// account only. The counts are read with the in-flight table locked, and a call leaves the table
202/// only after its line is logged, so a call that ends meanwhile is in one count or the other.
203fn reserve(deps: &CallDeps<'_, impl GoogleHttp, impl OAuthHttp, impl TokenSecrets>, access: &Access, def: &AgentDefinition, now: DateTime<Utc>, send: bool) -> Result<Asking, String> {
204    let ms = now.timestamp_millis();
205    // Per store as well as account and agent: one store in srv, one per test.
206    let key = (std::sync::Arc::as_ptr(deps.identity_store) as usize, access.account.id.clone(), def.id.clone());
207    let mut pending = in_flight();
208    let count = |actions: &[&str], since: i64, which: CallsCounted| {
209        deps.identity_store.google_calls_count(&access.account.id, &def.id, "gmail", actions, since, which).map_err(|e| format!("store: {e}"))
210    };
211    let asked = count(&["send_draft", "trash_thread"], ms - 3_600_000, CallsCounted::Asked)?;
212    let sent = if send { count(&["send_draft"], ms - 86_400_000, CallsCounted::Ok)? } else { 0 };
213    let waiting = pending.get(&key).copied().unwrap_or(0);
214    if send && sent + waiting >= SENDS_PER_DAY {
215        return Err(format!("you have sent {SENDS_PER_DAY} mails from this account today, the most an agent may: wait until tomorrow"));
216    }
217    if asked + waiting >= ASKS_PER_HOUR {
218        return Err(format!("you have asked the person {ASKS_PER_HOUR} times in the last hour to send or trash mail: wait before asking again"));
219    }
220    *pending.entry(key.clone()).or_insert(0) += 1;
221    Ok(Asking(Some(key)))
222}
223
224async fn ask<A: Approver>(approver: &A, def: &AgentDefinition, (title, message): (String, String), yes: &str, no: &str, what: &str, if_no: &str) -> Result<(), String> {
225    match approver.ask(def, title, message, yes, no).await? {
226        Answer::Yes => Ok(()),
227        Answer::No => Err(format!("the person said no, so {what} was not done{if_no}")),
228        Answer::Unanswered => Err(format!("the person didn't answer, so {what} was not done. Don't ask again straight away; tell them in your reply what you wanted to do")),
229    }
230}
231
232async fn send_draft<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets, A: Approver>(
233    deps: &CallDeps<'_, G, O, S>,
234    approver: &A,
235    access: &Access,
236    def: &AgentDefinition,
237    args: &GmailArgs,
238    now: DateTime<Utc>,
239) -> Result<Value, String> {
240    let fetch = write::draft_fetch_plan(args)?;
241    let view = read_draft(deps, access, &fetch).await?;
242    if !view.has_recipient() {
243        return Err("the draft has no recipient: update_draft it with to first".to_string());
244    }
245    let note = thread_note(deps, access, &view).await;
246    let question = write::send_question_in(&def.name, &access.email(), &view, &note);
247    // A no repeats the warning, so the agent learns why the person may have said it.
248    let if_no = if note.strangers { format!(". {} Check the recipients and the thread_id.", thread::NO_PARTICIPANT) } else { String::new() };
249    ask(approver, def, question, "Send", "Don't send", "sending", &if_no).await?;
250    // What the person said yes to is what goes: read the draft again and compare. A window was shown,
251    // so whatever ends the call from here is logged as an answered question (it counts toward the
252    // hourly limit, as a no does).
253    let after_yes = async {
254        // The raw message is read between two identical reads of the draft, so it is the message the
255        // person saw (a save makes a new version id), and it is what is sent, not the draft's id.
256        let raw = send(deps, access, &write::draft_raw_plan(args)?).await?.body;
257        let snapshot = raw.pointer("/message/raw").and_then(Value::as_str).filter(|r| !r.is_empty()).ok_or("Gmail did not return the draft's message, so it was not sent")?;
258        let again = read_draft(deps, access, &fetch).await?;
259        if again.digest() != view.digest() {
260            return Err("the draft changed after the person approved it, so it was not sent. Call send_draft again to ask about the new text".to_string());
261        }
262        let reply = send(deps, access, &write::send_plan(&view.id, snapshot, raw.pointer("/message/threadId").and_then(Value::as_str))?).await?;
263        Ok(json!({
264            "sent": true,
265            "message_id": reply.body.get("id").and_then(Value::as_str).unwrap_or(""),
266            "thread_id": reply.body.get("threadId").and_then(Value::as_str).unwrap_or(""),
267        }))
268    };
269    after_yes.await.map_err(|e: String| format!("{ANSWERED_YES}{e}"))
270}
271
272/// What the window says about the thread a draft replies into: one metadata read of the thread. A
273/// thread that can't be read does not stop the send; the person is told it was not checked.
274async fn thread_note<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(deps: &CallDeps<'_, G, O, S>, access: &Access, view: &DraftView) -> ThreadNote {
275    if view.thread_id.is_empty() {
276        return ThreadNote::default();
277    }
278    let read = async { send(deps, access, &thread::context_plan(&view.thread_id)?).await.map(|r| thread::context_of(&r.body)) };
279    match read.await {
280        Ok(ctx) => ThreadNote::of(view, &ctx, &access.email()),
281        Err(_) => ThreadNote::unchecked(),
282    }
283}
284
285/// The draft as it is stored now, whole: text Gmail keeps outside the message is loaded first, and a
286/// draft whose text can't be loaded is not one the person can be shown, so it is refused.
287async fn read_draft<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
288    deps: &CallDeps<'_, G, O, S>,
289    access: &Access,
290    fetch: &super::GoogleRequest,
291) -> Result<DraftView, String> {
292    let mut draft = send(deps, access, fetch).await?.body;
293    let mut thread = json!({ "messages": [draft.get("message").cloned().unwrap_or(Value::Null)] });
294    let token = access_token_for(deps.oauth, deps.secrets, deps.id_store, deps.identity_store, &access.account, None).await?;
295    load_external_text(deps.google, &token, &mut thread).await;
296    draft["message"] = thread["messages"][0].clone();
297    if gmail::has_unloaded_text(draft.pointer("/message/payload").unwrap_or(&Value::Null)) {
298        return Err("part of this draft's text is too large to show the person, so it was not sent: send a shorter mail".to_string());
299    }
300    Ok(DraftView::of(&draft))
301}
302
303async fn trash_thread<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets, A: Approver>(
304    deps: &CallDeps<'_, G, O, S>,
305    approver: &A,
306    access: &Access,
307    def: &AgentDefinition,
308    args: &GmailArgs,
309    now: DateTime<Utc>,
310) -> Result<Value, String> {
311    let trash = write::trash_plan(args)?;
312    let summary = gmail::summary_plan(args.thread_id.as_deref().unwrap_or(""))?;
313    let headers = send(deps, access, &summary).await?.body;
314    let question = write::trash_question(&def.name, &access.email(), &headers);
315    ask(approver, def, question, "Move to trash", "Keep it", "trashing", "").await?;
316    let reply = send(deps, access, &trash).await.map_err(|e| format!("{ANSWERED_YES}{e}"))?;
317    Ok(json!({ "thread_id": reply.body.get("id").and_then(Value::as_str).unwrap_or(""), "trashed": true }))
318}
319
320#[cfg(test)]
321#[path = "gmail_flow_tests.rs"]
322mod tests;