1use futures::StreamExt;
15use reqwest_eventsource::RequestBuilderExt;
16
17use super::Error;
18
19#[derive(Clone)]
23pub struct Client {
24 address: String,
27 signature: Option<String>,
30 identity: Option<crate::identity::Identity>,
34 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 pub fn signature(mut self, signature: impl Into<String>) -> Self {
53 self.signature = Some(signature.into());
54 self
55 }
56
57 pub fn identity(mut self, identity: crate::identity::Identity) -> Self {
63 self.identity = Some(identity);
64 self
65 }
66
67 pub fn address(&self) -> &str {
69 &self.address
70 }
71
72 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 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 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 #[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 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 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 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 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 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 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 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 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#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
276#[schemars(rename = "daemon.AuthEnvelope")]
277pub struct AuthEnvelope {
278 pub signature: Option<String>,
281}
282
283#[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#[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#[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 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 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 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}