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