Skip to main content

agentmux_srv_core/backend/google/
calls.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! One agent tool call to Google, end to end: whose account and grant
5//! ([`super::access`]), whether the token covers the action, a fresh token
6//! (srv refreshes it; the agent never sees it), the request, the trimmed
7//! answer, and a line in the account's log (D7) however it ends.
8
9use std::sync::Arc;
10
11use chrono::{DateTime, Utc};
12use serde_json::{json, Value};
13
14use crate::backend::storage::google_grants::{GoogleCall, GrantLevel};
15use crate::backend::storage::store::{AgentDefinition, Store};
16use crate::identity::oauth_tokens::{access_token_for, HttpReply, OAuthHttp, TokenSecrets};
17
18use super::access::{access_for, Access};
19use super::calendar::{self, CalendarArgs};
20use super::drive::{self, DriveArgs};
21use super::gmail::{self, GmailArgs};
22use super::{google_error, GoogleHttp, Service};
23
24/// What a call needs from srv.
25pub struct CallDeps<'a, G: GoogleHttp, O: OAuthHttp, S: TokenSecrets> {
26    pub google: &'a G,
27    pub oauth: &'a O,
28    pub secrets: &'a S,
29    pub mstore: &'a Store,
30    pub id_store: &'a Arc<Store>,
31    pub identity_store: &'a Arc<Store>,
32}
33
34/// A `Calendar` read action for agent `def`. The answer names the account
35/// and carries the trimmed result.
36pub async fn calendar_read<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
37    deps: &CallDeps<'_, G, O, S>,
38    def: &AgentDefinition,
39    action: &str,
40    args: &CalendarArgs,
41    account: Option<&str>,
42    now: DateTime<Utc>,
43) -> Result<Value, String> {
44    if !calendar::READ_ACTIONS.contains(&action) {
45        return Err(format!("Calendar has no action \"{action}\"; one of {}", calendar::READ_ACTIONS.join(", ")));
46    }
47    let access = access_for(deps.mstore, deps.id_store, deps.identity_store, def, Service::Calendar, account)?;
48    let ids = calendar::logged_ids(action, args);
49    let result = calendar_read_with(deps, &access, action, args, now).await;
50    let result = still_held(deps, &access, result);
51    log_call(deps, &access, def, Service::Calendar, action, ids, &result, now);
52    result.map(|r| json!({ "account": access.email(), "result": r }))
53}
54
55/// A read that came back after the grant was turned off, or the account disconnected, returns the
56/// sentence saying so instead of Google's content.
57fn still_held<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
58    deps: &CallDeps<'_, G, O, S>,
59    access: &Access,
60    result: Result<Value, String>,
61) -> Result<Value, String> {
62    let kept = result?;
63    access.still_held(deps.id_store, deps.identity_store, GrantLevel::Read)?;
64    Ok(kept)
65}
66
67/// A line in the account's log (D7) for one call, however it ended.
68#[allow(clippy::too_many_arguments)]
69pub fn log_call<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
70    deps: &CallDeps<'_, G, O, S>,
71    access: &Access,
72    def: &AgentDefinition,
73    service: Service,
74    action: &str,
75    ids: String,
76    result: &Result<Value, String>,
77    now: DateTime<Utc>,
78) {
79    let outcome = match result {
80        Ok(_) => "ok".to_string(),
81        Err(e) => format!("error: {}", super::clip(e, 200)),
82    };
83    // An account disconnected while the call ran took its log with it: a line now would outlive it.
84    if !matches!(crate::identity::resolver::resolve_account(deps.id_store, deps.identity_store, &access.account.id), Ok(Some(_))) {
85        return;
86    }
87    let line = GoogleCall {
88        at: now.timestamp_millis(),
89        agent_id: def.id.clone(),
90        agent_name: def.name.clone(),
91        service: service.as_str().to_string(),
92        action: action.to_string(),
93        ids,
94        outcome,
95    };
96    if let Err(e) = deps.identity_store.google_call_log(&access.account.id, &line) {
97        tracing::warn!(target: "google", account_id = %access.account.id, error = %e, "google: couldn't write the call log");
98    }
99}
100
101async fn calendar_read_with<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
102    deps: &CallDeps<'_, G, O, S>,
103    access: &Access,
104    action: &str,
105    args: &CalendarArgs,
106    now: DateTime<Utc>,
107) -> Result<Value, String> {
108    debug_assert!(access.level >= GrantLevel::Read);
109    if !calendar::granted_for(action, &access.granted_scopes()) {
110        return Err(format!(
111            "{} hasn't granted the Calendar permission {action} needs (it was only partly granted). The person can turn Calendar on again for the account in Connectors",
112            access.email()
113        ));
114    }
115    let req = calendar::plan(action, args, now)?;
116    let token = access_token_for(deps.oauth, deps.secrets, deps.id_store, deps.identity_store, &access.account, None).await?;
117    let reply = deps.google.send(&req, &token).await?;
118    if !(200..300).contains(&reply.status) {
119        return Err(google_error(&reply));
120    }
121    Ok(calendar::shape(action, &reply.body))
122}
123
124/// A `Drive` read action for agent `def`. `pick_files` is not one of them (the handler asks
125/// the person); everything else is a request to Google and a trimmed answer.
126pub async fn drive_read<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
127    deps: &CallDeps<'_, G, O, S>,
128    def: &AgentDefinition,
129    action: &str,
130    args: &DriveArgs,
131    account: Option<&str>,
132    now: DateTime<Utc>,
133) -> Result<Value, String> {
134    if !drive::READ_ACTIONS.contains(&action) {
135        return Err(format!("Drive has no action \"{action}\"; one of {}, pick_files", drive::READ_ACTIONS.join(", ")));
136    }
137    let access = access_for(deps.mstore, deps.id_store, deps.identity_store, def, Service::Drive, account)?;
138    let ids = drive::logged_ids(action, args);
139    let result = drive_read_with(deps, &access, action, args).await;
140    let result = still_held(deps, &access, result);
141    log_call(deps, &access, def, Service::Drive, action, ids, &result, now);
142    result.map(|r| json!({ "account": access.email(), "result": r }))
143}
144
145async fn drive_read_with<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
146    deps: &CallDeps<'_, G, O, S>,
147    access: &Access,
148    action: &str,
149    args: &DriveArgs,
150) -> Result<Value, String> {
151    debug_assert!(access.level >= GrantLevel::Read);
152    if !drive::granted_for(action, &access.granted_scopes()) {
153        return Err(format!(
154            "{} hasn't granted the Drive permission {action} needs. The person can turn Drive on again for the account in Connectors",
155            access.email()
156        ));
157    }
158    let req = drive::plan(action, args)?;
159    let token = access_token_for(deps.oauth, deps.secrets, deps.id_store, deps.identity_store, &access.account, None).await?;
160    let reply = deps.google.send(&req, &token).await?;
161    if !(200..300).contains(&reply.status) {
162        return Err(drive_error(&reply, action));
163    }
164    if action != "read_file_content" {
165        return Ok(drive::shape(action, &reply.body));
166    }
167    let meta = reply.body;
168    let content_req = drive::content_plan(&meta)?;
169    let content = deps.google.send(&content_req, &token).await?;
170    if !(200..300).contains(&content.status) {
171        return Err(drive_error(&content, action));
172    }
173    Ok(drive::shape_content(&meta, &content.body))
174}
175
176/// A `Gmail` read action for agent `def`.
177pub async fn gmail_read<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
178    deps: &CallDeps<'_, G, O, S>,
179    def: &AgentDefinition,
180    action: &str,
181    args: &GmailArgs,
182    account: Option<&str>,
183    now: DateTime<Utc>,
184) -> Result<Value, String> {
185    if !gmail::READ_ACTIONS.contains(&action) {
186        return Err(format!("Gmail has no action \"{action}\"; one of {}", gmail::READ_ACTIONS.join(", ")));
187    }
188    let access = access_for(deps.mstore, deps.id_store, deps.identity_store, def, Service::Gmail, account)?;
189    let ids = gmail::logged_ids(action, args);
190    let result = gmail_read_with(deps, &access, action, args).await;
191    let result = still_held(deps, &access, result);
192    log_call(deps, &access, def, Service::Gmail, action, ids, &result, now);
193    result.map(|r| json!({ "account": access.email(), "result": r }))
194}
195
196async fn gmail_read_with<G: GoogleHttp, O: OAuthHttp, S: TokenSecrets>(
197    deps: &CallDeps<'_, G, O, S>,
198    access: &Access,
199    action: &str,
200    args: &GmailArgs,
201) -> Result<Value, String> {
202    debug_assert!(access.level >= GrantLevel::Read);
203    if !gmail::granted_for(action, &access.granted_scopes()) {
204        return Err(format!(
205            "{} hasn't granted the Gmail permission {action} needs. The person can turn Gmail on again for the account in Connectors",
206            access.email()
207        ));
208    }
209    let req = gmail::plan(action, args)?;
210    let token = access_token_for(deps.oauth, deps.secrets, deps.id_store, deps.identity_store, &access.account, None).await?;
211    let reply = deps.google.send(&req, &token).await?;
212    if !(200..300).contains(&reply.status) {
213        return Err(gmail_error(&reply));
214    }
215    if action == "get_thread" {
216        // A long mail's text can be stored outside the message: fetch those parts (not files) first.
217        let mut thread = reply.body;
218        load_external_text(deps.google, &token, &mut thread).await;
219        return Ok(gmail::shape_thread(&thread, gmail::raw_headers_arg(args)?));
220    }
221    if action != "search_threads" {
222        return Ok(gmail::shape(action, &reply.body));
223    }
224    // Google's search lists ids and snippets; the first few threads get their headers, one
225    // request each. A thread whose headers can't be had is listed without them.
226    let mut summaries = Vec::new();
227    let threads = reply.body.get("threads").and_then(Value::as_array).cloned().unwrap_or_default();
228    for t in threads.iter().take(gmail::SUMMARIZED) {
229        let id = t.get("id").and_then(Value::as_str).unwrap_or("");
230        let one = match gmail::summary_plan(id) {
231            Ok(r) => deps.google.send(&r, &token).await.ok().filter(|r| (200..300).contains(&r.status)).map(|r| r.body),
232            Err(_) => None,
233        };
234        summaries.push(one.unwrap_or(Value::Null));
235    }
236    Ok(gmail::shape_search(&reply.body, &summaries))
237}
238
239/// Fetch the text parts `thread` (`{ messages: [..] }`) keeps outside its messages and put them in,
240/// as far as Google gives them. Files are never fetched.
241pub(super) async fn load_external_text<G: GoogleHttp>(google: &G, token: &str, thread: &mut Value) {
242    let mut parts = std::collections::HashMap::new();
243    for (mid, aid) in gmail::external_text_parts(thread) {
244        let Ok(r) = gmail::part_plan(&mid, &aid) else { continue };
245        let Some(body) = google.send(&r, token).await.ok().filter(|r| (200..300).contains(&r.status)).map(|r| r.body) else { continue };
246        match body.get("data").and_then(Value::as_str) {
247            Some(d) if d.len() <= gmail::EXTERNAL_PART_CHARS => {
248                parts.insert(aid, d.to_string());
249            }
250            _ => {}
251        }
252    }
253    gmail::fill_external(thread, &parts);
254}
255
256/// Google's refusal of a Gmail call. A 404 is a thread that isn't there.
257fn gmail_error(reply: &HttpReply) -> String {
258    match reply.status {
259        404 => "Google found no such thread for this account (the id may be from another account, or the thread was deleted)".to_string(),
260        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")) => {
261            "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()
262        }
263        _ => google_error(reply),
264    }
265}
266
267/// Google's refusal of a Drive call. A 404 on `drive.file` is usually a file the person
268/// hasn't picked, which the generic sentence doesn't say.
269fn drive_error(reply: &HttpReply, action: &str) -> String {
270    if reply.status == 404 && action != "search_files" {
271        return "Google found no such file for this account. With the permission AgentMux asks for, an agent reaches only the files the person picked (Drive pick_files asks them) and the ones AgentMux made".to_string();
272    }
273    google_error(reply)
274}
275
276#[cfg(test)]
277#[path = "calls_tests.rs"]
278mod tests;