Skip to main content

fauna_api/ant/
chat.rs

1use std::collections::{HashMap, VecDeque};
2use std::ops::Deref;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
5
6use chrono::{DateTime, Utc};
7use futures_util::stream::{self, BoxStream};
8use futures_util::{SinkExt, StreamExt};
9use serde::{Deserialize, Serialize};
10use serde_json::{Map, Value, json};
11use tokio::sync::mpsc;
12use tokio_tungstenite::tungstenite::Message;
13
14use super::persona::Identity;
15use crate::authentification::{CredentialsOrApiKey, Profile};
16use crate::drive::{self, FileDates};
17use crate::error::{Error, Result};
18use crate::groups::Group;
19use crate::http::{client, encode, ok, websocket};
20use crate::parrot::agent::Memory;
21use crate::parrot::generative::{Content, Part, StreamEvent, Tool, file_ref};
22use crate::parrot::room::{ChatRoom as ParrotChatRoom, RoomHooks, connect_room};
23use crate::parrot::share::ChatTarget;
24use crate::parrot::socket::answer_tool_call;
25use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
26use crate::termite::versioning::Repository;
27
28/// Messages as an Ant socket takes them: FILE parts as Drive refs (offline files
29/// uploaded to tmp/ first), with their role.
30pub(crate) async fn serialize_messages(
31    authorization: &CredentialsOrApiKey,
32    messages: &[Content],
33) -> Result<Vec<Value>> {
34    let mut out = Vec::with_capacity(messages.len());
35    for message in messages {
36        let mut parts = Vec::with_capacity(message.parts.len());
37        for part in &message.parts {
38            match part {
39                Part::File(part) if !part.file.online() => {
40                    let file = &part.file;
41                    let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
42                    let bytes = file.clone().download(false, None).await?;
43                    let mut ready = drive::from_bytes(
44                        authorization.clone(),
45                        &dest,
46                        &file.content_type,
47                        bytes,
48                        FileDates::default(),
49                    );
50                    ready.upload(None).await?;
51                    parts.push(file_ref(&ready));
52                }
53                part => parts.push(part.wire()),
54            }
55        }
56        out.push(json!({ "parts": parts, "role": message.role }));
57    }
58    Ok(out)
59}
60
61/// A persona's tool calls, answered with the caller's tools; one it doesn't have
62/// comes back declined. Every other frame is a stream event, until done or error.
63pub(crate) async fn agent_stream(
64    url: String,
65    generate: Value,
66    tools: Vec<Tool>,
67) -> Result<BoxStream<'static, StreamEvent>> {
68    let socket = match tokio_tungstenite::connect_async(url.as_str()).await {
69        Ok((socket, _)) => socket,
70        Err(_) => return Err(Error::Message("WebSocket connection failed".to_string())),
71    };
72    let (mut write, read) = socket.split();
73    write.send(Message::text(generate.to_string())).await?;
74    write
75        .send(Message::text(json!({ "event": "start" }).to_string()))
76        .await?;
77    let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
78    tokio::spawn(async move {
79        while let Some(message) = queue.recv().await {
80            if write.send(message).await.is_err() {
81                break;
82            }
83        }
84        let _ = write.close().await;
85    });
86
87    let state = (read, outbox, tools, VecDeque::<StreamEvent>::new(), false);
88    Ok(stream::unfold(
89        state,
90        |(mut read, outbox, tools, mut queue, finished)| async move {
91            if finished {
92                return None;
93            }
94            loop {
95                if let Some(event) = queue.pop_front() {
96                    let finished =
97                        matches!(event, StreamEvent::Done { .. } | StreamEvent::Error { .. });
98                    return Some((event, (read, outbox, tools, queue, finished)));
99                }
100                match read.next().await {
101                    Some(Ok(Message::Text(raw))) => {
102                        let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
103                            continue;
104                        };
105                        if packet["event"] == "tool_call" {
106                            answer_tool_call(
107                                &outbox,
108                                &tools,
109                                packet["id"].as_str().unwrap_or_default().to_string(),
110                                packet["name"].as_str().unwrap_or_default(),
111                                packet["args"].as_object().cloned().unwrap_or_default(),
112                            );
113                            continue;
114                        }
115                        if let Ok(event) = serde_json::from_value::<StreamEvent>(packet) {
116                            queue.push_back(event);
117                        }
118                    }
119                    Some(Ok(Message::Close(_))) | Some(Err(_)) | None => return None,
120                    Some(Ok(_)) => {}
121                }
122            }
123        },
124    )
125    .boxed())
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct ChatLast {
131    #[serde(default)]
132    pub parts: Vec<Value>,
133    pub role: String,
134    #[serde(
135        deserialize_with = "crate::http::deserialize_date",
136        serialize_with = "crate::http::serialize_date"
137    )]
138    pub created_at: DateTime<Utc>,
139    pub position: u32,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub author: Option<Profile>,
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub model: Option<String>,
144}
145
146/// `{ name, id, last }` in the TypeScript SDK: one chat in the list.
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct ChatEntry {
149    pub name: String,
150    pub id: String,
151    #[serde(default)]
152    pub last: Option<ChatLast>,
153}
154
155/// The `opts` argument of the chat calls that take only a group.
156#[derive(Debug, Clone, Default)]
157pub struct GroupOptions {
158    pub group: Option<Group>,
159}
160
161fn authorized(
162    request: reqwest::RequestBuilder,
163    authorization: &CredentialsOrApiKey,
164    group: Option<&Group>,
165) -> reqwest::RequestBuilder {
166    let request = request.header(
167        "Authorization",
168        match authorization {
169            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
170            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
171        },
172    );
173    match group {
174        Some(group) => request.header("Group", &group.id),
175        None => request,
176    }
177}
178
179pub async fn list_chats(
180    authorization: &CredentialsOrApiKey,
181    opts: GroupOptions,
182) -> Result<Vec<ChatEntry>> {
183    let response = authorized(
184        client().get(format!("{}/chats", super::get_url())),
185        authorization,
186        opts.group.as_ref(),
187    )
188    .send()
189    .await?;
190    let rows: Value = ok(response).await?.json().await?;
191    Ok(rows
192        .as_array()
193        .into_iter()
194        .flatten()
195        .filter_map(|row| serde_json::from_value(row.clone()).ok())
196        .collect())
197}
198
199/// The `opts` argument of `create_chat`.
200#[derive(Debug, Clone, Default)]
201pub struct CreateChatOptions {
202    pub group: Option<Group>,
203    pub audience: Option<Vec<String>>,
204    pub repository: Option<Repository>,
205}
206
207/// `{ name, id }` in the TypeScript SDK.
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209pub struct CreatedChat {
210    pub name: String,
211    pub id: String,
212}
213
214/// Create a chat. `repository` (the owner's) is the computer its personas start from.
215pub async fn create_chat(
216    authorization: &CredentialsOrApiKey,
217    name: &str,
218    opts: CreateChatOptions,
219) -> Result<CreatedChat> {
220    let mut body = Map::new();
221    body.insert("name".to_string(), Value::from(name));
222    if let Some(audience) = opts.audience.filter(|audience| !audience.is_empty()) {
223        body.insert("audience".to_string(), json!(audience));
224    }
225    if let Some(repository) = &opts.repository {
226        body.insert("repository".to_string(), Value::from(repository.id));
227    }
228    let response = authorized(
229        client().post(format!("{}/chats", super::get_url())),
230        authorization,
231        opts.group.as_ref(),
232    )
233    .json(&body)
234    .send()
235    .await?;
236    Ok(ok(response).await?.json().await?)
237}
238
239pub async fn delete_chat(
240    authorization: &CredentialsOrApiKey,
241    id: &str,
242    opts: GroupOptions,
243) -> Result<()> {
244    let response = authorized(
245        client().delete(format!("{}/chat", super::get_url())),
246        authorization,
247        opts.group.as_ref(),
248    )
249    .header("Chat", id)
250    .send()
251    .await?;
252    ok(response).await?;
253    Ok(())
254}
255
256/// `{ id, name, groupId, remapped }` in the TypeScript SDK.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(rename_all = "camelCase")]
259pub struct MovedChat {
260    pub id: String,
261    pub name: String,
262    pub group_id: String,
263    pub remapped: bool,
264}
265
266pub async fn move_chat_to_group(
267    authorization: &CredentialsOrApiKey,
268    id: &str,
269    group_id: &str,
270) -> Result<MovedChat> {
271    let response = authorized(
272        client().post(format!("{}/chat/move", super::get_url())),
273        authorization,
274        None,
275    )
276    .header("Chat", id)
277    .json(&json!({ "groupId": group_id }))
278    .send()
279    .await?;
280    Ok(ok(response).await?.json().await?)
281}
282
283pub async fn rename_chat(
284    authorization: &CredentialsOrApiKey,
285    id: &str,
286    name: &str,
287    opts: GroupOptions,
288) -> Result<()> {
289    let response = authorized(
290        client().post(format!("{}/chat/rename", super::get_url())),
291        authorization,
292        opts.group.as_ref(),
293    )
294    .header("Chat", id)
295    .json(&json!({ "name": name }))
296    .send()
297    .await?;
298    ok(response).await?;
299    Ok(())
300}
301
302/// The `opts` argument of `Agent::generate`.
303#[derive(Debug, Clone, Default)]
304pub struct AgentGenerateOptions {
305    pub tools: Option<Vec<Tool>>,
306}
307
308#[derive(Clone)]
309pub struct Agent {
310    room: Room,
311    parent: Weak<AntChatState>,
312    pub id: String,
313    pub persona: Identity,
314    /// A repository picked for this agent, used directly; None when it follows the chat's.
315    pub repository: Option<u64>,
316}
317
318impl Agent {
319    pub fn parent(&self) -> Option<AntChatRoom> {
320        self.parent.upgrade().map(|state| AntChatRoom {
321            room: self.room.clone(),
322            state,
323        })
324    }
325
326    /// Pick a repository for this agent (used directly), or None to follow the chat's again.
327    pub fn set_repository(&self, repository: Option<&Repository>) {
328        self.room.post(&json!({
329            "event": "set-agent-repository",
330            "agentId": self.id,
331            "repository": repository.map(|repository| repository.id),
332        }));
333    }
334
335    fn chat_id(&self) -> String {
336        self.parent().map(|room| room.chat_id()).unwrap_or_default()
337    }
338
339    fn access(&self) -> (Option<Group>, Option<String>) {
340        match self.room.authorization() {
341            Authorization::AccessCode { access_code, .. } => (None, Some(access_code.clone())),
342            Authorization::Server { group, .. } => (
343                group
344                    .as_ref()
345                    .map(|group| Group::from_json(&json!({ "id": group }))),
346                None,
347            ),
348        }
349    }
350
351    pub async fn observe(&self, content: &str) -> Result<Memory> {
352        let (group, access_code) = self.access();
353        observe_agent(
354            self.room.get_authorization(),
355            &self.chat_id(),
356            &self.id,
357            content,
358            AgentOptions { group, access_code },
359        )
360        .await
361    }
362
363    /// Stream a reply as this agent, under the room's own authorization. `tools` answer the persona's calls to them.
364    pub async fn generate(
365        &self,
366        messages: &[Content],
367        opts: AgentGenerateOptions,
368    ) -> Result<BoxStream<'static, StreamEvent>> {
369        let (group, access_code) = self.access();
370        generate_agent(
371            self.room.get_authorization(),
372            &self.chat_id(),
373            &self.id,
374            messages,
375            GenerateOptions {
376                group,
377                access_code,
378                tools: opts.tools,
379            },
380        )
381        .await
382    }
383
384    pub fn to_json(&self) -> Value {
385        json!({ "id": self.id, "persona": self.persona })
386    }
387
388    pub fn from_json(json: &Value, parent: &AntChatRoom) -> Option<Agent> {
389        Some(Agent {
390            room: parent.room.clone(),
391            parent: Arc::downgrade(&parent.state),
392            id: match &json["id"] {
393                Value::String(id) => id.clone(),
394                id => id.to_string(),
395            },
396            persona: serde_json::from_value(json["persona"].clone()).ok()?,
397            repository: json["repository"]
398                .as_f64()
399                .filter(|repository| *repository > 0.0)
400                .map(|repository| repository as u64),
401        })
402    }
403}
404
405type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;
406
407#[derive(Default)]
408struct AntChat {
409    chat_id: String,
410    name: String,
411    agents: HashMap<String, Agent>,
412    repository: Option<u64>,
413    owner: String,
414}
415
416struct AntChatState {
417    chat: Mutex<AntChat>,
418    watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
419    next_watcher: AtomicU64,
420}
421
422fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
423    mutex.lock().unwrap_or_else(PoisonError::into_inner)
424}
425
426/// `{ room, self, chatId }` in the TypeScript SDK, with `self` as `me`.
427#[derive(Clone)]
428pub struct ArchitectChat {
429    pub room: ParrotChatRoom,
430    pub me: Presence,
431    pub chat_id: String,
432}
433
434/// The `opts` argument of `AntChatRoom::connect`. `server` names the room when it
435/// isn't the chat's id.
436#[derive(Default)]
437pub struct ConnectOptions {
438    pub group: Option<Group>,
439    pub hooks: Option<Arc<dyn Hooks>>,
440    pub server: Option<String>,
441}
442
443#[derive(Clone)]
444pub struct AntChatRoom {
445    room: Room,
446    state: Arc<AntChatState>,
447}
448
449pub use self::AntChatRoom as ChatRoom;
450
451impl Deref for AntChatRoom {
452    type Target = Room;
453    fn deref(&self) -> &Room {
454        &self.room
455    }
456}
457
458fn positive(value: &Value) -> Option<u64> {
459    value
460        .as_f64()
461        .filter(|repository| *repository > 0.0)
462        .map(|repository| repository as u64)
463}
464
465impl AntChatRoom {
466    fn chat(&self) -> MutexGuard<'_, AntChat> {
467        lock(&self.state.chat)
468    }
469
470    pub fn chat_id(&self) -> String {
471        self.chat().chat_id.clone()
472    }
473
474    pub fn name(&self) -> String {
475        self.chat().name.clone()
476    }
477
478    pub fn agents(&self) -> HashMap<String, Agent> {
479        self.chat().agents.clone()
480    }
481
482    /// The owner's Termite repository personas start from, by id; None when it has none.
483    pub fn repository(&self) -> Option<u64> {
484        self.chat().repository
485    }
486
487    /// Who owns the chat: `credentials:{id}` or `group:{id}`.
488    pub fn owner(&self) -> String {
489        self.chat().owner.clone()
490    }
491
492    /// The group that owns the chat, whose repositories it takes; None for a person's.
493    pub fn group(&self) -> Option<Group> {
494        let owner = self.owner();
495        owner
496            .strip_prefix("group:")
497            .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
498            .map(|id| Group::from_json(&json!({ "id": id })))
499    }
500
501    /// Attach one of the owner's repositories, or None to detach. Personas' forks of the old one are deleted.
502    pub async fn set_repository(&self, repository: Option<&Repository>) -> Result<()> {
503        self.post(&json!({ "event": "set-repository", "repository": repository.map(|repository| repository.id) }));
504        Ok(())
505    }
506
507    /// Hear about every repository change, from anyone in the room. Returns a function that stops listening.
508    pub fn watch_repository(
509        &self,
510        listener: impl Fn(Option<u64>) + Send + Sync + 'static,
511    ) -> Box<dyn FnOnce() + Send + Sync> {
512        let id = self.state.next_watcher.fetch_add(1, Ordering::Relaxed);
513        lock(&self.state.watchers).push((id, Arc::new(listener)));
514        let state = Arc::downgrade(&self.state);
515        Box::new(move || {
516            if let Some(state) = state.upgrade() {
517                lock(&state.watchers).retain(|(other, _)| *other != id);
518            }
519        })
520    }
521
522    fn apply_repository(&self, raw: &Value) {
523        let repository = positive(raw);
524        {
525            let mut chat = self.chat();
526            if chat.repository == repository {
527                return;
528            }
529            chat.repository = repository;
530        }
531        let watchers: Vec<RepositoryWatcher> = lock(&self.state.watchers)
532            .iter()
533            .map(|(_, listener)| listener.clone())
534            .collect();
535        for listener in watchers {
536            listener(repository);
537        }
538    }
539
540    pub fn hydrate(&self, state: &Value) {
541        {
542            let mut chat = self.chat();
543            if let Some(id) = state["id"].as_str() {
544                chat.chat_id = id.to_string();
545            }
546            if let Some(name) = state["name"].as_str() {
547                chat.name = name.to_string();
548            }
549            if let Some(owner) = state["owner"].as_str() {
550                chat.owner = owner.to_string();
551            }
552        }
553        self.apply_repository(&state["repository"]);
554        let agents: HashMap<String, Agent> = state["agents"]
555            .as_array()
556            .into_iter()
557            .flatten()
558            .filter_map(|agent| Agent::from_json(agent, self))
559            .map(|agent| (agent.id.clone(), agent))
560            .collect();
561        self.chat().agents = agents;
562    }
563
564    pub fn handle_event(&self, packet: &Value) -> bool {
565        let pick = |key: &str| {
566            if packet["data"][key].is_null() {
567                &packet[key]
568            } else {
569                &packet["data"][key]
570            }
571        };
572        match packet["event"].as_str().unwrap_or_default() {
573            "upsert-agent" => {
574                if let Some(agent) = Agent::from_json(pick("agent"), self) {
575                    self.chat().agents.insert(agent.id.clone(), agent);
576                }
577                true
578            }
579            "remove-agent" => {
580                let id = match pick("id") {
581                    Value::Null => String::new(),
582                    Value::String(id) => id.clone(),
583                    id => id.to_string(),
584                };
585                if !id.is_empty() {
586                    self.chat().agents.remove(&id);
587                }
588                true
589            }
590            "update-chat" => {
591                let chat = pick("chat");
592                if let Some(name) = chat["name"].as_str() {
593                    self.chat().name = name.to_string();
594                }
595                if chat.get("repository").is_some() {
596                    self.apply_repository(&chat["repository"]);
597                }
598                true
599            }
600            _ => false,
601        }
602    }
603
604    pub fn upsert_agent(&self, identity: Identity) -> Agent {
605        let agent = {
606            let mut chat = self.chat();
607            let preferred = identity.id.trim().to_string();
608            let id = if !preferred.is_empty() && !chat.agents.contains_key(&preferred) {
609                preferred
610            } else {
611                let mut n = 0;
612                while chat.agents.contains_key(&n.to_string()) {
613                    n += 1;
614                }
615                n.to_string()
616            };
617            let agent = Agent {
618                room: self.room.clone(),
619                parent: Arc::downgrade(&self.state),
620                id,
621                persona: identity,
622                repository: None,
623            };
624            chat.agents.insert(agent.id.clone(), agent.clone());
625            agent
626        };
627        self.post(&json!({ "event": "upsert-agent", "agent": agent.to_json() }));
628        agent
629    }
630
631    pub fn remove_agent(&self, id: &str) {
632        self.chat().agents.remove(id);
633        self.post(&json!({ "event": "remove-agent", "id": id }));
634    }
635
636    /// Lazily mint/open the architect Parrot ChatRoom.
637    pub async fn get_chat(&self, hooks: Option<Arc<dyn RoomHooks>>) -> Result<ArchitectChat> {
638        let authorization = self.get_authorization();
639        let request = authorized(
640            client().post(format!("{}/chat/ensure", super::get_url())),
641            authorization,
642            None,
643        );
644        let request = match self.authorization() {
645            Authorization::AccessCode { access_code, .. } => {
646                request.header("Access-Code", access_code)
647            }
648            Authorization::Server { group, .. } => {
649                let request = request.header("Chat", self.chat_id());
650                match group {
651                    Some(group) => request.header("Group", group),
652                    None => request,
653                }
654            }
655        };
656        let json: Value = ok(request.json(&json!({})).send().await?)
657            .await?
658            .json()
659            .await?;
660        let chat_id = json["chatId"].as_str().unwrap_or_default().to_string();
661        let code = json["code"].as_str().unwrap_or_default().to_string();
662        if chat_id.is_empty() || code.is_empty() {
663            return Err(Error::Message("Invalid ensure response.".to_string()));
664        }
665        let target = match self.authorization() {
666            Authorization::AccessCode { .. } => ChatTarget::Code { code },
667            Authorization::Server { .. } => ChatTarget::Reference {
668                reference: json["reference"]
669                    .as_str()
670                    .filter(|reference| !reference.is_empty())
671                    .map(str::to_string)
672                    .unwrap_or_else(|| format!("parrot:chat:{chat_id}")),
673            },
674        };
675        let (room, me) = connect_room(authorization, &target, hooks).await?;
676        Ok(ArchitectChat { room, me, chat_id })
677    }
678
679    pub async fn connect(
680        authorization: &CredentialsOrApiKey,
681        target_id: &str,
682        opts: ConnectOptions,
683    ) -> Result<(AntChatRoom, Presence)> {
684        AntChatRoom::open(
685            Authorization::Server {
686                authorization: authorization.clone(),
687                server: opts.server.unwrap_or_else(|| target_id.to_string()),
688                group: opts.group.as_ref().map(|group| group.id.clone()),
689            },
690            opts.hooks,
691        )
692        .await
693    }
694
695    pub async fn join(
696        authorization: &CredentialsOrApiKey,
697        access_code: &str,
698        hooks: Option<Arc<dyn Hooks>>,
699    ) -> Result<(AntChatRoom, Presence)> {
700        AntChatRoom::open(
701            Authorization::AccessCode {
702                authorization: authorization.clone(),
703                access_code: access_code.to_string(),
704            },
705            hooks,
706        )
707        .await
708    }
709
710    async fn open(
711        auth: Authorization,
712        hooks: Option<Arc<dyn Hooks>>,
713    ) -> Result<(AntChatRoom, Presence)> {
714        let state = Arc::new(AntChatState {
715            chat: Mutex::new(AntChat::default()),
716            watchers: Mutex::new(Vec::new()),
717            next_watcher: AtomicU64::new(0),
718        });
719        let me = connect_server(
720            auth,
721            &format!("{}/chat", super::get_url()),
722            Arc::new(AntChatHooks {
723                state: state.clone(),
724                user: hooks.unwrap_or_else(|| Arc::new(())),
725            }),
726        )
727        .await?;
728        Ok((
729            AntChatRoom {
730                room: me.room().clone(),
731                state,
732            },
733            me,
734        ))
735    }
736}
737
738struct AntChatHooks {
739    state: Arc<AntChatState>,
740    user: Arc<dyn Hooks>,
741}
742
743impl AntChatHooks {
744    fn room(&self, room: &Room) -> AntChatRoom {
745        AntChatRoom {
746            room: room.clone(),
747            state: self.state.clone(),
748        }
749    }
750}
751
752impl Hooks for AntChatHooks {
753    fn create_room(&self, room: &Room, state: &Value) {
754        lock(&self.state.chat).chat_id = room.id().to_string();
755        self.user.create_room(room, state);
756    }
757
758    fn create_presence(&self, room: &Room, presence: &Presence) {
759        self.user.create_presence(room, presence);
760    }
761
762    fn remove_presence(&self, room: &Room, presence: &Presence) {
763        self.user.remove_presence(room, presence);
764    }
765
766    fn on_connection(&self, room: &Room, state: &Value) {
767        self.room(room).hydrate(state);
768        self.user.on_connection(room, state);
769    }
770
771    fn on_event(&self, room: &Room, packet: &Value) -> bool {
772        let handled = self.room(room).handle_event(packet);
773        self.user.on_event(room, packet) || handled
774    }
775
776    fn on_presence(&self, room: &Room) {
777        self.user.on_presence(room);
778    }
779
780    fn on_closed(&self, room: &Room, reason: Option<&str>) {
781        self.user.on_closed(room, reason);
782    }
783}
784
785/// The `opts` argument of `observe_agent`: a group's chat, or a guest's access code.
786#[derive(Debug, Clone, Default)]
787pub struct AgentOptions {
788    pub group: Option<Group>,
789    pub access_code: Option<String>,
790}
791
792fn scoped(
793    request: reqwest::RequestBuilder,
794    chat_id: &str,
795    group: Option<&Group>,
796    access_code: Option<&str>,
797) -> reqwest::RequestBuilder {
798    match access_code.filter(|code| !code.is_empty()) {
799        Some(access_code) => request.header("Access-Code", access_code),
800        None => {
801            let request = request.header("Chat", chat_id);
802            match group {
803                Some(group) => request.header("Group", &group.id),
804                None => request,
805            }
806        }
807    }
808}
809
810/// Write a standalone fact onto this agent's Parrot graph (`ant/chats/…/memory`).
811pub async fn observe_agent(
812    authorization: &CredentialsOrApiKey,
813    chat_id: &str,
814    agent_id: &str,
815    content: &str,
816    opts: AgentOptions,
817) -> Result<Memory> {
818    let request = authorized(
819        client().post(format!("{}/chat/agent/observe", super::get_url())),
820        authorization,
821        None,
822    );
823    let response = scoped(
824        request,
825        chat_id,
826        opts.group.as_ref(),
827        opts.access_code.as_deref(),
828    )
829    .json(&json!({ "agentId": agent_id, "content": content }))
830    .send()
831    .await?;
832    Ok(ok(response).await?.json().await?)
833}
834
835/// The `opts` argument of `generate_agent`. Dropping the returned stream closes the socket.
836#[derive(Debug, Clone, Default)]
837pub struct GenerateOptions {
838    pub group: Option<Group>,
839    pub access_code: Option<String>,
840    pub tools: Option<Vec<Tool>>,
841}
842
843pub(crate) fn socket_auth(
844    authorization: &CredentialsOrApiKey,
845    chat_header: (&str, &str),
846    group: Option<&Group>,
847    access_code: Option<&str>,
848) -> String {
849    let mut headers = Map::new();
850    headers.insert(
851        "Authorization".to_string(),
852        Value::from(match authorization {
853            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
854            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
855        }),
856    );
857    match access_code.filter(|code| !code.is_empty()) {
858        Some(access_code) => {
859            headers.insert("Access-Code".to_string(), Value::from(access_code));
860        }
861        None => {
862            headers.insert(chat_header.0.to_string(), Value::from(chat_header.1));
863            if let Some(group) = group {
864                headers.insert("Group".to_string(), Value::from(group.id.as_str()));
865            }
866        }
867    }
868    encode(&Value::Object(headers).to_string())
869}
870
871/// Stream a persona reply for one chat agent (memories under ant/chats/…), with
872/// `tool` and `tool-result` events for its own tools. `tools` are answered here
873/// when the persona calls them, like `use_computer` asking for a computer.
874pub async fn generate_agent(
875    authorization: &CredentialsOrApiKey,
876    chat_id: &str,
877    agent_id: &str,
878    messages: &[Content],
879    opts: GenerateOptions,
880) -> Result<BoxStream<'static, StreamEvent>> {
881    let auth = socket_auth(
882        authorization,
883        ("Chat", chat_id),
884        opts.group.as_ref(),
885        opts.access_code.as_deref(),
886    );
887    let url = format!(
888        "{}/chat/agent/generate?authorization={auth}",
889        websocket(&super::get_url())
890    );
891    let tools = opts.tools.unwrap_or_default();
892    let messages = serialize_messages(authorization, messages).await?;
893    let functions: Vec<&crate::parrot::generative::Function> =
894        tools.iter().map(|tool| &tool.function).collect();
895    let generate = json!({ "event": "generate", "agentId": agent_id, "messages": messages, "tools": functions });
896    agent_stream(url, generate, tools).await
897}
898
899#[cfg(test)]
900mod tests {
901    use serde_json::{Value, json};
902    use tokio::sync::mpsc;
903
904    use super::*;
905    use crate::authentification::ApiKey;
906
907    fn persona(id: &str) -> Value {
908        json!({
909            "id": id, "background": "Nurse", "dialect": "Southern",
910            "demographic": {
911                "age": 30, "sex": "MALE", "race": "BLACK", "ethnicity": [], "religion": "CHRISTIAN",
912                "birthplace": [0, 0], "location": [0, 0], "marital": "MARRIED", "education": "BACHELOR",
913                "occupation": "nurse", "income": 60000
914            }
915        })
916    }
917
918    #[test]
919    fn ant_chat_rooms_track_agents_and_repository() {
920        let (ws, mut outbox) = mpsc::unbounded_channel();
921        let room = AntChatRoom {
922            room: Room::new(
923                "http://localhost/chat".to_string(),
924                ws,
925                Authorization::Server {
926                    authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
927                    server: "c1".to_string(),
928                    group: None,
929                },
930                "c1".to_string(),
931            ),
932            state: Arc::new(AntChatState {
933                chat: Mutex::new(AntChat::default()),
934                watchers: Mutex::new(Vec::new()),
935                next_watcher: AtomicU64::new(0),
936            }),
937        };
938        let seen = Arc::new(Mutex::new(Vec::new()));
939        let sink = seen.clone();
940        let _stop = room.watch_repository(move |repository| sink.lock().unwrap().push(repository));
941        room.hydrate(&json!({
942            "id": "c1", "name": "Panel", "owner": "group:5", "repository": 9,
943            "agents": [{ "id": "0", "persona": persona("p0"), "repository": 3 }, { "id": "bad" }]
944        }));
945        assert_eq!(room.group().unwrap().id, "5");
946        assert_eq!(room.agents().len(), 1);
947        assert_eq!(room.agents()["0"].repository, Some(3));
948        assert_eq!(room.agents()["0"].parent().unwrap().chat_id(), "c1");
949
950        let identity: Identity = serde_json::from_value(persona("0")).unwrap();
951        let agent = room.upsert_agent(identity);
952        assert_eq!(agent.id, "1");
953        let Some(Message::Text(frame)) = outbox.blocking_recv() else {
954            panic!("expected a frame");
955        };
956        assert_eq!(
957            serde_json::from_str::<Value>(frame.as_str()).unwrap()["event"],
958            "upsert-agent"
959        );
960
961        assert!(room.handle_event(&json!({ "event": "remove-agent", "data": { "id": "0" } })));
962        assert!(room.handle_event(
963            &json!({ "event": "update-chat", "chat": { "name": "Jury", "repository": null } })
964        ));
965        assert_eq!(room.agents().len(), 1);
966        assert_eq!(room.name(), "Jury");
967        assert_eq!(*seen.lock().unwrap(), vec![Some(9), None]);
968    }
969}