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