1use std::sync::Arc;
2
3use chrono::SecondsFormat;
4use futures_util::StreamExt;
5use serde::{Deserialize, Serialize};
6use serde_json::{Map, Value, json};
7
8use super::generative::{Content, File as FilePart, Part, file_ref};
9use super::room::{ChatRoom, RoomHooks, connect_room};
10use super::share::{ChatTarget, OpenRoomOptions, open_room};
11use crate::authentification::CredentialsOrApiKey;
12use crate::billing::PageQuery;
13use crate::cicada::inboxes::Inbox;
14use crate::drive::{self, DriveAuthorization, FileDates};
15use crate::error::Result;
16use crate::groups::Group;
17use crate::http::{client, ok};
18use crate::shared::server::Presence;
19use crate::termite::versioning::Repository;
20
21#[derive(Default)]
23pub struct OpenChatOptions {
24 pub share: Option<bool>,
25 pub hooks: Option<Arc<dyn RoomHooks>>,
26}
27
28#[derive(Clone)]
31pub struct OpenedChat {
32 pub room: ChatRoom,
33 pub me: Presence,
34 pub reference: String,
35 pub code: Option<String>,
36}
37
38pub async fn open_chat(
44 authorization: &CredentialsOrApiKey,
45 chat_id: &str,
46 options: OpenChatOptions,
47) -> Result<OpenedChat> {
48 let opened = open_room(
49 authorization,
50 chat_id,
51 OpenRoomOptions {
52 share: options.share,
53 },
54 )
55 .await?;
56 let target = match &opened.code {
57 Some(code) if !code.is_empty() => ChatTarget::Code { code: code.clone() },
58 _ => ChatTarget::Reference {
59 reference: opened.reference.clone(),
60 },
61 };
62 let (room, me) = connect_room(authorization, &target, options.hooks).await?;
63 Ok(OpenedChat {
64 room,
65 me,
66 reference: opened.reference,
67 code: opened.code,
68 })
69}
70
71#[derive(Debug, Clone, Default)]
73pub struct CreateChatOptions {
74 pub human: Option<bool>,
76 pub temporary: Option<bool>,
80 pub system_prompt: Option<String>,
82 pub locked: Option<bool>,
85 pub repository: Option<Repository>,
88 pub inbox: Option<Inbox>,
91}
92
93pub async fn create_chat(
103 authorization: &CredentialsOrApiKey,
104 name: Option<&str>,
105 group: Option<&Group>,
106 options: CreateChatOptions,
107) -> Result<String> {
108 let mut request = client()
109 .post(format!("{}/chat/create", super::get_url()))
110 .header(
111 "Authorization",
112 match authorization {
113 CredentialsOrApiKey::Credentials(credentials) => {
114 format!("Token {}", credentials.token)
115 }
116 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
117 },
118 );
119 if let Some(group) = group {
120 request = request.header("Group", &group.id);
121 }
122 let response = request
123 .json(&json!({
124 "name": name.unwrap_or_default(),
125 "human": options.human == Some(true),
126 "temporary": options.temporary == Some(true),
127 "systemPrompt": options.system_prompt,
128 "locked": options.locked == Some(true),
129 "repository": options.repository.as_ref().map(|repository| repository.id),
130 "inbox": options.inbox.as_ref().map(|inbox| inbox.id.as_str()),
131 }))
132 .send()
133 .await?;
134 let json: serde_json::Value = ok(response).await?.json().await?;
135 Ok(json["id"].as_str().unwrap_or_default().to_string())
136}
137
138pub async fn delete_chat(
139 authorization: &CredentialsOrApiKey,
140 id: &str,
141 group: Option<&Group>,
142) -> Result<()> {
143 let mut request = client()
144 .post(format!("{}/chat/delete", super::get_url()))
145 .header(
146 "Authorization",
147 match authorization {
148 CredentialsOrApiKey::Credentials(credentials) => {
149 format!("Token {}", credentials.token)
150 }
151 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
152 },
153 );
154 if let Some(group) = group {
155 request = request.header("Group", &group.id);
156 }
157 let response = request.json(&json!({ "id": id })).send().await?;
158 ok(response).await?;
159 Ok(())
160}
161
162#[derive(Debug, Clone, Serialize)]
163#[serde(rename_all = "camelCase")]
164pub struct ChatSummary {
165 pub id: String,
166 pub name: String,
167 pub principal_id: String,
168 pub human: bool,
170 pub locked: bool,
172 pub repository: Option<u64>,
174 pub created: i64,
176 pub updated: i64,
178 #[serde(skip_serializing)]
179 pub last: Option<Content>,
180 pub unread: u32,
183}
184
185impl ChatSummary {
186 pub fn from_json(json: &Value) -> ChatSummary {
187 let text = |value: &Value| match value {
188 Value::String(text) => text.clone(),
189 Value::Null => String::new(),
190 value => value.to_string(),
191 };
192 ChatSummary {
193 id: text(&json["id"]),
194 name: text(&json["name"]),
195 principal_id: text(&json["principalId"]),
196 human: json["human"] == true,
197 locked: json["locked"] == true,
198 repository: json["repository"].as_u64().filter(|id| *id > 0),
199 created: json["created"].as_f64().unwrap_or_default() as i64,
200 updated: json["updated"].as_f64().unwrap_or_default() as i64,
201 last: json["last"]
202 .is_object()
203 .then(|| Content::from_json(&json["last"], None)),
204 unread: json["unread"].as_u64().unwrap_or_default() as u32,
205 }
206 }
207}
208
209impl<'de> Deserialize<'de> for ChatSummary {
210 fn deserialize<D: serde::Deserializer<'de>>(
211 deserializer: D,
212 ) -> std::result::Result<Self, D::Error> {
213 Ok(ChatSummary::from_json(&Value::deserialize(deserializer)?))
214 }
215}
216
217pub async fn list_chats(
218 authorization: &CredentialsOrApiKey,
219 group: Option<&Group>,
220) -> Result<Vec<ChatSummary>> {
221 let mut request = client()
222 .get(format!("{}/chat/all", super::get_url()))
223 .header(
224 "Authorization",
225 match authorization {
226 CredentialsOrApiKey::Credentials(credentials) => {
227 format!("Token {}", credentials.token)
228 }
229 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
230 },
231 );
232 if let Some(group) = group {
233 request = request.header("Group", &group.id);
234 }
235 let response = request.send().await?;
236 let rows: Vec<Value> = ok(response).await?.json().await?;
237 Ok(rows.iter().map(ChatSummary::from_json).collect())
238}
239
240pub async fn rename_chat(
241 authorization: &CredentialsOrApiKey,
242 id: &str,
243 name: &str,
244 group: Option<&Group>,
245) -> Result<()> {
246 let mut request = client()
247 .post(format!("{}/chat/rename", super::get_url()))
248 .header(
249 "Authorization",
250 match authorization {
251 CredentialsOrApiKey::Credentials(credentials) => {
252 format!("Token {}", credentials.token)
253 }
254 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
255 },
256 );
257 if let Some(group) = group {
258 request = request.header("Group", &group.id);
259 }
260 let response = request
261 .json(&json!({ "id": id, "name": name }))
262 .send()
263 .await?;
264 ok(response).await?;
265 Ok(())
266}
267
268pub async fn mark_read(
273 authorization: &CredentialsOrApiKey,
274 id: &str,
275 position: Option<u32>,
276 group: Option<&Group>,
277) -> Result<u32> {
278 let mut request = client()
279 .post(format!("{}/chat/mark-read", super::get_url()))
280 .header(
281 "Authorization",
282 match authorization {
283 CredentialsOrApiKey::Credentials(credentials) => {
284 format!("Token {}", credentials.token)
285 }
286 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
287 },
288 );
289 if let Some(group) = group {
290 request = request.header("Group", &group.id);
291 }
292 let response = request
293 .json(&json!({ "id": id, "position": position }))
294 .send()
295 .await?;
296 let json: Value = ok(response).await?.json().await?;
297 Ok(json["unread"].as_u64().unwrap_or_default() as u32)
298}
299
300pub async fn autocomplete(
304 authorization: &CredentialsOrApiKey,
305 id: &str,
306 text: &str,
307 group: Option<&Group>,
308 on_text: Option<impl Fn(&str)>,
309) -> Result<String> {
310 let mut request = client()
311 .post(format!("{}/chat/autocomplete", super::get_url()))
312 .header(
313 "Authorization",
314 match authorization {
315 CredentialsOrApiKey::Credentials(credentials) => {
316 format!("Token {}", credentials.token)
317 }
318 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
319 },
320 );
321 if let Some(group) = group {
322 request = request.header("Group", &group.id);
323 }
324 let response = request
325 .json(&json!({ "id": id, "text": text }))
326 .send()
327 .await?;
328 let response = ok(response).await?;
329
330 let mut pending = Vec::new();
331 let mut rest = String::new();
332 let mut body = response.bytes_stream();
333 while let Some(chunk) = body.next().await {
334 pending.extend_from_slice(&chunk?);
335 while let Some(end) = pending.windows(2).position(|pair| pair == b"\n\n") {
336 let event: Vec<u8> = pending.drain(..end + 2).collect();
337 for line in String::from_utf8_lossy(&event[..end]).lines() {
338 if let Some(data) = line.strip_prefix("data: ") {
339 rest.push_str(&serde_json::from_str::<String>(data)?);
340 }
341 }
342 if let Some(on_text) = &on_text {
343 on_text(&rest);
344 }
345 }
346 }
347 Ok(rest)
348}
349
350fn hydrate_file_part(
351 authorization: &CredentialsOrApiKey,
352 part: &Value,
353 group: Option<&Group>,
354) -> Part {
355 let name = part["name"].as_str().unwrap_or("file");
356 let content_type = part["contentType"]
357 .as_str()
358 .unwrap_or("application/octet-stream");
359 let mut meta = part.clone();
360 meta["name"] = Value::from(name);
361 meta["contentType"] = Value::from(content_type);
362 if let Some(access_code) = part["accessCode"].as_str().filter(|code| !code.is_empty()) {
363 return Part::File(FilePart {
364 file: drive::File::from_json(
365 &meta,
366 DriveAuthorization::AccessCode {
367 authorization: authorization.clone(),
368 access_code: access_code.to_string(),
369 },
370 ),
371 });
372 }
373 if let Some(path) = part["path"].as_str().filter(|path| !path.is_empty()) {
374 return Part::File(FilePart {
375 file: drive::File::from_json(
376 &meta,
377 DriveAuthorization::Path {
378 authorization: authorization.clone(),
379 path: path.to_string(),
380 group: part["group"]
381 .as_str()
382 .map(str::to_string)
383 .or_else(|| group.map(|group| group.id.clone())),
384 },
385 ),
386 });
387 }
388 Part::File(FilePart {
389 file: drive::from_bytes(
390 authorization.clone(),
391 name,
392 content_type,
393 Vec::new(),
394 FileDates::default(),
395 ),
396 })
397}
398
399pub async fn read_chat(
401 authorization: &CredentialsOrApiKey,
402 id: &str,
403 group: Option<&Group>,
404 query: PageQuery,
405) -> Result<Vec<Content>> {
406 let mut request = client()
407 .post(format!("{}/chat/read", super::get_url()))
408 .header(
409 "Authorization",
410 match authorization {
411 CredentialsOrApiKey::Credentials(credentials) => {
412 format!("Token {}", credentials.token)
413 }
414 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
415 },
416 );
417 if let Some(group) = group {
418 request = request.header("Group", &group.id);
419 }
420 let response = request
421 .json(&json!({ "id": id, "cursor": query.cursor, "max": query.max }))
422 .send()
423 .await?;
424 let json: Value = ok(response).await?.json().await?;
425
426 let file = |part: &Value| hydrate_file_part(authorization, part, group);
427 let messages = json
428 .as_array()
429 .into_iter()
430 .flatten()
431 .map(|message| Content::from_json(message, Some(&file)))
432 .collect();
433 Ok(messages)
434}
435
436pub async fn write_chat(
437 authorization: &CredentialsOrApiKey,
438 id: &str,
439 messages: &[Content],
440 group: Option<&Group>,
441) -> Result<()> {
442 let mut serialized_messages = Vec::with_capacity(messages.len());
443 for message in messages {
444 let mut serialized_parts = Vec::with_capacity(message.parts.len());
445
446 for part in &message.parts {
447 match part {
448 Part::File(part) if !part.file.online() => {
449 let file = &part.file;
450 let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
451 let bytes = file.clone().download(false, None).await?;
452 let mut ready = drive::from_bytes(
453 authorization.clone(),
454 &dest,
455 &file.content_type,
456 bytes,
457 FileDates::default(),
458 );
459 ready.upload(None).await?;
460 serialized_parts.push(file_ref(&ready));
461 }
462 part => serialized_parts.push(part.wire()),
463 }
464 }
465
466 let mut wire = Map::new();
467 wire.insert("parts".to_string(), Value::Array(serialized_parts));
468 wire.insert("role".to_string(), serde_json::to_value(message.role)?);
469 if let Some(author) = &message.author {
470 wire.insert("author".to_string(), serde_json::to_value(author)?);
471 }
472 if let Some(model) = &message.model {
473 wire.insert("model".to_string(), Value::from(model.as_str()));
474 }
475 wire.insert(
476 "createdAt".to_string(),
477 Value::from(
478 message
479 .created_at
480 .to_rfc3339_opts(SecondsFormat::Millis, true),
481 ),
482 );
483 serialized_messages.push(Value::Object(wire));
484 }
485
486 let mut request = client()
487 .post(format!("{}/chat/write", super::get_url()))
488 .header(
489 "Authorization",
490 match authorization {
491 CredentialsOrApiKey::Credentials(credentials) => {
492 format!("Token {}", credentials.token)
493 }
494 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
495 },
496 );
497 if let Some(group) = group {
498 request = request.header("Group", &group.id);
499 }
500 let response = request
501 .json(&json!({ "id": id, "messages": serialized_messages }))
502 .send()
503 .await?;
504 ok(response).await?;
505 Ok(())
506}