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