Skip to main content

weirdnet_agent/remote/
mod.rs

1//! Remote inference and remote tasks between one user's own nodes.
2//!
3//! Two protocols over any ordered, reliable message channel (Weirdnet streams in the apps):
4//!
5//! - [`infer`]: offload one model turn to a stronger node. The asking side sends the request,
6//!   tokens stream back, a cancel travels the other way, and [`infer::RemoteModel`] falls back
7//!   to the next node or a local backend when a node cannot take the turn.
8//! - [`task`]: run a whole agent task on another node (Node companions). Agent events stream
9//!   back, approval cards are answered on the asking device, and cancel travels the other way.
10//!
11//! Transport and identity belong to the app: a [`Dialer`] opens a [`Channel`] to a node, and the
12//! serving side must check that the caller is one of the user's linked devices before it calls
13//! [`infer::serve`] or [`task::serve`]. Messages are JSON; [`codec`] frames them on byte streams.
14
15pub mod codec;
16pub mod infer;
17mod memory;
18pub mod task;
19
20use async_trait::async_trait;
21use serde::de::DeserializeOwned;
22use serde::{Deserialize, Serialize};
23
24pub use memory::{MemoryDialer, memory_pair};
25
26/// Why a remote call did not complete.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
28#[serde(rename_all = "snake_case", tag = "kind")]
29pub enum RemoteError {
30    #[error("node unreachable: {message}")]
31    Unreachable { message: String },
32    #[error("node busy")]
33    Busy,
34    #[error("node refused: {message}")]
35    Refused { message: String },
36    #[error("model unavailable on the node: {message}")]
37    Unavailable { message: String },
38    #[error("remote run failed: {message}")]
39    Failed { message: String },
40    #[error("protocol error: {message}")]
41    Protocol { message: String },
42    #[error("connection closed")]
43    Closed,
44    #[error("timed out")]
45    Timeout,
46}
47
48impl RemoteError {
49    pub fn protocol(message: impl Into<String>) -> Self {
50        RemoteError::Protocol { message: message.into() }
51    }
52}
53
54/// The sending half of a channel: one message per call.
55#[async_trait]
56pub trait FrameTx: Send {
57    async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError>;
58}
59
60/// The receiving half of a channel. `recv` must be cancel-safe: it is raced against other
61/// futures, so a dropped call must not lose a message (back it with a reader task and a queue).
62/// `Ok(None)` means the peer closed its side.
63#[async_trait]
64pub trait FrameRx: Send {
65    async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError>;
66}
67
68/// A two-way message channel to one node.
69pub struct Channel {
70    pub tx: Box<dyn FrameTx>,
71    pub rx: Box<dyn FrameRx>,
72}
73
74impl Channel {
75    pub fn new(tx: Box<dyn FrameTx>, rx: Box<dyn FrameRx>) -> Self {
76        Self { tx, rx }
77    }
78
79    pub async fn send<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
80        send_json(self.tx.as_mut(), msg).await
81    }
82
83    pub async fn recv<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
84        recv_json(self.rx.as_mut()).await
85    }
86}
87
88/// Opens channels to the user's nodes. The app implements it over its network and checks the
89/// far end is a linked device; tests use [`MemoryDialer`].
90#[async_trait]
91pub trait Dialer: Send + Sync {
92    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError>;
93}
94
95pub(crate) async fn send_json<T: Serialize + Sync + ?Sized>(tx: &mut dyn FrameTx, msg: &T) -> Result<(), RemoteError> {
96    let bytes = serde_json::to_vec(msg).map_err(|e| RemoteError::protocol(e.to_string()))?;
97    tx.send(bytes).await
98}
99
100pub(crate) async fn recv_json<T: DeserializeOwned>(rx: &mut dyn FrameRx) -> Result<Option<T>, RemoteError> {
101    match rx.recv().await? {
102        None => Ok(None),
103        Some(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| RemoteError::protocol(e.to_string())),
104    }
105}
106
107/// A request id unique enough for one channel (time plus a process counter).
108pub(crate) fn request_id() -> String {
109    use std::sync::atomic::{AtomicU64, Ordering};
110    static SEQ: AtomicU64 = AtomicU64::new(0);
111    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
112    format!("{nanos:x}-{}", SEQ.fetch_add(1, Ordering::Relaxed))
113}