1use 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
24pub 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
34pub 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
55fn 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#[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 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
124pub 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
176pub 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 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 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
239pub(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
256fn 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
267fn 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;