Skip to main content

fauna_api/ant/
timeline.rs

1use std::collections::HashMap;
2use std::ops::Deref;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
5
6use futures_util::future::BoxFuture;
7use futures_util::stream::BoxStream;
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value, json};
10
11use super::chat::{agent_stream, serialize_messages, socket_auth};
12use super::format::{AntFormat, AntFormatOrFormat};
13use super::persona::Identity;
14use crate::authentification::CredentialsOrApiKey;
15use crate::drive::{self, FileMeta, from_access_code};
16use crate::error::{Error, Result};
17use crate::groups::Group;
18use crate::http::{client, encode, ok, websocket};
19use crate::parrot::agent::Memory;
20use crate::parrot::generative::{Content, StreamEvent, Tool};
21use crate::parrot::room::{ChatRoom, RoomHooks, connect_room};
22use crate::parrot::share::ChatTarget;
23use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
24use crate::termite::versioning::{FileOrFiles, Repository};
25
26pub use super::graph::{
27    FileNode, GraphEdge, GraphNode, GraphNodeWire, LinkedInNode, StartNode, Stimuli, TextNode,
28    WebsiteNode, XNode,
29};
30
31fn authorized(
32    request: reqwest::RequestBuilder,
33    authorization: &CredentialsOrApiKey,
34    group: Option<&Group>,
35) -> reqwest::RequestBuilder {
36    let request = request.header(
37        "Authorization",
38        match authorization {
39            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
40            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
41        },
42    );
43    match group {
44        Some(group) => request.header("Group", &group.id),
45        None => request,
46    }
47}
48
49fn scoped(
50    request: reqwest::RequestBuilder,
51    timeline_id: &str,
52    group: Option<&Group>,
53    access_code: Option<&str>,
54) -> reqwest::RequestBuilder {
55    match access_code.filter(|code| !code.is_empty()) {
56        Some(access_code) => request.header("Access-Code", access_code),
57        None => {
58            let request = request.header("Timeline", timeline_id);
59            match group {
60                Some(group) => request.header("Group", &group.id),
61                None => request,
62            }
63        }
64    }
65}
66
67/// `{ name, id }` in the TypeScript SDK: one timeline.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69pub struct TimelineEntry {
70    pub name: String,
71    pub id: String,
72}
73
74/// The `opts` argument of the timeline calls that take only a group.
75#[derive(Debug, Clone, Default)]
76pub struct GroupOptions {
77    pub group: Option<Group>,
78}
79
80pub async fn list_timelines(
81    authorization: &CredentialsOrApiKey,
82    opts: GroupOptions,
83) -> Result<Vec<TimelineEntry>> {
84    let response = authorized(
85        client().get(format!("{}/timelines", super::get_url())),
86        authorization,
87        opts.group.as_ref(),
88    )
89    .send()
90    .await?;
91    Ok(ok(response).await?.json().await?)
92}
93
94/// The `opts` argument of `create_timeline`.
95#[derive(Debug, Clone, Default)]
96pub struct CreateTimelineOptions {
97    pub group: Option<Group>,
98    pub audience: Option<Vec<String>>,
99    pub repository: Option<Repository>,
100}
101
102/// Create a timeline. `repository` (the owner's) is the computer its personas start from.
103pub async fn create_timeline(
104    authorization: &CredentialsOrApiKey,
105    name: &str,
106    opts: CreateTimelineOptions,
107) -> Result<TimelineEntry> {
108    let mut body = Map::new();
109    body.insert("name".to_string(), Value::from(name));
110    if let Some(audience) = opts.audience.filter(|audience| !audience.is_empty()) {
111        body.insert("audience".to_string(), json!(audience));
112    }
113    if let Some(repository) = &opts.repository {
114        body.insert("repository".to_string(), Value::from(repository.id));
115    }
116    let response = authorized(
117        client().post(format!("{}/timelines", super::get_url())),
118        authorization,
119        opts.group.as_ref(),
120    )
121    .json(&body)
122    .send()
123    .await?;
124    Ok(ok(response).await?.json().await?)
125}
126
127pub async fn delete_timeline(
128    authorization: &CredentialsOrApiKey,
129    id: &str,
130    opts: GroupOptions,
131) -> Result<()> {
132    let response = authorized(
133        client().delete(format!("{}/timeline", super::get_url())),
134        authorization,
135        opts.group.as_ref(),
136    )
137    .header("Timeline", id)
138    .send()
139    .await?;
140    ok(response).await?;
141    Ok(())
142}
143
144pub async fn rename_timeline(
145    authorization: &CredentialsOrApiKey,
146    id: &str,
147    name: &str,
148    opts: GroupOptions,
149) -> Result<()> {
150    let response = authorized(
151        client().post(format!("{}/timeline/rename", super::get_url())),
152        authorization,
153        opts.group.as_ref(),
154    )
155    .header("Timeline", id)
156    .json(&json!({ "name": name }))
157    .send()
158    .await?;
159    ok(response).await?;
160    Ok(())
161}
162
163/// The `opts` argument of the calls a guest makes with an access code.
164#[derive(Debug, Clone, Default)]
165pub struct AccessOptions {
166    pub group: Option<Group>,
167    pub access_code: Option<String>,
168}
169
170/// `{ edges }` in the TypeScript SDK.
171#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
172pub struct TrustGraph {
173    #[serde(default)]
174    pub edges: Vec<TrustEdge>,
175}
176
177pub async fn get_trust(
178    authorization: &CredentialsOrApiKey,
179    timeline_id: &str,
180    opts: AccessOptions,
181) -> Result<TrustGraph> {
182    let request = authorized(
183        client().get(format!("{}/timeline/trust", super::get_url())),
184        authorization,
185        None,
186    );
187    let response = scoped(
188        request,
189        timeline_id,
190        opts.group.as_ref(),
191        opts.access_code.as_deref(),
192    )
193    .send()
194    .await?;
195    Ok(ok(response).await?.json().await?)
196}
197
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199#[serde(rename_all = "camelCase")]
200pub struct TrustEdge {
201    pub from: String,
202    pub to: String,
203    pub weight: f64,
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub updated_at: Option<f64>,
206}
207
208fn trust_edge(json: &Value) -> Option<TrustEdge> {
209    let edge: TrustEdge = serde_json::from_value(json.clone()).ok()?;
210    (!edge.from.is_empty() && !edge.to.is_empty() && edge.weight > 0.0).then_some(edge)
211}
212
213/// A file node's short-lived Drive code, with the file's name and type.
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "camelCase")]
216pub struct FileAccessCodeMeta {
217    pub code: String,
218    #[serde(default)]
219    pub name: String,
220    #[serde(default)]
221    pub content_type: String,
222}
223
224#[derive(Clone)]
225pub struct Poll {
226    pub id: String,
227    pub goal: String,
228    pub query: Vec<AntFormatOrFormat>,
229    pub results: Value,
230}
231
232impl Poll {
233    pub fn new(id: &str, goal: &str, query: Vec<AntFormatOrFormat>) -> Poll {
234        Poll {
235            id: id.to_string(),
236            goal: goal.to_string(),
237            query,
238            results: Value::Null,
239        }
240    }
241
242    pub fn from_json(json: &Value) -> Poll {
243        let read = |format: &Value| {
244            format
245                .get("type")
246                .is_some()
247                .then(|| AntFormat::from_json(format).ok())
248                .flatten()
249        };
250        let query = match &json["query"] {
251            Value::Array(formats) => formats.iter().filter_map(read).collect(),
252            format @ Value::Object(_) => read(format).into_iter().collect(),
253            _ => Vec::new(),
254        };
255        Poll {
256            id: match &json["id"] {
257                Value::String(id) => id.clone(),
258                Value::Null => String::new(),
259                id => id.to_string(),
260            },
261            goal: json["goal"].as_str().unwrap_or_default().to_string(),
262            query,
263            results: json["results"].clone(),
264        }
265    }
266
267    pub fn to_json(&self) -> Value {
268        json!({
269            "id": self.id,
270            "goal": self.goal,
271            "query": self.query.iter().map(AntFormatOrFormat::to_json).collect::<Vec<_>>(),
272            "results": self.results,
273        })
274    }
275}
276
277/// `"QUEUED" | "RUNNING" | "DONE" | "ABORTED" | "FAILED"` in the TypeScript SDK.
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
279#[serde(rename_all = "UPPERCASE")]
280pub enum RunStatus {
281    Queued,
282    Running,
283    Done,
284    Aborted,
285    Failed,
286}
287
288/// A note an agent left on a run: a reflection, a comment or a forward.
289#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290#[serde(rename_all = "camelCase")]
291pub struct AgentNote {
292    pub agent_id: String,
293    pub text: String,
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub to: Option<String>,
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub error: Option<String>,
298}
299
300/// `{ id, kind, title }` in the TypeScript SDK: a step of a trajectory.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302pub struct TrajectoryNode {
303    pub id: String,
304    pub kind: String,
305    pub title: String,
306}
307
308/// `{ post, comments }` in the TypeScript SDK.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310pub struct Thread {
311    pub post: String,
312    #[serde(default)]
313    pub comments: Vec<AgentNote>,
314}
315
316/// One path a run took through the graph, with what its agents said along it.
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318pub struct Trajectory {
319    pub id: String,
320    #[serde(default)]
321    pub nodes: Vec<TrajectoryNode>,
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub reflections: Option<Vec<AgentNote>>,
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub thread: Option<Thread>,
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub forwards: Option<Vec<AgentNote>>,
328}
329
330/// `"browse" | "reflect" | "discuss" | "forward" | "answer"` in the TypeScript SDK.
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
332#[serde(rename_all = "lowercase")]
333pub enum StimulusPhase {
334    Browse,
335    Reflect,
336    Discuss,
337    Forward,
338    Answer,
339}
340
341/// `{ reference }` in the TypeScript SDK: the machine room of an agent's computer.
342#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
343pub struct AgentSession {
344    pub reference: String,
345}
346
347/// `{ id, agentId, text }` in the TypeScript SDK.
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349#[serde(rename_all = "camelCase")]
350pub struct FeedItem {
351    pub id: String,
352    pub agent_id: String,
353    pub text: String,
354}
355
356/// How far a run is through one stimulus.
357#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
358#[serde(rename_all = "camelCase")]
359pub struct StimulusProgress {
360    pub stimulus_label: String,
361    pub phase: StimulusPhase,
362    pub done: f64,
363    pub total: f64,
364    /// Each agent's computer while it works there: its machine room, by agent id.
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    pub sessions: Option<HashMap<String, AgentSession>>,
367    #[serde(default, skip_serializing_if = "Option::is_none")]
368    pub feed: Option<Vec<FeedItem>>,
369}
370
371/// Where a run is in the graph right now.
372#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
373#[serde(rename_all = "camelCase")]
374pub struct RunProgress {
375    #[serde(default)]
376    pub active_node_ids: Vec<String>,
377    #[serde(default)]
378    pub active_edge_ids: Vec<String>,
379    #[serde(default)]
380    pub cluster_hits: HashMap<String, f64>,
381    #[serde(default)]
382    pub cluster_required: HashMap<String, f64>,
383    #[serde(default)]
384    pub by_stimulus: HashMap<String, StimulusProgress>,
385}
386
387#[derive(Debug, Clone, PartialEq)]
388pub struct Run {
389    pub id: String,
390    pub poll_id: String,
391    pub iteration: f64,
392    pub status: RunStatus,
393    pub trajectories: Vec<Trajectory>,
394    pub polls: Option<Value>,
395    pub progress: Option<RunProgress>,
396    pub agent_ids: Vec<String>,
397    pub reach: Option<HashMap<String, Vec<String>>>,
398    pub started_at: f64,
399    pub finished_at: Option<f64>,
400    pub error: Option<String>,
401}
402
403fn normalize_run_status(raw: Option<&str>) -> RunStatus {
404    match raw.unwrap_or_default().to_uppercase().as_str() {
405        "QUEUED" => RunStatus::Queued,
406        "RUNNING" | "PENDING" | "ABORTING" => RunStatus::Running,
407        "DONE" => RunStatus::Done,
408        "ABORTED" => RunStatus::Aborted,
409        "FAILED" => RunStatus::Failed,
410        _ => RunStatus::Queued,
411    }
412}
413
414impl Run {
415    pub fn new(wire: &Value) -> Run {
416        let progress = if wire["progress"].is_null() {
417            &wire["polls"]["progress"]
418        } else {
419            &wire["progress"]
420        };
421        Run {
422            id: wire["id"].as_str().unwrap_or_default().to_string(),
423            poll_id: wire["pollId"].as_str().unwrap_or_default().to_string(),
424            iteration: wire["iteration"].as_f64().unwrap_or_default(),
425            status: normalize_run_status(wire["status"].as_str()),
426            trajectories: serde_json::from_value(wire["trajectories"].clone()).unwrap_or_default(),
427            polls: (!wire["polls"].is_null()).then(|| wire["polls"].clone()),
428            progress: serde_json::from_value(progress.clone()).ok(),
429            agent_ids: serde_json::from_value(wire["agentIds"].clone()).unwrap_or_default(),
430            reach: serde_json::from_value(wire["reach"].clone()).ok(),
431            started_at: wire["startedAt"].as_f64().unwrap_or_default(),
432            finished_at: wire["finishedAt"].as_f64(),
433            error: wire["error"].as_str().map(str::to_string),
434        }
435    }
436}
437
438pub fn run_is_active(status: Option<&str>) -> bool {
439    matches!(
440        normalize_run_status(status),
441        RunStatus::Queued | RunStatus::Running
442    )
443}
444
445/// `{ room, self, chatId }` in the TypeScript SDK, with `self` as `me`.
446#[derive(Clone)]
447pub struct TimelineChat {
448    pub room: ChatRoom,
449    pub me: Presence,
450    pub chat_id: String,
451}
452
453/// The `opts` argument of `Agent::generate`.
454#[derive(Debug, Clone, Default)]
455pub struct AgentGenerateOptions {
456    pub tools: Option<Vec<Tool>>,
457}
458
459#[derive(Clone)]
460pub struct Agent {
461    room: Room,
462    parent: Weak<TimelineState>,
463    pub id: String,
464    pub persona: Identity,
465    /// A repository picked in this agent's own chat, used directly; None when it follows the timeline's.
466    pub repository: Option<u64>,
467}
468
469impl Agent {
470    pub fn parent(&self) -> Option<TimelineRoom> {
471        self.parent.upgrade().map(|state| TimelineRoom {
472            room: self.room.clone(),
473            state,
474        })
475    }
476
477    pub fn from_json(json: &Value, parent: &TimelineRoom) -> Option<Agent> {
478        Some(Agent {
479            room: parent.room.clone(),
480            parent: Arc::downgrade(&parent.state),
481            id: match &json["id"] {
482                Value::String(id) => id.clone(),
483                id => id.to_string(),
484            },
485            persona: serde_json::from_value(json["persona"].clone()).ok()?,
486            repository: json["repository"]
487                .as_f64()
488                .filter(|repository| *repository > 0.0)
489                .map(|repository| repository as u64),
490        })
491    }
492
493    /// Pick a repository for this agent's chats (used directly), or None to follow the timeline's again.
494    pub fn set_repository(&self, repository: Option<&Repository>) {
495        self.room.post(&json!({
496            "event": "set-agent-repository",
497            "agentId": self.id,
498            "repository": repository.map(|repository| repository.id),
499        }));
500    }
501
502    /// Lazily mint/open this agent's Parrot ChatRoom.
503    pub async fn get_chat(&self, hooks: Option<Arc<dyn RoomHooks>>) -> Result<TimelineChat> {
504        let parent = self
505            .parent()
506            .ok_or_else(|| Error::Message("Room not found".to_string()))?;
507        parent.open_chat(&self.id, hooks).await
508    }
509
510    fn timeline_id(&self) -> String {
511        self.parent()
512            .map(|room| room.timeline_id())
513            .unwrap_or_default()
514    }
515
516    fn access(&self) -> AccessOptions {
517        match self.room.authorization() {
518            Authorization::AccessCode { access_code, .. } => AccessOptions {
519                group: None,
520                access_code: Some(access_code.clone()),
521            },
522            Authorization::Server { group, .. } => AccessOptions {
523                group: group
524                    .as_ref()
525                    .map(|group| Group::from_json(&json!({ "id": group }))),
526                access_code: None,
527            },
528        }
529    }
530
531    pub async fn observe(&self, content: &str) -> Result<Memory> {
532        observe_agent(
533            self.room.get_authorization(),
534            &self.timeline_id(),
535            &self.id,
536            content,
537            self.access(),
538        )
539        .await
540    }
541
542    /// Stream a reply as this agent, under the room's own authorization. `tools` answer the persona's calls to them.
543    pub async fn generate(
544        &self,
545        messages: &[Content],
546        opts: AgentGenerateOptions,
547    ) -> Result<BoxStream<'static, StreamEvent>> {
548        let access = self.access();
549        generate_agent(
550            self.room.get_authorization(),
551            &self.timeline_id(),
552            &self.id,
553            messages,
554            GenerateOptions {
555                group: access.group,
556                access_code: access.access_code,
557                tools: opts.tools,
558            },
559        )
560        .await
561    }
562
563    pub fn to_json(&self) -> Value {
564        json!({ "id": self.id, "persona": self.persona })
565    }
566}
567
568type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;
569
570struct Timeline {
571    timeline_id: String,
572    name: String,
573    agents: HashMap<String, Agent>,
574    polls: HashMap<String, Poll>,
575    runs: HashMap<String, Run>,
576    nodes: HashMap<String, GraphNode>,
577    edges: HashMap<String, GraphEdge>,
578    file_access_codes: HashMap<String, FileAccessCodeMeta>,
579    trust_edges: HashMap<String, TrustEdge>,
580    status: String,
581    removed: bool,
582    repository: Option<u64>,
583    owner: String,
584}
585
586impl Default for Timeline {
587    fn default() -> Self {
588        Timeline {
589            timeline_id: String::new(),
590            name: String::new(),
591            agents: HashMap::new(),
592            polls: HashMap::new(),
593            runs: HashMap::new(),
594            nodes: HashMap::new(),
595            edges: HashMap::new(),
596            file_access_codes: HashMap::new(),
597            trust_edges: HashMap::new(),
598            status: "IDLE".to_string(),
599            removed: false,
600            repository: None,
601            owner: String::new(),
602        }
603    }
604}
605
606struct TimelineState {
607    timeline: Mutex<Timeline>,
608    watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
609    next_watcher: AtomicU64,
610}
611
612fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
613    mutex.lock().unwrap_or_else(PoisonError::into_inner)
614}
615
616/// The `opts` argument of `upload_file_node`.
617#[derive(Debug, Clone, Default)]
618pub struct UploadFileOptions {
619    pub name: String,
620    pub content_type: Option<String>,
621    pub x: f64,
622    pub y: f64,
623    pub node_id: Option<String>,
624    pub kind: Option<Stimuli>,
625}
626
627/// `{ node, accessCode }` in the TypeScript SDK.
628#[derive(Debug, Clone)]
629pub struct UploadedFile {
630    pub node: GraphNode,
631    pub access_code: FileAccessCodeMeta,
632}
633
634/// The `opts` argument of `TimelineRoom::connect`. `server` carries only the
635/// timeline id for own and group timelines; grant joins may pass a full
636/// `principalId:timelineId`.
637#[derive(Default)]
638pub struct ConnectOptions {
639    pub group: Option<Group>,
640    pub hooks: Option<Arc<dyn Hooks>>,
641    pub server: Option<String>,
642}
643
644#[derive(Clone)]
645pub struct TimelineRoom {
646    room: Room,
647    state: Arc<TimelineState>,
648}
649
650impl Deref for TimelineRoom {
651    type Target = Room;
652    fn deref(&self) -> &Room {
653        &self.room
654    }
655}
656
657fn pick<'a>(packet: &'a Value, key: &str) -> &'a Value {
658    if !packet[key].is_null() {
659        &packet[key]
660    } else if !packet["data"][key].is_null() {
661        &packet["data"][key]
662    } else {
663        &packet["data"]
664    }
665}
666
667fn id_of(packet: &Value) -> Option<String> {
668    let id = if packet["id"].is_null() {
669        &packet["data"]["id"]
670    } else {
671        &packet["id"]
672    };
673    match id {
674        Value::String(id) if !id.is_empty() => Some(id.clone()),
675        Value::Number(id) => Some(id.to_string()),
676        _ => None,
677    }
678}
679
680impl TimelineRoom {
681    fn timeline(&self) -> MutexGuard<'_, Timeline> {
682        lock(&self.state.timeline)
683    }
684
685    /// Client-facing timeline id within the current principal.
686    pub fn timeline_id(&self) -> String {
687        self.timeline().timeline_id.clone()
688    }
689
690    pub fn name(&self) -> String {
691        self.timeline().name.clone()
692    }
693
694    pub fn agents(&self) -> HashMap<String, Agent> {
695        self.timeline().agents.clone()
696    }
697
698    pub fn polls(&self) -> HashMap<String, Poll> {
699        self.timeline().polls.clone()
700    }
701
702    pub fn runs(&self) -> HashMap<String, Run> {
703        self.timeline().runs.clone()
704    }
705
706    pub fn nodes(&self) -> HashMap<String, GraphNode> {
707        self.timeline().nodes.clone()
708    }
709
710    pub fn edges(&self) -> HashMap<String, GraphEdge> {
711        self.timeline().edges.clone()
712    }
713
714    /// Short-lived Drive codes for file nodes (hydrate + upload + remint).
715    pub fn file_access_codes(&self) -> HashMap<String, FileAccessCodeMeta> {
716        self.timeline().file_access_codes.clone()
717    }
718
719    pub fn trust_edges(&self) -> HashMap<String, TrustEdge> {
720        self.timeline().trust_edges.clone()
721    }
722
723    pub fn status(&self) -> String {
724        self.timeline().status.clone()
725    }
726
727    /// Set when the timeline is deleted while this room is open.
728    pub fn removed(&self) -> bool {
729        self.timeline().removed
730    }
731
732    /// The owner's Termite repository personas start from, by id; None when it has none.
733    pub fn repository(&self) -> Option<u64> {
734        self.timeline().repository
735    }
736
737    /// Who owns the timeline: `credentials:{id}` or `group:{id}`.
738    pub fn owner(&self) -> String {
739        self.timeline().owner.clone()
740    }
741
742    /// The group that owns the timeline, whose repositories it takes; None for a person's.
743    pub fn group(&self) -> Option<Group> {
744        let owner = self.owner();
745        owner
746            .strip_prefix("group:")
747            .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
748            .map(|id| Group::from_json(&json!({ "id": id })))
749    }
750
751    fn access(&self) -> (Option<Group>, Option<String>) {
752        match self.authorization() {
753            Authorization::AccessCode { access_code, .. } => (None, Some(access_code.clone())),
754            Authorization::Server { group, .. } => (
755                group
756                    .as_ref()
757                    .map(|group| Group::from_json(&json!({ "id": group }))),
758                None,
759            ),
760        }
761    }
762
763    fn scoped(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
764        let (group, access_code) = self.access();
765        scoped(
766            authorized(request, self.get_authorization(), None),
767            &self.timeline_id(),
768            group.as_ref(),
769            access_code.as_deref(),
770        )
771    }
772
773    /// Attach one of the owner's repositories, or None to detach. Personas' chat forks of the old one are deleted.
774    pub async fn set_repository(&self, repository: Option<&Repository>) -> Result<()> {
775        self.post(&json!({ "event": "set-repository", "repository": repository.map(|repository| repository.id) }));
776        Ok(())
777    }
778
779    /// Hear about every repository change, from anyone in the room. Returns a function that stops listening.
780    pub fn watch_repository(
781        &self,
782        listener: impl Fn(Option<u64>) + Send + Sync + 'static,
783    ) -> Box<dyn FnOnce() + Send + Sync> {
784        let id = self.state.next_watcher.fetch_add(1, Ordering::Relaxed);
785        lock(&self.state.watchers).push((id, Arc::new(listener)));
786        let state = Arc::downgrade(&self.state);
787        Box::new(move || {
788            if let Some(state) = state.upgrade() {
789                lock(&state.watchers).retain(|(other, _)| *other != id);
790            }
791        })
792    }
793
794    fn apply_repository(&self, raw: &Value) {
795        let repository = raw
796            .as_f64()
797            .filter(|repository| *repository > 0.0)
798            .map(|repository| repository as u64);
799        {
800            let mut timeline = self.timeline();
801            if timeline.repository == repository {
802                return;
803            }
804            timeline.repository = repository;
805        }
806        let watchers: Vec<RepositoryWatcher> = lock(&self.state.watchers)
807            .iter()
808            .map(|(_, listener)| listener.clone())
809            .collect();
810        for listener in watchers {
811            listener(repository);
812        }
813    }
814
815    /// The trust graph a run ended with: the timeline's graph as the run started,
816    /// plus everything it changed. `trust_edges` is the graph every run starts from.
817    pub async fn run_trust(&self, run_id: &str) -> Result<Vec<TrustEdge>> {
818        let response = self
819            .scoped(client().get(format!(
820                "{}/timeline/run?runId={}",
821                super::get_url(),
822                encode(run_id)
823            )))
824            .send()
825            .await?;
826        let run: Value = ok(response).await?.json().await?;
827        Ok(run["overlay"]
828            .as_array()
829            .into_iter()
830            .flatten()
831            .filter_map(trust_edge)
832            .collect())
833    }
834
835    pub fn hydrate(&self, state: &Value) {
836        {
837            let mut timeline = self.timeline();
838            if let Some(id) = state["id"].as_str() {
839                timeline.timeline_id = id.to_string();
840            }
841            if let Some(name) = state["name"].as_str() {
842                timeline.name = name.to_string();
843            }
844            if let Some(owner) = state["owner"].as_str() {
845                timeline.owner = owner.to_string();
846            }
847        }
848        self.apply_repository(&state["repository"]);
849        let agents: HashMap<String, Agent> = state["agents"]
850            .as_array()
851            .into_iter()
852            .flatten()
853            .filter_map(|agent| Agent::from_json(agent, self))
854            .map(|agent| (agent.id.clone(), agent))
855            .collect();
856        let mut timeline = self.timeline();
857        timeline.status = state["status"].as_str().unwrap_or("IDLE").to_string();
858        timeline.agents = agents;
859        timeline.polls = state["polls"]
860            .as_array()
861            .into_iter()
862            .flatten()
863            .map(Poll::from_json)
864            .map(|poll| (poll.id.clone(), poll))
865            .collect();
866        timeline.runs = state["runs"]
867            .as_array()
868            .into_iter()
869            .flatten()
870            .map(Run::new)
871            .map(|run| (run.id.clone(), run))
872            .collect();
873        timeline.nodes = state["graph"]["nodes"]
874            .as_array()
875            .into_iter()
876            .flatten()
877            .filter_map(|node| serde_json::from_value::<GraphNodeWire>(node.clone()).ok())
878            .filter(|node| !node.id.is_empty())
879            .map(|node| (node.id.clone(), GraphNode::from_json(&node, None)))
880            .collect();
881        timeline.edges = state["graph"]["edges"]
882            .as_array()
883            .into_iter()
884            .flatten()
885            .filter(|edge| edge["id"].as_str().is_some_and(|id| !id.is_empty()))
886            .map(GraphEdge::from_json)
887            .map(|edge| (edge.id.clone(), edge))
888            .collect();
889        timeline.trust_edges = state["trustEdges"]
890            .as_array()
891            .into_iter()
892            .flatten()
893            .filter_map(trust_edge)
894            .map(|edge| (format!("{}->{}", edge.from, edge.to), edge))
895            .collect();
896        timeline.file_access_codes = state["fileAccessCodes"]
897            .as_object()
898            .into_iter()
899            .flatten()
900            .filter_map(|(node_id, meta)| {
901                let meta: FileAccessCodeMeta = serde_json::from_value(meta.clone()).ok()?;
902                (!meta.code.is_empty()).then(|| (node_id.clone(), meta))
903            })
904            .collect();
905        let node_ids: Vec<String> = timeline.file_access_codes.keys().cloned().collect();
906        let authorization = self.get_authorization().clone();
907        for node_id in node_ids {
908            attach_drive_file(&mut timeline, &authorization, &node_id);
909        }
910    }
911
912    /// Applies a domain frame. Returns the work still to do when a file node needs a
913    /// fresh Drive code; run it to finish applying the frame.
914    pub fn handle_event(&self, packet: &Value) -> Option<BoxFuture<'static, Result<()>>> {
915        let event = packet["event"].as_str().unwrap_or_default();
916        match event {
917            "upsert-agent" => {
918                if let Some(agent) = Agent::from_json(pick(packet, "agent"), self) {
919                    self.timeline().agents.insert(agent.id.clone(), agent);
920                }
921            }
922            "remove-agent" => {
923                if let Some(id) = id_of(packet) {
924                    self.timeline().agents.remove(&id);
925                }
926            }
927            "upsert-poll" => {
928                let poll = pick(packet, "poll");
929                if !poll["id"].is_null() {
930                    let poll = Poll::from_json(poll);
931                    self.timeline().polls.insert(poll.id.clone(), poll);
932                }
933            }
934            "remove-poll" => {
935                if let Some(id) = id_of(packet) {
936                    self.timeline().polls.remove(&id);
937                }
938            }
939            "upsert-run" | "run-status" => {
940                let run = pick(packet, "run");
941                if run["id"].as_str().is_some_and(|id| !id.is_empty()) {
942                    let run = Run::new(run);
943                    self.timeline().runs.insert(run.id.clone(), run);
944                }
945            }
946            "remove-run" => {
947                if let Some(id) = id_of(packet) {
948                    self.timeline().runs.remove(&id);
949                }
950            }
951            "status" => {
952                let status = if packet["status"].is_null() {
953                    &packet["data"]["status"]
954                } else {
955                    &packet["status"]
956                };
957                if let Some(status) = status.as_str() {
958                    self.timeline().status = status.to_string();
959                }
960            }
961            "update-timeline" => {
962                let timeline = if packet["timeline"].is_null() {
963                    &packet["data"]["timeline"]
964                } else {
965                    &packet["timeline"]
966                };
967                if let Some(name) = timeline["name"].as_str().filter(|name| !name.is_empty()) {
968                    self.timeline().name = name.to_string();
969                }
970                if timeline.get("repository").is_some() {
971                    self.apply_repository(&timeline["repository"]);
972                }
973            }
974            "timeline-removed" => self.timeline().removed = true,
975            "upsert-graph-node" => return self.upsert_graph_node_frame(packet),
976            "remove-graph-node" => {
977                if let Some(id) = id_of(packet) {
978                    let mut timeline = self.timeline();
979                    timeline.nodes.remove(&id);
980                    timeline.file_access_codes.remove(&id);
981                    timeline
982                        .edges
983                        .retain(|_, edge| edge.from_node_id != id && edge.to_node_id != id);
984                }
985            }
986            "upsert-graph-edge" => {
987                let edge = pick(packet, "edge");
988                if edge["id"].as_str().is_some_and(|id| !id.is_empty()) {
989                    let edge = GraphEdge::from_json(edge);
990                    self.timeline().edges.insert(edge.id.clone(), edge);
991                }
992            }
993            "remove-graph-edge" => {
994                if let Some(id) = id_of(packet) {
995                    self.timeline().edges.remove(&id);
996                }
997            }
998            "upsert-trust-edge" => {
999                if let Some(edge) = trust_edge(pick(packet, "edge")) {
1000                    self.timeline()
1001                        .trust_edges
1002                        .insert(format!("{}->{}", edge.from, edge.to), edge);
1003                }
1004            }
1005            "remove-trust-edge" => {
1006                let field = |key: &str| {
1007                    if packet[key].is_null() {
1008                        packet["data"][key].as_str()
1009                    } else {
1010                        packet[key].as_str()
1011                    }
1012                };
1013                if let (Some(from), Some(to)) = (field("from"), field("to"))
1014                    && !from.is_empty()
1015                    && !to.is_empty()
1016                {
1017                    self.timeline().trust_edges.remove(&format!("{from}->{to}"));
1018                }
1019            }
1020            _ => {}
1021        }
1022        None
1023    }
1024
1025    fn upsert_graph_node_frame(&self, packet: &Value) -> Option<BoxFuture<'static, Result<()>>> {
1026        let node = pick(packet, "node");
1027        let access_code = if packet["accessCode"].is_null() {
1028            &packet["data"]["accessCode"]
1029        } else {
1030            &packet["accessCode"]
1031        };
1032        let wire: Option<GraphNodeWire> = serde_json::from_value(node.clone())
1033            .ok()
1034            .filter(|node: &GraphNodeWire| !node.id.is_empty());
1035        let wire = wire?;
1036        let authorization = self.get_authorization().clone();
1037        let mut timeline = self.timeline();
1038        let incoming = merge_previous(
1039            timeline.nodes.get(&wire.id),
1040            GraphNode::from_json(&wire, None),
1041        );
1042        timeline.nodes.insert(wire.id.clone(), incoming);
1043        if let Ok(meta) = serde_json::from_value::<FileAccessCodeMeta>(access_code.clone())
1044            && !meta.code.is_empty()
1045        {
1046            timeline.file_access_codes.insert(wire.id.clone(), meta);
1047            attach_drive_file(&mut timeline, &authorization, &wire.id);
1048            return None;
1049        }
1050        let needs_file = match timeline.nodes.get(&wire.id) {
1051            Some(GraphNode::File(_)) => true,
1052            Some(GraphNode::X(node)) => node.wire_path.is_some() || !node.media.is_empty(),
1053            Some(GraphNode::LinkedIn(node)) => node.wire_path.is_some() || !node.media.is_empty(),
1054            _ => false,
1055        };
1056        if needs_file && !timeline.file_access_codes.contains_key(&wire.id) {
1057            drop(timeline);
1058            let room = self.clone();
1059            let id = wire.id;
1060            return Some(Box::pin(async move {
1061                room.remint_file_access_code(&id).await?;
1062                Ok(())
1063            }));
1064        }
1065        None
1066    }
1067
1068    pub fn upsert_graph_node(&self, node: GraphNode) -> GraphNode {
1069        let next = {
1070            let mut timeline = self.timeline();
1071            let next = merge_file(timeline.nodes.get(node.id()), node);
1072            timeline.nodes.insert(next.id().to_string(), next.clone());
1073            next
1074        };
1075        self.post(&json!({ "event": "upsert-graph-node", "node": next.to_json() }));
1076        next
1077    }
1078
1079    pub fn remove_graph_node(&self, id: &str) {
1080        if id == "start" {
1081            return;
1082        }
1083        {
1084            let mut timeline = self.timeline();
1085            timeline.nodes.remove(id);
1086            timeline.file_access_codes.remove(id);
1087            timeline
1088                .edges
1089                .retain(|_, edge| edge.from_node_id != id && edge.to_node_id != id);
1090        }
1091        self.post(&json!({ "event": "remove-graph-node", "id": id }));
1092    }
1093
1094    pub fn upsert_graph_edge(&self, edge: GraphEdge) -> GraphEdge {
1095        self.timeline().edges.insert(edge.id.clone(), edge.clone());
1096        self.post(&json!({ "event": "upsert-graph-edge", "edge": edge.to_json() }));
1097        edge
1098    }
1099
1100    pub fn remove_graph_edge(&self, id: &str) {
1101        self.timeline().edges.remove(id);
1102        self.post(&json!({ "event": "remove-graph-edge", "id": id }));
1103    }
1104
1105    /// Upload bytes to the host drive and create/update a durable file node.
1106    pub async fn upload_file_node(
1107        &self,
1108        file: Vec<u8>,
1109        opts: UploadFileOptions,
1110    ) -> Result<UploadedFile> {
1111        let content_type = opts
1112            .content_type
1113            .filter(|content_type| !content_type.is_empty())
1114            .unwrap_or_else(|| "application/octet-stream".to_string());
1115        let mut request = self
1116            .scoped(client().post(format!("{}/timeline/graph/file", super::get_url())))
1117            .header("Content-Type", content_type)
1118            .header("Filename", &opts.name)
1119            .header("X", opts.x.to_string())
1120            .header("Y", opts.y.to_string());
1121        if let Some(node_id) = opts.node_id.filter(|id| !id.is_empty()) {
1122            request = request.header("Node-Id", node_id);
1123        }
1124        if let Some(kind) = opts.kind {
1125            request = request.header(
1126                "Kind",
1127                serde_json::to_value(kind)?.as_str().unwrap_or_default(),
1128            );
1129        }
1130        let json: Value = ok(request.body(file).send().await?).await?.json().await?;
1131        let access_code: FileAccessCodeMeta = serde_json::from_value(json["accessCode"].clone())?;
1132        let wire: GraphNodeWire = serde_json::from_value(json["node"].clone())?;
1133        let handle = from_access_code(
1134            self.get_authorization().clone(),
1135            &access_code.code,
1136            FileMeta {
1137                name: access_code.name.clone(),
1138                content_type: access_code.content_type.clone(),
1139                ..FileMeta::default()
1140            },
1141        );
1142        let node = GraphNode::from_json(&wire, Some(FileOrFiles::File(handle)));
1143        {
1144            let mut timeline = self.timeline();
1145            timeline.nodes.insert(node.id().to_string(), node.clone());
1146            timeline
1147                .file_access_codes
1148                .insert(node.id().to_string(), access_code.clone());
1149        }
1150        Ok(UploadedFile { node, access_code })
1151    }
1152
1153    pub async fn remint_file_access_code(&self, node_id: &str) -> Result<FileAccessCodeMeta> {
1154        let response = self
1155            .scoped(client().post(format!(
1156                "{}/timeline/graph/file/access-code",
1157                super::get_url()
1158            )))
1159            .json(&json!({ "nodeId": node_id }))
1160            .send()
1161            .await?;
1162        let meta: FileAccessCodeMeta = ok(response).await?.json().await?;
1163        let authorization = self.get_authorization().clone();
1164        let mut timeline = self.timeline();
1165        timeline
1166            .file_access_codes
1167            .insert(node_id.to_string(), meta.clone());
1168        attach_drive_file(&mut timeline, &authorization, node_id);
1169        Ok(meta)
1170    }
1171
1172    /// Build a drive::File handle for a graph file node (remints if needed).
1173    pub async fn file_for_node(&self, node_id: &str) -> Result<drive::File> {
1174        let meta = self.open_graph_file(node_id).await?;
1175        Ok(from_access_code(
1176            self.get_authorization().clone(),
1177            &meta.code,
1178            FileMeta {
1179                name: meta.name,
1180                content_type: meta.content_type,
1181                ..FileMeta::default()
1182            },
1183        ))
1184    }
1185
1186    /// Remint if needed and return the short-lived Drive access code for a file node.
1187    pub async fn open_graph_file(&self, node_id: &str) -> Result<FileAccessCodeMeta> {
1188        let known = self
1189            .timeline()
1190            .file_access_codes
1191            .get(node_id)
1192            .filter(|meta| !meta.code.is_empty())
1193            .cloned();
1194        match known {
1195            Some(meta) => Ok(meta),
1196            None => self.remint_file_access_code(node_id).await,
1197        }
1198    }
1199
1200    pub fn upsert_agent(&self, identity: Identity) -> Agent {
1201        let agent = {
1202            let mut timeline = self.timeline();
1203            let preferred = identity.id.trim().to_string();
1204            let id = if !preferred.is_empty() && !timeline.agents.contains_key(&preferred) {
1205                preferred
1206            } else {
1207                let mut n = 0;
1208                while timeline.agents.contains_key(&n.to_string()) {
1209                    n += 1;
1210                }
1211                n.to_string()
1212            };
1213            let agent = Agent {
1214                room: self.room.clone(),
1215                parent: Arc::downgrade(&self.state),
1216                id,
1217                persona: identity,
1218                repository: None,
1219            };
1220            timeline.agents.insert(agent.id.clone(), agent.clone());
1221            agent
1222        };
1223        self.post(&json!({ "event": "upsert-agent", "agent": agent.to_json() }));
1224        agent
1225    }
1226
1227    pub fn remove_agent(&self, id: &str) {
1228        self.timeline().agents.remove(id);
1229        self.post(&json!({ "event": "remove-agent", "id": id }));
1230    }
1231
1232    pub fn upsert_poll(&self, goal: &str, query: Vec<AntFormatOrFormat>) -> Poll {
1233        let poll = {
1234            let mut timeline = self.timeline();
1235            let mut id = 0;
1236            while timeline.polls.contains_key(&id.to_string()) {
1237                id += 1;
1238            }
1239            let poll = Poll::new(&id.to_string(), goal, query);
1240            timeline.polls.insert(poll.id.clone(), poll.clone());
1241            poll
1242        };
1243        self.post(&json!({ "event": "upsert-poll", "poll": poll.to_json() }));
1244        poll
1245    }
1246
1247    pub fn remove_poll(&self, id: &str) {
1248        self.timeline().polls.remove(id);
1249        self.post(&json!({ "event": "remove-poll", "id": id }));
1250    }
1251
1252    /// Create the poll and queue its run in one request. Resolves the run id;
1253    /// the run itself arrives through the room's `upsert-run` delta.
1254    pub async fn start_run(&self, goal: &str, query: &[AntFormatOrFormat]) -> Result<String> {
1255        let response = self
1256            .scoped(client().post(format!("{}/timeline/run", super::get_url())))
1257            .json(&json!({
1258                "goal": goal,
1259                "query": query.iter().map(AntFormatOrFormat::to_json).collect::<Vec<_>>(),
1260            }))
1261            .send()
1262            .await?;
1263        let json: Value = ok(response).await?.json().await?;
1264        Ok(match &json["runId"] {
1265            Value::String(id) => id.clone(),
1266            Value::Null => String::new(),
1267            id => id.to_string(),
1268        })
1269    }
1270
1271    pub async fn abort_run(&self, run_id: &str) -> Result<()> {
1272        let response = self
1273            .scoped(client().post(format!("{}/timeline/run/abort", super::get_url())))
1274            .json(&json!({ "runId": run_id }))
1275            .send()
1276            .await?;
1277        ok(response).await?;
1278        Ok(())
1279    }
1280
1281    /// Lazily mint/open the architect Parrot ChatRoom.
1282    pub async fn get_chat(&self, hooks: Option<Arc<dyn RoomHooks>>) -> Result<TimelineChat> {
1283        self.open_chat("", hooks).await
1284    }
1285
1286    /// Ensure a Parrot chat (architect when `agent_id` is empty) and connect live.
1287    /// Timeline members join by reference (non-guest); access-code guests use the
1288    /// short-lived code so leave/reap semantics stay correct.
1289    pub async fn open_chat(
1290        &self,
1291        agent_id: &str,
1292        hooks: Option<Arc<dyn RoomHooks>>,
1293    ) -> Result<TimelineChat> {
1294        let response = self
1295            .scoped(client().post(format!("{}/timeline/chat/ensure", super::get_url())))
1296            .json(&json!({ "agentId": agent_id }))
1297            .send()
1298            .await?;
1299        let json: Value = ok(response).await?.json().await?;
1300        let chat_id = json["chatId"].as_str().unwrap_or_default().to_string();
1301        let code = json["code"].as_str().unwrap_or_default().to_string();
1302        if chat_id.is_empty() || code.is_empty() {
1303            return Err(Error::Message("Invalid ensure response.".to_string()));
1304        }
1305        let target = match self.authorization() {
1306            Authorization::AccessCode { .. } => ChatTarget::Code { code },
1307            Authorization::Server { .. } => ChatTarget::Reference {
1308                reference: json["reference"]
1309                    .as_str()
1310                    .filter(|reference| !reference.is_empty())
1311                    .map(str::to_string)
1312                    .unwrap_or_else(|| format!("parrot:chat:{chat_id}")),
1313            },
1314        };
1315        let (room, me) = connect_room(self.get_authorization(), &target, hooks).await?;
1316        Ok(TimelineChat { room, me, chat_id })
1317    }
1318
1319    /// Connect to an owned timeline. Principal is resolved server-side from auth
1320    /// (+ optional Group).
1321    pub async fn connect(
1322        authorization: &CredentialsOrApiKey,
1323        target_id: &str,
1324        opts: ConnectOptions,
1325    ) -> Result<(TimelineRoom, Presence)> {
1326        TimelineRoom::open(
1327            Authorization::Server {
1328                authorization: authorization.clone(),
1329                server: opts.server.unwrap_or_else(|| target_id.to_string()),
1330                group: opts.group.as_ref().map(|group| group.id.clone()),
1331            },
1332            opts.hooks,
1333        )
1334        .await
1335    }
1336
1337    pub async fn join(
1338        authorization: &CredentialsOrApiKey,
1339        access_code: &str,
1340        hooks: Option<Arc<dyn Hooks>>,
1341    ) -> Result<(TimelineRoom, Presence)> {
1342        TimelineRoom::open(
1343            Authorization::AccessCode {
1344                authorization: authorization.clone(),
1345                access_code: access_code.to_string(),
1346            },
1347            hooks,
1348        )
1349        .await
1350    }
1351
1352    async fn open(
1353        auth: Authorization,
1354        hooks: Option<Arc<dyn Hooks>>,
1355    ) -> Result<(TimelineRoom, Presence)> {
1356        let state = Arc::new(TimelineState {
1357            timeline: Mutex::new(Timeline::default()),
1358            watchers: Mutex::new(Vec::new()),
1359            next_watcher: AtomicU64::new(0),
1360        });
1361        let me = connect_server(
1362            auth,
1363            &format!("{}/timeline", super::get_url()),
1364            Arc::new(TimelineHooks {
1365                state: state.clone(),
1366                user: hooks.unwrap_or_else(|| Arc::new(())),
1367            }),
1368        )
1369        .await?;
1370        Ok((
1371            TimelineRoom {
1372                room: me.room().clone(),
1373                state,
1374            },
1375            me,
1376        ))
1377    }
1378}
1379
1380/// Keeps a file node's file (and its path) when the incoming copy has none.
1381fn merge_file(previous: Option<&GraphNode>, next: GraphNode) -> GraphNode {
1382    match (previous, next) {
1383        (Some(GraphNode::File(previous)), GraphNode::File(mut next)) => {
1384            if next.file.is_none() {
1385                next.file = previous.file.clone();
1386            }
1387            if next.wire_path.as_deref().is_none_or(str::is_empty) {
1388                next.wire_path = previous.wire_path.clone();
1389            }
1390            GraphNode::File(next)
1391        }
1392        (_, next) => next,
1393    }
1394}
1395
1396/// `merge_file`, plus a post's media when the incoming copy has none.
1397fn merge_previous(previous: Option<&GraphNode>, next: GraphNode) -> GraphNode {
1398    let previous_media = match previous {
1399        Some(GraphNode::X(node)) => Some(&node.media),
1400        Some(GraphNode::LinkedIn(node)) => Some(&node.media),
1401        _ => None,
1402    };
1403    match (previous_media, merge_file(previous, next)) {
1404        (Some(media), GraphNode::X(mut node)) if node.media.is_empty() && !media.is_empty() => {
1405            node.media = media.clone();
1406            GraphNode::X(node)
1407        }
1408        (Some(media), GraphNode::LinkedIn(mut node))
1409            if node.media.is_empty() && !media.is_empty() =>
1410        {
1411            node.media = media.clone();
1412            GraphNode::LinkedIn(node)
1413        }
1414        (_, next) => next,
1415    }
1416}
1417
1418fn attach_drive_file(timeline: &mut Timeline, authorization: &CredentialsOrApiKey, node_id: &str) {
1419    let Some(meta) = timeline
1420        .file_access_codes
1421        .get(node_id)
1422        .filter(|meta| !meta.code.is_empty())
1423        .cloned()
1424    else {
1425        return;
1426    };
1427    let Some(node) = timeline.nodes.get_mut(node_id) else {
1428        return;
1429    };
1430    let file = from_access_code(
1431        authorization.clone(),
1432        &meta.code,
1433        FileMeta {
1434            name: meta.name,
1435            content_type: meta.content_type,
1436            ..FileMeta::default()
1437        },
1438    );
1439    match node {
1440        GraphNode::File(node) => node.file = Some(file),
1441        GraphNode::X(node) => match node.media.first_mut() {
1442            Some(first) => *first = file,
1443            None => node.media = vec![file],
1444        },
1445        GraphNode::LinkedIn(node) => match node.media.first_mut() {
1446            Some(first) => *first = file,
1447            None => node.media = vec![file],
1448        },
1449        _ => {}
1450    }
1451}
1452
1453struct TimelineHooks {
1454    state: Arc<TimelineState>,
1455    user: Arc<dyn Hooks>,
1456}
1457
1458impl TimelineHooks {
1459    fn room(&self, room: &Room) -> TimelineRoom {
1460        TimelineRoom {
1461            room: room.clone(),
1462            state: self.state.clone(),
1463        }
1464    }
1465}
1466
1467impl Hooks for TimelineHooks {
1468    fn create_room(&self, room: &Room, state: &Value) {
1469        lock(&self.state.timeline).timeline_id = room.id().to_string();
1470        self.user.create_room(room, state);
1471    }
1472
1473    fn create_presence(&self, room: &Room, presence: &Presence) {
1474        self.user.create_presence(room, presence);
1475    }
1476
1477    fn remove_presence(&self, room: &Room, presence: &Presence) {
1478        self.user.remove_presence(room, presence);
1479    }
1480
1481    fn on_connection(&self, room: &Room, state: &Value) {
1482        self.room(room).hydrate(state);
1483        self.user.on_connection(room, state);
1484    }
1485
1486    // When applying the frame needs a fresh file code, the user hears it now and
1487    // again once the code is in.
1488    fn on_event(&self, room: &Room, packet: &Value) -> bool {
1489        if let Some(pending) = self.room(room).handle_event(packet) {
1490            self.user.on_event(room, packet);
1491            let user = self.user.clone();
1492            let room = room.clone();
1493            let packet = packet.clone();
1494            tokio::spawn(async move {
1495                let _ = pending.await;
1496                user.on_event(&room, &packet);
1497            });
1498            return true;
1499        }
1500        self.user.on_event(room, packet);
1501        true
1502    }
1503
1504    fn on_presence(&self, room: &Room) {
1505        self.user.on_presence(room);
1506    }
1507
1508    fn on_closed(&self, room: &Room, reason: Option<&str>) {
1509        self.user.on_closed(room, reason);
1510    }
1511}
1512
1513/// Write a standalone fact onto this agent's Parrot graph (`ant/timelines/…/memory`).
1514pub async fn observe_agent(
1515    authorization: &CredentialsOrApiKey,
1516    timeline_id: &str,
1517    agent_id: &str,
1518    content: &str,
1519    opts: AccessOptions,
1520) -> Result<Memory> {
1521    let request = authorized(
1522        client().post(format!("{}/timeline/agent/observe", super::get_url())),
1523        authorization,
1524        None,
1525    );
1526    let response = scoped(
1527        request,
1528        timeline_id,
1529        opts.group.as_ref(),
1530        opts.access_code.as_deref(),
1531    )
1532    .json(&json!({ "agentId": agent_id, "content": content }))
1533    .send()
1534    .await?;
1535    Ok(ok(response).await?.json().await?)
1536}
1537
1538/// The `opts` argument of `generate_agent`. Dropping the returned stream closes the socket.
1539#[derive(Debug, Clone, Default)]
1540pub struct GenerateOptions {
1541    pub group: Option<Group>,
1542    pub access_code: Option<String>,
1543    pub tools: Option<Vec<Tool>>,
1544}
1545
1546/// Stream a persona reply for one agent (Gemini Flash + medium thinking + memories).
1547/// Parrot-compatible StreamEvents for chat generate mode, plus `tool` and
1548/// `tool-result` events for the persona's own tools. `tools` are answered here
1549/// when the persona calls them, like `use_computer` asking for a computer.
1550pub async fn generate_agent(
1551    authorization: &CredentialsOrApiKey,
1552    timeline_id: &str,
1553    agent_id: &str,
1554    messages: &[Content],
1555    opts: GenerateOptions,
1556) -> Result<BoxStream<'static, StreamEvent>> {
1557    let auth = socket_auth(
1558        authorization,
1559        ("Timeline", timeline_id),
1560        opts.group.as_ref(),
1561        opts.access_code.as_deref(),
1562    );
1563    let url = format!(
1564        "{}/timeline/agent/generate?authorization={auth}",
1565        websocket(&super::get_url())
1566    );
1567    let tools = opts.tools.unwrap_or_default();
1568    let messages = serialize_messages(authorization, messages).await?;
1569    let functions: Vec<&crate::parrot::generative::Function> =
1570        tools.iter().map(|tool| &tool.function).collect();
1571    let generate = json!({ "event": "generate", "agentId": agent_id, "messages": messages, "tools": functions });
1572    agent_stream(url, generate, tools).await
1573}
1574
1575#[cfg(test)]
1576mod tests {
1577    use serde_json::json;
1578    use tokio::sync::mpsc;
1579
1580    use super::*;
1581    use crate::authentification::ApiKey;
1582    use crate::drive::DriveAuthorization;
1583
1584    fn timeline_room() -> TimelineRoom {
1585        let (ws, _outbox) = mpsc::unbounded_channel();
1586        TimelineRoom {
1587            room: Room::new(
1588                "http://localhost/timeline".to_string(),
1589                ws,
1590                Authorization::Server {
1591                    authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
1592                    server: "t1".to_string(),
1593                    group: Some("4".to_string()),
1594                },
1595                "t1".to_string(),
1596            ),
1597            state: Arc::new(TimelineState {
1598                timeline: Mutex::new(Timeline::default()),
1599                watchers: Mutex::new(Vec::new()),
1600                next_watcher: AtomicU64::new(0),
1601            }),
1602        }
1603    }
1604
1605    #[test]
1606    fn runs_and_polls_read_the_wire() {
1607        let run = Run::new(&json!({
1608            "id": "r1", "pollId": "0", "status": "aborting", "agentIds": ["0"],
1609            "polls": { "progress": { "activeNodeIds": ["n1"], "byStimulus": { "n1": { "stimulusLabel": "Post", "phase": "browse", "done": 1, "total": 3 } } } },
1610            "trajectories": [{ "id": "t", "nodes": [{ "id": "n1", "kind": "x", "title": "Post" }] }],
1611            "startedAt": 5
1612        }));
1613        assert_eq!(run.status, RunStatus::Running);
1614        assert_eq!(
1615            run.progress.unwrap().by_stimulus["n1"].phase,
1616            StimulusPhase::Browse
1617        );
1618        assert_eq!(run.trajectories[0].nodes[0].title, "Post");
1619        assert!(run_is_active(Some("pending")));
1620        assert!(!run_is_active(Some("done")));
1621
1622        let poll = Poll::from_json(&json!({
1623            "id": "0", "goal": "Would they share it?",
1624            "query": [{ "type": "linkedin", "answer": "Share" }, "not a format"]
1625        }));
1626        assert_eq!(poll.query.len(), 1);
1627        let json = poll.clone().to_json();
1628        assert_eq!(json["query"][0]["type"], "linkedin");
1629        assert_eq!(json["query"][0]["answer"], "Share");
1630    }
1631
1632    #[test]
1633    fn timeline_rooms_follow_graph_frames_and_attach_files() {
1634        let room = timeline_room();
1635        room.hydrate(&json!({
1636            "id": "t1", "name": "Launch", "owner": "group:4", "status": "RUNNING",
1637            "graph": {
1638                "nodes": [
1639                    { "id": "start", "kind": "start", "x": 0, "y": 0, "label": "Start" },
1640                    { "id": "f1", "kind": "file", "x": 1, "y": 1, "label": "deck.pdf", "filePath": "ant/deck.pdf" }
1641                ],
1642                "edges": [{ "id": "e1", "fromNodeId": "start", "toNodeId": "f1" }]
1643            },
1644            "fileAccessCodes": { "f1": { "code": "abc", "name": "deck.pdf", "contentType": "application/pdf" } },
1645            "trustEdges": [{ "from": "0", "to": "1", "weight": 0.4 }, { "from": "1", "to": "0", "weight": 0 }]
1646        }));
1647        assert_eq!(room.status(), "RUNNING");
1648        assert_eq!(room.trust_edges().len(), 1);
1649        let GraphNode::File(file) = &room.nodes()["f1"] else {
1650            panic!("expected a file node");
1651        };
1652        assert!(matches!(
1653            &file.file.as_ref().unwrap().authorization,
1654            DriveAuthorization::AccessCode { access_code, .. } if access_code == "abc"
1655        ));
1656
1657        assert!(room
1658            .handle_event(&json!({ "event": "upsert-graph-node", "node": { "id": "f1", "kind": "file", "x": 5, "y": 5, "label": "deck.pdf" } }))
1659            .is_none());
1660        let GraphNode::File(file) = &room.nodes()["f1"] else {
1661            panic!("expected a file node");
1662        };
1663        assert_eq!(file.x, 5.0);
1664        assert_eq!(file.wire_path.as_deref(), Some("ant/deck.pdf"));
1665        assert!(file.file.is_some());
1666
1667        assert!(room
1668            .handle_event(&json!({ "event": "upsert-graph-node", "node": { "id": "f2", "kind": "file", "x": 0, "y": 0, "label": "new.png" } }))
1669            .is_some());
1670        room.handle_event(&json!({ "event": "remove-graph-node", "data": { "id": "f1" } }));
1671        assert!(room.edges().is_empty());
1672        room.handle_event(&json!({ "event": "timeline-removed" }));
1673        assert!(room.removed());
1674    }
1675}