fauna-api 1.0.811

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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>,
    /// An agent is on for this inbox.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent: Option<bool>,
    /// The Termite repository its agent's desktop works in.
    #[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(())
}

/// Attaches a Termite repository, where the inbox's agent's desktop works, or detaches it
/// with None. It must be the inbox owner's.
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?)
}

// ─── Live room ───────────────────────────────────────────────────────────────

/// The `opts` argument of `InboxRoom::connect`.
#[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>>>,
}

/// An inbox's live room. Its presences are who has the inbox open; it rings them for calls
/// to the inbox's lines, and lists the calls in progress there, which anyone in it can join.
#[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()
    }

    /// Who owns the inbox: `credentials:{id}` or `group:{id}`.
    pub fn owner(&self) -> String {
        self.live().owner.clone()
    }

    /// Calls ringing on the inbox's lines that nobody has taken yet.
    pub fn ringing(&self) -> HashMap<String, IncomingCall> {
        self.live().ringing.clone()
    }

    /// Calls in progress on the inbox's lines.
    pub fn calls(&self) -> HashMap<String, ActiveCall> {
        self.live().calls.clone()
    }

    /// The group that owns the inbox; None for a person's.
    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);
    }
}

/// Each inbox has at most one agent, with its own model and "System prompt"
/// (`instructions`). It answers the inbox's new messages and reaches people
/// from the inbox's own accounts. `daily_limit` and `spent_today` are dollars per
/// UTC day; at the limit the agent pauses until midnight UTC. `reasoning` is one
/// of the text model's catalog tiers, empty for its default; `voice_model` is the
/// realtime voice the agent talks with on calls, None for the catalog's first. `persona` is
/// who the agent is, a partial demographic; its calls use the voice nearest it. With
/// `approve_outbound`, the agent's replies to anyone but the owners wait: Fauna texts the
/// draft to the owners, and an owner's SEND sends it while any other answer drops it.
#[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,
    )?)))
}

/// The `settings` argument of `set_agent`.
#[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,
}

/// Turns the agent on (it answers messages sent from now on) or updates it.
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(())
}

/// The `call` argument of `agent_call`.
#[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>,
}

/// `{ calling, from, callId }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacedCall {
    pub calling: String,
    pub from: String,
    pub call_id: String,
}

/// Has the inbox's agent phone `to` from one of the inbox's lines (`from`, or its first)
/// and follow `directions`. Returns once the call is placed; the transcript lands on the
/// thread with that number. Owners only; counts toward the agent's daily limit.
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": {} })));
    }
}