Skip to main content

weirdnet_agent/remote/
mod.rs

1//! Remote inference and remote tasks between one user's own nodes.
2//!
3//! Protocols over any ordered, reliable message channel (Weirdnet streams in the apps):
4//!
5//! - [`infer`]: offload one model turn to a stronger node. `/weirdnet-agent/infer/1` (JSON) is
6//!   the original protocol and is still served; [`infer::v2`] (`/weirdnet-agent/infer/2`, CBOR)
7//!   adds priorities and a real queue, jobs with attempts and resume from an assistant prefix,
8//!   offsets on every text frame, reasoning and tool-call frames, usage and metadata, raw mode
9//!   and embeddings.
10//! - [`catalog`]: `/weirdnet-agent/catalog/1`, the models an inference node offers, queried once
11//!   or subscribed to.
12//! - [`pool`]: the asking side over both. It tries inference nodes in order, fails over before
13//!   and (opt-in) during an answer, resumes from what it has already shown, cancels a stalled
14//!   stream, and runs jobs. [`infer::RemoteModel`] is a thin [`ModelBackend`](crate::ModelBackend)
15//!   over it.
16//! - [`pool_model`]: a model cloud (for example [Ymir](https://github.com/WeirdBrains/ymir)) as
17//!   one [`ModelBackend`](crate::ModelBackend) with mid-answer resume and a local fallback
18//!   ([`pool_model::PoolModel`]), and a live view of its catalog ([`pool_model::PoolWatch`]).
19//! - [`task`]: run a whole agent task on another node (Node companions). Agent events stream
20//!   back, approval cards are answered on the asking device, and cancel travels the other way.
21//!
22//! Transport and identity belong to the app: a [`Dialer`] opens a [`Channel`] to a node, and the
23//! serving side passes the transport-authenticated peer as a [`Caller`] to the serve functions,
24//! which ask the host to authorize it before anything else. Nothing about the caller is taken
25//! from a message body except the certificate it presents, which the host checks against the
26//! peer. The `pool` and `serve` cargo features add the Weirdnet (`weirdnet-net`,
27//! `weirdnet-sync`) halves; this module has no networking of its own. [`codec`] frames messages
28//! on byte streams.
29
30pub mod catalog;
31pub mod codec;
32pub mod infer;
33mod memory;
34pub mod pool;
35pub mod pool_model;
36pub mod task;
37
38use async_trait::async_trait;
39use serde::de::DeserializeOwned;
40use serde::{Deserialize, Serialize};
41
42pub use memory::{MemoryDialer, memory_pair};
43
44/// Why a remote call did not complete.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
46#[serde(rename_all = "snake_case", tag = "kind")]
47#[non_exhaustive]
48pub enum RemoteError {
49    #[error("node unreachable: {message}")]
50    Unreachable { message: String },
51    #[error("node busy")]
52    Busy,
53    #[error("node refused: {message}")]
54    Refused { message: String },
55    #[error("model unavailable on the node: {message}")]
56    Unavailable { message: String },
57    #[error("remote run failed: {message}")]
58    Failed { message: String },
59    #[error("protocol error: {message}")]
60    Protocol { message: String },
61    #[error("connection closed")]
62    Closed,
63    #[error("timed out")]
64    Timeout,
65    /// The node does not serve this protocol (an older or different app).
66    #[error("not supported by the node: {message}")]
67    Unsupported { message: String },
68    /// The request was malformed (for example raw mode with a `context_ref`).
69    #[error("bad request: {message}")]
70    BadRequest { message: String },
71    /// Cancelled by the asker.
72    #[error("cancelled")]
73    Cancelled,
74    /// No frame arrived within the stall timeout; the asker cancelled the stream.
75    #[error("stalled: no frame for {ms} ms")]
76    Stalled { ms: u64 },
77}
78
79impl RemoteError {
80    pub fn protocol(message: impl Into<String>) -> Self {
81        RemoteError::Protocol { message: message.into() }
82    }
83
84    pub fn refused(message: impl Into<String>) -> Self {
85        RemoteError::Refused { message: message.into() }
86    }
87
88    pub fn unavailable(message: impl Into<String>) -> Self {
89        RemoteError::Unavailable { message: message.into() }
90    }
91
92    /// The request itself can't be served (`BadRequest`) or the asker gave up (`Cancelled`):
93    /// another node would answer the same, so a pool returns it at once instead of failing over.
94    pub fn is_request_error(&self) -> bool {
95        matches!(self, RemoteError::BadRequest { .. } | RemoteError::Cancelled)
96    }
97
98    /// A node's own answer about this request (it does not serve it, refuses the caller, lacks the
99    /// model or is busy), as opposed to a transport or engine failure. When every node fails, a
100    /// pool reports the last such answer before any transport error, so callers see why.
101    pub fn is_node_answer(&self) -> bool {
102        matches!(self, RemoteError::Unsupported { .. } | RemoteError::Refused { .. } | RemoteError::Unavailable { .. } | RemoteError::Busy)
103            || self.is_request_error()
104    }
105
106    /// Infer/1 peers (0.3 and older) know only the original kinds; newer ones are sent there as
107    /// `failed`.
108    pub(crate) fn for_v1(self) -> Self {
109        match self {
110            e @ (RemoteError::Unsupported { .. } | RemoteError::BadRequest { .. } | RemoteError::Cancelled | RemoteError::Stalled { .. }) => {
111                RemoteError::Failed { message: e.to_string() }
112            }
113            e => e,
114        }
115    }
116}
117
118/// Who is calling a served protocol. `peer` is the transport-authenticated peer id (Noise on
119/// Weirdnet), never one the caller sent. `cert_bytes` is the certificate the caller presented
120/// (for Weirdnet, a CBOR `weirdnet_net::user::NodeCert`), if any: hosts check it against `peer`
121/// (for example with `weirdnet_sync::Roster::check_caller`, see the `serve` feature) and must
122/// not trust it on its own.
123#[derive(Debug, Clone, PartialEq, Eq, Default)]
124pub struct Caller {
125    pub peer: String,
126    pub cert_bytes: Option<Vec<u8>>,
127}
128
129impl Caller {
130    pub fn new(peer: impl Into<String>) -> Self {
131        Self { peer: peer.into(), cert_bytes: None }
132    }
133
134    pub fn with_cert(mut self, cert_bytes: Vec<u8>) -> Self {
135        self.cert_bytes = Some(cert_bytes);
136        self
137    }
138
139    /// Takes the certificate a request presented when the transport gave none.
140    pub(crate) fn presenting(mut self, cert: Option<Vec<u8>>) -> Self {
141        if self.cert_bytes.is_none() {
142            self.cert_bytes = cert;
143        }
144        self
145    }
146}
147
148/// A caller an [`Authorize`] let in: its transport peer and, when the authorizer knows them, the
149/// device roles it holds (for Weirdnet, the user-signed grants in the `weirdnet-sync` roster).
150/// Hosts use it to scope a session per device or role ([`task::TaskHost::session_for`]).
151#[derive(Debug, Clone, PartialEq, Eq)]
152#[non_exhaustive]
153pub struct Admitted {
154    pub peer: String,
155    /// `None` when the authorizer has no role information (no grant, or roles not checked).
156    pub roles: Option<Vec<String>>,
157}
158
159impl Admitted {
160    pub fn new(peer: impl Into<String>, roles: Option<Vec<String>>) -> Self {
161        Self { peer: peer.into(), roles }
162    }
163
164    pub fn has_role(&self, role: &str) -> bool {
165        self.roles.as_ref().is_some_and(|r| r.iter().any(|x| x == role))
166    }
167}
168
169/// Decides whether a caller may use a served protocol. Hosts implement it (for Weirdnet with
170/// `serve::RosterAuth`); a closure works too.
171pub trait Authorize: Send + Sync {
172    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError>;
173
174    /// [`authorize`](Self::authorize), returning who was let in. The default knows no roles;
175    /// `serve::RosterAuth` fills them in.
176    fn admit(&self, caller: &Caller) -> Result<Admitted, RemoteError> {
177        self.authorize(caller)?;
178        Ok(Admitted::new(caller.peer.clone(), None))
179    }
180}
181
182impl<F> Authorize for F
183where
184    F: Fn(&Caller) -> Result<(), RemoteError> + Send + Sync,
185{
186    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
187        self(caller)
188    }
189}
190
191/// The sending half of a channel: one message per call.
192#[async_trait]
193pub trait FrameTx: Send {
194    async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError>;
195}
196
197/// The receiving half of a channel. `recv` must be cancel-safe: it is raced against other
198/// futures, so a dropped call must not lose a message (back it with a reader task and a queue).
199/// `Ok(None)` means the peer closed its side.
200#[async_trait]
201pub trait FrameRx: Send {
202    async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError>;
203}
204
205/// A two-way message channel to one node.
206pub struct Channel {
207    pub tx: Box<dyn FrameTx>,
208    pub rx: Box<dyn FrameRx>,
209}
210
211impl Channel {
212    pub fn new(tx: Box<dyn FrameTx>, rx: Box<dyn FrameRx>) -> Self {
213        Self { tx, rx }
214    }
215
216    /// Sends one JSON message (infer/1, task/1).
217    pub async fn send<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
218        send_json(self.tx.as_mut(), msg).await
219    }
220
221    /// Receives one JSON message (infer/1, task/1).
222    pub async fn recv<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
223        recv_json(self.rx.as_mut()).await
224    }
225
226    /// Sends one CBOR message (infer/2, catalog/1).
227    pub async fn send_cbor<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
228        let bytes = to_cbor(msg)?;
229        self.tx.send(bytes).await
230    }
231
232    /// Receives one CBOR message (infer/2, catalog/1).
233    pub async fn recv_cbor<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
234        match self.rx.recv().await? {
235            None => Ok(None),
236            Some(bytes) => from_cbor(&bytes).map(Some),
237        }
238    }
239}
240
241/// Opens channels to the user's nodes. The app implements it over its network and checks the
242/// far end is a linked device; tests use [`MemoryDialer`]. A node that does not serve
243/// `protocol` should answer [`RemoteError::Unsupported`], so the pool can fall back to infer/1.
244#[async_trait]
245pub trait Dialer: Send + Sync {
246    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError>;
247}
248
249pub(crate) async fn send_json<T: Serialize + Sync + ?Sized>(tx: &mut dyn FrameTx, msg: &T) -> Result<(), RemoteError> {
250    let bytes = serde_json::to_vec(msg).map_err(|e| RemoteError::protocol(e.to_string()))?;
251    tx.send(bytes).await
252}
253
254pub(crate) async fn recv_json<T: DeserializeOwned>(rx: &mut dyn FrameRx) -> Result<Option<T>, RemoteError> {
255    match rx.recv().await? {
256        None => Ok(None),
257        Some(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| RemoteError::protocol(e.to_string())),
258    }
259}
260
261/// CBOR encoding used by infer/2 and catalog/1.
262pub fn to_cbor<T: Serialize>(msg: &T) -> Result<Vec<u8>, RemoteError> {
263    cbor4ii::serde::to_vec(Vec::new(), msg).map_err(|e| RemoteError::protocol(e.to_string()))
264}
265
266/// CBOR decoding used by infer/2 and catalog/1.
267pub fn from_cbor<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, RemoteError> {
268    cbor4ii::serde::from_slice(bytes).map_err(|e| RemoteError::protocol(e.to_string()))
269}
270
271/// A request id unique enough for one channel (time plus a process counter).
272pub(crate) fn request_id() -> String {
273    use std::sync::atomic::{AtomicU64, Ordering};
274    static SEQ: AtomicU64 = AtomicU64::new(0);
275    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
276    format!("{nanos:x}-{}", SEQ.fetch_add(1, Ordering::Relaxed))
277}
278
279/// Serde helpers that write `Vec<u8>` as a CBOR byte string (not an array of numbers).
280pub(crate) mod bytes {
281    use serde::de::{self, SeqAccess, Visitor};
282    use serde::{Deserializer, Serializer};
283
284    pub fn serialize<S: Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
285        s.serialize_bytes(v)
286    }
287
288    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
289        d.deserialize_byte_buf(BytesVisitor)
290    }
291
292    pub(super) struct BytesVisitor;
293
294    impl<'de> Visitor<'de> for BytesVisitor {
295        type Value = Vec<u8>;
296
297        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
298            f.write_str("a byte string")
299        }
300
301        fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Vec<u8>, E> {
302            Ok(v.to_vec())
303        }
304
305        fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<Vec<u8>, E> {
306            Ok(v)
307        }
308
309        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
310            let mut out = Vec::new();
311            while let Some(b) = seq.next_element::<u8>()? {
312                out.push(b);
313            }
314            Ok(out)
315        }
316    }
317
318    /// `Option<Vec<u8>>` as an optional byte string.
319    pub mod opt {
320        use serde::{Deserialize, Deserializer, Serializer};
321
322        pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
323            match v {
324                Some(b) => s.serialize_some(&Wrap(b)),
325                None => s.serialize_none(),
326            }
327        }
328
329        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
330            Ok(Option::<Owned>::deserialize(d)?.map(|o| o.0))
331        }
332
333        struct Wrap<'a>(&'a [u8]);
334
335        impl serde::Serialize for Wrap<'_> {
336            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
337                s.serialize_bytes(self.0)
338            }
339        }
340
341        struct Owned(Vec<u8>);
342
343        impl<'de> Deserialize<'de> for Owned {
344            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
345                d.deserialize_byte_buf(super::BytesVisitor).map(Owned)
346            }
347        }
348    }
349}