Skip to main content

chat_core/
capnp.rs

1//! Minimal Cap'n Proto builder for ChatCoreOut messages.
2//!
3//! Builds single-segment Cap'n Proto messages without any external dependencies.
4//! Follows the wire format: [segment_count-1: u32] [segment0_size_words: u32] [segment0_bytes...]
5//!
6//! ChatCoreOut union layout (matching chat_core.capnp):
7//!   Data section: 1 word (8 bytes)
8//!     - bytes 0-1: union discriminant (u16 LE)
9//!   Pointer section: 1 pointer (8 bytes)
10//!     - ptr 0: Text for content/thinking/error, or struct for toolCallDetected
11//!
12//! Union discriminants:
13//!   0 = content (Text)
14//!   1 = thinking (Text)
15//!   2 = toolCallDetected (ToolCallDetectedMsg struct)
16//!   3 = complete (Void)
17//!   4 = error (Text)
18
19const WORD: usize = 8;
20
21/// Build a ChatCoreOut message with a Text payload (content, thinking, error).
22pub fn build_text_event(discriminant: u16, text: &str) -> Vec<u8> {
23    let text_bytes = text.as_bytes();
24    let text_len = text_bytes.len() + 1; // +1 for NUL terminator
25    let text_words = text_len.div_ceil(WORD);
26
27    // Segment: root struct (1 data word + 1 ptr word) + text list
28    let segment_words = 2 + text_words;
29    let total = 8 + segment_words * WORD; // 8 bytes header + segment
30
31    let mut buf = vec![0u8; total];
32
33    // Message header: segment_count - 1 = 0, segment_size_words
34    buf[0..4].copy_from_slice(&0u32.to_le_bytes()); // 1 segment
35    buf[4..8].copy_from_slice(&(segment_words as u32).to_le_bytes());
36
37    // Root struct pointer at offset 0 (self-referencing: offset=0)
38    // Data offset = 0 words from pointer, data_size = 1 word, ptr_size = 1
39    // But in flat format, the struct starts immediately after the header.
40    // The root pointer IS the first word of the segment in standard format,
41    // but for flat (no root pointer) format used by hyprstream, data starts at offset 0.
42
43    // Data word: union discriminant at bytes 0-1
44    let data_offset = 8; // after header
45    buf[data_offset..data_offset + 2].copy_from_slice(&discriminant.to_le_bytes());
46
47    // Pointer word: text list pointer
48    // List pointer: offset_words | 0b01 (list tag) | element_size=2 (1 byte) | count
49    let ptr_offset = data_offset + WORD;
50    let list_offset_words: i32 = 0; // text starts right after ptr section
51    let ptr_val: u64 = ((list_offset_words as u32 as u64) << 2)
52        | 1 // list tag
53        | ((2u64) << 32) // element size = byte
54        | ((text_len as u64) << 35); // element count
55    buf[ptr_offset..ptr_offset + 8].copy_from_slice(&ptr_val.to_le_bytes());
56
57    // Text data (NUL-terminated)
58    let text_offset = ptr_offset + WORD;
59    buf[text_offset..text_offset + text_bytes.len()].copy_from_slice(text_bytes);
60    // NUL terminator is already 0 from vec initialization
61
62    buf
63}
64
65/// Build a ChatCoreOut.complete message (Void, no payload).
66pub fn build_complete() -> Vec<u8> {
67    // Just a struct with discriminant=3, no pointer data
68    let segment_words = 2; // 1 data word + 1 ptr word (empty)
69    let total = 8 + segment_words * WORD;
70    let mut buf = vec![0u8; total];
71
72    buf[0..4].copy_from_slice(&0u32.to_le_bytes());
73    buf[4..8].copy_from_slice(&(segment_words as u32).to_le_bytes());
74
75    // discriminant = 3 (complete)
76    buf[8..10].copy_from_slice(&3u16.to_le_bytes());
77
78    buf
79}
80
81/// Build a ChatCoreOut.toolCallDetected message.
82/// The ToolCallDetectedMsg struct has 4 text fields:
83///   ptr 0: id, ptr 1: uuid, ptr 2: description, ptr 3: arguments
84pub fn build_tool_call_detected(
85    id: &str,
86    uuid: &str,
87    description: &str,
88    arguments: &str,
89) -> Vec<u8> {
90    // For simplicity, encode as JSON in a text field rather than nested struct.
91    // This avoids complex multi-pointer Cap'n Proto layout.
92    // The TS side can parse either native capnp or this JSON-in-text form.
93    let json = format!(
94        r#"{{"id":"{}","uuid":"{}","description":"{}","arguments":{}}}"#,
95        id.replace('"', r#"\""#),
96        uuid.replace('"', r#"\""#),
97        description.replace('"', r#"\""#),
98        arguments, // already JSON
99    );
100    build_text_event(2, &json)
101}
102
103/// Encode multiple ChatCoreOut events into a single buffer.
104/// Format: [u32 LE count] [u32 LE len0] [event0 bytes] [u32 LE len1] [event1 bytes] ...
105pub fn encode_event_list(events: &[Vec<u8>]) -> Vec<u8> {
106    let total_len: usize = 4 + events.iter().map(|e| 4 + e.len()).sum::<usize>();
107    let mut buf = Vec::with_capacity(total_len);
108    buf.extend_from_slice(&(events.len() as u32).to_le_bytes());
109    for event in events {
110        buf.extend_from_slice(&(event.len() as u32).to_le_bytes());
111        buf.extend_from_slice(event);
112    }
113    buf
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn test_build_text_event() {
122        let msg = build_text_event(0, "hello");
123        // Should be: 8 header + 8 data + 8 ptr + 8 text = 32 bytes
124        assert_eq!(msg.len(), 32);
125        // Discriminant at offset 8
126        assert_eq!(u16::from_le_bytes([msg[8], msg[9]]), 0);
127    }
128
129    #[test]
130    fn test_build_complete() {
131        let msg = build_complete();
132        assert_eq!(msg.len(), 24); // 8 header + 16 struct
133        assert_eq!(u16::from_le_bytes([msg[8], msg[9]]), 3);
134    }
135
136    #[test]
137    fn test_encode_event_list() {
138        let events = vec![build_text_event(0, "hi"), build_complete()];
139        let encoded = encode_event_list(&events);
140        let count = u32::from_le_bytes([encoded[0], encoded[1], encoded[2], encoded[3]]);
141        assert_eq!(count, 2);
142    }
143}