fauna-api 1.0.816

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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use super::generative::{Content, File as FilePart, Function, Part, file_ref};
use super::room::RoomMessage;
use crate::authentification::{Credentials, CredentialsOrApiKey, Profile};
use crate::billing::PageQuery;
use crate::drive::{self, DriveAuthorization, FileDates};
use crate::error::Result;
use crate::http::{client, ok};

/// Address a live room by a redeemable access code or by its globally-unique
/// reference (`parrot:chat:{chatId}` for a durable-bound room, `parrot:room:{uuid}`
/// for an unbound ephemeral one).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChatTarget {
    Code { code: String },
    Reference { reference: String },
}

/// `{ chatId, groupId }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MovedChat {
    pub chat_id: String,
    pub group_id: String,
}

pub async fn move_chat_to_group(
    credentials: &Credentials,
    chat_id: &str,
    group_id: &str,
) -> Result<MovedChat> {
    let response = client()
        .post(format!("{}/chat/move", super::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "chatId": chat_id, "groupId": group_id }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// The `options` argument of `open_room`.
#[derive(Debug, Clone, Default)]
pub struct OpenRoomOptions {
    pub chat_id: Option<String>,
    pub messages: Option<Vec<Content>>,
    pub share: Option<bool>,
    pub write: Option<bool>,
}

/// `{ reference, roomId, code? }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenedRoom {
    pub reference: String,
    pub room_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
}

/// Host a live room server-side. Pass `chat_id` to bind the room to a durable
/// chat (reference becomes `parrot:chat:{chatId}`, billed to the chat's
/// balance-holder) and seed the newest window from durable; omit it for an
/// unbound ephemeral room. `messages` seeds only ephemeral rooms. `share: true`
/// also mints an access code; people who join with it read along, and with
/// `write: true` they can send too (replies to them run without the chat's
/// repository and memories). Returns the room's `reference` (+ `code` when shared).
pub async fn open_room(
    authorization: &CredentialsOrApiKey,
    options: OpenRoomOptions,
) -> Result<OpenedRoom> {
    let messages = match &options.messages {
        Some(messages) => Some(serialize_transcript(messages).await?),
        None => None,
    };
    let mut body = Map::new();
    insert(&mut body, "chatId", options.chat_id.map(Value::from));
    insert(&mut body, "messages", messages.map(Value::Array));
    insert(&mut body, "share", options.share.map(Value::from));
    insert(&mut body, "write", options.write.map(Value::from));
    let response = client()
        .post(format!("{}/chat/live/open", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&body)
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(OpenedRoom {
        reference: text(&json["reference"]),
        room_id: text(&json["roomId"]),
        code: json["code"].as_str().map(str::to_string),
    })
}

fn insert(body: &mut Map<String, Value>, key: &str, value: Option<Value>) {
    if let Some(value) = value {
        body.insert(key.to_string(), value);
    }
}

fn text(value: &Value) -> String {
    match value {
        Value::String(value) => value.clone(),
        Value::Null => String::new(),
        value => value.to_string(),
    }
}

/// A room message's parts, FILE parts opened the way `RoomMessage.fromJSON` opens them.
pub(crate) fn room_parts(
    parts: &Value,
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
) -> Vec<Part> {
    parts
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|part| {
            if part["type"] != "FILE" {
                return Part::from_json(part);
            }
            let mut meta = part.clone();
            meta["name"] = Value::from(part["name"].as_str().unwrap_or("file"));
            meta["contentType"] = Value::from(
                part["contentType"]
                    .as_str()
                    .unwrap_or("application/octet-stream"),
            );
            let nonempty = |key: &str| part[key].as_str().filter(|value| !value.is_empty());
            let authorization = authorization.clone();
            let file_authorization = if let Some(access_code) = nonempty("accessCode") {
                DriveAuthorization::AccessCode {
                    authorization,
                    access_code: access_code.to_string(),
                }
            } else if let Some(path) = nonempty("path") {
                DriveAuthorization::Path {
                    authorization,
                    path: path.to_string(),
                    group: part["group"].as_str().map(str::to_string),
                }
            } else if let ChatTarget::Code { code } = target {
                DriveAuthorization::AccessCode {
                    authorization,
                    access_code: code.clone(),
                }
            } else if let Some(reference) = nonempty("ref") {
                DriveAuthorization::Path {
                    authorization,
                    path: reference.to_string(),
                    group: None,
                }
            } else {
                DriveAuthorization::AccessCode {
                    authorization,
                    access_code: String::new(),
                }
            };
            Some(Part::File(FilePart {
                file: drive::File::from_json(&meta, file_authorization),
            }))
        })
        .collect()
}

fn target_headers(
    request: reqwest::RequestBuilder,
    target: &ChatTarget,
) -> reqwest::RequestBuilder {
    match target {
        ChatTarget::Code { code } => request.header("Access-Code", code),
        ChatTarget::Reference { reference } => request.header("Server", reference),
    }
}

/// Page older room transcript messages, newest first. `cursor` is how many
/// messages to skip from the newest.
pub async fn page_messages(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
    query: PageQuery,
) -> Result<Vec<RoomMessage>> {
    let request = client()
        .get(format!(
            "{}/chat/live/messages?cursor={}&max={}",
            super::get_url(),
            query.cursor,
            query.max
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    let response = target_headers(request, target).send().await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(json
        .as_array()
        .into_iter()
        .flatten()
        .map(|message| RoomMessage::from_json(message, authorization, target))
        .collect())
}

/// Result of appending to a live room: either the durable transcript row (when
/// the room was idle) or a queued buffer row (when the model was mid-reply).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppendResult {
    Sent { id: Option<String> },
    Queued { queue_id: Option<String> },
}

impl AppendResult {
    pub(crate) fn from_json(json: &Value) -> AppendResult {
        if json["queued"] == true {
            AppendResult::Queued {
                queue_id: json["queueId"].as_str().map(str::to_string),
            }
        } else {
            AppendResult::Sent {
                id: json["id"].as_str().map(str::to_string),
            }
        }
    }
}

/// `Function | Function[]` in the TypeScript SDK: a list is available, a single
/// one forces that tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum FunctionOrFunctions {
    Function(Function),
    Functions(Vec<Function>),
}

/// The `options` argument of `append_room_message`.
#[derive(Debug, Clone, Default)]
pub struct AppendOptions {
    pub reply_to: Option<String>,
    pub model: Option<String>,
    pub reasoning: Option<String>,
    /// Function schemas (array = available; singular = force that tool).
    pub tools: Option<FunctionOrFunctions>,
}

/// Append one message to a live room's single transcript. Any member may append;
/// USER messages are attributed to the caller and nudge the server's debounced
/// model reply. If the room is currently replying the server BUFFERS the send
/// into the shared queue (`Queued { queue_id }`); it drains FIFO when the
/// reply finishes. Otherwise it lands in the transcript (`Sent { id }`).
/// File parts are already-online Drive refs (path / accessCode); the body is JSON.
pub async fn append_room_message(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
    message: &Content,
    options: AppendOptions,
) -> Result<AppendResult> {
    let serialized_parts: Vec<Value> = message.parts.iter().map(Part::wire).collect();

    let mut body = Map::new();
    body.insert("role".to_string(), serde_json::to_value(message.role)?);
    body.insert("parts".to_string(), Value::Array(serialized_parts));
    insert(&mut body, "replyTo", options.reply_to.map(Value::from));
    insert(&mut body, "model", options.model.map(Value::from));
    insert(&mut body, "reasoning", options.reasoning.map(Value::from));
    insert(
        &mut body,
        "tools",
        options.tools.map(serde_json::to_value).transpose()?,
    );

    let request = client()
        .post(format!("{}/chat/live/append", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    let response = target_headers(request, target).json(&body).send().await?;
    let response = ok(response).await?;
    let json: Value = response.json().await.unwrap_or(Value::Null);
    Ok(AppendResult::from_json(&json))
}

/// A file in a chat: one a person attached, or one Parrot opened.
#[derive(Debug, Clone)]
pub struct Attachment {
    pub file: drive::File,
    /// The chat it's in and its name in the chat folder, so a file room can let chat members edit it.
    pub chat: String,
    pub r#ref: String,
    /// Position of the message it came in; unset while the reply attaching it is still being written.
    pub message: Option<u32>,
    pub author: Option<Profile>,
    pub created_at: DateTime<Utc>,
}

impl Attachment {
    pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Attachment {
        let name = json["name"]
            .as_str()
            .or_else(|| json["ref"].as_str())
            .unwrap_or("file");
        let meta = json!({
            "name": name,
            "contentType": json["contentType"].as_str().unwrap_or("application/octet-stream"),
            "contentLength": json["contentLength"].as_f64().unwrap_or_default(),
        });
        Attachment {
            file: drive::File::from_json(
                &meta,
                DriveAuthorization::AccessCode {
                    authorization: authorization.clone(),
                    access_code: text(&json["accessCode"]),
                },
            ),
            chat: text(&json["chat"]),
            r#ref: text(&json["ref"]),
            message: json["message"].as_f64().map(|message| message as u32),
            author: if json["author"].is_object() {
                serde_json::from_value(json["author"].clone()).ok()
            } else {
                None
            },
            created_at: crate::tickets::parse_date(&json["created"]).unwrap_or_else(Utc::now),
        }
    }
}

/// Every file in the chat behind a live room, newest first.
pub async fn list_room_attachments(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
) -> Result<Vec<Attachment>> {
    let request = client()
        .get(format!("{}/chat/live/attachments", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    let response = target_headers(request, target).send().await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(json
        .as_array()
        .into_iter()
        .flatten()
        .map(|row| Attachment::from_json(row, authorization))
        .collect())
}

/// Attach a repository to the chat behind a live room, or detach it with None.
/// The repository must be the chat owner's; only the chat's members may change it.
pub async fn set_room_repository(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
    repository: Option<u64>,
) -> Result<()> {
    let request = client()
        .post(format!("{}/chat/repository", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    let response = target_headers(request, target)
        .json(&json!({ "repository": repository }))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// Remove a queued (buffered) message from a live room. The message was buffered
/// while the model was mid-reply and never entered the transcript, so this is not
/// an unsend: the server just drops the queue row and fans it out to every member.
pub async fn unqueue_room_message(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
    queue_id: &str,
) -> Result<()> {
    let request = client()
        .post(format!("{}/chat/live/unqueue", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    let response = target_headers(request, target)
        .json(&json!({ "queueId": queue_id }))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// The `options` argument of `steer_room`.
#[derive(Debug, Clone, Default)]
pub struct SteerOptions {
    pub queue_id: Option<String>,
    pub all: Option<bool>,
    pub stop: Option<bool>,
    pub model: Option<String>,
    pub reasoning: Option<String>,
}

/// Steer a live room: stop the in-progress model reply and have the server
/// re-answer after the normal debounce window. Any member may steer. `queue_id`
/// releases just that one queued row into the transcript first (per-item steer);
/// `all` flushes the whole queue in FIFO order (steer-all). Released rows behave
/// like idle sends: the model does NOT reply immediately.
/// `stop` cancels the current reply without scheduling a new one.
pub async fn steer_room(
    authorization: &CredentialsOrApiKey,
    target: &ChatTarget,
    options: SteerOptions,
) -> Result<()> {
    let mut body = Map::new();
    insert(&mut body, "queueId", options.queue_id.map(Value::from));
    insert(&mut body, "all", options.all.map(Value::from));
    insert(&mut body, "stop", options.stop.map(Value::from));
    insert(&mut body, "model", options.model.map(Value::from));
    insert(&mut body, "reasoning", options.reasoning.map(Value::from));
    let request = client()
        .post(format!("{}/chat/live/steer", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    let response = target_headers(request, target).json(&body).send().await?;
    ok(response).await?;
    Ok(())
}

/// Serialize a transcript for the seed body: online FILE parts are path /
/// accessCode refs only. Offline files are uploaded to tmp/ first.
pub(crate) async fn serialize_transcript(messages: &[Content]) -> Result<Vec<Value>> {
    let mut out = Vec::with_capacity(messages.len());
    for message in messages {
        let mut parts = Vec::with_capacity(message.parts.len());
        for part in &message.parts {
            match part {
                Part::File(part) if !part.file.online() => {
                    let file = &part.file;
                    let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
                    let bytes = file.clone().download(false, None).await?;
                    let owner = match &file.authorization {
                        DriveAuthorization::Path { authorization, .. }
                        | DriveAuthorization::AccessCode { authorization, .. }
                        | DriveAuthorization::Repository { authorization, .. } => {
                            authorization.clone()
                        }
                    };
                    let mut ready = drive::from_bytes(
                        owner,
                        &dest,
                        &file.content_type,
                        bytes,
                        FileDates::default(),
                    );
                    ready.upload(None).await?;
                    parts.push(file_ref(&ready));
                }
                part => parts.push(part.wire()),
            }
        }
        let mut wire = Map::new();
        wire.insert("role".to_string(), serde_json::to_value(message.role)?);
        wire.insert("parts".to_string(), Value::Array(parts));
        insert(
            &mut wire,
            "author",
            message
                .author
                .as_ref()
                .map(serde_json::to_value)
                .transpose()?,
        );
        insert(
            &mut wire,
            "model",
            message.model.map(|model| Value::from(model.as_str())),
        );
        out.push(Value::Object(wire));
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::AppendResult;
    use serde_json::json;

    #[test]
    fn append_results_say_whether_the_send_queued() {
        assert_eq!(
            AppendResult::from_json(&json!({ "queued": false, "id": "42" })),
            AppendResult::Sent {
                id: Some("42".to_string())
            }
        );
        assert_eq!(
            AppendResult::from_json(&json!({ "queued": true, "queueId": "7" })),
            AppendResult::Queued {
                queue_id: Some("7".to_string())
            }
        );
        assert_eq!(
            AppendResult::from_json(&json!({})),
            AppendResult::Sent { id: None }
        );
    }
}