Skip to main content

diavlos_client/
lib.rs

1//! The Diavlos library. For agents you build yourself.
2//!
3//! The same calls as the MCP tools: send, ask, next (and take, ack, renew,
4//! nack), read, claim, release, who, rooms. Everything goes through the
5//! local helper, which is started on first use.
6//!
7//! ```no_run
8//! # async fn demo() -> diavlos_core::Result<()> {
9//! use diavlos_client::{Paths, Room, SendOptions};
10//! let paths = Paths::resolve(None).unwrap();
11//! let room = Room::join(&paths, "dv1.…", "my-bot").await?;
12//! loop {
13//!     let msg = room.next(0).await?;
14//!     if msg.kind == diavlos_core::MessageType::Task {
15//!         room.send("done", SendOptions::done(&msg.id)).await?;
16//!     }
17//! }
18//! # }
19//! ```
20
21pub mod client;
22pub mod paths;
23pub mod proto;
24
25pub use client::Client;
26pub use paths::Paths;
27
28use diavlos_core::{Error, Message, MessageType, Result};
29use proto::{
30    DraftWire, JoinResult, NextResult, ReadResult, Request, RoomStatus, SendResult, WhoEntry,
31};
32
33/// Options for `send`.
34#[derive(Debug, Clone, Default)]
35pub struct SendOptions {
36    pub kind: Option<MessageType>,
37    pub to: Option<String>,
38    pub reply_to: Option<String>,
39    pub trace: Option<String>,
40    pub data: serde_json::Value,
41    pub action: Option<diavlos_core::Action>,
42    /// Files to send with it, as paths on this machine.
43    pub files: Vec<std::path::PathBuf>,
44}
45
46impl SendOptions {
47    pub fn kind(kind: MessageType) -> Self {
48        SendOptions {
49            kind: Some(kind),
50            ..Default::default()
51        }
52    }
53    /// A `done` answering a task.
54    pub fn done(task_id: &str) -> Self {
55        SendOptions {
56            kind: Some(MessageType::Done),
57            reply_to: Some(task_id.into()),
58            ..Default::default()
59        }
60    }
61    /// A `reply` answering a message.
62    pub fn reply(msg_id: &str) -> Self {
63        SendOptions {
64            kind: Some(MessageType::Reply),
65            reply_to: Some(msg_id.into()),
66            ..Default::default()
67        }
68    }
69}
70
71/// One room, seen as one identity.
72#[derive(Debug, Clone)]
73pub struct Room {
74    client: Client,
75    pub room: String,
76    pub identity: String,
77    /// Your name inside the room, once known.
78    pub name: Option<String>,
79}
80
81impl Room {
82    /// Join with an invite. `identity` is the local key label to join as
83    /// (made on first use). The name inside the room comes from the invite.
84    pub async fn join(paths: &Paths, invite: &str, identity: &str) -> Result<Room> {
85        let client = Client::new(paths.clone());
86        let v = client
87            .call(&Request::Join {
88                invite: invite.to_string(),
89                identity: identity.to_string(),
90            })
91            .await?;
92        let r: JoinResult = serde_json::from_value(v)?;
93        Ok(Room {
94            client,
95            room: r.room.name,
96            identity: identity.to_string(),
97            name: Some(r.name),
98        })
99    }
100
101    /// A room you are already in.
102    /// Fetch a file (by id, or every file on a message) and save it under
103    /// the helper's `files/<room>/` folder.
104    pub async fn get_file(&self, id: &str) -> Result<Vec<proto::SavedFile>> {
105        let v = self
106            .client
107            .call(&Request::GetFile {
108                room: self.room.clone(),
109                identity: self.identity.clone(),
110                id: id.to_string(),
111            })
112            .await?;
113        Ok(serde_json::from_value(v)?)
114    }
115
116    pub fn open(paths: &Paths, room: &str, identity: &str) -> Room {
117        Room {
118            client: Client::new(paths.clone()),
119            room: room.to_string(),
120            identity: identity.to_string(),
121            name: None,
122        }
123    }
124
125    pub async fn send(&self, text: &str, opts: SendOptions) -> Result<Message> {
126        let v = self
127            .client
128            .call(&Request::Send {
129                room: self.room.clone(),
130                identity: self.identity.clone(),
131                draft: DraftWire {
132                    text: text.to_string(),
133                    kind: opts.kind,
134                    to: opts.to,
135                    reply_to: opts.reply_to,
136                    trace: opts.trace,
137                    data: opts.data,
138                    class: None,
139                    action: opts.action,
140                    files: absolute(&opts.files)?,
141                },
142            })
143            .await?;
144        let r: SendResult = serde_json::from_value(v)?;
145        Ok(r.message)
146    }
147
148    /// Send a question and wait for a reply to that exact message.
149    pub async fn ask(
150        &self,
151        text: &str,
152        timeout_secs: u64,
153        action: Option<diavlos_core::Action>,
154    ) -> Result<Message> {
155        let v = self
156            .client
157            .call(&Request::Ask {
158                room: self.room.clone(),
159                identity: self.identity.clone(),
160                draft: DraftWire {
161                    text: text.to_string(),
162                    kind: Some(MessageType::Question),
163                    action,
164                    ..Default::default()
165                },
166                timeout_secs,
167            })
168            .await?;
169        let r: proto::AskResult = serde_json::from_value(v)?;
170        Ok(r.reply)
171    }
172
173    /// Wait for the next message from someone else. `0` waits forever.
174    ///
175    /// Acked as soon as it is handed over: if this process dies before it
176    /// has dealt with the message, the message is not handed out again.
177    /// For at-least-once, use [`Room::take`] and [`Room::ack`].
178    pub async fn next(&self, timeout_secs: u64) -> Result<Message> {
179        let v = self
180            .client
181            .call(&Request::Next {
182                room: self.room.clone(),
183                identity: self.identity.clone(),
184                timeout_secs,
185                manual_ack: false,
186                lease_secs: None,
187            })
188            .await?;
189        Ok(serde_json::from_value(v)?)
190    }
191
192    /// Wait for the next message from someone else and hold it: it stays
193    /// yours until you [`ack`](Room::ack), [`nack`](Room::nack) or the lease
194    /// runs out, and is then handed out again. `0` waits forever.
195    pub async fn take(&self, timeout_secs: u64, lease_secs: Option<u64>) -> Result<NextResult> {
196        let v = self
197            .client
198            .call(&Request::Next {
199                room: self.room.clone(),
200                identity: self.identity.clone(),
201                timeout_secs,
202                manual_ack: true,
203                lease_secs,
204            })
205            .await?;
206        Ok(serde_json::from_value(v)?)
207    }
208
209    /// Taken on. Not "finished": say `done` in the room for that.
210    pub async fn ack(&self, token: &str) -> Result<()> {
211        self.client
212            .call(&Request::Ack {
213                identity: self.identity.clone(),
214                token: token.to_string(),
215            })
216            .await?;
217        Ok(())
218    }
219
220    /// Still working: keep it yours for `lease_secs` more.
221    pub async fn renew(&self, token: &str, lease_secs: Option<u64>) -> Result<()> {
222        self.client
223            .call(&Request::Renew {
224                identity: self.identity.clone(),
225                token: token.to_string(),
226                lease_secs,
227            })
228            .await?;
229        Ok(())
230    }
231
232    /// Not now: hand it out again after `retry_in_secs`.
233    pub async fn nack(&self, token: &str, retry_in_secs: Option<u64>) -> Result<()> {
234        self.client
235            .call(&Request::Nack {
236                identity: self.identity.clone(),
237                token: token.to_string(),
238                retry_in_secs,
239            })
240            .await?;
241        Ok(())
242    }
243
244    /// Look at messages from your bookmark onward, or from `since`. Never
245    /// deletes and moves nothing.
246    pub async fn read(&self, since: Option<u64>, limit: u32) -> Result<Vec<Message>> {
247        let v = self
248            .client
249            .call(&Request::Read {
250                room: self.room.clone(),
251                identity: self.identity.clone(),
252                since,
253                limit,
254                ack: false,
255            })
256            .await?;
257        let r: ReadResult = serde_json::from_value(v)?;
258        Ok(r.messages)
259    }
260
261    /// Take a task. First wins; second is told no.
262    pub async fn claim(&self, task_id: &str) -> Result<Message> {
263        let v = self
264            .client
265            .call(&Request::Claim {
266                room: self.room.clone(),
267                identity: self.identity.clone(),
268                task_id: task_id.to_string(),
269            })
270            .await?;
271        let r: SendResult = serde_json::from_value(v)?;
272        Ok(r.message)
273    }
274
275    /// Give a task back.
276    pub async fn release(&self, task_id: &str) -> Result<Message> {
277        let v = self
278            .client
279            .call(&Request::Release {
280                room: self.room.clone(),
281                identity: self.identity.clone(),
282                task_id: task_id.to_string(),
283            })
284            .await?;
285        let r: SendResult = serde_json::from_value(v)?;
286        Ok(r.message)
287    }
288
289    /// Who is here.
290    pub async fn who(&self) -> Result<Vec<WhoEntry>> {
291        let v = self
292            .client
293            .call(&Request::Who {
294                room: self.room.clone(),
295            })
296            .await?;
297        Ok(serde_json::from_value(v)?)
298    }
299}
300
301/// The rooms this helper knows.
302pub async fn rooms(paths: &Paths) -> Result<Vec<RoomStatus>> {
303    let v = Client::new(paths.clone()).call(&Request::Rooms).await?;
304    Ok(serde_json::from_value(v)?)
305}
306
307/// Paths as the helper needs them: full paths, since it does not share
308/// this process's working folder.
309pub fn absolute(paths: &[std::path::PathBuf]) -> Result<Vec<String>> {
310    paths
311        .iter()
312        .map(|p| {
313            std::path::absolute(p)
314                .map(|p| p.to_string_lossy().to_string())
315                .map_err(|e| Error::Invalid(format!("{}: {e}", p.display())))
316        })
317        .collect()
318}