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