fauna-api 1.0.861

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
use std::sync::Arc;

use chrono::SecondsFormat;
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use super::generative::{Content, File as FilePart, Part, file_ref};
use super::room::{ChatRoom, RoomHooks, connect_room};
use super::share::{ChatTarget, OpenRoomOptions, open_room};
use crate::authentification::CredentialsOrApiKey;
use crate::billing::PageQuery;
use crate::drive::{self, DriveAuthorization, FileDates};
use crate::error::Result;
use crate::groups::Group;
use crate::http::{client, ok};
use crate::shared::server::Presence;
use crate::termite::versioning::Repository;

/// The `options` argument of `open_chat`.
#[derive(Default)]
pub struct OpenChatOptions {
    pub share: Option<bool>,
    pub hooks: Option<Arc<dyn RoomHooks>>,
}

/// What `open_chat` resolves to: `{ room, self, reference, code? }` in the
/// TypeScript SDK, with `self` as `me`.
#[derive(Clone)]
pub struct OpenedChat {
    pub room: ChatRoom,
    pub me: Presence,
    pub reference: String,
    pub code: Option<String>,
}

/// Open a chat as a live room: host it server-side, then connect
/// (`parrot:chat:{chatId}`, billed to the chat's balance-holder). `share: true`
/// also mints an access code others can redeem. Returns the connected
/// `ChatRoom`, the caller's `Presence`, the room `reference`, and the access
/// `code` when shared.
pub async fn open_chat(
    authorization: &CredentialsOrApiKey,
    chat_id: &str,
    options: OpenChatOptions,
) -> Result<OpenedChat> {
    let opened = open_room(
        authorization,
        chat_id,
        OpenRoomOptions {
            share: options.share,
            write: None,
        },
    )
    .await?;
    let target = match &opened.code {
        Some(code) if !code.is_empty() => ChatTarget::Code { code: code.clone() },
        _ => ChatTarget::Reference {
            reference: opened.reference.clone(),
        },
    };
    let (room, me) = connect_room(authorization, &target, options.hooks).await?;
    Ok(OpenedChat {
        room,
        me,
        reference: opened.reference,
        code: opened.code,
    })
}

/// The `options` argument of `create_chat`.
#[derive(Debug, Clone, Default)]
pub struct CreateChatOptions {
    /// People only for good: sends never start a model reply.
    pub human: Option<bool>,
    /// Temporary for good: never listed, its replies read only the newest turns
    /// that fit, nothing in it becomes a memory, and it's deleted by you or after
    /// a day without a message.
    pub temporary: Option<bool>,
    /// Instructs every model reply in the chat.
    pub system_prompt: Option<String>,
    /// Only you can delete it or move it to another group; it still goes away
    /// with its group.
    pub locked: Option<bool>,
    /// The Termite repository Parrot works in during replies: yours for a
    /// personal chat, the group's for a group chat.
    pub repository: Option<Repository>,
}

/// Create a chat, owned by the caller or by `group`. `human` makes it a people
/// only chat for good: sends never start a model reply. `temporary` makes it
/// temporary for good; share it like any chat. `system_prompt`
/// instructs every model reply in the chat. `locked` lets only you delete it or
/// move it to another group. `repository` is a Termite repository Parrot works
/// in during replies. `name` defaults to `New Chat`.
pub async fn create_chat(
    authorization: &CredentialsOrApiKey,
    name: Option<&str>,
    group: Option<&Group>,
    options: CreateChatOptions,
) -> Result<String> {
    let mut request = client()
        .post(format!("{}/chat/create", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({
            "name": name.unwrap_or("New Chat"),
            "human": options.human == Some(true),
            "temporary": options.temporary == Some(true),
            "systemPrompt": options.system_prompt,
            "locked": options.locked == Some(true),
            "repository": options.repository.as_ref().map(|repository| repository.id),
        }))
        .send()
        .await?;
    let json: serde_json::Value = ok(response).await?.json().await?;
    Ok(json["id"].as_str().unwrap_or_default().to_string())
}

pub async fn delete_chat(
    authorization: &CredentialsOrApiKey,
    id: &str,
    group: Option<&Group>,
) -> Result<()> {
    let mut request = client()
        .post(format!("{}/chat/delete", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.json(&json!({ "id": id })).send().await?;
    ok(response).await?;
    Ok(())
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatSummary {
    pub id: String,
    pub name: String,
    pub principal_id: String,
    /// People only: sends never start a model reply.
    pub human: bool,
    /// Only whoever made it can delete it or move it.
    pub locked: bool,
    /// The repository Parrot works in, by id.
    pub repository: Option<u64>,
    /// Milliseconds since the epoch.
    pub created: i64,
    /// Milliseconds since the epoch.
    pub updated: i64,
    #[serde(skip_serializing)]
    pub last: Option<Content>,
    /// Messages the caller hasn't read. A person and each of their API keys keep
    /// their own place; one that never marked the chat sees only its newest 20.
    pub unread: u32,
}

impl ChatSummary {
    pub fn from_json(json: &Value) -> ChatSummary {
        let text = |value: &Value| match value {
            Value::String(text) => text.clone(),
            Value::Null => String::new(),
            value => value.to_string(),
        };
        ChatSummary {
            id: text(&json["id"]),
            name: text(&json["name"]),
            principal_id: text(&json["principalId"]),
            human: json["human"] == true,
            locked: json["locked"] == true,
            repository: json["repository"].as_u64().filter(|id| *id > 0),
            created: json["created"].as_f64().unwrap_or_default() as i64,
            updated: json["updated"].as_f64().unwrap_or_default() as i64,
            last: json["last"]
                .is_object()
                .then(|| Content::from_json(&json["last"], None)),
            unread: json["unread"].as_u64().unwrap_or_default() as u32,
        }
    }
}

impl<'de> Deserialize<'de> for ChatSummary {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        Ok(ChatSummary::from_json(&Value::deserialize(deserializer)?))
    }
}

pub async fn list_chats(
    authorization: &CredentialsOrApiKey,
    group: Option<&Group>,
) -> Result<Vec<ChatSummary>> {
    let mut request = client()
        .get(format!("{}/chat/all", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request.send().await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().map(ChatSummary::from_json).collect())
}

pub async fn rename_chat(
    authorization: &CredentialsOrApiKey,
    id: &str,
    name: &str,
    group: Option<&Group>,
) -> Result<()> {
    let mut request = client()
        .post(format!("{}/chat/rename", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "id": id, "name": name }))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

/// Mark a chat read for the caller, up to `position` (the next unread one) or
/// all of it. Signed in with an API key, the key keeps its own place, apart from
/// its person. Sending a message reads the chat for its sender. Returns what's
/// left unread.
pub async fn mark_read(
    authorization: &CredentialsOrApiKey,
    id: &str,
    position: Option<u32>,
    group: Option<&Group>,
) -> Result<u32> {
    let mut request = client()
        .post(format!("{}/chat/mark-read", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "id": id, "position": position }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(json["unread"].as_u64().unwrap_or_default() as u32)
}

/// The rest of a draft reply in a chat, from its newest messages and how you write to the
/// same people in its owner's other chats. Empty when the draft needs nothing more. It streams
/// as the model writes it: `on_text` gets the rest so far each time more arrives.
pub async fn autocomplete(
    authorization: &CredentialsOrApiKey,
    id: &str,
    text: &str,
    group: Option<&Group>,
    on_text: Option<impl Fn(&str)>,
) -> Result<String> {
    let mut request = client()
        .post(format!("{}/chat/autocomplete", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "id": id, "text": text }))
        .send()
        .await?;
    let response = ok(response).await?;

    let mut pending = Vec::new();
    let mut rest = String::new();
    let mut body = response.bytes_stream();
    while let Some(chunk) = body.next().await {
        pending.extend_from_slice(&chunk?);
        while let Some(end) = pending.windows(2).position(|pair| pair == b"\n\n") {
            let event: Vec<u8> = pending.drain(..end + 2).collect();
            for line in String::from_utf8_lossy(&event[..end]).lines() {
                if let Some(data) = line.strip_prefix("data: ") {
                    rest.push_str(&serde_json::from_str::<String>(data)?);
                }
            }
            if let Some(on_text) = &on_text {
                on_text(&rest);
            }
        }
    }
    Ok(rest)
}

fn hydrate_file_part(
    authorization: &CredentialsOrApiKey,
    part: &Value,
    group: Option<&Group>,
) -> Part {
    let name = part["name"].as_str().unwrap_or("file");
    let content_type = part["contentType"]
        .as_str()
        .unwrap_or("application/octet-stream");
    let mut meta = part.clone();
    meta["name"] = Value::from(name);
    meta["contentType"] = Value::from(content_type);
    if let Some(access_code) = part["accessCode"].as_str().filter(|code| !code.is_empty()) {
        return Part::File(FilePart {
            file: drive::File::from_json(
                &meta,
                DriveAuthorization::AccessCode {
                    authorization: authorization.clone(),
                    access_code: access_code.to_string(),
                },
            ),
        });
    }
    if let Some(path) = part["path"].as_str().filter(|path| !path.is_empty()) {
        return Part::File(FilePart {
            file: drive::File::from_json(
                &meta,
                DriveAuthorization::Path {
                    authorization: authorization.clone(),
                    path: path.to_string(),
                    group: part["group"]
                        .as_str()
                        .map(str::to_string)
                        .or_else(|| group.map(|group| group.id.clone())),
                },
            ),
        });
    }
    Part::File(FilePart {
        file: drive::from_bytes(
            authorization.clone(),
            name,
            content_type,
            Vec::new(),
            FileDates::default(),
        ),
    })
}

/// One page of a chat, newest first.
pub async fn read_chat(
    authorization: &CredentialsOrApiKey,
    id: &str,
    group: Option<&Group>,
    query: PageQuery,
) -> Result<Vec<Content>> {
    let mut request = client()
        .post(format!("{}/chat/read", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "id": id, "cursor": query.cursor, "max": query.max }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;

    let file = |part: &Value| hydrate_file_part(authorization, part, group);
    let messages = json
        .as_array()
        .into_iter()
        .flatten()
        .map(|message| Content::from_json(message, Some(&file)))
        .collect();
    Ok(messages)
}

pub async fn write_chat(
    authorization: &CredentialsOrApiKey,
    id: &str,
    messages: &[Content],
    group: Option<&Group>,
) -> Result<()> {
    let mut serialized_messages = Vec::with_capacity(messages.len());
    for message in messages {
        let mut serialized_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 mut ready = drive::from_bytes(
                        authorization.clone(),
                        &dest,
                        &file.content_type,
                        bytes,
                        FileDates::default(),
                    );
                    ready.upload(None).await?;
                    serialized_parts.push(file_ref(&ready));
                }
                part => serialized_parts.push(part.wire()),
            }
        }

        let mut wire = Map::new();
        wire.insert("parts".to_string(), Value::Array(serialized_parts));
        wire.insert("role".to_string(), serde_json::to_value(message.role)?);
        if let Some(author) = &message.author {
            wire.insert("author".to_string(), serde_json::to_value(author)?);
        }
        if let Some(model) = &message.model {
            wire.insert("model".to_string(), Value::from(model.as_str()));
        }
        wire.insert(
            "createdAt".to_string(),
            Value::from(
                message
                    .created_at
                    .to_rfc3339_opts(SecondsFormat::Millis, true),
            ),
        );
        serialized_messages.push(Value::Object(wire));
    }

    let mut request = client()
        .post(format!("{}/chat/write", super::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(group) = group {
        request = request.header("Group", &group.id);
    }
    let response = request
        .json(&json!({ "id": id, "messages": serialized_messages }))
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}