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    Hello { name: String, pane_id: String },
32    Ping,
33    Pong,
34    Error { message: String },
35    Timer { label: String },
36    ToolCall { name: String, args: serde_json::Value, call_id: String },
37    ToolResult { call_id: String, result: String, is_error: bool },
38    Delegate { task: String, context: String },
39    Status { state: String, detail: String },
40}
41
42static COUNTER: AtomicU32 = AtomicU32::new(0);
43
44impl Envelope {
45    pub fn new(from: impl Into<String>, kind: MessageKind) -> Self {
46        let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
47        let ts = std::time::SystemTime::now()
48            .duration_since(std::time::UNIX_EPOCH)
49            .unwrap_or_default()
50            .as_millis() as u64;
51        Self {
52            id: format!("{:04x}{:04x}", (ts & 0xFFFF) as u16, seq),
53            to: None,
54            r#ref: None,
55            from: from.into(),
56            kind,
57            ts,
58        }
59    }
60
61    /// Builder: set `to` for directed messaging.
62    pub fn with_to(mut self, t: impl Into<String>) -> Self {
63        self.to = Some(t.into());
64        self
65    }
66
67    /// Builder: set `ref` for threading.
68    pub fn with_ref(mut self, r: impl Into<String>) -> Self {
69        self.r#ref = Some(r.into());
70        self
71    }
72
73    /// Builder: conditionally set `ref`.
74    pub fn maybe_with_ref(mut self, r: Option<String>) -> Self {
75        self.r#ref = r;
76        self
77    }
78
79    /// Encode to wire format: `@@RZ:<json>`
80    pub fn encode(&self) -> eyre::Result<String> {
81        let json = serde_json::to_string(self)?;
82        Ok(format!("{SENTINEL}{json}"))
83    }
84
85    /// Decode from wire format (with or without sentinel prefix).
86    pub fn decode(line: &str) -> eyre::Result<Self> {
87        let payload = line.strip_prefix(SENTINEL).unwrap_or(line);
88        Ok(serde_json::from_str(payload.trim())?)
89    }
90}