Skip to main content

agentmux_srv_core/backend/google/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Google connectors: srv calls Google for an agent, with the account's
5//! token, which no agent ever holds
6//! (docs/specs/SPEC_GOOGLE_CONNECTORS_GMAIL_CALENDAR_DRIVE_2026_10_14.md D2).
7//!
8//! - [`Service`]: each service's scopes, by grant level (§3.2).
9//! - [`GoogleHttp`]: Google's REST APIs, behind a trait so tests stub them.
10//! - [`calendar`], [`drive`], [`gmail`]: the `Calendar`, `Drive` and `Gmail` tools' actions, as
11//!   requests and trimmed answers.
12
13use std::future::Future;
14
15use serde_json::Value;
16
17use crate::backend::storage::google_grants::GrantLevel;
18use crate::identity::oauth_tokens::HttpReply;
19
20pub mod access;
21pub mod calendar;
22pub mod calls;
23pub mod drive;
24pub mod gmail;
25pub mod gmail_flow;
26pub mod gmail_sender;
27pub mod gmail_thread;
28pub mod gmail_write;
29
30const SCOPE_PREFIX: &str = "https://www.googleapis.com/auth/";
31
32/// A Google service an account can be used for.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Service {
35    Calendar,
36    Drive,
37    Gmail,
38}
39
40impl Service {
41    pub fn as_str(self) -> &'static str {
42        match self {
43            Service::Calendar => "calendar",
44            Service::Drive => "drive",
45            Service::Gmail => "gmail",
46        }
47    }
48
49    /// The scopes a level needs, as Google names them.
50    pub fn scopes(self, level: GrantLevel) -> Vec<String> {
51        let names: &[&str] = match (self, level) {
52            (Service::Calendar, GrantLevel::Read) => {
53                &["calendar.calendarlist.readonly", "calendar.events.readonly", "calendar.events.freebusy"]
54            }
55            (Service::Calendar, GrantLevel::Write) => &[
56                "calendar.calendarlist.readonly",
57                "calendar.events.readonly",
58                "calendar.events.freebusy",
59                "calendar.events",
60            ],
61            // `drive.file` is the one non-sensitive Drive scope: the files the person picked
62            // and the ones AgentMux made. Reading and writing them is the same scope.
63            (Service::Drive, _) => &["drive.file"],
64            // Reading mail is `gmail.readonly`, a restricted scope: only a client the person brought
65            // (their own, or their organization's internal one) is offered it (spec G3).
66            (Service::Gmail, GrantLevel::Read) => &["gmail.readonly"],
67            // Writing adds drafts and sending (`gmail.compose`) and labels and trash (`gmail.modify`),
68            // asked for only when the person turns Gmail writes on.
69            (Service::Gmail, GrantLevel::Write) => &["gmail.readonly", "gmail.compose", "gmail.modify"],
70        };
71        names.iter().map(|n| format!("{SCOPE_PREFIX}{n}")).collect()
72    }
73}
74
75/// One request to a Google REST API.
76#[derive(Debug, Clone, PartialEq)]
77pub struct GoogleRequest {
78    pub method: reqwest::Method,
79    pub url: String,
80    pub query: Vec<(&'static str, String)>,
81    pub body: Option<Value>,
82    /// Read the answer as text (an export or a file's bytes), at most [`TEXT_CAP`] bytes of
83    /// it, instead of as JSON. It comes back as `{ "text", "truncated" }`.
84    pub text: bool,
85}
86
87/// The most bytes of a file `read_file_content` takes from Google.
88pub const TEXT_CAP: usize = 200_000;
89
90/// Google's REST APIs.
91pub trait GoogleHttp: Sync {
92    fn send(&self, req: &GoogleRequest, token: &str) -> impl Future<Output = Result<HttpReply, String>> + Send;
93}
94
95/// [`GoogleHttp`] over the network.
96pub struct LiveGoogleHttp;
97
98impl GoogleHttp for LiveGoogleHttp {
99    async fn send(&self, req: &GoogleRequest, token: &str) -> Result<HttpReply, String> {
100        let mut b = crate::identity::oauth_client::http()
101            .request(req.method.clone(), &req.url)
102            .bearer_auth(token)
103            .header("Accept", if req.text { "*/*" } else { "application/json" })
104            .query(&req.query);
105        if let Some(body) = &req.body {
106            b = b.json(body);
107        }
108        let mut resp = b.send().await.map_err(|e| format!("request failed: {}", e.without_url()))?;
109        let status = resp.status().as_u16();
110        if req.text && (200..300).contains(&status) {
111            let mut buf: Vec<u8> = Vec::new();
112            let mut truncated = false;
113            while let Some(chunk) = resp.chunk().await.map_err(|e| format!("request failed: {}", e.without_url()))? {
114                let room = TEXT_CAP - buf.len();
115                if chunk.len() > room {
116                    buf.extend_from_slice(&chunk[..room]);
117                    truncated = true;
118                    break;
119                }
120                buf.extend_from_slice(&chunk);
121            }
122            let text = String::from_utf8_lossy(&buf).into_owned();
123            return Ok(HttpReply { status, body: serde_json::json!({ "text": text, "truncated": truncated }) });
124        }
125        let body = resp.json().await.unwrap_or_else(|_| serde_json::json!({}));
126        Ok(HttpReply { status, body })
127    }
128}
129
130/// Google's own message for a failed call, in one sentence for the agent.
131pub fn google_error(reply: &HttpReply) -> String {
132    let msg = reply.body.pointer("/error/message").and_then(Value::as_str).unwrap_or("").trim();
133    let reason = reply.body.pointer("/error/errors/0/reason").and_then(Value::as_str).unwrap_or("");
134    match (reply.status, msg.is_empty()) {
135        (401, _) => "Google refused the account's token; reconnect it in Connectors".to_string(),
136        (403, _) if reason.contains("insufficient") || msg.contains("insufficient") => {
137            "the account hasn't granted the permission this needs; turn the service on again in Connectors".to_string()
138        }
139        (404, _) => "Google found no such calendar, event or file (or the account can't see it)".to_string(),
140        (429, _) => "Google is rate-limiting this account; try again in a minute".to_string(),
141        (s, false) => format!("Google answered HTTP {s}: {}", msg.chars().take(300).collect::<String>()),
142        (s, true) => format!("Google answered HTTP {s}"),
143    }
144}
145
146/// `s` cut to `max` characters, with an ellipsis when cut.
147pub(crate) fn clip(s: &str, max: usize) -> String {
148    if s.chars().count() <= max {
149        return s.to_string();
150    }
151    let mut out: String = s.chars().take(max).collect();
152    out.push('…');
153    out
154}
155
156#[cfg(test)]
157mod tests;