1use std::collections::HashMap;
2use std::ops::Deref;
3use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value, json};
8use tokio::sync::watch;
9
10use super::contacts::post as send;
11use super::phone::{ActiveCall, IncomingCall, RingEnd};
12use crate::ant::persona::PartialDemographic;
13use crate::authentification::{Credentials, CredentialsOrApiKey};
14use crate::error::Result;
15use crate::groups::Group;
16use crate::integrations::Platform;
17use crate::parrot::generative::{Text, Voice};
18use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
19use crate::termite::versioning::Repository;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct InboxGroup {
23 pub id: String,
24 pub name: String,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub icon: Option<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
30#[serde(rename_all = "camelCase")]
31pub struct Inbox {
32 pub id: String,
33 pub name: String,
34 pub created_at: DateTime<Utc>,
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub group: Option<InboxGroup>,
37 #[serde(skip_serializing_if = "Option::is_none")]
39 pub agent: Option<bool>,
40 #[serde(skip_serializing_if = "Option::is_none")]
42 pub repository: Option<String>,
43}
44
45fn text(value: &Value, fallback: &str) -> String {
46 match value {
47 Value::Null => fallback.to_string(),
48 Value::String(text) => text.clone(),
49 value => value.to_string(),
50 }
51}
52
53fn truthy(value: &Value) -> bool {
54 match value {
55 Value::Null => false,
56 Value::Bool(value) => *value,
57 Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
58 Value::String(text) => !text.is_empty(),
59 _ => true,
60 }
61}
62
63impl Inbox {
64 fn from_json(raw: &Value) -> Inbox {
65 let group = &raw["group"];
66 Inbox {
67 id: text(&raw["id"], "undefined"),
68 name: raw["name"].as_str().unwrap_or_default().to_string(),
69 created_at: crate::tickets::parse_date(&raw["createdAt"]).unwrap_or_default(),
70 group: group.is_object().then(|| InboxGroup {
71 id: text(&group["id"], "undefined"),
72 name: text(&group["name"], ""),
73 icon: truthy(&group["icon"]).then(|| text(&group["icon"], "")),
74 }),
75 agent: truthy(&raw["agent"]).then_some(true),
76 repository: truthy(&raw["repository"]).then(|| text(&raw["repository"], "")),
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(rename_all = "camelCase")]
83pub struct InboxAccount {
84 pub platform: Platform,
85 pub account_id: String,
86}
87
88async fn post(
89 authorization: &CredentialsOrApiKey,
90 path: &str,
91 body: Value,
92) -> Result<reqwest::Response> {
93 send(authorization, path, Some(body)).await
94}
95
96fn inboxes(json: &Value) -> Vec<Inbox> {
97 json.as_array()
98 .into_iter()
99 .flatten()
100 .map(Inbox::from_json)
101 .collect()
102}
103
104pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Inbox>> {
105 let json: Value = post(authorization, "/cicada/inboxes", json!({}))
106 .await?
107 .json()
108 .await?;
109 Ok(inboxes(&json))
110}
111
112pub async fn create(authorization: &CredentialsOrApiKey, name: &str) -> Result<Inbox> {
113 let json: Value = post(
114 authorization,
115 "/cicada/inboxes/create",
116 json!({ "name": name }),
117 )
118 .await?
119 .json()
120 .await?;
121 Ok(Inbox::from_json(&json))
122}
123
124pub async fn rename(
125 authorization: &CredentialsOrApiKey,
126 inbox_id: &str,
127 name: &str,
128) -> Result<Inbox> {
129 let json: Value = post(
130 authorization,
131 "/cicada/inboxes/rename",
132 json!({ "inbox": inbox_id, "name": name }),
133 )
134 .await?
135 .json()
136 .await?;
137 Ok(Inbox::from_json(&json))
138}
139
140pub async fn remove(authorization: &CredentialsOrApiKey, inbox_id: &str) -> Result<()> {
141 post(
142 authorization,
143 "/cicada/inboxes/delete",
144 json!({ "inbox": inbox_id }),
145 )
146 .await?;
147 Ok(())
148}
149
150pub async fn set_repository(
153 authorization: &CredentialsOrApiKey,
154 inbox_id: &str,
155 repository: Option<&Repository>,
156) -> Result<Inbox> {
157 let json: Value = post(
158 authorization,
159 "/cicada/inboxes/repository",
160 json!({ "inbox": inbox_id, "repository": repository.map(|r| r.id) }),
161 )
162 .await?
163 .json()
164 .await?;
165 Ok(Inbox::from_json(&json))
166}
167
168pub async fn move_to_group(
169 authorization: &CredentialsOrApiKey,
170 inbox_id: &str,
171 group_id: &str,
172) -> Result<Inbox> {
173 let json: Value = post(
174 authorization,
175 "/cicada/inboxes/move",
176 json!({ "inbox": inbox_id, "group": group_id }),
177 )
178 .await?
179 .json()
180 .await?;
181 Ok(Inbox::from_json(&json))
182}
183
184pub async fn assign(
185 authorization: &CredentialsOrApiKey,
186 inbox_id: &str,
187 account: &InboxAccount,
188) -> Result<()> {
189 post(
190 authorization,
191 "/cicada/inboxes/accounts",
192 json!({ "inbox": inbox_id, "platform": account.platform, "accountId": account.account_id }),
193 )
194 .await?;
195 Ok(())
196}
197
198pub async fn list_accounts(
199 authorization: &CredentialsOrApiKey,
200 inbox_id: &str,
201) -> Result<Vec<InboxAccount>> {
202 Ok(post(
203 authorization,
204 "/cicada/inboxes/accounts/list",
205 json!({ "inbox": inbox_id }),
206 )
207 .await?
208 .json()
209 .await?)
210}
211
212#[derive(Default)]
216pub struct ConnectOptions {
217 pub hooks: Option<Arc<dyn Hooks>>,
218}
219
220#[derive(Default)]
221struct InboxLive {
222 inbox_id: String,
223 name: String,
224 owner: String,
225 ringing: HashMap<String, IncomingCall>,
226 calls: HashMap<String, ActiveCall>,
227 ends: HashMap<String, watch::Sender<Option<RingEnd>>>,
228}
229
230#[derive(Clone)]
233pub struct InboxRoom {
234 room: Room,
235 state: Arc<Mutex<InboxLive>>,
236}
237
238impl Deref for InboxRoom {
239 type Target = Room;
240 fn deref(&self) -> &Room {
241 &self.room
242 }
243}
244
245impl InboxRoom {
246 fn live(&self) -> MutexGuard<'_, InboxLive> {
247 self.state.lock().unwrap_or_else(PoisonError::into_inner)
248 }
249
250 pub fn inbox_id(&self) -> String {
251 self.live().inbox_id.clone()
252 }
253
254 pub fn name(&self) -> String {
255 self.live().name.clone()
256 }
257
258 pub fn owner(&self) -> String {
260 self.live().owner.clone()
261 }
262
263 pub fn ringing(&self) -> HashMap<String, IncomingCall> {
265 self.live().ringing.clone()
266 }
267
268 pub fn calls(&self) -> HashMap<String, ActiveCall> {
270 self.live().calls.clone()
271 }
272
273 pub fn group(&self) -> Option<Group> {
275 let owner = self.owner();
276 owner
277 .strip_prefix("group:")
278 .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
279 .map(|id| Group::from_json(&json!({ "id": id })))
280 }
281
282 fn ring(&self, live: &mut InboxLive, json: &Value) {
283 let id = text(&json["id"], "");
284 if id.is_empty() || live.ringing.contains_key(&id) {
285 return;
286 }
287 let (ends, ended) = watch::channel(None);
288 live.ends.insert(id.clone(), ends);
289 live.ringing.insert(
290 id,
291 IncomingCall::from_json(json, self.get_authorization(), Some(ended)),
292 );
293 }
294
295 fn stop_ringing(live: &mut InboxLive, id: &str, reason: RingEnd) {
296 if let Some(ends) = live.ends.remove(id) {
297 ends.send_replace(Some(reason));
298 }
299 live.ringing.remove(id);
300 }
301
302 pub fn hydrate(&self, state: &Value) {
303 let mut live = self.live();
304 if !state["id"].is_null() {
305 live.inbox_id = text(&state["id"], "");
306 }
307 if let Some(name) = state["name"].as_str() {
308 live.name = name.to_string();
309 }
310 if let Some(owner) = state["owner"].as_str() {
311 live.owner = owner.to_string();
312 }
313 for call in state["ringing"].as_array().into_iter().flatten() {
314 self.ring(&mut live, call);
315 }
316 for call in state["calls"].as_array().into_iter().flatten() {
317 live.calls.insert(
318 text(&call["id"], ""),
319 ActiveCall::from_json(call, self.get_authorization()),
320 );
321 }
322 }
323
324 pub fn handle_event(&self, packet: &Value) -> bool {
325 let id = text(&packet["data"]["id"], "");
326 let mut live = self.live();
327 match packet["event"].as_str() {
328 Some("incoming") => self.ring(&mut live, &packet["data"]),
329 Some("ring-end") => {
330 let reason = serde_json::from_value(packet["data"]["reason"].clone())
331 .unwrap_or(RingEnd::HungUp);
332 InboxRoom::stop_ringing(&mut live, &id, reason);
333 }
334 Some("call") => {
335 InboxRoom::stop_ringing(&mut live, &id, RingEnd::Taken);
336 live.calls.insert(
337 id,
338 ActiveCall::from_json(&packet["data"], self.get_authorization()),
339 );
340 }
341 Some("call-ended") => {
342 InboxRoom::stop_ringing(&mut live, &id, RingEnd::HungUp);
343 live.calls.remove(&id);
344 }
345 _ => return false,
346 }
347 true
348 }
349
350 pub async fn connect(
351 authorization: &CredentialsOrApiKey,
352 target_id: &str,
353 opts: ConnectOptions,
354 ) -> Result<(InboxRoom, Presence)> {
355 let state = Arc::new(Mutex::new(InboxLive {
356 inbox_id: target_id.to_string(),
357 ..InboxLive::default()
358 }));
359 let me = connect_server(
360 Authorization::Server {
361 authorization: authorization.clone(),
362 server: target_id.to_string(),
363 group: None,
364 },
365 &format!("{}/cicada/inbox/live", super::get_url()),
366 Arc::new(InboxHooks {
367 state: state.clone(),
368 user: opts.hooks.unwrap_or_else(|| Arc::new(())),
369 }),
370 )
371 .await?;
372 let room = InboxRoom {
373 room: me.room().clone(),
374 state,
375 };
376 let closing = room.clone();
377 let mut closed = room.socket_closed();
378 tokio::spawn(async move {
379 let _ = closed.wait_for(|closed| *closed).await;
380 let mut live = closing.live();
381 let ringing: Vec<String> = live.ringing.keys().cloned().collect();
382 for id in ringing {
383 InboxRoom::stop_ringing(&mut live, &id, RingEnd::HungUp);
384 }
385 });
386 Ok((room, me))
387 }
388}
389
390struct InboxHooks {
391 state: Arc<Mutex<InboxLive>>,
392 user: Arc<dyn Hooks>,
393}
394
395impl InboxHooks {
396 fn room(&self, room: &Room) -> InboxRoom {
397 InboxRoom {
398 room: room.clone(),
399 state: self.state.clone(),
400 }
401 }
402}
403
404impl Hooks for InboxHooks {
405 fn create_room(&self, room: &Room, state: &Value) {
406 self.user.create_room(room, state);
407 }
408
409 fn create_presence(&self, room: &Room, presence: &Presence) {
410 self.user.create_presence(room, presence);
411 }
412
413 fn remove_presence(&self, room: &Room, presence: &Presence) {
414 self.user.remove_presence(room, presence);
415 }
416
417 fn on_connection(&self, room: &Room, state: &Value) {
418 self.room(room).hydrate(state);
419 self.user.on_connection(room, state);
420 }
421
422 fn on_event(&self, room: &Room, packet: &Value) -> bool {
423 let handled = self.room(room).handle_event(packet);
424 self.user.on_event(room, packet) || handled
425 }
426
427 fn on_presence(&self, room: &Room) {
428 self.user.on_presence(room);
429 }
430
431 fn on_closed(&self, room: &Room, reason: Option<&str>) {
432 self.user.on_closed(room, reason);
433 }
434}
435
436#[derive(Debug, Clone, PartialEq, Serialize)]
446#[serde(rename_all = "camelCase")]
447pub struct AgentSettings {
448 pub model: Text,
449 pub reasoning: String,
450 pub voice_model: Option<Voice>,
451 pub persona: PartialDemographic,
452 pub instructions: String,
453 pub daily_limit: f64,
454 pub spent_today: f64,
455 pub approve_outbound: bool,
456 pub enabled_at: DateTime<Utc>,
457}
458
459impl AgentSettings {
460 pub fn from_json(json: &Value) -> AgentSettings {
461 AgentSettings {
462 model: serde_json::from_value(json["model"].clone()).unwrap_or(Text::Auto),
463 reasoning: text(&json["reasoning"], ""),
464 voice_model: serde_json::from_value(json["voiceModel"].clone()).ok(),
465 persona: serde_json::from_value(json["persona"].clone()).unwrap_or_default(),
466 instructions: text(&json["instructions"], ""),
467 daily_limit: json["dailyLimit"].as_f64().unwrap_or_default(),
468 spent_today: json["spentToday"].as_f64().unwrap_or_default(),
469 approve_outbound: json["approveOutbound"].as_bool().unwrap_or_default(),
470 enabled_at: crate::tickets::parse_date(&json["enabledAt"]).unwrap_or_default(),
471 }
472 }
473}
474
475pub async fn get_agent(
476 authorization: &CredentialsOrApiKey,
477 inbox: &str,
478) -> Result<Option<AgentSettings>> {
479 let text = post(
480 authorization,
481 "/cicada/inboxes/agent",
482 json!({ "inbox": inbox }),
483 )
484 .await?
485 .text()
486 .await?;
487 if text.trim().is_empty() {
488 return Ok(None);
489 }
490 Ok(Some(AgentSettings::from_json(&serde_json::from_str(
491 &text,
492 )?)))
493}
494
495#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
497#[serde(rename_all = "camelCase")]
498pub struct AgentDraft {
499 pub model: Text,
500 #[serde(default, skip_serializing_if = "Option::is_none")]
501 pub reasoning: Option<String>,
502 #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub voice_model: Option<Voice>,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub persona: Option<PartialDemographic>,
506 pub instructions: String,
507 pub daily_limit: f64,
508 pub approve_outbound: bool,
509}
510
511pub async fn set_agent(
513 authorization: &CredentialsOrApiKey,
514 inbox: &str,
515 settings: &AgentDraft,
516) -> Result<AgentSettings> {
517 let mut body = Map::new();
518 body.insert("inbox".to_string(), Value::from(inbox));
519 if let Value::Object(fields) = serde_json::to_value(settings)? {
520 body.extend(fields);
521 }
522 let json: Value = post(
523 authorization,
524 "/cicada/inboxes/agent/set",
525 Value::Object(body),
526 )
527 .await?
528 .json()
529 .await?;
530 Ok(AgentSettings::from_json(&json))
531}
532
533pub async fn clear_agent(authorization: &CredentialsOrApiKey, inbox: &str) -> Result<()> {
534 post(
535 authorization,
536 "/cicada/inboxes/agent/clear",
537 json!({ "inbox": inbox }),
538 )
539 .await?;
540 Ok(())
541}
542
543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
545pub struct AgentCallRequest {
546 pub to: String,
547 pub directions: String,
548 #[serde(default, skip_serializing_if = "Option::is_none")]
549 pub from: Option<String>,
550}
551
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "camelCase")]
555pub struct PlacedCall {
556 pub calling: String,
557 pub from: String,
558 pub call_id: String,
559}
560
561pub async fn agent_call(
565 authorization: &Credentials,
566 inbox: &str,
567 call: &AgentCallRequest,
568) -> Result<PlacedCall> {
569 let mut body = Map::new();
570 body.insert("inbox".to_string(), Value::from(inbox));
571 if let Value::Object(fields) = serde_json::to_value(call)? {
572 body.extend(fields);
573 }
574 Ok(post(
575 &CredentialsOrApiKey::Credentials(authorization.clone()),
576 "/cicada/inboxes/agent/call",
577 Value::Object(body),
578 )
579 .await?
580 .json()
581 .await?)
582}
583
584#[cfg(test)]
585mod tests {
586 use tokio::sync::mpsc;
587
588 use super::*;
589 use crate::authentification::ApiKey;
590
591 fn inbox_room() -> InboxRoom {
592 let (ws, _outbox) = mpsc::unbounded_channel();
593 InboxRoom {
594 room: Room::new(
595 "http://localhost/cicada/inbox/live".to_string(),
596 ws,
597 Authorization::Server {
598 authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
599 server: "3".to_string(),
600 group: None,
601 },
602 "9".to_string(),
603 ),
604 state: Arc::new(Mutex::new(InboxLive::default())),
605 }
606 }
607
608 #[tokio::test]
609 async fn rooms_ring_take_and_end_calls() {
610 let room = inbox_room();
611 room.hydrate(&json!({
612 "id": "3", "name": "Personal", "owner": "group:7",
613 "ringing": [{ "id": "CA1", "line": "+15550001111", "peer": "+15550002222" }],
614 "calls": [],
615 }));
616 assert_eq!(room.inbox_id(), "3");
617 assert_eq!(room.group().map(|g| g.id), Some("7".to_string()));
618 let ringing = room.ringing()["CA1"].clone();
619
620 let call = json!({ "id": "CA1", "direction": "IN", "line": "+15550001111", "peer": "+15550002222",
621 "startedAt": 1_000, "agent": false, "people": [{ "id": "s1", "profile": { "email": "a@b.c" } }] });
622 assert!(room.handle_event(&json!({ "event": "call", "data": call })));
623 assert_eq!(ringing.ringing().await, RingEnd::Taken);
624 assert!(room.ringing().is_empty());
625 assert_eq!(room.calls()["CA1"].people[0].id, "s1");
626
627 assert!(room.handle_event(&json!({ "event": "call-ended", "data": { "id": "CA1" } })));
628 assert!(room.calls().is_empty());
629 assert!(!room.handle_event(&json!({ "event": "upsert-agent", "data": {} })));
630 }
631}