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
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// SPF Smart Gateway - Message Framing Protocol
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Length-prefixed message framing for persistent bidirectional streams.
// Replaces one-shot read_to_end/finish pattern in mesh transport.
// Supports 8 stream types: TOOL_RPC, CHAT, VOICE, PIPELINE, BRAIN_SYNC, WEIGHT_SYNC, CONTROL
//
// Frame format: [1-byte type][4-byte length BE][payload bytes]
// Max frame size: 10MB (matches existing mesh limit)
//
// Depends on: nothing (Layer 2 protocol definition)

use std::io;

// ============================================================================
// STREAM TYPES
// ============================================================================

/// Stream type identifiers — first byte of every frame
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum StreamType {
    /// Tool RPC calls (existing mesh functionality) — JSON-RPC format
    ToolRpc = 0x01,
    /// Text chat messages (user ↔ user, user ↔ agent, agent ↔ agent)
    ChatText = 0x02,
    /// Voice audio frames (Opus codec)
    VoiceAudio = 0x03,
    /// Pipeline task assignment (orchestrator → worker)
    PipelineTask = 0x04,
    /// Pipeline result (worker → orchestrator)
    PipelineResult = 0x05,
    /// Brain knowledge sync between nodes
    BrainSync = 0x06,
    /// Transformer weight sharing / delta sync
    WeightSync = 0x07,
    /// Control messages: heartbeat, status, peer management
    Control = 0x08,
}

impl StreamType {
    /// Convert byte to StreamType
    pub fn from_byte(b: u8) -> Option<Self> {
        match b {
            0x01 => Some(Self::ToolRpc),
            0x02 => Some(Self::ChatText),
            0x03 => Some(Self::VoiceAudio),
            0x04 => Some(Self::PipelineTask),
            0x05 => Some(Self::PipelineResult),
            0x06 => Some(Self::BrainSync),
            0x07 => Some(Self::WeightSync),
            0x08 => Some(Self::Control),
            _ => None,
        }
    }

    /// Convert StreamType to byte
    pub fn as_byte(self) -> u8 {
        self as u8
    }

    /// Human-readable name for logging
    pub fn name(self) -> &'static str {
        match self {
            Self::ToolRpc => "TOOL_RPC",
            Self::ChatText => "CHAT_TEXT",
            Self::VoiceAudio => "VOICE_AUDIO",
            Self::PipelineTask => "PIPELINE_TASK",
            Self::PipelineResult => "PIPELINE_RESULT",
            Self::BrainSync => "BRAIN_SYNC",
            Self::WeightSync => "WEIGHT_SYNC",
            Self::Control => "CONTROL",
        }
    }

    /// Whether this stream type carries real-time data (low latency required)
    pub fn is_realtime(self) -> bool {
        matches!(self, Self::VoiceAudio | Self::ChatText | Self::Control)
    }

    /// Whether this stream type carries bulk data (high throughput preferred)
    pub fn is_bulk(self) -> bool {
        matches!(self, Self::BrainSync | Self::WeightSync | Self::PipelineTask | Self::PipelineResult)
    }
}

// ============================================================================
// FRAME FORMAT
// ============================================================================

/// Maximum frame payload size: 10MB (matches mesh.rs MAX_MSG_SIZE)
pub const MAX_FRAME_SIZE: u32 = 10_485_760;

/// Frame header size: 1 (type) + 4 (length) = 5 bytes
pub const FRAME_HEADER_SIZE: usize = 5;

/// A single framed message ready for transmission
#[derive(Debug, Clone)]
pub struct Frame {
    /// Stream type identifier
    pub stream_type: StreamType,
    /// Payload bytes (JSON, audio, binary, etc.)
    pub payload: Vec<u8>,
}

impl Frame {
    /// Create a new frame
    pub fn new(stream_type: StreamType, payload: Vec<u8>) -> Self {
        Self { stream_type, payload }
    }

    /// Create a Tool RPC frame from JSON string
    pub fn tool_rpc(json: &str) -> Self {
        Self::new(StreamType::ToolRpc, json.as_bytes().to_vec())
    }

    /// Create a Chat frame from text
    pub fn chat(text: &str) -> Self {
        Self::new(StreamType::ChatText, text.as_bytes().to_vec())
    }

    /// Create a Control frame from JSON
    pub fn control(json: &str) -> Self {
        Self::new(StreamType::Control, json.as_bytes().to_vec())
    }

    /// Create a Pipeline Task frame
    pub fn pipeline_task(payload: Vec<u8>) -> Self {
        Self::new(StreamType::PipelineTask, payload)
    }

    /// Create a Pipeline Result frame
    pub fn pipeline_result(payload: Vec<u8>) -> Self {
        Self::new(StreamType::PipelineResult, payload)
    }

    /// Serialize frame to wire format: [type:1][length:4 BE][payload:N]
    pub fn to_bytes(&self) -> Vec<u8> {
        let len = self.payload.len() as u32;
        let mut buf = Vec::with_capacity(FRAME_HEADER_SIZE + self.payload.len());
        buf.push(self.stream_type.as_byte());
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(&self.payload);
        buf
    }

    /// Payload as UTF-8 string (for JSON/text frames)
    pub fn payload_str(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(&self.payload)
    }
}

// ============================================================================
// FRAME READER / WRITER — for use with any Read/Write stream
// ============================================================================

/// Read a single frame from a byte stream.
/// Returns None on clean EOF (stream closed by peer).
/// Returns Err on protocol violations or I/O errors.
pub fn read_frame(reader: &mut dyn io::Read) -> io::Result<Option<Frame>> {
    // Read header: 5 bytes [type:1][length:4]
    let mut header = [0u8; FRAME_HEADER_SIZE];
    match reader.read_exact(&mut header) {
        Ok(()) => {},
        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
        Err(e) => return Err(e),
    }

    let type_byte = header[0];
    let length = u32::from_be_bytes([header[1], header[2], header[3], header[4]]);

    // Validate stream type
    let stream_type = StreamType::from_byte(type_byte).ok_or_else(|| {
        io::Error::new(io::ErrorKind::InvalidData, format!("Unknown stream type: 0x{:02x}", type_byte))
    })?;

    // Validate frame size
    if length > MAX_FRAME_SIZE {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("Frame too large: {} bytes (max {})", length, MAX_FRAME_SIZE),
        ));
    }

    // Read payload
    let mut payload = vec![0u8; length as usize];
    reader.read_exact(&mut payload)?;

    Ok(Some(Frame { stream_type, payload }))
}

/// Write a single frame to a byte stream.
pub fn write_frame(writer: &mut dyn io::Write, frame: &Frame) -> io::Result<()> {
    let len = frame.payload.len();
    if len > MAX_FRAME_SIZE as usize {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Frame payload too large: {} bytes (max {})", len, MAX_FRAME_SIZE),
        ));
    }

    writer.write_all(&[frame.stream_type.as_byte()])?;
    writer.write_all(&(len as u32).to_be_bytes())?;
    writer.write_all(&frame.payload)?;
    writer.flush()?;
    Ok(())
}

// ============================================================================
// ASYNC FRAME READER / WRITER — for tokio AsyncRead/AsyncWrite
// ============================================================================

/// Read a frame from an async byte stream (iroh SendStream/RecvStream).
/// This operates on raw byte slices for compatibility with iroh's API.
///
/// For iroh streams: caller reads bytes into buffer, passes to parse_frame.
/// iroh RecvStream doesn't implement AsyncRead directly — we work with
/// the bytes it gives us.

/// Parse a frame from a complete byte buffer.
/// Returns (frame, bytes_consumed) on success.
/// Returns None if buffer doesn't contain a complete frame yet.
pub fn parse_frame(buf: &[u8]) -> Result<Option<(Frame, usize)>, io::Error> {
    if buf.len() < FRAME_HEADER_SIZE {
        return Ok(None); // Need more data
    }

    let type_byte = buf[0];
    let length = u32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]);

    let stream_type = StreamType::from_byte(type_byte).ok_or_else(|| {
        io::Error::new(io::ErrorKind::InvalidData, format!("Unknown stream type: 0x{:02x}", type_byte))
    })?;

    if length > MAX_FRAME_SIZE {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("Frame too large: {} bytes (max {})", length, MAX_FRAME_SIZE),
        ));
    }

    let total_len = FRAME_HEADER_SIZE + length as usize;
    if buf.len() < total_len {
        return Ok(None); // Need more data
    }

    let payload = buf[FRAME_HEADER_SIZE..total_len].to_vec();
    Ok(Some((Frame { stream_type, payload }, total_len)))
}

/// Serialize a frame into a byte buffer for writing to iroh SendStream.
/// Same as Frame::to_bytes() but takes components directly.
pub fn encode_frame(stream_type: StreamType, payload: &[u8]) -> Result<Vec<u8>, io::Error> {
    if payload.len() > MAX_FRAME_SIZE as usize {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("Payload too large: {} bytes", payload.len()),
        ));
    }
    let mut buf = Vec::with_capacity(FRAME_HEADER_SIZE + payload.len());
    buf.push(stream_type.as_byte());
    buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
    buf.extend_from_slice(payload);
    Ok(buf)
}

// ============================================================================
// LEGACY DETECTION
// ============================================================================

/// Detect whether incoming data is legacy JSON-RPC or new framed protocol.
/// Legacy mesh messages start with '{' (0x7B) — raw JSON.
/// New framed messages start with 0x01-0x08 — stream type byte.
///
/// Call this on the first byte(s) of a new stream to determine protocol version.
pub fn is_legacy_jsonrpc(first_byte: u8) -> bool {
    // ASCII '{' = 0x7B. All stream types are 0x01-0x08.
    // No overlap — clean detection.
    first_byte == b'{'
}

/// Detect protocol from first byte
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Protocol {
    /// Legacy one-shot JSON-RPC (existing mesh behavior)
    LegacyJsonRpc,
    /// New framed protocol with persistent streams
    Framed(StreamType),
    /// Unknown protocol
    Unknown(u8),
}

pub fn detect_protocol(first_byte: u8) -> Protocol {
    if first_byte == b'{' {
        Protocol::LegacyJsonRpc
    } else if let Some(st) = StreamType::from_byte(first_byte) {
        Protocol::Framed(st)
    } else {
        Protocol::Unknown(first_byte)
    }
}

// ============================================================================
// CONTROL MESSAGES
// ============================================================================

/// Well-known control message types (sent as JSON in Control frames)
pub mod control {
    /// Heartbeat — sent periodically to keep stream alive
    pub const HEARTBEAT: &str = r#"{"type":"heartbeat"}"#;

    /// Status request
    pub const STATUS_REQUEST: &str = r#"{"type":"status_request"}"#;

    /// Peer closing stream gracefully
    pub const STREAM_CLOSE: &str = r#"{"type":"stream_close"}"#;

    /// Peer requesting stream type upgrade/change
    pub const STREAM_UPGRADE: &str = r#"{"type":"stream_upgrade"}"#;

    /// Initial role/team/version exchange on persistent stream connect.
    pub const HANDSHAKE: &str = r#"{"type":"handshake"}"#;

    /// Build a handshake frame JSON string from role/team/name/version.
    pub fn build_handshake(role: &str, name: &str, version: &str) -> String {
        format!(r#"{{"type":"handshake","role":"{}","name":"{}","version":"{}"}}"#, role, name, version)
    }

    /// Parse role from a handshake frame payload. Returns None if not a handshake.
    pub fn parse_role(payload: &str) -> Option<String> {
        if payload.contains(r#""type":"handshake""#) || payload.contains(r#""type": "handshake""#) {
            let start = payload.find(r#""role":"#)?;
            let role_start = start + 8;
            payload[role_start..].find('"').map(|end| payload[role_start..role_start + end].to_string())
        } else {
            None
        }
    }

    /// Parse name from a handshake frame payload.
    pub fn parse_name(payload: &str) -> Option<String> {
        let start = payload.find(r#""name":"#)?;
        let name_start = start + 8;
        payload[name_start..].find('"').map(|end| payload[name_start..name_start + end].to_string())
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_stream_type_roundtrip() {
        for byte in 0x01..=0x08 {
            let st = StreamType::from_byte(byte).unwrap();
            assert_eq!(st.as_byte(), byte);
        }
        assert!(StreamType::from_byte(0x00).is_none());
        assert!(StreamType::from_byte(0x0A).is_none());
        assert!(StreamType::from_byte(0xFF).is_none());
    }

    #[test]
    fn test_frame_to_bytes_and_parse() {
        let frame = Frame::tool_rpc(r#"{"method":"spf_status"}"#);
        let bytes = frame.to_bytes();

        // Verify header
        assert_eq!(bytes[0], 0x01); // TOOL_RPC
        let len = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
        assert_eq!(len as usize, frame.payload.len());

        // Parse back
        let (parsed, consumed) = parse_frame(&bytes).unwrap().unwrap();
        assert_eq!(parsed.stream_type, StreamType::ToolRpc);
        assert_eq!(parsed.payload, frame.payload);
        assert_eq!(consumed, bytes.len());
    }

    #[test]
    fn test_read_write_frame_sync() {
        let original = Frame::chat("Hello from SPF mesh!");
        let mut buffer = Vec::new();

        write_frame(&mut buffer, &original).unwrap();

        let mut cursor = Cursor::new(&buffer);
        let read_back = read_frame(&mut cursor).unwrap().unwrap();

        assert_eq!(read_back.stream_type, StreamType::ChatText);
        assert_eq!(read_back.payload_str().unwrap(), "Hello from SPF mesh!");
    }

    #[test]
    fn test_multiple_frames() {
        let frames = vec![
            Frame::tool_rpc(r#"{"method":"test1"}"#),
            Frame::chat("message two"),
            Frame::control(control::HEARTBEAT),
        ];

        let mut buffer = Vec::new();
        for f in &frames {
            write_frame(&mut buffer, f).unwrap();
        }

        let mut cursor = Cursor::new(&buffer);
        for expected in &frames {
            let read = read_frame(&mut cursor).unwrap().unwrap();
            assert_eq!(read.stream_type, expected.stream_type);
            assert_eq!(read.payload, expected.payload);
        }

        // Next read should return None (EOF)
        let eof = read_frame(&mut cursor).unwrap();
        assert!(eof.is_none());
    }

    #[test]
    fn test_parse_frame_incomplete() {
        // Only header, no payload
        let bytes = vec![0x01, 0x00, 0x00, 0x00, 0x05]; // type=TOOL_RPC, len=5
        let result = parse_frame(&bytes).unwrap();
        assert!(result.is_none()); // Needs 5 more bytes

        // Too short for header
        let result2 = parse_frame(&[0x01, 0x00]).unwrap();
        assert!(result2.is_none());
    }

    #[test]
    fn test_oversized_frame_rejected() {
        let mut header = vec![0x01]; // TOOL_RPC
        let big_len = MAX_FRAME_SIZE + 1;
        header.extend_from_slice(&big_len.to_be_bytes());
        header.extend_from_slice(&[0u8; 100]); // some payload bytes

        let result = parse_frame(&header);
        assert!(result.is_err());
    }

    #[test]
    fn test_unknown_stream_type_rejected() {
        let bytes = vec![0xFF, 0x00, 0x00, 0x00, 0x01, 0x42]; // type=0xFF
        let result = parse_frame(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_legacy_detection() {
        assert!(is_legacy_jsonrpc(b'{'));
        assert!(!is_legacy_jsonrpc(0x01));
        assert!(!is_legacy_jsonrpc(0x08));

        assert_eq!(detect_protocol(b'{'), Protocol::LegacyJsonRpc);
        assert_eq!(detect_protocol(0x01), Protocol::Framed(StreamType::ToolRpc));
        assert_eq!(detect_protocol(0x08), Protocol::Framed(StreamType::Control));
        assert_eq!(detect_protocol(0x09), Protocol::Unknown(0x09));
        assert_eq!(detect_protocol(0xAA), Protocol::Unknown(0xAA));
    }

    #[test]
    fn test_stream_type_properties() {
        assert!(StreamType::VoiceAudio.is_realtime());
        assert!(StreamType::ChatText.is_realtime());
        assert!(!StreamType::BrainSync.is_realtime());

        assert!(StreamType::BrainSync.is_bulk());
        assert!(StreamType::WeightSync.is_bulk());
        assert!(!StreamType::ChatText.is_bulk());
    }

    #[test]
    fn test_encode_frame() {
        let payload = b"test payload";
        let bytes = encode_frame(StreamType::PipelineTask, payload).unwrap();
        assert_eq!(bytes[0], 0x04);
        let len = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
        assert_eq!(len, payload.len() as u32);
        assert_eq!(&bytes[5..], payload);
    }

    #[test]
    fn test_empty_frame() {
        let frame = Frame::new(StreamType::Control, vec![]);
        let bytes = frame.to_bytes();
        assert_eq!(bytes.len(), FRAME_HEADER_SIZE); // Just header, no payload

        let (parsed, consumed) = parse_frame(&bytes).unwrap().unwrap();
        assert_eq!(parsed.payload.len(), 0);
        assert_eq!(consumed, FRAME_HEADER_SIZE);
    }
}