Skip to main content

codive_core/
message.rs

1//! Message types for the Agent system
2//!
3//! This module defines the core types for representing conversations
4//! between users, assistants, and tools.
5//!
6//! # Type Design
7//!
8//! The message system uses Rust's enums to ensure type safety:
9//! - [`Role`] - Who sent the message (User or Assistant)
10//! - [`ContentPart`] - What the message contains (text, tool calls, results)
11//! - [`Message`] - A complete message with metadata
12//!
13//! # Example
14//!
15//! ```rust
16//! use codive_core::message::{Message, Role, ContentPart};
17//!
18//! // Create a simple text message
19//! let msg = Message::user("Hello, can you help me?");
20//!
21//! // Create an assistant response with multiple parts
22//! let response = Message::assistant(vec![
23//!     ContentPart::text("Let me help you with that."),
24//! ]);
25//! ```
26
27use serde::{Deserialize, Serialize};
28use std::time::SystemTime;
29
30// ============================================================================
31// Role
32// ============================================================================
33
34/// The role of a message sender
35///
36/// This enum is kept simple intentionally:
37/// - `User` - Messages from the human user
38/// - `Assistant` - Messages from the AI assistant
39///
40/// Note: "System" prompts are handled separately in the provider layer,
41/// not as regular messages in the conversation.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum Role {
45    /// Message from the human user
46    User,
47    /// Message from the AI assistant
48    Assistant,
49}
50
51impl Role {
52    /// Returns true if this is a user message
53    pub fn is_user(&self) -> bool {
54        matches!(self, Role::User)
55    }
56
57    /// Returns true if this is an assistant message
58    pub fn is_assistant(&self) -> bool {
59        matches!(self, Role::Assistant)
60    }
61}
62
63// ============================================================================
64// Tool Types
65// ============================================================================
66
67/// A unique identifier for a tool call
68///
69/// Tool call IDs are used to match tool results back to their requests.
70/// They are typically generated by the LLM provider.
71pub type ToolCallId = String;
72
73/// A request to execute a tool
74///
75/// Tool calls are generated by the assistant when it wants to use a tool.
76/// The agent executes the tool and returns a [`ToolResult`].
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct ToolCall {
79    /// Unique identifier for this tool call
80    pub id: ToolCallId,
81    /// Name of the tool to execute
82    pub name: String,
83    /// Arguments as JSON (tool-specific schema)
84    pub arguments: serde_json::Value,
85}
86
87impl ToolCall {
88    /// Create a new tool call
89    pub fn new(
90        id: impl Into<String>,
91        name: impl Into<String>,
92        arguments: serde_json::Value,
93    ) -> Self {
94        Self {
95            id: id.into(),
96            name: name.into(),
97            arguments,
98        }
99    }
100}
101
102/// The result of executing a tool
103///
104/// Tool results are sent back to the assistant after a tool is executed.
105/// They include the original call ID for matching.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct ToolResult {
108    /// ID of the original tool call this is responding to
109    pub call_id: ToolCallId,
110    /// The tool's output (success case)
111    pub output: Option<String>,
112    /// Error message if the tool failed
113    pub error: Option<String>,
114}
115
116impl ToolResult {
117    /// Create a successful tool result
118    pub fn success(call_id: impl Into<String>, output: impl Into<String>) -> Self {
119        Self {
120            call_id: call_id.into(),
121            output: Some(output.into()),
122            error: None,
123        }
124    }
125
126    /// Create a failed tool result
127    pub fn failure(call_id: impl Into<String>, error: impl Into<String>) -> Self {
128        Self {
129            call_id: call_id.into(),
130            output: None,
131            error: Some(error.into()),
132        }
133    }
134
135    /// Returns true if this result represents a successful execution
136    pub fn is_success(&self) -> bool {
137        self.error.is_none()
138    }
139}
140
141// ============================================================================
142// ContentPart
143// ============================================================================
144
145/// A part of a message's content
146///
147/// Messages can contain multiple content parts, allowing for rich interactions:
148/// - Text for regular conversation
149/// - Tool calls when the assistant wants to use tools
150/// - Tool results when reporting tool execution outcomes
151///
152/// # Why an enum?
153///
154/// Rust enums are "algebraic data types" - each variant can hold different data.
155/// This is perfect for modeling the different types of content a message can have.
156/// The compiler ensures we handle all cases.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(tag = "type", rename_all = "snake_case")]
159pub enum ContentPart {
160    /// Plain text content
161    Text {
162        /// The text content
163        text: String,
164    },
165    /// A request to execute a tool (from assistant)
166    ToolCall(ToolCall),
167    /// The result of a tool execution (from user, in response to tool call)
168    ToolResult(ToolResult),
169}
170
171impl ContentPart {
172    /// Create a text content part
173    pub fn text(text: impl Into<String>) -> Self {
174        Self::Text { text: text.into() }
175    }
176
177    /// Create a tool call content part
178    pub fn tool_call(
179        id: impl Into<String>,
180        name: impl Into<String>,
181        arguments: serde_json::Value,
182    ) -> Self {
183        Self::ToolCall(ToolCall::new(id, name, arguments))
184    }
185
186    /// Create a successful tool result content part
187    pub fn tool_result_success(call_id: impl Into<String>, output: impl Into<String>) -> Self {
188        Self::ToolResult(ToolResult::success(call_id, output))
189    }
190
191    /// Create a failed tool result content part
192    pub fn tool_result_failure(call_id: impl Into<String>, error: impl Into<String>) -> Self {
193        Self::ToolResult(ToolResult::failure(call_id, error))
194    }
195
196    /// Returns true if this is a text part
197    pub fn is_text(&self) -> bool {
198        matches!(self, ContentPart::Text { .. })
199    }
200
201    /// Returns true if this is a tool call
202    pub fn is_tool_call(&self) -> bool {
203        matches!(self, ContentPart::ToolCall(_))
204    }
205
206    /// Returns true if this is a tool result
207    pub fn is_tool_result(&self) -> bool {
208        matches!(self, ContentPart::ToolResult(_))
209    }
210
211    /// Extract text content if this is a text part
212    pub fn as_text(&self) -> Option<&str> {
213        match self {
214            ContentPart::Text { text } => Some(text),
215            _ => None,
216        }
217    }
218
219    /// Extract tool call if this is a tool call part
220    pub fn as_tool_call(&self) -> Option<&ToolCall> {
221        match self {
222            ContentPart::ToolCall(call) => Some(call),
223            _ => None,
224        }
225    }
226
227    /// Extract tool result if this is a tool result part
228    pub fn as_tool_result(&self) -> Option<&ToolResult> {
229        match self {
230            ContentPart::ToolResult(result) => Some(result),
231            _ => None,
232        }
233    }
234}
235
236// ============================================================================
237// Message
238// ============================================================================
239
240/// A unique identifier for a message
241pub type MessageId = String;
242
243/// A message in a conversation
244///
245/// Messages are the fundamental unit of conversation. Each message has:
246/// - An ID for tracking and referencing
247/// - A role (who sent it)
248/// - Content (what was said/done)
249/// - Timestamps for ordering and history
250///
251/// # Content Model
252///
253/// Messages contain a vector of [`ContentPart`]s, allowing for:
254/// - Simple text-only messages
255/// - Messages with multiple tool calls
256/// - Mixed content (text + tool calls)
257#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258pub struct Message {
259    /// Unique identifier for this message
260    pub id: MessageId,
261    /// Who sent this message
262    pub role: Role,
263    /// The message content (can have multiple parts)
264    pub content: Vec<ContentPart>,
265    /// When the message was created
266    #[serde(with = "system_time_serde")]
267    pub created_at: SystemTime,
268}
269
270impl Message {
271    /// Create a new message with the given role and content
272    pub fn new(role: Role, content: Vec<ContentPart>) -> Self {
273        Self {
274            id: generate_message_id(),
275            role,
276            content,
277            created_at: SystemTime::now(),
278        }
279    }
280
281    /// Create a user message with text content
282    pub fn user(text: impl Into<String>) -> Self {
283        Self::new(Role::User, vec![ContentPart::text(text)])
284    }
285
286    /// Create an assistant message with the given content parts
287    pub fn assistant(content: Vec<ContentPart>) -> Self {
288        Self::new(Role::Assistant, content)
289    }
290
291    /// Create an assistant message with just text
292    pub fn assistant_text(text: impl Into<String>) -> Self {
293        Self::assistant(vec![ContentPart::text(text)])
294    }
295
296    /// Create a user message containing tool results
297    pub fn tool_results(results: Vec<ToolResult>) -> Self {
298        Self::new(
299            Role::User,
300            results.into_iter().map(ContentPart::ToolResult).collect(),
301        )
302    }
303
304    /// Get all text content concatenated
305    ///
306    /// Useful for simple display or when you only care about text.
307    pub fn text_content(&self) -> String {
308        self.content
309            .iter()
310            .filter_map(|part| part.as_text())
311            .collect::<Vec<_>>()
312            .join("")
313    }
314
315    /// Get all tool calls in this message
316    pub fn tool_calls(&self) -> Vec<&ToolCall> {
317        self.content
318            .iter()
319            .filter_map(|part| part.as_tool_call())
320            .collect()
321    }
322
323    /// Returns true if this message contains any tool calls
324    pub fn has_tool_calls(&self) -> bool {
325        self.content.iter().any(|part| part.is_tool_call())
326    }
327
328    /// Returns true if this message is from the user
329    pub fn is_user(&self) -> bool {
330        self.role.is_user()
331    }
332
333    /// Returns true if this message is from the assistant
334    pub fn is_assistant(&self) -> bool {
335        self.role.is_assistant()
336    }
337}
338
339// ============================================================================
340// Helper Functions
341// ============================================================================
342
343/// Generate a unique message ID
344///
345/// Uses timestamp + atomic counter to ensure uniqueness even
346/// when messages are created in rapid succession.
347fn generate_message_id() -> MessageId {
348    use std::sync::atomic::{AtomicU64, Ordering};
349    static COUNTER: AtomicU64 = AtomicU64::new(0);
350
351    let timestamp = SystemTime::now()
352        .duration_since(SystemTime::UNIX_EPOCH)
353        .unwrap_or_default()
354        .as_millis() as u64;
355    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
356    format!("msg_{}_{}", timestamp, counter)
357}
358
359/// Serde module for SystemTime
360///
361/// SystemTime doesn't have a default serde implementation,
362/// so we serialize it as milliseconds since UNIX epoch.
363mod system_time_serde {
364    use serde::{Deserialize, Deserializer, Serialize, Serializer};
365    use std::time::{Duration, SystemTime, UNIX_EPOCH};
366
367    pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
368    where
369        S: Serializer,
370    {
371        let millis = time
372            .duration_since(UNIX_EPOCH)
373            .unwrap_or_default()
374            .as_millis() as u64;
375        millis.serialize(serializer)
376    }
377
378    pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
379    where
380        D: Deserializer<'de>,
381    {
382        let millis = u64::deserialize(deserializer)?;
383        Ok(UNIX_EPOCH + Duration::from_millis(millis))
384    }
385}
386
387// ============================================================================
388// Tests
389// ============================================================================
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    #[test]
396    fn test_role_serialization() {
397        assert_eq!(serde_json::to_string(&Role::User).unwrap(), "\"user\"");
398        assert_eq!(
399            serde_json::to_string(&Role::Assistant).unwrap(),
400            "\"assistant\""
401        );
402    }
403
404    #[test]
405    fn test_role_deserialization() {
406        let user: Role = serde_json::from_str("\"user\"").unwrap();
407        let assistant: Role = serde_json::from_str("\"assistant\"").unwrap();
408        assert_eq!(user, Role::User);
409        assert_eq!(assistant, Role::Assistant);
410    }
411
412    #[test]
413    fn test_role_helpers() {
414        assert!(Role::User.is_user());
415        assert!(!Role::User.is_assistant());
416        assert!(Role::Assistant.is_assistant());
417        assert!(!Role::Assistant.is_user());
418    }
419
420    #[test]
421    fn test_content_part_text() {
422        let part = ContentPart::text("Hello, world!");
423        assert!(part.is_text());
424        assert_eq!(part.as_text(), Some("Hello, world!"));
425        assert!(!part.is_tool_call());
426        assert!(!part.is_tool_result());
427    }
428
429    #[test]
430    fn test_content_part_tool_call() {
431        let part = ContentPart::tool_call(
432            "call_1",
433            "read_file",
434            serde_json::json!({"path": "/tmp/test.txt"}),
435        );
436        assert!(part.is_tool_call());
437        assert!(!part.is_text());
438
439        let call = part.as_tool_call().unwrap();
440        assert_eq!(call.name, "read_file");
441        assert_eq!(call.id, "call_1");
442    }
443
444    #[test]
445    fn test_content_part_tool_result() {
446        let success = ContentPart::tool_result_success("call_1", "file contents here");
447        assert!(success.is_tool_result());
448        assert!(success.as_tool_result().unwrap().is_success());
449
450        let failure = ContentPart::tool_result_failure("call_2", "file not found");
451        assert!(failure.is_tool_result());
452        assert!(!failure.as_tool_result().unwrap().is_success());
453    }
454
455    #[test]
456    fn test_message_user() {
457        let msg = Message::user("Hello, agent!");
458        assert!(msg.is_user());
459        assert!(!msg.is_assistant());
460        assert_eq!(msg.text_content(), "Hello, agent!");
461        assert!(!msg.has_tool_calls());
462    }
463
464    #[test]
465    fn test_message_assistant_text() {
466        let msg = Message::assistant_text("I can help with that.");
467        assert!(msg.is_assistant());
468        assert_eq!(msg.text_content(), "I can help with that.");
469    }
470
471    #[test]
472    fn test_message_with_tool_calls() {
473        let msg = Message::assistant(vec![
474            ContentPart::text("Let me read that file."),
475            ContentPart::tool_call(
476                "call_1",
477                "read_file",
478                serde_json::json!({"path": "/tmp/test.txt"}),
479            ),
480        ]);
481
482        assert!(msg.has_tool_calls());
483        assert_eq!(msg.tool_calls().len(), 1);
484        assert_eq!(msg.tool_calls()[0].name, "read_file");
485        assert_eq!(msg.text_content(), "Let me read that file.");
486    }
487
488    #[test]
489    fn test_message_serialization_roundtrip() {
490        let original = Message::user("Test message");
491        let json = serde_json::to_string(&original).unwrap();
492        let restored: Message = serde_json::from_str(&json).unwrap();
493
494        assert_eq!(original.id, restored.id);
495        assert_eq!(original.role, restored.role);
496        assert_eq!(original.text_content(), restored.text_content());
497        // Note: created_at comparison might have slight precision loss
498    }
499
500    #[test]
501    fn test_tool_call_serialization() {
502        let call = ToolCall::new("call_123", "bash", serde_json::json!({"command": "ls -la"}));
503        let json = serde_json::to_string(&call).unwrap();
504        let restored: ToolCall = serde_json::from_str(&json).unwrap();
505
506        assert_eq!(call.id, restored.id);
507        assert_eq!(call.name, restored.name);
508        assert_eq!(call.arguments, restored.arguments);
509    }
510
511    #[test]
512    fn test_tool_result_success() {
513        let result = ToolResult::success("call_1", "output text");
514        assert!(result.is_success());
515        assert_eq!(result.output, Some("output text".to_string()));
516        assert_eq!(result.error, None);
517    }
518
519    #[test]
520    fn test_tool_result_failure() {
521        let result = ToolResult::failure("call_1", "something went wrong");
522        assert!(!result.is_success());
523        assert_eq!(result.output, None);
524        assert_eq!(result.error, Some("something went wrong".to_string()));
525    }
526
527    #[test]
528    fn test_content_part_serde_tagged() {
529        // Verify the serde tag format
530        let text = ContentPart::text("hello");
531        let json = serde_json::to_string(&text).unwrap();
532        assert!(json.contains("\"type\":\"text\""));
533
534        let call = ContentPart::tool_call("id", "name", serde_json::json!({}));
535        let json = serde_json::to_string(&call).unwrap();
536        assert!(json.contains("\"type\":\"tool_call\""));
537    }
538
539    #[test]
540    fn test_message_id_generation() {
541        let msg1 = Message::user("first");
542        let msg2 = Message::user("second");
543        // IDs should be unique
544        assert_ne!(msg1.id, msg2.id);
545        // IDs should have our prefix
546        assert!(msg1.id.starts_with("msg_"));
547    }
548}