brainwires-core 0.10.0

Core types, traits, and error handling for the Brainwires Agent Framework
Documentation
1
2
3
4
5
6
7
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
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Role of the message sender
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// Message from the user.
    User,
    /// Message from the AI assistant.
    Assistant,
    /// System prompt or instruction.
    System,
    /// Tool result message.
    Tool,
}

/// Message content can be simple text or complex structured content
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContent {
    /// Simple text content
    Text(String),
    /// Array of content blocks (for multimodal messages)
    Blocks(Vec<ContentBlock>),
}

/// Content block for structured messages
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    /// Text content block.
    Text {
        /// The text content.
        text: String,
    },
    /// Image content block (base64 encoded).
    Image {
        /// The image source data.
        source: ImageSource,
    },
    /// Tool use request.
    ToolUse {
        /// Unique identifier for this tool invocation.
        id: String,
        /// Name of the tool to call.
        name: String,
        /// Input arguments for the tool.
        input: Value,
    },
    /// Tool result.
    ToolResult {
        /// ID of the tool use this result corresponds to.
        tool_use_id: String,
        /// Result content.
        content: String,
        /// Whether this result represents an error.
        #[serde(skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,
    },
}

/// Image source for image content blocks
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ImageSource {
    /// Base64-encoded image data.
    Base64 {
        /// MIME type (e.g. "image/png").
        media_type: String,
        /// Base64-encoded image data.
        data: String,
    },
}

/// A message in the conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// Role of the message sender
    pub role: Role,
    /// Content of the message
    pub content: MessageContent,
    /// Optional name for the message sender (useful for multi-agent conversations)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Optional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

impl Message {
    /// Create a new user message
    pub fn user<S: Into<String>>(content: S) -> Self {
        Self {
            role: Role::User,
            content: MessageContent::Text(content.into()),
            name: None,
            metadata: None,
        }
    }

    /// Create a new assistant message
    pub fn assistant<S: Into<String>>(content: S) -> Self {
        Self {
            role: Role::Assistant,
            content: MessageContent::Text(content.into()),
            name: None,
            metadata: None,
        }
    }

    /// Create a new system message
    pub fn system<S: Into<String>>(content: S) -> Self {
        Self {
            role: Role::System,
            content: MessageContent::Text(content.into()),
            name: None,
            metadata: None,
        }
    }

    /// Create a tool result message
    pub fn tool_result<S: Into<String>>(tool_use_id: S, content: S) -> Self {
        Self {
            role: Role::Tool,
            content: MessageContent::Blocks(vec![ContentBlock::ToolResult {
                tool_use_id: tool_use_id.into(),
                content: content.into(),
                is_error: None,
            }]),
            name: None,
            metadata: None,
        }
    }

    /// Get the text content of a message (if it's simple text)
    pub fn text(&self) -> Option<&str> {
        match &self.content {
            MessageContent::Text(text) => Some(text),
            MessageContent::Blocks(_) => None,
        }
    }

    /// Get a text representation of the message content, including Blocks.
    /// For Text messages, returns the text directly.
    /// For Blocks messages, concatenates text from all blocks into a readable summary
    /// so that conversation history is preserved when serializing for API calls.
    pub fn text_or_summary(&self) -> String {
        match &self.content {
            MessageContent::Text(text) => text.clone(),
            MessageContent::Blocks(blocks) => {
                let mut parts = Vec::new();
                for block in blocks {
                    match block {
                        ContentBlock::Text { text } => {
                            parts.push(text.clone());
                        }
                        ContentBlock::ToolUse { name, input, .. } => {
                            parts.push(format!("[Called tool: {} with args: {}]", name, input));
                        }
                        ContentBlock::ToolResult {
                            content, is_error, ..
                        } => {
                            if is_error == &Some(true) {
                                parts.push(format!("[Tool error: {}]", content));
                            } else {
                                parts.push(format!("[Tool result: {}]", content));
                            }
                        }
                        ContentBlock::Image { .. } => {
                            parts.push("[Image]".to_string());
                        }
                    }
                }
                parts.join("\n")
            }
        }
    }

    /// Get mutable reference to the text content
    pub fn text_mut(&mut self) -> Option<&mut String> {
        match &mut self.content {
            MessageContent::Text(text) => Some(text),
            MessageContent::Blocks(_) => None,
        }
    }
}

/// Usage statistics for a chat completion
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Usage {
    /// Number of tokens in the prompt
    pub prompt_tokens: u32,
    /// Number of tokens in the completion
    pub completion_tokens: u32,
    /// Total number of tokens
    pub total_tokens: u32,
}

impl Usage {
    /// Create a new usage statistics
    pub fn new(prompt_tokens: u32, completion_tokens: u32) -> Self {
        Self {
            prompt_tokens,
            completion_tokens,
            total_tokens: prompt_tokens + completion_tokens,
        }
    }
}

/// Response from a chat completion
#[derive(Debug, Clone)]
pub struct ChatResponse {
    /// The generated message
    pub message: Message,
    /// Usage statistics
    pub usage: Usage,
    /// Optional finish reason
    pub finish_reason: Option<String>,
}

/// Serialize a slice of Messages into the STATELESS protocol format for conversation history.
///
/// Properly handles all message content types:
/// - `MessageContent::Text` → `{ "role": "user"|"assistant", "content": "..." }`
/// - `ContentBlock::ToolUse` → `{ "role": "function_call", "call_id", "name", "arguments" }`
/// - `ContentBlock::ToolResult` → `{ "role": "tool", "call_id", "content" }`
/// - `ContentBlock::Text` within Blocks → flushed as user/assistant text
/// - System messages and empty assistant messages are skipped
pub fn serialize_messages_to_stateless_history(messages: &[Message]) -> Vec<Value> {
    let mut history = Vec::new();

    for msg in messages {
        // Skip system messages
        if msg.role == Role::System {
            continue;
        }

        let role_str = match msg.role {
            Role::User => "user",
            Role::Assistant => "assistant",
            Role::Tool => "tool",
            Role::System => continue, // already handled above
        };

        match &msg.content {
            MessageContent::Text(text) => {
                // Skip empty assistant messages
                if msg.role == Role::Assistant && text.trim().is_empty() {
                    continue;
                }
                history.push(serde_json::json!({
                    "role": role_str,
                    "content": text,
                }));
            }
            MessageContent::Blocks(blocks) => {
                // Accumulate text blocks, emit tool entries individually
                let mut text_parts = Vec::new();

                for block in blocks {
                    match block {
                        ContentBlock::Text { text } => {
                            text_parts.push(text.clone());
                        }
                        ContentBlock::ToolUse { id, name, input } => {
                            // Flush accumulated text before tool entry
                            if !text_parts.is_empty() {
                                let combined = text_parts.join("\n");
                                if !(msg.role == Role::Assistant && combined.trim().is_empty()) {
                                    history.push(serde_json::json!({
                                        "role": role_str,
                                        "content": combined,
                                    }));
                                }
                                text_parts.clear();
                            }
                            history.push(serde_json::json!({
                                "role": "function_call",
                                "call_id": id,
                                "name": name,
                                "arguments": input.to_string(),
                            }));
                        }
                        ContentBlock::ToolResult {
                            tool_use_id,
                            content,
                            ..
                        } => {
                            // Flush accumulated text before tool entry
                            if !text_parts.is_empty() {
                                let combined = text_parts.join("\n");
                                if !(msg.role == Role::Assistant && combined.trim().is_empty()) {
                                    history.push(serde_json::json!({
                                        "role": role_str,
                                        "content": combined,
                                    }));
                                }
                                text_parts.clear();
                            }
                            history.push(serde_json::json!({
                                "role": "tool",
                                "call_id": tool_use_id,
                                "content": content,
                            }));
                        }
                        ContentBlock::Image { .. } => {
                            // Images can't be serialized to stateless text format; skip
                        }
                    }
                }

                // Flush any remaining text
                if !text_parts.is_empty() {
                    let combined = text_parts.join("\n");
                    if !(msg.role == Role::Assistant && combined.trim().is_empty()) {
                        history.push(serde_json::json!({
                            "role": role_str,
                            "content": combined,
                        }));
                    }
                }
            }
        }
    }

    history
}

/// Streaming chunk from a chat completion
#[derive(Debug, Clone)]
pub enum StreamChunk {
    /// Text delta
    Text(String),
    /// Tool use started.
    ToolUse {
        /// Unique tool use identifier.
        id: String,
        /// Name of the tool being invoked.
        name: String,
    },
    /// Tool input delta (partial JSON streaming).
    ToolInputDelta {
        /// Tool use identifier this delta belongs to.
        id: String,
        /// Partial JSON fragment.
        partial_json: String,
    },
    /// Tool call request from backend (for client-side execution).
    ToolCall {
        /// Unique call identifier.
        call_id: String,
        /// Response identifier for correlating results.
        response_id: String,
        /// Chat session identifier, if any.
        chat_id: Option<String>,
        /// Name of the tool to execute.
        tool_name: String,
        /// MCP server name hosting the tool.
        server: String,
        /// Parameters for the tool call.
        parameters: serde_json::Value,
    },
    /// Usage statistics (usually sent at the end)
    Usage(Usage),
    /// The model auto-compacted (summarised) the context window.
    ///
    /// Emitted by Claude 4.6+ when `context_window_management_event` fires.
    /// Agents should replace their message history with a synthetic assistant
    /// message containing the summary so future turns stay coherent.
    ContextCompacted {
        /// The model-generated summary that replaces the compacted messages.
        summary: String,
        /// Approximate number of tokens freed by compaction.
        tokens_freed: Option<u32>,
    },
    /// Stream completed
    Done,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_message_user() {
        let msg = Message::user("Hello");
        assert_eq!(msg.role, Role::User);
        assert_eq!(msg.text(), Some("Hello"));
    }

    #[test]
    fn test_message_assistant() {
        let msg = Message::assistant("Response");
        assert_eq!(msg.role, Role::Assistant);
        assert_eq!(msg.text(), Some("Response"));
    }

    #[test]
    fn test_message_tool_result() {
        let msg = Message::tool_result("tool-1", "Result");
        assert_eq!(msg.role, Role::Tool);
    }

    #[test]
    fn test_usage_new() {
        let usage = Usage::new(100, 50);
        assert_eq!(usage.total_tokens, 150);
    }

    #[test]
    fn test_role_serialization() {
        let role = Role::User;
        let json = serde_json::to_string(&role).unwrap();
        assert_eq!(json, "\"user\"");
    }

    #[test]
    fn test_stateless_history_simple_text() {
        let messages = vec![Message::user("Hello"), Message::assistant("Hi there")];
        let history = serialize_messages_to_stateless_history(&messages);
        assert_eq!(history.len(), 2);
        assert_eq!(history[0]["role"], "user");
        assert_eq!(history[1]["role"], "assistant");
    }

    #[test]
    fn test_stateless_history_skips_system() {
        let messages = vec![Message::system("You are helpful"), Message::user("Hello")];
        let history = serialize_messages_to_stateless_history(&messages);
        assert_eq!(history.len(), 1);
        assert_eq!(history[0]["role"], "user");
    }

    #[test]
    fn test_stateless_history_tool_round_trip() {
        let messages = vec![
            Message::user("Read the file"),
            Message {
                role: Role::Assistant,
                content: MessageContent::Blocks(vec![
                    ContentBlock::Text {
                        text: "I'll check.".to_string(),
                    },
                    ContentBlock::ToolUse {
                        id: "call-1".to_string(),
                        name: "read_file".to_string(),
                        input: json!({"path": "main.rs"}),
                    },
                ]),
                name: None,
                metadata: None,
            },
            Message::tool_result("call-1", "fn main() {}"),
            Message::assistant("The file contains a main function."),
        ];
        let history = serialize_messages_to_stateless_history(&messages);
        assert_eq!(history.len(), 5);
        assert_eq!(history[0]["role"], "user");
        assert_eq!(history[1]["role"], "assistant");
        assert_eq!(history[2]["role"], "function_call");
        assert_eq!(history[3]["role"], "tool");
        assert_eq!(history[4]["role"], "assistant");
    }
}