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. With
186/// `approve_outbound`, the agent's replies to anyone but the owners wait: Fauna texts the
187/// draft to the owners, and an owner's SEND sends it while any other answer drops it.
188#[derive(Debug, Clone, PartialEq, Serialize)]
189#[serde(rename_all = "camelCase")]
190pub struct AgentSettings {
191    pub model: Text,
192    pub reasoning: String,
193    pub voice_model: Option<Voice>,
194    pub instructions: String,
195    pub daily_limit: f64,
196    pub spent_today: f64,
197    pub approve_outbound: bool,
198    pub enabled_at: DateTime<Utc>,
199}
200
201impl AgentSettings {
202    pub fn from_json(json: &Value) -> AgentSettings {
203        AgentSettings {
204            model: serde_json::from_value(json["model"].clone()).unwrap_or(Text::Auto),
205            reasoning: text(&json["reasoning"], ""),
206            voice_model: serde_json::from_value(json["voiceModel"].clone()).ok(),
207            instructions: text(&json["instructions"], ""),
208            daily_limit: json["dailyLimit"].as_f64().unwrap_or_default(),
209            spent_today: json["spentToday"].as_f64().unwrap_or_default(),
210            approve_outbound: json["approveOutbound"].as_bool().unwrap_or_default(),
211            enabled_at: crate::tickets::parse_date(&json["enabledAt"]).unwrap_or_default(),
212        }
213    }
214}
215
216pub async fn get_agent(
217    authorization: &CredentialsOrApiKey,
218    inbox: &str,
219) -> Result<Option<AgentSettings>> {
220    let text = post(
221        authorization,
222        "/cicada/inboxes/agent",
223        json!({ "inbox": inbox }),
224    )
225    .await?
226    .text()
227    .await?;
228    if text.trim().is_empty() {
229        return Ok(None);
230    }
231    Ok(Some(AgentSettings::from_json(&serde_json::from_str(
232        &text,
233    )?)))
234}
235
236/// The `settings` argument of `set_agent`.
237#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
238#[serde(rename_all = "camelCase")]
239pub struct AgentDraft {
240    pub model: Text,
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub reasoning: Option<String>,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub voice_model: Option<Voice>,
245    pub instructions: String,
246    pub daily_limit: f64,
247    pub approve_outbound: bool,
248}
249
250/// Turns the agent on (it answers messages sent from now on) or updates it.
251pub async fn set_agent(
252    authorization: &CredentialsOrApiKey,
253    inbox: &str,
254    settings: &AgentDraft,
255) -> Result<AgentSettings> {
256    let mut body = Map::new();
257    body.insert("inbox".to_string(), Value::from(inbox));
258    if let Value::Object(fields) = serde_json::to_value(settings)? {
259        body.extend(fields);
260    }
261    let json: Value = post(
262        authorization,
263        "/cicada/inboxes/agent/set",
264        Value::Object(body),
265    )
266    .await?
267    .json()
268    .await?;
269    Ok(AgentSettings::from_json(&json))
270}
271
272pub async fn clear_agent(authorization: &CredentialsOrApiKey, inbox: &str) -> Result<()> {
273    post(
274        authorization,
275        "/cicada/inboxes/agent/clear",
276        json!({ "inbox": inbox }),
277    )
278    .await?;
279    Ok(())
280}
281
282/// The `call` argument of `agent_call`.
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
284pub struct AgentCallRequest {
285    pub to: String,
286    pub directions: String,
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub from: Option<String>,
289}
290
291/// `{ calling, from, callId }` in the TypeScript SDK.
292#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
293#[serde(rename_all = "camelCase")]
294pub struct PlacedCall {
295    pub calling: String,
296    pub from: String,
297    pub call_id: String,
298}
299
300/// Has the inbox's agent phone `to` from one of the inbox's lines (`from`, or its first)
301/// and follow `directions`. Returns once the call is placed; the transcript lands on the
302/// thread with that number. Owners only; counts toward the agent's daily limit.
303pub async fn agent_call(
304    authorization: &Credentials,
305    inbox: &str,
306    call: &AgentCallRequest,
307) -> Result<PlacedCall> {
308    let mut body = Map::new();
309    body.insert("inbox".to_string(), Value::from(inbox));
310    if let Value::Object(fields) = serde_json::to_value(call)? {
311        body.extend(fields);
312    }
313    Ok(post(
314        &CredentialsOrApiKey::Credentials(authorization.clone()),
315        "/cicada/inboxes/agent/call",
316        Value::Object(body),
317    )
318    .await?
319    .json()
320    .await?)
321}