Skip to main content

fauna_api/parrot/
share.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use super::generative::{Content, File as FilePart, Function, Part};
6use super::room::RoomMessage;
7use crate::authentification::{Credentials, CredentialsOrApiKey, Profile};
8use crate::billing::PageQuery;
9use crate::drive::{self, DriveAuthorization};
10use crate::error::Result;
11use crate::http::{client, ok};
12
13/// Address a chat's live room by a redeemable access code or by its reference,
14/// `parrot:chat:{chatId}`.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ChatTarget {
17    Code { code: String },
18    Reference { reference: String },
19}
20
21/// `{ chatId, groupId }` in the TypeScript SDK.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct MovedChat {
25    pub chat_id: String,
26    pub group_id: String,
27}
28
29pub async fn move_chat_to_group(
30    credentials: &Credentials,
31    chat_id: &str,
32    group_id: &str,
33) -> Result<MovedChat> {
34    let response = client()
35        .post(format!("{}/chat/move", super::get_url()))
36        .header("Authorization", format!("Token {}", credentials.token))
37        .json(&json!({ "chatId": chat_id, "groupId": group_id }))
38        .send()
39        .await?;
40    Ok(ok(response).await?.json().await?)
41}
42
43/// The `options` argument of `open_room`.
44#[derive(Debug, Clone, Default)]
45pub struct OpenRoomOptions {
46    pub share: Option<bool>,
47    pub write: Option<bool>,
48}
49
50/// `{ reference, roomId, code? }` in the TypeScript SDK.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct OpenedRoom {
54    pub reference: String,
55    pub room_id: String,
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub code: Option<String>,
58}
59
60/// Host a chat's live room server-side (`parrot:chat:{chatId}`, billed to the
61/// chat's balance-holder). `share: true` also mints an access code; people who
62/// join with it read along, and with `write: true` they can send too (replies to
63/// them run without the chat's repository and memories). Returns the room's
64/// `reference` (+ `code` when shared).
65pub async fn open_room(
66    authorization: &CredentialsOrApiKey,
67    chat_id: &str,
68    options: OpenRoomOptions,
69) -> Result<OpenedRoom> {
70    let mut body = Map::new();
71    body.insert("chatId".to_string(), Value::from(chat_id));
72    insert(&mut body, "share", options.share.map(Value::from));
73    insert(&mut body, "write", options.write.map(Value::from));
74    let response = client()
75        .post(format!("{}/chat/live/open", super::get_url()))
76        .header(
77            "Authorization",
78            match authorization {
79                CredentialsOrApiKey::Credentials(credentials) => {
80                    format!("Token {}", credentials.token)
81                }
82                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
83            },
84        )
85        .json(&body)
86        .send()
87        .await?;
88    let json: Value = ok(response).await?.json().await?;
89    Ok(OpenedRoom {
90        reference: text(&json["reference"]),
91        room_id: text(&json["roomId"]),
92        code: json["code"].as_str().map(str::to_string),
93    })
94}
95
96fn insert(body: &mut Map<String, Value>, key: &str, value: Option<Value>) {
97    if let Some(value) = value {
98        body.insert(key.to_string(), value);
99    }
100}
101
102fn text(value: &Value) -> String {
103    match value {
104        Value::String(value) => value.clone(),
105        Value::Null => String::new(),
106        value => value.to_string(),
107    }
108}
109
110/// A room message's parts, FILE parts opened the way `RoomMessage.fromJSON` opens them.
111pub(crate) fn room_parts(
112    parts: &Value,
113    authorization: &CredentialsOrApiKey,
114    target: &ChatTarget,
115) -> Vec<Part> {
116    parts
117        .as_array()
118        .into_iter()
119        .flatten()
120        .filter_map(|part| {
121            if part["type"] != "FILE" {
122                return Part::from_json(part);
123            }
124            let mut meta = part.clone();
125            meta["name"] = Value::from(part["name"].as_str().unwrap_or("file"));
126            meta["contentType"] = Value::from(
127                part["contentType"]
128                    .as_str()
129                    .unwrap_or("application/octet-stream"),
130            );
131            let nonempty = |key: &str| part[key].as_str().filter(|value| !value.is_empty());
132            let authorization = authorization.clone();
133            let file_authorization = if let Some(access_code) = nonempty("accessCode") {
134                DriveAuthorization::AccessCode {
135                    authorization,
136                    access_code: access_code.to_string(),
137                }
138            } else if let Some(path) = nonempty("path") {
139                DriveAuthorization::Path {
140                    authorization,
141                    path: path.to_string(),
142                    group: part["group"].as_str().map(str::to_string),
143                }
144            } else if let ChatTarget::Code { code } = target {
145                DriveAuthorization::AccessCode {
146                    authorization,
147                    access_code: code.clone(),
148                }
149            } else if let Some(reference) = nonempty("ref") {
150                DriveAuthorization::Path {
151                    authorization,
152                    path: reference.to_string(),
153                    group: None,
154                }
155            } else {
156                DriveAuthorization::AccessCode {
157                    authorization,
158                    access_code: String::new(),
159                }
160            };
161            Some(Part::File(FilePart {
162                file: drive::File::from_json(&meta, file_authorization),
163            }))
164        })
165        .collect()
166}
167
168fn target_headers(
169    request: reqwest::RequestBuilder,
170    target: &ChatTarget,
171) -> reqwest::RequestBuilder {
172    match target {
173        ChatTarget::Code { code } => request.header("Access-Code", code),
174        ChatTarget::Reference { reference } => request.header("Server", reference),
175    }
176}
177
178/// Page older room transcript messages, newest first. `cursor` is how many
179/// messages to skip from the newest.
180pub async fn page_messages(
181    authorization: &CredentialsOrApiKey,
182    target: &ChatTarget,
183    query: PageQuery,
184) -> Result<Vec<RoomMessage>> {
185    let request = client()
186        .get(format!(
187            "{}/chat/live/messages?cursor={}&max={}",
188            super::get_url(),
189            query.cursor,
190            query.max
191        ))
192        .header(
193            "Authorization",
194            match authorization {
195                CredentialsOrApiKey::Credentials(credentials) => {
196                    format!("Token {}", credentials.token)
197                }
198                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
199            },
200        );
201    let response = target_headers(request, target).send().await?;
202    let json: Value = ok(response).await?.json().await?;
203    Ok(json
204        .as_array()
205        .into_iter()
206        .flatten()
207        .map(|message| RoomMessage::from_json(message, authorization, target))
208        .collect())
209}
210
211/// Result of appending to a live room: either the durable transcript row (when
212/// the room was idle) or a queued buffer row (when the model was mid-reply).
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub enum AppendResult {
215    Sent { id: Option<String> },
216    Queued { queue_id: Option<String> },
217}
218
219impl AppendResult {
220    pub(crate) fn from_json(json: &Value) -> AppendResult {
221        if json["queued"] == true {
222            AppendResult::Queued {
223                queue_id: json["queueId"].as_str().map(str::to_string),
224            }
225        } else {
226            AppendResult::Sent {
227                id: json["id"].as_str().map(str::to_string),
228            }
229        }
230    }
231}
232
233/// `Function | Function[]` in the TypeScript SDK: a list is available, a single
234/// one forces that tool.
235#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
236#[serde(untagged)]
237#[allow(clippy::large_enum_variant)]
238pub enum FunctionOrFunctions {
239    Function(Function),
240    Functions(Vec<Function>),
241}
242
243/// The `options` argument of `append_room_message`.
244#[derive(Debug, Clone, Default)]
245pub struct AppendOptions {
246    pub reply_to: Option<String>,
247    pub model: Option<String>,
248    pub reasoning: Option<String>,
249    /// The sender's IANA time zone (`America/New_York`): the reply reads today's date and time in it.
250    pub time_zone: Option<String>,
251    /// Function schemas (array = available; singular = force that tool).
252    pub tools: Option<FunctionOrFunctions>,
253    /// The sending page's presence id, required with `tools`: only that page runs them.
254    pub seat: Option<String>,
255}
256
257/// Append one message to a live room's single transcript. Any member may append;
258/// USER messages are attributed to the caller and nudge the server's debounced
259/// model reply. If the room is currently replying the server BUFFERS the send
260/// into the shared queue (`Queued { queue_id }`); it drains FIFO when the
261/// reply finishes. Otherwise it lands in the transcript (`Sent { id }`).
262/// File parts are already-online Drive refs (path / accessCode); the body is JSON.
263pub async fn append_room_message(
264    authorization: &CredentialsOrApiKey,
265    target: &ChatTarget,
266    message: &Content,
267    options: AppendOptions,
268) -> Result<AppendResult> {
269    let serialized_parts: Vec<Value> = message.parts.iter().map(Part::wire).collect();
270
271    let mut body = Map::new();
272    body.insert("role".to_string(), serde_json::to_value(message.role)?);
273    body.insert("parts".to_string(), Value::Array(serialized_parts));
274    insert(&mut body, "replyTo", options.reply_to.map(Value::from));
275    insert(&mut body, "model", options.model.map(Value::from));
276    insert(&mut body, "reasoning", options.reasoning.map(Value::from));
277    insert(&mut body, "timeZone", options.time_zone.map(Value::from));
278    insert(
279        &mut body,
280        "tools",
281        options.tools.map(serde_json::to_value).transpose()?,
282    );
283    insert(&mut body, "seat", options.seat.map(Value::from));
284
285    let request = client()
286        .post(format!("{}/chat/live/append", super::get_url()))
287        .header(
288            "Authorization",
289            match authorization {
290                CredentialsOrApiKey::Credentials(credentials) => {
291                    format!("Token {}", credentials.token)
292                }
293                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
294            },
295        );
296    let response = target_headers(request, target).json(&body).send().await?;
297    let response = ok(response).await?;
298    let json: Value = response.json().await.unwrap_or(Value::Null);
299    Ok(AppendResult::from_json(&json))
300}
301
302/// A file in a chat: one a person attached, or one Parrot opened.
303#[derive(Debug, Clone)]
304pub struct Attachment {
305    pub file: drive::File,
306    /// The chat it's in and its name in the chat folder, so a file room can let chat members edit it.
307    pub chat: String,
308    pub r#ref: String,
309    /// Position of the message it came in; unset while the reply attaching it is still being written.
310    pub message: Option<u32>,
311    pub author: Option<Profile>,
312    pub created_at: DateTime<Utc>,
313}
314
315impl Attachment {
316    pub fn from_json(json: &Value, authorization: &CredentialsOrApiKey) -> Attachment {
317        let name = json["name"]
318            .as_str()
319            .or_else(|| json["ref"].as_str())
320            .unwrap_or("file");
321        let meta = json!({
322            "name": name,
323            "contentType": json["contentType"].as_str().unwrap_or("application/octet-stream"),
324            "contentLength": json["contentLength"].as_f64().unwrap_or_default(),
325        });
326        Attachment {
327            file: drive::File::from_json(
328                &meta,
329                DriveAuthorization::AccessCode {
330                    authorization: authorization.clone(),
331                    access_code: text(&json["accessCode"]),
332                },
333            ),
334            chat: text(&json["chat"]),
335            r#ref: text(&json["ref"]),
336            message: json["message"].as_f64().map(|message| message as u32),
337            author: if json["author"].is_object() {
338                serde_json::from_value(json["author"].clone()).ok()
339            } else {
340                None
341            },
342            created_at: crate::tickets::parse_date(&json["created"]).unwrap_or_else(Utc::now),
343        }
344    }
345}
346
347/// Every file in the chat behind a live room, newest first.
348pub async fn list_room_attachments(
349    authorization: &CredentialsOrApiKey,
350    target: &ChatTarget,
351) -> Result<Vec<Attachment>> {
352    let request = client()
353        .get(format!("{}/chat/live/attachments", super::get_url()))
354        .header(
355            "Authorization",
356            match authorization {
357                CredentialsOrApiKey::Credentials(credentials) => {
358                    format!("Token {}", credentials.token)
359                }
360                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
361            },
362        );
363    let response = target_headers(request, target).send().await?;
364    let json: Value = ok(response).await?.json().await?;
365    Ok(json
366        .as_array()
367        .into_iter()
368        .flatten()
369        .map(|row| Attachment::from_json(row, authorization))
370        .collect())
371}
372
373/// Attach a repository to the chat behind a live room, or detach it with None.
374/// The repository must be the chat owner's; only the chat's members may change it.
375pub async fn set_room_repository(
376    authorization: &CredentialsOrApiKey,
377    target: &ChatTarget,
378    repository: Option<u64>,
379) -> Result<()> {
380    let request = client()
381        .post(format!("{}/chat/repository", super::get_url()))
382        .header(
383            "Authorization",
384            match authorization {
385                CredentialsOrApiKey::Credentials(credentials) => {
386                    format!("Token {}", credentials.token)
387                }
388                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
389            },
390        );
391    let response = target_headers(request, target)
392        .json(&json!({ "repository": repository }))
393        .send()
394        .await?;
395    ok(response).await?;
396    Ok(())
397}
398
399/// Remove a queued (buffered) message from a live room. The message was buffered
400/// while the model was mid-reply and never entered the transcript, so this is not
401/// an unsend: the server just drops the queue row and fans it out to every member.
402pub async fn unqueue_room_message(
403    authorization: &CredentialsOrApiKey,
404    target: &ChatTarget,
405    queue_id: &str,
406) -> Result<()> {
407    let request = client()
408        .post(format!("{}/chat/live/unqueue", super::get_url()))
409        .header(
410            "Authorization",
411            match authorization {
412                CredentialsOrApiKey::Credentials(credentials) => {
413                    format!("Token {}", credentials.token)
414                }
415                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
416            },
417        );
418    let response = target_headers(request, target)
419        .json(&json!({ "queueId": queue_id }))
420        .send()
421        .await?;
422    ok(response).await?;
423    Ok(())
424}
425
426/// The `options` argument of `steer_room`.
427#[derive(Debug, Clone, Default)]
428pub struct SteerOptions {
429    pub queue_id: Option<String>,
430    pub all: Option<bool>,
431    pub stop: Option<bool>,
432    pub model: Option<String>,
433    pub reasoning: Option<String>,
434    pub time_zone: Option<String>,
435}
436
437/// Steer a live room: stop the in-progress model reply and have the server
438/// re-answer after the normal debounce window. Any member may steer. `queue_id`
439/// releases just that one queued row into the transcript first (per-item steer);
440/// `all` flushes the whole queue in FIFO order (steer-all). Released rows behave
441/// like idle sends: the model does NOT reply immediately.
442/// `stop` cancels the current reply without scheduling a new one.
443pub async fn steer_room(
444    authorization: &CredentialsOrApiKey,
445    target: &ChatTarget,
446    options: SteerOptions,
447) -> Result<()> {
448    let mut body = Map::new();
449    insert(&mut body, "queueId", options.queue_id.map(Value::from));
450    insert(&mut body, "all", options.all.map(Value::from));
451    insert(&mut body, "stop", options.stop.map(Value::from));
452    insert(&mut body, "model", options.model.map(Value::from));
453    insert(&mut body, "reasoning", options.reasoning.map(Value::from));
454    insert(&mut body, "timeZone", options.time_zone.map(Value::from));
455    let request = client()
456        .post(format!("{}/chat/live/steer", super::get_url()))
457        .header(
458            "Authorization",
459            match authorization {
460                CredentialsOrApiKey::Credentials(credentials) => {
461                    format!("Token {}", credentials.token)
462                }
463                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
464            },
465        );
466    let response = target_headers(request, target).json(&body).send().await?;
467    ok(response).await?;
468    Ok(())
469}
470
471#[cfg(test)]
472mod tests {
473    use super::AppendResult;
474    use serde_json::json;
475
476    #[test]
477    fn append_results_say_whether_the_send_queued() {
478        assert_eq!(
479            AppendResult::from_json(&json!({ "queued": false, "id": "42" })),
480            AppendResult::Sent {
481                id: Some("42".to_string())
482            }
483        );
484        assert_eq!(
485            AppendResult::from_json(&json!({ "queued": true, "queueId": "7" })),
486            AppendResult::Queued {
487                queue_id: Some("7".to_string())
488            }
489        );
490        assert_eq!(
491            AppendResult::from_json(&json!({})),
492            AppendResult::Sent { id: None }
493        );
494    }
495}