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