Skip to main content

objectiveai_sdk/daemon/
client.rs

1//! THE daemon client: one [`Client`] holding the daemon's base
2//! address + auth signature + a shared HTTP pool, minting every
3//! per-endpoint structure — the materialized SSE listeners, the
4//! laboratory file tree, the viewer-plugin bundle download — and
5//! implementing [`CommandExecutor`] itself for `POST /execute`
6//! (feature `cli-executor`; no separate executor struct).
7//!
8//! Listener methods are async and return the materialized structure
9//! only once its SSE stream has actually OPENED (the `Open` frame is
10//! awaited — a bad address or a 401 is an `Err` here, never a
11//! silently-frozen view). One listener = one connection; reconnection
12//! is the caller's loop.
13
14use futures::StreamExt;
15use reqwest_eventsource::RequestBuilderExt;
16
17use super::Error;
18
19/// The daemon's HTTP surface behind one handle — see the module docs.
20/// Construct with [`Client::new`] from the daemon's published base
21/// address (e.g. `http://127.0.0.1:49152`).
22#[derive(Clone)]
23pub struct Client {
24    /// The daemon's base address, trailing-slash-trimmed; routes are
25    /// appended.
26    address: String,
27    /// Optional auth signature, sent as the `X-OBJECTIVEAI-SIGNATURE`
28    /// header on every request.
29    signature: Option<String>,
30    /// The client's own caller [`Identity`](crate::identity::Identity)
31    /// — the DEFAULT for surfaces that carry one (`/execute` headers):
32    /// a per-call identity, when given, wins over it.
33    identity: Option<crate::identity::Identity>,
34    /// The shared connection pool — every minted structure rides it.
35    http: reqwest::Client,
36}
37
38impl Client {
39    pub fn new(address: impl Into<String>) -> Self {
40        let address = address.into();
41        Self {
42            address: address.trim_end_matches('/').to_string(),
43            signature: None,
44            identity: None,
45            http: reqwest::Client::new(),
46        }
47    }
48
49    /// Attach the daemon auth signature (the pre-derived
50    /// `sha256=<hex(SHA256(DAEMON_SECRET))>`). Without it the daemon
51    /// must be running without a secret.
52    pub fn signature(mut self, signature: impl Into<String>) -> Self {
53        self.signature = Some(signature.into());
54        self
55    }
56
57    /// Attach this client's caller identity — the default identity
58    /// bag for every surface that carries one (`/execute`'s
59    /// `X-OBJECTIVEAI-*` headers). A per-call identity passed to
60    /// [`execute`](crate::cli::command::CommandExecutor::execute)
61    /// overrides it call-by-call.
62    pub fn identity(mut self, identity: crate::identity::Identity) -> Self {
63        self.identity = Some(identity);
64        self
65    }
66
67    /// The daemon's base address (trimmed), as constructed.
68    pub fn address(&self) -> &str {
69        &self.address
70    }
71
72    /// Open `{address}{route}` as an SSE stream and WAIT for it to
73    /// open — the `Open` frame (the 2xx response) must arrive before
74    /// this returns. 401s and transport failures surface here.
75    ///
76    /// PUBLIC as a low-level escape hatch: proxies (the viewer's Rust
77    /// shell) forward RAW SSE bodies to their own consumers — a shape
78    /// the materialized listeners deliberately don't serve.
79    pub async fn open_sse(
80        &self,
81        route: &str,
82    ) -> Result<reqwest_eventsource::EventSource, Error> {
83        let mut request = self
84            .http
85            .get(format!("{}{route}", self.address))
86            .header("Accept", "text/event-stream");
87        if let Some(signature) = &self.signature {
88            request = request.header("X-OBJECTIVEAI-SIGNATURE", signature);
89        }
90        let mut source = request.eventsource()?;
91        // reqwest-eventsource yields `Open` first on a successful
92        // response; an error (invalid status included) or immediate
93        // end means the stream never opened.
94        match source.next().await {
95            Some(Ok(reqwest_eventsource::Event::Open)) => Ok(source),
96            Some(Err(e)) => Err(Error::Open(e)),
97            Some(Ok(reqwest_eventsource::Event::Message(_))) | None => {
98                Err(Error::Closed)
99            }
100        }
101    }
102
103    /// A plain request to `{address}{route}` with the signature
104    /// stamped. PUBLIC as a low-level escape hatch (see
105    /// [`open_sse`](Self::open_sse)); the typed surfaces are the
106    /// front door.
107    pub fn request(
108        &self,
109        method: reqwest::Method,
110        route: &str,
111    ) -> reqwest::RequestBuilder {
112        let mut request = self
113            .http
114            .request(method, format!("{}{route}", self.address));
115        if let Some(signature) = &self.signature {
116            request = request.header("X-OBJECTIVEAI-SIGNATURE", signature);
117        }
118        request
119    }
120
121    /// The `/listen` broadcast as a typed stream —
122    /// [`CommandListener`](super::command_listener::CommandListener):
123    /// every CLI execution the daemon runs, request + response items,
124    /// dispatched onto the command tree's leaf types.
125    #[cfg(feature = "cli")]
126    pub async fn command_listener(
127        &self,
128    ) -> Result<super::command_listener::CommandListener, Error> {
129        super::command_listener::CommandListener::connect(self).await
130    }
131
132    /// The `/agents/instances/list` view: every agent's
133    /// active/inactive status, live.
134    pub async fn agents_instances_list_listener(
135        &self,
136    ) -> Result<super::agents_instances_list_listener::AgentsInstancesListListener, Error>
137    {
138        super::agents_instances_list_listener::AgentsInstancesListListener::connect(
139            self,
140        )
141        .await
142    }
143
144    /// The `/agents/instances/{aih}` view: ONE agent's full
145    /// conversation, DB history + live rows.
146    pub async fn agents_instances_listener(
147        &self,
148        agent_instance_hierarchy: &str,
149    ) -> Result<super::agents_instances_listener::AgentsInstancesListener, Error>
150    {
151        super::agents_instances_listener::AgentsInstancesListener::connect(
152            self,
153            agent_instance_hierarchy,
154        )
155        .await
156    }
157
158    /// The `/laboratories/list` view: the live laboratories merge
159    /// (connected ∪ local scan).
160    pub async fn laboratories_list_listener(
161        &self,
162    ) -> Result<super::laboratories_list_listener::LaboratoriesListListener, Error>
163    {
164        super::laboratories_list_listener::LaboratoriesListListener::connect(self)
165            .await
166    }
167
168    /// The `/laboratories/{id}` view: ONE laboratory's record with
169    /// attachments.
170    pub async fn laboratories_listener(
171        &self,
172        laboratory_id: &str,
173    ) -> Result<super::laboratories_listener::LaboratoriesListener, Error> {
174        super::laboratories_listener::LaboratoriesListener::connect(
175            self,
176            laboratory_id,
177        )
178        .await
179    }
180
181    /// The `/channels` offer-lifecycle view — answer its offers with
182    /// [`accept_channel`](Self::accept_channel).
183    pub async fn channel_listener(
184        &self,
185    ) -> Result<super::channel_listener::ChannelListener, Error> {
186        super::channel_listener::ChannelListener::connect(self).await
187    }
188
189    /// Accept an open channel offer: a bare
190    /// `POST /channels/{id}/accept` (first-wins). Returns the owner
191    /// secret (`S_owner`) from the response body — the per-channel
192    /// capability for `channels logs reply|list|open|subscribe` and
193    /// `channels close`.
194    pub async fn accept_channel(&self, channel_id: &str) -> Result<String, Error> {
195        let response = self
196            .request(
197                reqwest::Method::POST,
198                &format!("/channels/{channel_id}/accept"),
199            )
200            .send()
201            .await?;
202        let status = response.status();
203        if !status.is_success() {
204            return Err(match status {
205                reqwest::StatusCode::NOT_FOUND => Error::NotFound,
206                reqwest::StatusCode::CONFLICT => Error::AlreadyAccepted,
207                reqwest::StatusCode::UNAUTHORIZED => Error::Unauthorized,
208                _ => Error::Status {
209                    status,
210                    body: response.text().await.unwrap_or_default().trim().to_string(),
211                },
212            });
213        }
214        let body = response.text().await?;
215        let accepted: super::channel_listener::ChannelAccepted =
216            serde_json::from_str(&body)?;
217        Ok(accepted.secret)
218    }
219
220    /// The `/laboratories/{id}/filetree` view: one laboratory's live
221    /// file tree.
222    pub async fn file_tree(
223        &self,
224        laboratory_id: &str,
225    ) -> Result<super::file_tree::FileTree, Error> {
226        super::file_tree::FileTree::connect_daemon(self, laboratory_id).await
227    }
228
229    /// Download a plugin's viewer-extension bundle:
230    /// `GET /plugins/{owner}/{name}/{version}/viewer`, the daemon
231    /// building it on demand and streaming tar.gz back. LOW-LEVEL by
232    /// design — raw bytes, no filesystem; the caller un-tars its own
233    /// way. `version` is the plugin repo's v-prefixed git tag
234    /// (`v1.2.3`), byte-for-byte.
235    pub async fn get_viewer_plugin(
236        &self,
237        owner: &str,
238        name: &str,
239        version: &str,
240    ) -> Result<super::ViewerPlugin, Error> {
241        let response = self
242            .request(
243                reqwest::Method::GET,
244                &format!("/plugins/{owner}/{name}/{version}/viewer"),
245            )
246            .send()
247            .await?;
248        let status = response.status();
249        if !status.is_success() {
250            return Err(match status {
251                reqwest::StatusCode::NOT_FOUND => Error::NotFound,
252                reqwest::StatusCode::UNAUTHORIZED => Error::Unauthorized,
253                _ => Error::Status {
254                    status,
255                    body: response.text().await.unwrap_or_default().trim().to_string(),
256                },
257            });
258        }
259        let commit_sha = response
260            .headers()
261            .get("x-objectiveai-sha")
262            .and_then(|v| v.to_str().ok())
263            .map(str::to_string);
264        Ok(super::ViewerPlugin::new(commit_sha, response))
265    }
266}
267
268/// The first client→daemon frame on the `/laboratory` host-channel
269/// WebSocket (the daemon's ONE remaining WebSocket) — the auth preamble,
270/// always sent, even to a secretless daemon (`{"signature": null}`). A
271/// daemon holding a `DAEMON_SECRET` verifies the signature and closes
272/// the connection on a missing/invalid one; a secretless daemon consumes
273/// the envelope and ignores the value. (The HTTP routes authenticate by
274/// the `X-OBJECTIVEAI-SIGNATURE` header instead.)
275#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
276#[schemars(rename = "daemon.AuthEnvelope")]
277pub struct AuthEnvelope {
278    /// The pre-derived `sha256=<hex(SHA256(DAEMON_SECRET))>`, or
279    /// `null` when the client has none.
280    pub signature: Option<String>,
281}
282
283/// A transport error's FULL cause chain — `Display` alone hides the
284/// interesting part (reqwest's "error decoding response body" says
285/// nothing without the hyper cause underneath, e.g. "connection reset"
286/// vs "connection closed before message completed").
287#[cfg(feature = "cli-executor")]
288fn error_chain(e: &dyn std::error::Error) -> String {
289    let mut message = e.to_string();
290    let mut source = e.source();
291    while let Some(cause) = source {
292        message.push_str(": ");
293        message.push_str(&cause.to_string());
294        source = cause.source();
295    }
296    message
297}
298
299/// Per-event untagged decode. `Err` is listed first so serde tries it
300/// before `Ok` — `cli::Error`'s `type:"error"` constant short-circuits
301/// every non-error wire shape, then `Ok(T)` is the fallthrough.
302#[cfg(feature = "cli-executor")]
303#[derive(serde::Deserialize)]
304#[serde(untagged)]
305enum Line<T> {
306    Err(crate::cli::Error),
307    Ok(T),
308}
309
310#[cfg(feature = "cli-executor")]
311impl<T> From<Line<T>> for Result<T, super::ExecuteError> {
312    fn from(line: Line<T>) -> Self {
313        match line {
314            Line::Err(e) => Err(super::ExecuteError::Cli(e)),
315            Line::Ok(t) => Ok(t),
316        }
317    }
318}
319
320/// `POST /execute` — the [`Client`] IS the executor: each command is
321/// one POST whose result streams back as SSE, run in-process by the
322/// daemon with the [`crate::identity::Identity`] headers applied as a
323/// per-request config override (a missing header DELETES that field
324/// for the run — the daemon never inherits its own resident value).
325/// The `plugin_*` trio is deliberately never stamped: plugin caller
326/// identity is unspoofable — only the daemon's own `plugins run` may
327/// assert it. Dropping the returned stream aborts the request, which
328/// cancels the in-process run.
329#[cfg(feature = "cli-executor")]
330impl crate::cli::command::CommandExecutor for Client {
331    type Error = super::ExecuteError;
332    type Stream<T>
333        = std::pin::Pin<
334        Box<dyn futures::Stream<Item = Result<T, super::ExecuteError>> + Send>,
335    >
336    where
337        T: Send + 'static;
338
339    async fn execute<R, T>(
340        &self,
341        request: R,
342        identity: Option<&crate::identity::Identity>,
343    ) -> Result<Self::Stream<T>, super::ExecuteError>
344    where
345        R: crate::cli::command::CommandRequest + Send + serde::Serialize,
346        T: crate::cli::command::CommandResponse
347            + serde::Serialize
348            + serde::de::DeserializeOwned
349            + Send
350            + 'static,
351    {
352        use eventsource_stream::Eventsource;
353        let mut req = self
354            .http
355            .post(format!("{}/execute", self.address))
356            .header("Accept", "text/event-stream")
357            .json(&request);
358        if let Some(signature) = &self.signature {
359            req = req.header("X-OBJECTIVEAI-SIGNATURE", signature);
360        }
361        // Per-call identity wins; the client's own is the default.
362        if let Some(args) = identity.or(self.identity.as_ref()) {
363            if let Some(v) = &args.agent_instance_hierarchy {
364                req = req.header("X-OBJECTIVEAI-AGENT-INSTANCE-HIERARCHY", v);
365            }
366            if let Some(v) = &args.agent_id {
367                req = req.header("X-OBJECTIVEAI-AGENT-ID", v);
368            }
369            if let Some(v) = &args.agent_full_id {
370                req = req.header("X-OBJECTIVEAI-AGENT-FULL-ID", v);
371            }
372            if let Some(v) = &args.agent_remote {
373                req = req.header("X-OBJECTIVEAI-AGENT-REMOTE", v);
374            }
375            if let Some(v) = &args.response_id {
376                req = req.header("X-OBJECTIVEAI-RESPONSE-ID", v);
377            }
378            if let Some(v) = &args.response_ids {
379                req = req.header("X-OBJECTIVEAI-RESPONSE-IDS", v);
380            }
381        }
382        let response = req.send().await.map_err(super::ExecuteError::Connect)?;
383        if !response.status().is_success() {
384            let status = response.status();
385            let body = response.text().await.unwrap_or_default();
386            return Err(super::ExecuteError::Http(
387                status,
388                body.trim().to_string(),
389            ));
390        }
391
392        // The SSE body owns the connection; dropping the returned
393        // stream drops the body, which aborts the request and cancels
394        // the daemon-side run. `eventsource-stream` parses without
395        // reconnecting (the command stream is finite — body end = done).
396        let events = response.bytes_stream().eventsource();
397        let stream = events.map(|event| match event {
398            Ok(event) => match serde_json::from_str::<Line<T>>(&event.data) {
399                Ok(line) => line.into(),
400                Err(e) => Err(super::ExecuteError::Json(e)),
401            },
402            // `EventStreamError::Transport` does NOT expose its inner
403            // reqwest error via `source()` — unwrap it by hand so the
404            // hyper cause chain (reset vs premature close vs framing)
405            // actually reaches the message.
406            Err(eventsource_stream::EventStreamError::Transport(e)) => Err(
407                super::ExecuteError::Sse(format!("transport: {}", error_chain(&e))),
408            ),
409            Err(e) => Err(super::ExecuteError::Sse(error_chain(&e))),
410        });
411
412        Ok(Box::pin(stream))
413    }
414
415    async fn execute_one<R, T>(
416        &self,
417        request: R,
418        identity: Option<&crate::identity::Identity>,
419    ) -> Result<T, super::ExecuteError>
420    where
421        R: crate::cli::command::CommandRequest + Send + serde::Serialize,
422        T: crate::cli::command::CommandResponse
423            + serde::Serialize
424            + serde::de::DeserializeOwned
425            + Send
426            + 'static,
427    {
428        let mut stream = self.execute::<R, T>(request, identity).await?;
429        stream.next().await.ok_or(super::ExecuteError::Empty)?
430    }
431}