Skip to main content

objectiveai_sdk/daemon/
file_tree.rs

1//! Materialized consumer of a live file-tree SSE stream — a
2//! laboratory MCP's own `/filetree` endpoint
3//! ([`FileTree::laboratory`]) or a CLI daemon's
4//! `/laboratories/{id}/filetree` proxy
5//! ([`Client::file_tree`](crate::daemon::Client::file_tree)); both
6//! speak the identical wire contract.
7//!
8//! [`FileTree`] is NOT a raw event stream — it connects once, then
9//! folds every incoming [`FileTreeEvent`] into an in-memory,
10//! self-updating recursive tree (the watched root's
11//! [`FileTreeNode`] children): a
12//! [`Snapshot`](FileTreeEvent::Snapshot) replaces the whole child set,
13//! [`Upserted`](FileTreeEvent::Upserted) inserts/replaces one node at
14//! its path (a directory node carries its whole subtree), and
15//! [`Removed`](FileTreeEvent::Removed) drops the node at its path.
16//!
17//! Ways to observe it:
18//! - [`tree`](FileTree::tree) — async snapshot of the current tree.
19//! - [`subscribe`](FileTree::subscribe) — async, blocks until the next
20//!   change.
21//! - [`changes`](FileTree::changes) — the raw change-counter receiver,
22//!   for race-free condition waits.
23//!
24//! The machine/machine_state query the daemon route accepts is not
25//! surfaced here (no consumer); add when needed.
26//!
27//! One [`FileTree`] = one connection: the internal pump runs until the
28//! laboratory closes the stream; after that the view is frozen at its
29//! last state. Dropping it aborts the pump. Reconnection is the
30//! caller's loop — mint a new [`FileTree`].
31
32use std::sync::Arc;
33
34use futures::StreamExt;
35use reqwest_eventsource::{Event, RequestBuilderExt};
36use tokio::sync::{Mutex, watch};
37
38use crate::daemon::Error;
39use crate::laboratories::filetree::{FileTreeEvent, FileTreeNode};
40
41/// The shared inner state, held by both the [`FileTree`] handle and
42/// its pump task.
43struct Shared {
44    /// The tree itself: the watched root's child nodes, kept live by
45    /// folding each event.
46    state: Mutex<Vec<FileTreeNode>>,
47    /// A monotonically-bumped change counter. Each applied event bumps
48    /// it, waking every [`subscribe`](FileTree::subscribe) waiter.
49    changes: watch::Sender<u64>,
50}
51
52/// The materialized `/filetree` view — see the module docs. Minted by
53/// [`Client::file_tree`](crate::daemon::Client::file_tree) (daemon
54/// flavor) or [`FileTree::laboratory`]; returned only once the stream
55/// has OPENED. Dropping it aborts the background pump.
56pub struct FileTree {
57    shared: Arc<Shared>,
58    pump: tokio::task::JoinHandle<()>,
59}
60
61impl FileTree {
62    /// The daemon flavor — minted by
63    /// [`Client::file_tree`](crate::daemon::Client::file_tree). Opens
64    /// the daemon's `/laboratories/{id}/filetree` proxy (the RAW
65    /// laboratory id — ids forbid `/`, so the URL is safe by
66    /// construction), awaiting the open frame, and starts the pump.
67    /// Same wire contract as the laboratory flavor — the daemon
68    /// re-emits the identical events from its own materialized state,
69    /// always serving the laboratory's workspace (its cwd).
70    pub(crate) async fn connect_daemon(
71        client: &crate::daemon::Client,
72        laboratory_id: &str,
73    ) -> Result<FileTree, Error> {
74        let source = client
75            .open_sse(&format!("/laboratories/{laboratory_id}/filetree"))
76            .await?;
77        Ok(Self::start(source))
78    }
79
80    /// The LABORATORY flavor: dial a laboratory's OWN `/filetree` (no
81    /// auth — loopback-only lab server), optionally scoped to `path`
82    /// (an absolute path inside the container), from its base HTTP
83    /// address (e.g. `http://127.0.0.1:<port>` — the loopback-published
84    /// container port; the port itself is the trust boundary). Awaits
85    /// the open frame, then starts the pump.
86    pub async fn laboratory(
87        base_url: &str,
88        path: Option<&str>,
89    ) -> Result<FileTree, Error> {
90        let mut request = reqwest::Client::new()
91            .get(format!("{}/filetree", base_url.trim_end_matches('/')))
92            .header("Accept", "text/event-stream");
93        if let Some(path) = path {
94            request = request.query(&[("path", path)]);
95        }
96        let mut source = request.eventsource()?;
97        // reqwest-eventsource yields `Open` first on a successful
98        // response; an error (invalid status included) or immediate
99        // end means the stream never opened.
100        match source.next().await {
101            Some(Ok(Event::Open)) => {}
102            Some(Err(e)) => return Err(Error::Open(e)),
103            Some(Ok(Event::Message(_))) | None => return Err(Error::Closed),
104        }
105        Ok(Self::start(source))
106    }
107
108    /// Build the shared state and spawn the pump over an
109    /// already-opened stream.
110    fn start(source: reqwest_eventsource::EventSource) -> FileTree {
111        let shared = Arc::new(Shared {
112            state: Mutex::new(Vec::new()),
113            changes: watch::channel(0u64).0,
114        });
115        let pump = tokio::spawn(pump(source, shared.clone()));
116        FileTree { shared, pump }
117    }
118
119    /// Snapshot the current tree — the watched root's child nodes.
120    /// Empty before the first snapshot has been folded.
121    pub async fn tree(&self) -> Vec<FileTreeNode> {
122        self.shared.state.lock().await.clone()
123    }
124
125    /// Block until the next change is applied. A fresh call waits for
126    /// the FIRST change after it is made, so a change that lands
127    /// between a preceding [`tree`](Self::tree) read and this
128    /// call is not observed by it — pair with the read in a loop, or
129    /// hold a [`changes`](Self::changes) receiver for race-free waits.
130    pub async fn subscribe(&self) {
131        let mut rx = self.shared.changes.subscribe();
132        let _ = rx.changed().await;
133    }
134
135    /// The raw change-counter receiver — for RACE-FREE condition
136    /// waits: hold ONE receiver across iterations of a
137    /// check-then-await loop, and an event landing between the check
138    /// and the await still resolves the next `changed()`.
139    pub fn changes(&self) -> watch::Receiver<u64> {
140        self.shared.changes.subscribe()
141    }
142}
143
144impl Drop for FileTree {
145    fn drop(&mut self) {
146        self.pump.abort();
147    }
148}
149
150/// Read SSE messages, fold each [`FileTreeEvent`] into `shared.state`,
151/// and bump the change counter. Runs until the stream closes. Parse
152/// errors and non-message events are skipped; a transport error ends
153/// the pump (the caller rebuilds — reconnection is not automatic).
154async fn pump(mut source: reqwest_eventsource::EventSource, shared: Arc<Shared>) {
155    while let Some(event) = source.next().await {
156        match event {
157            Ok(Event::Open) => continue,
158            Ok(Event::Message(message)) => {
159                let Ok(event) = serde_json::from_str::<FileTreeEvent>(&message.data)
160                else {
161                    // Skip a frame we can't parse rather than tearing down.
162                    continue;
163                };
164                {
165                    let mut state = shared.state.lock().await;
166                    event.apply(&mut state);
167                }
168                shared.changes.send_modify(|version| {
169                    *version = version.wrapping_add(1);
170                });
171            }
172            // Transport error (including the stream closing): stop.
173            Err(_) => break,
174        }
175    }
176}