Skip to main content

fauna_api/cicada/
inboxes.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use super::contacts::post as send;
6use crate::authentification::{Credentials, CredentialsOrApiKey};
7use crate::error::Result;
8use crate::integrations::Platform;
9use crate::parrot::generative::{Text, Voice};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct InboxGroup {
13    pub id: String,
14    pub name: String,
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub icon: Option<String>,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "camelCase")]
21pub struct Inbox {
22    pub id: String,
23    pub name: String,
24    pub created_at: DateTime<Utc>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub group: Option<InboxGroup>,
27    /// An agent is on for this inbox.
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub agent: Option<bool>,
30}
31
32fn text(value: &Value, fallback: &str) -> String {
33    match value {
34        Value::Null => fallback.to_string(),
35        Value::String(text) => text.clone(),
36        value => value.to_string(),
37    }
38}
39
40fn truthy(value: &Value) -> bool {
41    match value {
42        Value::Null => false,
43        Value::Bool(value) => *value,
44        Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
45        Value::String(text) => !text.is_empty(),
46        _ => true,
47    }
48}
49
50impl Inbox {
51    fn from_json(raw: &Value) -> Inbox {
52        let group = &raw["group"];
53        Inbox {
54            id: text(&raw["id"], "undefined"),
55            name: raw["name"].as_str().unwrap_or_default().to_string(),
56            created_at: crate::tickets::parse_date(&raw["createdAt"]).unwrap_or_default(),
57            group: group.is_object().then(|| InboxGroup {
58                id: text(&group["id"], "undefined"),
59                name: text(&group["name"], ""),
60                icon: truthy(&group["icon"]).then(|| text(&group["icon"], "")),
61            }),
62            agent: truthy(&raw["agent"]).then_some(true),
63        }
64    }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase")]
69pub struct InboxAccount {
70    pub platform: Platform,
71    pub account_id: String,
72}
73
74async fn post(
75    authorization: &CredentialsOrApiKey,
76    path: &str,
77    body: Value,
78) -> Result<reqwest::Response> {
79    send(authorization, path, Some(body)).await
80}
81
82fn inboxes(json: &Value) -> Vec<Inbox> {
83    json.as_array()
84        .into_iter()
85        .flatten()
86        .map(Inbox::from_json)
87        .collect()
88}
89
90pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Inbox>> {
91    let json: Value = post(authorization, "/cicada/inboxes", json!({}))
92        .await?
93        .json()
94        .await?;
95    Ok(inboxes(&json))
96}
97
98pub async fn create(authorization: &CredentialsOrApiKey, name: &str) -> Result<Inbox> {
99    let json: Value = post(
100        authorization,
101        "/cicada/inboxes/create",
102        json!({ "name": name }),
103    )
104    .await?
105    .json()
106    .await?;
107    Ok(Inbox::from_json(&json))
108}
109
110pub async fn rename(
111    authorization: &CredentialsOrApiKey,
112    inbox_id: &str,
113    name: &str,
114) -> Result<Inbox> {
115    let json: Value = post(
116        authorization,
117        "/cicada/inboxes/rename",
118        json!({ "inbox": inbox_id, "name": name }),
119    )
120    .await?
121    .json()
122    .await?;
123    Ok(Inbox::from_json(&json))
124}
125
126pub async fn remove(authorization: &CredentialsOrApiKey, inbox_id: &str) -> Result<()> {
127    post(
128        authorization,
129        "/cicada/inboxes/delete",
130        json!({ "inbox": inbox_id }),
131    )
132    .await?;
133    Ok(())
134}
135
136pub async fn move_to_group(
137    authorization: &CredentialsOrApiKey,
138    inbox_id: &str,
139    group_id: &str,
140) -> Result<Inbox> {
141    let json: Value = post(
142        authorization,
143        "/cicada/inboxes/move",
144        json!({ "inbox": inbox_id, "group": group_id }),
145    )
146    .await?
147    .json()
148    .await?;
149    Ok(Inbox::from_json(&json))
150}
151
152pub async fn assign(
153    authorization: &CredentialsOrApiKey,
154    inbox_id: &str,
155    account: &InboxAccount,
156) -> Result<()> {
157    post(
158        authorization,
159        "/cicada/inboxes/accounts",
160        json!({ "inbox": inbox_id, "platform": account.platform, "accountId": account.account_id }),
161    )
162    .await?;
163    Ok(())
164}
165
166pub async fn list_accounts(
167    authorization: &CredentialsOrApiKey,
168    inbox_id: &str,
169) -> Result<Vec<InboxAccount>> {
170    Ok(post(
171        authorization,
172        "/cicada/inboxes/accounts/list",
173        json!({ "inbox": inbox_id }),
174    )
175    .await?
176    .json()
177    .await?)
178}
179
180/// Each inbox has at most one agent, with its own model and "System prompt"
181/// (`instructions`). It answers the inbox's new messages and reaches people
182/// from the inbox's own accounts. `daily_limit` and `spent_today` are dollars per
183/// UTC day; at the limit the agent pauses until midnight UTC. `reasoning` is one
184/// of the text model's catalog tiers, empty for its default; `voice_model` is the
185/// realtime voice the agent talks with on calls, None for the catalog's first.
186#[derive(Debug, Clone, PartialEq, Serialize)]
187#[serde(rename_all = "camelCase")]
188pub struct AgentSettings {
189    pub model: Text,
190    pub reasoning: String,
191    pub voice_model: Option<Voice>,
192    pub instructions: String,
193    pub daily_limit: f64,
194    pub spent_today: f64,
195    pub enabled_at: DateTime<Utc>,
196}
197
198impl AgentSettings {
199    pub fn from_json(json: &Value) -> AgentSettings {
200        AgentSettings {
201            model: serde_json::from_value(json["model"].clone()).unwrap_or(Text::Auto),
202            reasoning: text(&json["reasoning"], ""),
203            voice_model: serde_json::from_value(json["voiceModel"].clone()).ok(),
204            instructions: text(&json["instructions"], ""),
205            daily_limit: json["dailyLimit"].as_f64().unwrap_or_default(),
206            spent_today: json["spentToday"].as_f64().unwrap_or_default(),
207            enabled_at: crate::tickets::parse_date(&json["enabledAt"]).unwrap_or_default(),
208        }
209    }
210}
211
212pub async fn get_agent(
213    authorization: &CredentialsOrApiKey,
214    inbox: &str,
215) -> Result<Option<AgentSettings>> {
216    let text = post(
217        authorization,
218        "/cicada/inboxes/agent",
219        json!({ "inbox": inbox }),
220    )
221    .await?
222    .text()
223    .await?;
224    if text.trim().is_empty() {
225        return Ok(None);
226    }
227    Ok(Some(AgentSettings::from_json(&serde_json::from_str(
228        &text,
229    )?)))
230}
231
232/// The `settings` argument of `set_agent`.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234#[serde(rename_all = "camelCase")]
235pub struct AgentDraft {
236    pub model: Text,
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub reasoning: Option<String>,
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub voice_model: Option<Voice>,
241    pub instructions: String,
242    pub daily_limit: f64,
243}
244
245/// Turns the agent on (it answers messages sent from now on) or updates it.
246pub async fn set_agent(
247    authorization: &CredentialsOrApiKey,
248    inbox: &str,
249    settings: &AgentDraft,
250) -> Result<AgentSettings> {
251    let mut body = Map::new();
252    body.insert("inbox".to_string(), Value::from(inbox));
253    if let Value::Object(fields) = serde_json::to_value(settings)? {
254        body.extend(fields);
255    }
256    let json: Value = post(
257        authorization,
258        "/cicada/inboxes/agent/set",
259        Value::Object(body),
260    )
261    .await?
262    .json()
263    .await?;
264    Ok(AgentSettings::from_json(&json))
265}
266
267pub async fn clear_agent(authorization: &CredentialsOrApiKey, inbox: &str) -> Result<()> {
268    post(
269        authorization,
270        "/cicada/inboxes/agent/clear",
271        json!({ "inbox": inbox }),
272    )
273    .await?;
274    Ok(())
275}
276
277/// The `call` argument of `agent_call`.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279pub struct AgentCallRequest {
280    pub to: String,
281    pub directions: String,
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub from: Option<String>,
284}
285
286/// `{ calling, from, callId }` in the TypeScript SDK.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase")]
289pub struct PlacedCall {
290    pub calling: String,
291    pub from: String,
292    pub call_id: String,
293}
294
295/// Has the inbox's agent phone `to` from one of the inbox's lines (`from`, or its first)
296/// and follow `directions`. Returns once the call is placed; the transcript lands on the
297/// thread with that number. Owners only; counts toward the agent's daily limit.
298pub async fn agent_call(
299    authorization: &Credentials,
300    inbox: &str,
301    call: &AgentCallRequest,
302) -> Result<PlacedCall> {
303    let mut body = Map::new();
304    body.insert("inbox".to_string(), Value::from(inbox));
305    if let Value::Object(fields) = serde_json::to_value(call)? {
306        body.extend(fields);
307    }
308    Ok(post(
309        &CredentialsOrApiKey::Credentials(authorization.clone()),
310        "/cicada/inboxes/agent/call",
311        Value::Object(body),
312    )
313    .await?
314    .json()
315    .await?)
316}