use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::sync::watch;
use super::contacts::post as send;
use super::phone::{ActiveCall, IncomingCall, RingEnd};
use crate::ant::persona::PartialDemographic;
use crate::authentification::{Credentials, CredentialsOrApiKey};
use crate::error::Result;
use crate::groups::Group;
use crate::integrations::Platform;
use crate::parrot::generative::{Text, Voice};
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
use crate::termite::versioning::Repository;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InboxGroup {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Inbox {
pub id: String,
pub name: String,
pub created_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<InboxGroup>,
#[serde(skip_serializing_if = "Option::is_none")]
pub agent: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub repository: Option<String>,
}
fn text(value: &Value, fallback: &str) -> String {
match value {
Value::Null => fallback.to_string(),
Value::String(text) => text.clone(),
value => value.to_string(),
}
}
fn truthy(value: &Value) -> bool {
match value {
Value::Null => false,
Value::Bool(value) => *value,
Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
Value::String(text) => !text.is_empty(),
_ => true,
}
}
impl Inbox {
fn from_json(raw: &Value) -> Inbox {
let group = &raw["group"];
Inbox {
id: text(&raw["id"], "undefined"),
name: raw["name"].as_str().unwrap_or_default().to_string(),
created_at: crate::tickets::parse_date(&raw["createdAt"]).unwrap_or_default(),
group: group.is_object().then(|| InboxGroup {
id: text(&group["id"], "undefined"),
name: text(&group["name"], ""),
icon: truthy(&group["icon"]).then(|| text(&group["icon"], "")),
}),
agent: truthy(&raw["agent"]).then_some(true),
repository: truthy(&raw["repository"]).then(|| text(&raw["repository"], "")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InboxAccount {
pub platform: Platform,
pub account_id: String,
}
async fn post(
authorization: &CredentialsOrApiKey,
path: &str,
body: Value,
) -> Result<reqwest::Response> {
send(authorization, path, Some(body)).await
}
fn inboxes(json: &Value) -> Vec<Inbox> {
json.as_array()
.into_iter()
.flatten()
.map(Inbox::from_json)
.collect()
}
pub async fn list(authorization: &CredentialsOrApiKey) -> Result<Vec<Inbox>> {
let json: Value = post(authorization, "/cicada/inboxes", json!({}))
.await?
.json()
.await?;
Ok(inboxes(&json))
}
pub async fn create(authorization: &CredentialsOrApiKey, name: &str) -> Result<Inbox> {
let json: Value = post(
authorization,
"/cicada/inboxes/create",
json!({ "name": name }),
)
.await?
.json()
.await?;
Ok(Inbox::from_json(&json))
}
pub async fn rename(
authorization: &CredentialsOrApiKey,
inbox_id: &str,
name: &str,
) -> Result<Inbox> {
let json: Value = post(
authorization,
"/cicada/inboxes/rename",
json!({ "inbox": inbox_id, "name": name }),
)
.await?
.json()
.await?;
Ok(Inbox::from_json(&json))
}
pub async fn remove(authorization: &CredentialsOrApiKey, inbox_id: &str) -> Result<()> {
post(
authorization,
"/cicada/inboxes/delete",
json!({ "inbox": inbox_id }),
)
.await?;
Ok(())
}
pub async fn set_repository(
authorization: &CredentialsOrApiKey,
inbox_id: &str,
repository: Option<&Repository>,
) -> Result<Inbox> {
let json: Value = post(
authorization,
"/cicada/inboxes/repository",
json!({ "inbox": inbox_id, "repository": repository.map(|r| r.id) }),
)
.await?
.json()
.await?;
Ok(Inbox::from_json(&json))
}
pub async fn move_to_group(
authorization: &CredentialsOrApiKey,
inbox_id: &str,
group_id: &str,
) -> Result<Inbox> {
let json: Value = post(
authorization,
"/cicada/inboxes/move",
json!({ "inbox": inbox_id, "group": group_id }),
)
.await?
.json()
.await?;
Ok(Inbox::from_json(&json))
}
pub async fn assign(
authorization: &CredentialsOrApiKey,
inbox_id: &str,
account: &InboxAccount,
) -> Result<()> {
post(
authorization,
"/cicada/inboxes/accounts",
json!({ "inbox": inbox_id, "platform": account.platform, "accountId": account.account_id }),
)
.await?;
Ok(())
}
pub async fn list_accounts(
authorization: &CredentialsOrApiKey,
inbox_id: &str,
) -> Result<Vec<InboxAccount>> {
Ok(post(
authorization,
"/cicada/inboxes/accounts/list",
json!({ "inbox": inbox_id }),
)
.await?
.json()
.await?)
}
#[derive(Default)]
pub struct ConnectOptions {
pub hooks: Option<Arc<dyn Hooks>>,
}
#[derive(Default)]
struct InboxLive {
inbox_id: String,
name: String,
owner: String,
ringing: HashMap<String, IncomingCall>,
calls: HashMap<String, ActiveCall>,
ends: HashMap<String, watch::Sender<Option<RingEnd>>>,
}
#[derive(Clone)]
pub struct InboxRoom {
room: Room,
state: Arc<Mutex<InboxLive>>,
}
impl Deref for InboxRoom {
type Target = Room;
fn deref(&self) -> &Room {
&self.room
}
}
impl InboxRoom {
fn live(&self) -> MutexGuard<'_, InboxLive> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn inbox_id(&self) -> String {
self.live().inbox_id.clone()
}
pub fn name(&self) -> String {
self.live().name.clone()
}
pub fn owner(&self) -> String {
self.live().owner.clone()
}
pub fn ringing(&self) -> HashMap<String, IncomingCall> {
self.live().ringing.clone()
}
pub fn calls(&self) -> HashMap<String, ActiveCall> {
self.live().calls.clone()
}
pub fn group(&self) -> Option<Group> {
let owner = self.owner();
owner
.strip_prefix("group:")
.filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
.map(|id| Group::from_json(&json!({ "id": id })))
}
fn ring(&self, live: &mut InboxLive, json: &Value) {
let id = text(&json["id"], "");
if id.is_empty() || live.ringing.contains_key(&id) {
return;
}
let (ends, ended) = watch::channel(None);
live.ends.insert(id.clone(), ends);
live.ringing.insert(
id,
IncomingCall::from_json(json, self.get_authorization(), Some(ended)),
);
}
fn stop_ringing(live: &mut InboxLive, id: &str, reason: RingEnd) {
if let Some(ends) = live.ends.remove(id) {
ends.send_replace(Some(reason));
}
live.ringing.remove(id);
}
pub fn hydrate(&self, state: &Value) {
let mut live = self.live();
if !state["id"].is_null() {
live.inbox_id = text(&state["id"], "");
}
if let Some(name) = state["name"].as_str() {
live.name = name.to_string();
}
if let Some(owner) = state["owner"].as_str() {
live.owner = owner.to_string();
}
for call in state["ringing"].as_array().into_iter().flatten() {
self.ring(&mut live, call);
}
for call in state["calls"].as_array().into_iter().flatten() {
live.calls.insert(
text(&call["id"], ""),
ActiveCall::from_json(call, self.get_authorization()),
);
}
}
pub fn handle_event(&self, packet: &Value) -> bool {
let id = text(&packet["data"]["id"], "");
let mut live = self.live();
match packet["event"].as_str() {
Some("incoming") => self.ring(&mut live, &packet["data"]),
Some("ring-end") => {
let reason = serde_json::from_value(packet["data"]["reason"].clone())
.unwrap_or(RingEnd::HungUp);
InboxRoom::stop_ringing(&mut live, &id, reason);
}
Some("call") => {
InboxRoom::stop_ringing(&mut live, &id, RingEnd::Taken);
live.calls.insert(
id,
ActiveCall::from_json(&packet["data"], self.get_authorization()),
);
}
Some("call-ended") => {
InboxRoom::stop_ringing(&mut live, &id, RingEnd::HungUp);
live.calls.remove(&id);
}
_ => return false,
}
true
}
pub async fn connect(
authorization: &CredentialsOrApiKey,
target_id: &str,
opts: ConnectOptions,
) -> Result<(InboxRoom, Presence)> {
let state = Arc::new(Mutex::new(InboxLive {
inbox_id: target_id.to_string(),
..InboxLive::default()
}));
let me = connect_server(
Authorization::Server {
authorization: authorization.clone(),
server: target_id.to_string(),
group: None,
},
&format!("{}/cicada/inbox/live", super::get_url()),
Arc::new(InboxHooks {
state: state.clone(),
user: opts.hooks.unwrap_or_else(|| Arc::new(())),
}),
)
.await?;
let room = InboxRoom {
room: me.room().clone(),
state,
};
let closing = room.clone();
let mut closed = room.socket_closed();
tokio::spawn(async move {
let _ = closed.wait_for(|closed| *closed).await;
let mut live = closing.live();
let ringing: Vec<String> = live.ringing.keys().cloned().collect();
for id in ringing {
InboxRoom::stop_ringing(&mut live, &id, RingEnd::HungUp);
}
});
Ok((room, me))
}
}
struct InboxHooks {
state: Arc<Mutex<InboxLive>>,
user: Arc<dyn Hooks>,
}
impl InboxHooks {
fn room(&self, room: &Room) -> InboxRoom {
InboxRoom {
room: room.clone(),
state: self.state.clone(),
}
}
}
impl Hooks for InboxHooks {
fn create_room(&self, room: &Room, state: &Value) {
self.user.create_room(room, state);
}
fn create_presence(&self, room: &Room, presence: &Presence) {
self.user.create_presence(room, presence);
}
fn remove_presence(&self, room: &Room, presence: &Presence) {
self.user.remove_presence(room, presence);
}
fn on_connection(&self, room: &Room, state: &Value) {
self.room(room).hydrate(state);
self.user.on_connection(room, state);
}
fn on_event(&self, room: &Room, packet: &Value) -> bool {
let handled = self.room(room).handle_event(packet);
self.user.on_event(room, packet) || handled
}
fn on_presence(&self, room: &Room) {
self.user.on_presence(room);
}
fn on_closed(&self, room: &Room, reason: Option<&str>) {
self.user.on_closed(room, reason);
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentSettings {
pub model: Text,
pub reasoning: String,
pub voice_model: Option<Voice>,
pub persona: PartialDemographic,
pub instructions: String,
pub daily_limit: f64,
pub spent_today: f64,
pub approve_outbound: bool,
pub enabled_at: DateTime<Utc>,
}
impl AgentSettings {
pub fn from_json(json: &Value) -> AgentSettings {
AgentSettings {
model: serde_json::from_value(json["model"].clone()).unwrap_or(Text::Auto),
reasoning: text(&json["reasoning"], ""),
voice_model: serde_json::from_value(json["voiceModel"].clone()).ok(),
persona: serde_json::from_value(json["persona"].clone()).unwrap_or_default(),
instructions: text(&json["instructions"], ""),
daily_limit: json["dailyLimit"].as_f64().unwrap_or_default(),
spent_today: json["spentToday"].as_f64().unwrap_or_default(),
approve_outbound: json["approveOutbound"].as_bool().unwrap_or_default(),
enabled_at: crate::tickets::parse_date(&json["enabledAt"]).unwrap_or_default(),
}
}
}
pub async fn get_agent(
authorization: &CredentialsOrApiKey,
inbox: &str,
) -> Result<Option<AgentSettings>> {
let text = post(
authorization,
"/cicada/inboxes/agent",
json!({ "inbox": inbox }),
)
.await?
.text()
.await?;
if text.trim().is_empty() {
return Ok(None);
}
Ok(Some(AgentSettings::from_json(&serde_json::from_str(
&text,
)?)))
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentDraft {
pub model: Text,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub voice_model: Option<Voice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub persona: Option<PartialDemographic>,
pub instructions: String,
pub daily_limit: f64,
pub approve_outbound: bool,
}
pub async fn set_agent(
authorization: &CredentialsOrApiKey,
inbox: &str,
settings: &AgentDraft,
) -> Result<AgentSettings> {
let mut body = Map::new();
body.insert("inbox".to_string(), Value::from(inbox));
if let Value::Object(fields) = serde_json::to_value(settings)? {
body.extend(fields);
}
let json: Value = post(
authorization,
"/cicada/inboxes/agent/set",
Value::Object(body),
)
.await?
.json()
.await?;
Ok(AgentSettings::from_json(&json))
}
pub async fn clear_agent(authorization: &CredentialsOrApiKey, inbox: &str) -> Result<()> {
post(
authorization,
"/cicada/inboxes/agent/clear",
json!({ "inbox": inbox }),
)
.await?;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentCallRequest {
pub to: String,
pub directions: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacedCall {
pub calling: String,
pub from: String,
pub call_id: String,
}
pub async fn agent_call(
authorization: &Credentials,
inbox: &str,
call: &AgentCallRequest,
) -> Result<PlacedCall> {
let mut body = Map::new();
body.insert("inbox".to_string(), Value::from(inbox));
if let Value::Object(fields) = serde_json::to_value(call)? {
body.extend(fields);
}
Ok(post(
&CredentialsOrApiKey::Credentials(authorization.clone()),
"/cicada/inboxes/agent/call",
Value::Object(body),
)
.await?
.json()
.await?)
}
#[cfg(test)]
mod tests {
use tokio::sync::mpsc;
use super::*;
use crate::authentification::ApiKey;
fn inbox_room() -> InboxRoom {
let (ws, _outbox) = mpsc::unbounded_channel();
InboxRoom {
room: Room::new(
"http://localhost/cicada/inbox/live".to_string(),
ws,
Authorization::Server {
authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
server: "3".to_string(),
group: None,
},
"9".to_string(),
),
state: Arc::new(Mutex::new(InboxLive::default())),
}
}
#[tokio::test]
async fn rooms_ring_take_and_end_calls() {
let room = inbox_room();
room.hydrate(&json!({
"id": "3", "name": "Personal", "owner": "group:7",
"ringing": [{ "id": "CA1", "line": "+15550001111", "peer": "+15550002222" }],
"calls": [],
}));
assert_eq!(room.inbox_id(), "3");
assert_eq!(room.group().map(|g| g.id), Some("7".to_string()));
let ringing = room.ringing()["CA1"].clone();
let call = json!({ "id": "CA1", "direction": "IN", "line": "+15550001111", "peer": "+15550002222",
"startedAt": 1_000, "agent": false, "people": [{ "id": "s1", "profile": { "email": "a@b.c" } }] });
assert!(room.handle_event(&json!({ "event": "call", "data": call })));
assert_eq!(ringing.ringing().await, RingEnd::Taken);
assert!(room.ringing().is_empty());
assert_eq!(room.calls()["CA1"].people[0].id, "s1");
assert!(room.handle_event(&json!({ "event": "call-ended", "data": { "id": "CA1" } })));
assert!(room.calls().is_empty());
assert!(!room.handle_event(&json!({ "event": "upsert-agent", "data": {} })));
}
}