Skip to main content

rz_agent_protocol/
lib.rs

1//! Wire protocol: JSON envelopes with `@@RZ:` sentinel.
2//!
3//! Every protocol message is a single line:
4//! ```text
5//! @@RZ:{"id":"...","from":"...","kind":{"kind":"chat","body":{"text":"..."}}}
6//! ```
7//! The `@@RZ:` prefix lets receivers distinguish protocol messages from
8//! normal shell output or human typing.
9
10use serde::{Deserialize, Serialize};
11use std::sync::atomic::{AtomicU32, Ordering};
12
13pub const SENTINEL: &str = "@@RZ:";
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct Envelope {
17    pub id: String,
18    pub from: String,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub to: Option<String>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub r#ref: Option<String>,
23    pub kind: MessageKind,
24    pub ts: u64,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28#[serde(tag = "kind", content = "body", rename_all = "snake_case")]
29pub enum MessageKind {
30    Chat { text: String },
31    Ping,
32    Pong,
33    Error { message: String },
34    Timer { label: String },
35}
36
37static COUNTER: AtomicU32 = AtomicU32::new(0);
38
39impl Envelope {
40    pub fn new(from: impl Into<String>, kind: MessageKind) -> Self {
41        let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
42        let ts = std::time::SystemTime::now()
43            .duration_since(std::time::UNIX_EPOCH)
44            .unwrap_or_default()
45            .as_millis() as u64;
46        Self {
47            id: format!("{:04x}{:04x}", (ts & 0xFFFF) as u16, seq),
48            to: None,
49            r#ref: None,
50            from: from.into(),
51            kind,
52            ts,
53        }
54    }
55
56    /// Builder: set `to` for directed messaging.
57    pub fn with_to(mut self, t: impl Into<String>) -> Self {
58        self.to = Some(t.into());
59        self
60    }
61
62    /// Builder: set `ref` for threading.
63    pub fn with_ref(mut self, r: impl Into<String>) -> Self {
64        self.r#ref = Some(r.into());
65        self
66    }
67
68    /// Builder: conditionally set `ref`.
69    pub fn maybe_with_ref(mut self, r: Option<String>) -> Self {
70        self.r#ref = r;
71        self
72    }
73
74    /// Encode to wire format: `@@RZ:<json>`
75    pub fn encode(&self) -> eyre::Result<String> {
76        let json = serde_json::to_string(self)?;
77        Ok(format!("{SENTINEL}{json}"))
78    }
79
80    /// Decode from wire format (with or without sentinel prefix).
81    pub fn decode(line: &str) -> eyre::Result<Self> {
82        let payload = line.strip_prefix(SENTINEL).unwrap_or(line);
83        Ok(serde_json::from_str(payload.trim())?)
84    }
85}