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    /// Infer/1 peers (0.3 and older) know only the original kinds; newer ones are sent there as
89    /// `failed`.
90    pub(crate) fn for_v1(self) -> Self {
91        match self {
92            e @ (RemoteError::Unsupported { .. } | RemoteError::BadRequest { .. } | RemoteError::Cancelled | RemoteError::Stalled { .. }) => {
93                RemoteError::Failed { message: e.to_string() }
94            }
95            e => e,
96        }
97    }
98}
99
100/// Who is calling a served protocol. `peer` is the transport-authenticated peer id (Noise on
101/// Weirdnet), never one the caller sent. `cert_bytes` is the certificate the caller presented
102/// (for Weirdnet, a CBOR `weirdnet_net::user::NodeCert`), if any: hosts check it against `peer`
103/// (for example with `weirdnet_sync::Roster::check_caller`, see the `serve` feature) and must
104/// not trust it on its own.
105#[derive(Debug, Clone, PartialEq, Eq, Default)]
106pub struct Caller {
107    pub peer: String,
108    pub cert_bytes: Option<Vec<u8>>,
109}
110
111impl Caller {
112    pub fn new(peer: impl Into<String>) -> Self {
113        Self { peer: peer.into(), cert_bytes: None }
114    }
115
116    pub fn with_cert(mut self, cert_bytes: Vec<u8>) -> Self {
117        self.cert_bytes = Some(cert_bytes);
118        self
119    }
120
121    /// Takes the certificate a request presented when the transport gave none.
122    pub(crate) fn presenting(mut self, cert: Option<Vec<u8>>) -> Self {
123        if self.cert_bytes.is_none() {
124            self.cert_bytes = cert;
125        }
126        self
127    }
128}
129
130/// Decides whether a caller may use a served protocol. Hosts implement it (for Weirdnet with
131/// `serve::RosterAuth`); a closure works too.
132pub trait Authorize: Send + Sync {
133    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError>;
134}
135
136impl<F> Authorize for F
137where
138    F: Fn(&Caller) -> Result<(), RemoteError> + Send + Sync,
139{
140    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
141        self(caller)
142    }
143}
144
145/// The sending half of a channel: one message per call.
146#[async_trait]
147pub trait FrameTx: Send {
148    async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError>;
149}
150
151/// The receiving half of a channel. `recv` must be cancel-safe: it is raced against other
152/// futures, so a dropped call must not lose a message (back it with a reader task and a queue).
153/// `Ok(None)` means the peer closed its side.
154#[async_trait]
155pub trait FrameRx: Send {
156    async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError>;
157}
158
159/// A two-way message channel to one node.
160pub struct Channel {
161    pub tx: Box<dyn FrameTx>,
162    pub rx: Box<dyn FrameRx>,
163}
164
165impl Channel {
166    pub fn new(tx: Box<dyn FrameTx>, rx: Box<dyn FrameRx>) -> Self {
167        Self { tx, rx }
168    }
169
170    /// Sends one JSON message (infer/1, task/1).
171    pub async fn send<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
172        send_json(self.tx.as_mut(), msg).await
173    }
174
175    /// Receives one JSON message (infer/1, task/1).
176    pub async fn recv<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
177        recv_json(self.rx.as_mut()).await
178    }
179
180    /// Sends one CBOR message (infer/2, catalog/1).
181    pub async fn send_cbor<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
182        let bytes = to_cbor(msg)?;
183        self.tx.send(bytes).await
184    }
185
186    /// Receives one CBOR message (infer/2, catalog/1).
187    pub async fn recv_cbor<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
188        match self.rx.recv().await? {
189            None => Ok(None),
190            Some(bytes) => from_cbor(&bytes).map(Some),
191        }
192    }
193}
194
195/// Opens channels to the user's nodes. The app implements it over its network and checks the
196/// far end is a linked device; tests use [`MemoryDialer`]. A node that does not serve
197/// `protocol` should answer [`RemoteError::Unsupported`], so the pool can fall back to infer/1.
198#[async_trait]
199pub trait Dialer: Send + Sync {
200    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError>;
201}
202
203pub(crate) async fn send_json<T: Serialize + Sync + ?Sized>(tx: &mut dyn FrameTx, msg: &T) -> Result<(), RemoteError> {
204    let bytes = serde_json::to_vec(msg).map_err(|e| RemoteError::protocol(e.to_string()))?;
205    tx.send(bytes).await
206}
207
208pub(crate) async fn recv_json<T: DeserializeOwned>(rx: &mut dyn FrameRx) -> Result<Option<T>, RemoteError> {
209    match rx.recv().await? {
210        None => Ok(None),
211        Some(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| RemoteError::protocol(e.to_string())),
212    }
213}
214
215/// CBOR encoding used by infer/2 and catalog/1.
216pub fn to_cbor<T: Serialize>(msg: &T) -> Result<Vec<u8>, RemoteError> {
217    cbor4ii::serde::to_vec(Vec::new(), msg).map_err(|e| RemoteError::protocol(e.to_string()))
218}
219
220/// CBOR decoding used by infer/2 and catalog/1.
221pub fn from_cbor<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, RemoteError> {
222    cbor4ii::serde::from_slice(bytes).map_err(|e| RemoteError::protocol(e.to_string()))
223}
224
225/// A request id unique enough for one channel (time plus a process counter).
226pub(crate) fn request_id() -> String {
227    use std::sync::atomic::{AtomicU64, Ordering};
228    static SEQ: AtomicU64 = AtomicU64::new(0);
229    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
230    format!("{nanos:x}-{}", SEQ.fetch_add(1, Ordering::Relaxed))
231}
232
233/// Serde helpers that write `Vec<u8>` as a CBOR byte string (not an array of numbers).
234pub(crate) mod bytes {
235    use serde::de::{self, SeqAccess, Visitor};
236    use serde::{Deserializer, Serializer};
237
238    pub fn serialize<S: Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
239        s.serialize_bytes(v)
240    }
241
242    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
243        d.deserialize_byte_buf(BytesVisitor)
244    }
245
246    pub(super) struct BytesVisitor;
247
248    impl<'de> Visitor<'de> for BytesVisitor {
249        type Value = Vec<u8>;
250
251        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
252            f.write_str("a byte string")
253        }
254
255        fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Vec<u8>, E> {
256            Ok(v.to_vec())
257        }
258
259        fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<Vec<u8>, E> {
260            Ok(v)
261        }
262
263        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
264            let mut out = Vec::new();
265            while let Some(b) = seq.next_element::<u8>()? {
266                out.push(b);
267            }
268            Ok(out)
269        }
270    }
271
272    /// `Option<Vec<u8>>` as an optional byte string.
273    pub mod opt {
274        use serde::{Deserialize, Deserializer, Serializer};
275
276        pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
277            match v {
278                Some(b) => s.serialize_some(&Wrap(b)),
279                None => s.serialize_none(),
280            }
281        }
282
283        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
284            Ok(Option::<Owned>::deserialize(d)?.map(|o| o.0))
285        }
286
287        struct Wrap<'a>(&'a [u8]);
288
289        impl serde::Serialize for Wrap<'_> {
290            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
291                s.serialize_bytes(self.0)
292            }
293        }
294
295        struct Owned(Vec<u8>);
296
297        impl<'de> Deserialize<'de> for Owned {
298            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
299                d.deserialize_byte_buf(super::BytesVisitor).map(Owned)
300            }
301        }
302    }
303}