Skip to main content

netsky_core/
envelope.rs

1//! Shared agent-bus envelope: the on-disk shape, filename convention, and
2//! atomic-with-create-new write used by every producer on the bus. Consumers
3//! read envelopes with their own deserializer; writers MUST go through this
4//! module so every inbox file agrees on filename shape.
5//!
6//! Filename: `{nanos:020}-{pid:010}-{rand_hex:08}-{seq:010}-from-{from}.json`.
7//! The nanos+pid+rand+seq quartet gives cross-process uniqueness that a
8//! process-local `AtomicU64` alone cannot: two fresh `netsky channel send`
9//! processes both start at `seq=0`, and a wall-clock nanosecond collision
10//! between them would clobber each other's envelope under the old shape.
11//!
12//! Ordering is best-effort: consumers sort filenames lexicographically,
13//! which orders by nanos first. Clock skew between producers or concurrent
14//! writers can reorder causal order. Consumers that need causal ordering
15//! must embed a sequence number in the envelope body.
16//!
17//! Write flow: serialize → write `.<name>.<attempt>.tmp` → hard-link to
18//! `<name>` (create-new semantics; fails on collision) → unlink tmp.
19//! Retries with a fresh name on collision; returns AlreadyExists after 8
20//! failed attempts so a wedged inbox cannot spin forever.
21
22use std::fs;
23use std::io;
24use std::path::{Path, PathBuf};
25use std::sync::atomic::{AtomicU64, Ordering};
26
27use serde::{Deserialize, Serialize};
28
29const CHANNEL_WRAPPER_TOKENS: &[&str] = &["</channel>", "<channel source="];
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct Envelope {
33    pub id: Option<String>,
34    pub from: String,
35    pub to: Option<String>,
36    pub kind: Option<String>,
37    pub in_reply_to: Option<String>,
38    pub thread: Option<String>,
39    pub swarm: Option<String>,
40    pub idempotency_key: Option<String>,
41    pub requires_ack: Option<bool>,
42    pub text: String,
43    pub ts: String,
44}
45
46impl Envelope {
47    pub fn new(from: impl Into<String>, text: impl Into<String>, ts: impl Into<String>) -> Self {
48        Self {
49            id: None,
50            from: from.into(),
51            to: None,
52            kind: None,
53            in_reply_to: None,
54            thread: None,
55            swarm: None,
56            idempotency_key: None,
57            requires_ack: None,
58            text: text.into(),
59            ts: ts.into(),
60        }
61    }
62}
63
64/// `from`/`target` id validator: `agent` prefix + non-empty lowercase-alnum
65/// suffix, optionally preceded by the `test-` test-harness namespace.
66/// Accepted shapes: `agent0`, `agent42`, `agentinfinity`, `test-agent97`,
67/// `test-agentinfinity`. Mirrored in the MCP agent source so filenames
68/// and inbox names round-trip under a single rule.
69pub fn valid_agent_id(id: &str) -> bool {
70    let core = id.strip_prefix("test-").unwrap_or(id);
71    match core.strip_prefix("agent") {
72        Some(suffix) => {
73            !suffix.is_empty()
74                && suffix
75                    .chars()
76                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
77        }
78        None => false,
79    }
80}
81
82/// Build the canonical inbox filename. `from` is trusted to have already
83/// passed [`valid_agent_id`] — callers that have not validated must do so
84/// before constructing envelopes.
85pub fn build_filename(from: &str) -> String {
86    static SEQ: AtomicU64 = AtomicU64::new(0);
87    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
88    let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0);
89    let pid = std::process::id();
90    let rand_hex: u32 = rand::random();
91    format!("{nanos:020}-{pid:010}-{rand_hex:08x}-{seq:010}-from-{from}.json")
92}
93
94/// Atomically write `env` into `inbox`. Loops up to 8 times on filename
95/// collision (AlreadyExists) with a fresh name each attempt. Returns the
96/// final path on success.
97pub fn write_envelope(inbox: &Path, env: &Envelope) -> io::Result<PathBuf> {
98    fs::create_dir_all(inbox)?;
99    let bytes =
100        serde_json::to_vec(env).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
101    let mut last_err: Option<io::Error> = None;
102    for attempt in 0..8 {
103        let name = build_filename(&env.from);
104        let final_path = inbox.join(&name);
105        let tmp_path = inbox.join(format!(".{name}.{attempt}.tmp"));
106        fs::write(&tmp_path, &bytes)?;
107        match fs::hard_link(&tmp_path, &final_path) {
108            Ok(()) => {
109                let _ = fs::remove_file(&tmp_path);
110                return Ok(final_path);
111            }
112            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
113                let _ = fs::remove_file(&tmp_path);
114                last_err = Some(e);
115                continue;
116            }
117            Err(e) => {
118                let _ = fs::remove_file(&tmp_path);
119                return Err(e);
120            }
121        }
122    }
123    Err(last_err.unwrap_or_else(|| {
124        io::Error::new(
125            io::ErrorKind::AlreadyExists,
126            "exhausted 8 attempts to create unique envelope filename",
127        )
128    }))
129}
130
131/// Reject content that would break the shell-facing `<channel>` framing.
132pub fn body_contains_wrapper_tokens(body: &str) -> bool {
133    CHANNEL_WRAPPER_TOKENS
134        .iter()
135        .any(|needle| body.contains(needle))
136}
137
138/// Validate the shared agent-bus envelope shape before a drain prints it
139/// into channel framing.
140pub fn validate_bus_envelope(env: &Envelope) -> Result<(), String> {
141    if !valid_agent_id(&env.from) {
142        return Err(format!(
143            "invalid from {:?} (expected agent<lowercase-alnum>)",
144            env.from
145        ));
146    }
147    if chrono::DateTime::parse_from_rfc3339(&env.ts).is_err() {
148        return Err(format!("invalid ts {:?} (expected RFC3339)", env.ts));
149    }
150    if body_contains_wrapper_tokens(&env.text) {
151        return Err("body contains <channel> wrapper token; framing-break rejected".to_string());
152    }
153    Ok(())
154}
155
156/// Escape the channel body defensively before it is wrapped in XML-like
157/// framing and shown to a model.
158pub fn xml_escape_body(s: &str) -> String {
159    let mut out = String::with_capacity(s.len());
160    for c in s.chars() {
161        match c {
162            '&' => out.push_str("&amp;"),
163            '<' => out.push_str("&lt;"),
164            '>' => out.push_str("&gt;"),
165            '"' => out.push_str("&quot;"),
166            '\'' => out.push_str("&apos;"),
167            other => out.push(other),
168        }
169    }
170    out
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn valid_agent_id_accepts_canonical_shapes() {
179        assert!(valid_agent_id("agent0"));
180        assert!(valid_agent_id("agent42"));
181        assert!(valid_agent_id("agentinfinity"));
182    }
183
184    #[test]
185    fn valid_agent_id_accepts_test_namespace() {
186        assert!(valid_agent_id("test-agent0"));
187        assert!(valid_agent_id("test-agent97"));
188        assert!(valid_agent_id("test-agentinfinity"));
189    }
190
191    #[test]
192    fn valid_agent_id_rejects_junk() {
193        assert!(!valid_agent_id(""));
194        assert!(!valid_agent_id("agent"));
195        assert!(!valid_agent_id("AGENT0"));
196        assert!(!valid_agent_id("agent-7"));
197        assert!(!valid_agent_id("bob"));
198        assert!(!valid_agent_id("agent 0"));
199        // `test-` is only a namespace prefix; bare `test-` or `test-bob` are not valid.
200        assert!(!valid_agent_id("test-"));
201        assert!(!valid_agent_id("test-bob"));
202        assert!(!valid_agent_id("test-agent"));
203    }
204
205    #[test]
206    fn build_filename_shape() {
207        let n = build_filename("agent7");
208        assert!(n.ends_with("-from-agent7.json"));
209        let parts: Vec<&str> = n.splitn(5, '-').collect();
210        assert_eq!(parts.len(), 5);
211        assert_eq!(parts[0].len(), 20);
212        assert_eq!(parts[1].len(), 10);
213        assert_eq!(parts[2].len(), 8);
214    }
215
216    #[test]
217    fn build_filename_is_unique_within_process() {
218        let mut seen = std::collections::HashSet::new();
219        for _ in 0..1000 {
220            assert!(seen.insert(build_filename("agent0")));
221        }
222    }
223
224    #[test]
225    fn write_envelope_round_trips() {
226        let tmp = tempfile::tempdir().unwrap();
227        let env = Envelope {
228            id: None,
229            from: "agent2".to_string(),
230            to: None,
231            kind: None,
232            in_reply_to: None,
233            thread: None,
234            swarm: None,
235            idempotency_key: None,
236            requires_ack: None,
237            text: "hello".to_string(),
238            ts: "2026-04-15T21:00:00Z".to_string(),
239        };
240        let path = write_envelope(tmp.path(), &env).unwrap();
241        let raw = fs::read_to_string(&path).unwrap();
242        let round: Envelope = serde_json::from_str(&raw).unwrap();
243        assert_eq!(round.from, env.from);
244        assert_eq!(round.text, env.text);
245    }
246
247    #[test]
248    fn legacy_envelope_deserializes_with_v1_defaults() {
249        let raw = r#"{"from":"agent0","text":"hello","ts":"2026-04-15T21:00:00Z"}"#;
250        let env: Envelope = serde_json::from_str(raw).unwrap();
251        assert_eq!(env.from, "agent0");
252        assert_eq!(env.text, "hello");
253        assert_eq!(env.ts, "2026-04-15T21:00:00Z");
254        assert_eq!(env.id, None);
255        assert_eq!(env.to, None);
256        assert_eq!(env.kind, None);
257        assert_eq!(env.in_reply_to, None);
258        assert_eq!(env.thread, None);
259        assert_eq!(env.swarm, None);
260        assert_eq!(env.idempotency_key, None);
261        assert_eq!(env.requires_ack, None);
262    }
263
264    #[test]
265    fn v1_envelope_round_trips_optional_fields() {
266        let env = Envelope {
267            id: Some("msg-1".to_string()),
268            from: "agent0".to_string(),
269            to: Some("agent4".to_string()),
270            kind: Some("brief".to_string()),
271            in_reply_to: Some("msg-0".to_string()),
272            thread: Some("thread-1".to_string()),
273            swarm: Some("swarm-1".to_string()),
274            idempotency_key: Some("idem-1".to_string()),
275            requires_ack: Some(true),
276            text: "hello".to_string(),
277            ts: "2026-04-15T21:00:00Z".to_string(),
278        };
279        let raw = serde_json::to_string(&env).unwrap();
280        let round: Envelope = serde_json::from_str(&raw).unwrap();
281        assert_eq!(round.id.as_deref(), Some("msg-1"));
282        assert_eq!(round.to.as_deref(), Some("agent4"));
283        assert_eq!(round.kind.as_deref(), Some("brief"));
284        assert_eq!(round.in_reply_to.as_deref(), Some("msg-0"));
285        assert_eq!(round.thread.as_deref(), Some("thread-1"));
286        assert_eq!(round.swarm.as_deref(), Some("swarm-1"));
287        assert_eq!(round.idempotency_key.as_deref(), Some("idem-1"));
288        assert_eq!(round.requires_ack, Some(true));
289    }
290
291    #[test]
292    fn write_envelope_rejects_name_collision() {
293        // Pre-populate the inbox with a file whose hard-link target we
294        // force to collide. We cannot cheaply force the AtomicU64+rand to
295        // repeat, so assert the happy path here and exercise the collision
296        // branch via a unit on the retry loop.
297        let tmp = tempfile::tempdir().unwrap();
298        let env = Envelope {
299            id: None,
300            from: "agent2".to_string(),
301            to: None,
302            kind: None,
303            in_reply_to: None,
304            thread: None,
305            swarm: None,
306            idempotency_key: None,
307            requires_ack: None,
308            text: "hi".to_string(),
309            ts: "2026-04-15T21:00:00Z".to_string(),
310        };
311        let a = write_envelope(tmp.path(), &env).unwrap();
312        let b = write_envelope(tmp.path(), &env).unwrap();
313        assert_ne!(a, b);
314    }
315}