codive-core 0.1.0

Core types, traits, and utilities for Codive
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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! Message types for the Agent system
//!
//! This module defines the core types for representing conversations
//! between users, assistants, and tools.
//!
//! # Type Design
//!
//! The message system uses Rust's enums to ensure type safety:
//! - [`Role`] - Who sent the message (User or Assistant)
//! - [`ContentPart`] - What the message contains (text, tool calls, results)
//! - [`Message`] - A complete message with metadata
//!
//! # Example
//!
//! ```rust
//! use codive_core::message::{Message, Role, ContentPart};
//!
//! // Create a simple text message
//! let msg = Message::user("Hello, can you help me?");
//!
//! // Create an assistant response with multiple parts
//! let response = Message::assistant(vec![
//!     ContentPart::text("Let me help you with that."),
//! ]);
//! ```

use serde::{Deserialize, Serialize};
use std::time::SystemTime;

// ============================================================================
// Role
// ============================================================================

/// The role of a message sender
///
/// This enum is kept simple intentionally:
/// - `User` - Messages from the human user
/// - `Assistant` - Messages from the AI assistant
///
/// Note: "System" prompts are handled separately in the provider layer,
/// not as regular messages in the conversation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// Message from the human user
    User,
    /// Message from the AI assistant
    Assistant,
}

impl Role {
    /// Returns true if this is a user message
    pub fn is_user(&self) -> bool {
        matches!(self, Role::User)
    }

    /// Returns true if this is an assistant message
    pub fn is_assistant(&self) -> bool {
        matches!(self, Role::Assistant)
    }
}

// ============================================================================
// Tool Types
// ============================================================================

/// A unique identifier for a tool call
///
/// Tool call IDs are used to match tool results back to their requests.
/// They are typically generated by the LLM provider.
pub type ToolCallId = String;

/// A request to execute a tool
///
/// Tool calls are generated by the assistant when it wants to use a tool.
/// The agent executes the tool and returns a [`ToolResult`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolCall {
    /// Unique identifier for this tool call
    pub id: ToolCallId,
    /// Name of the tool to execute
    pub name: String,
    /// Arguments as JSON (tool-specific schema)
    pub arguments: serde_json::Value,
}

impl ToolCall {
    /// Create a new tool call
    pub fn new(
        id: impl Into<String>,
        name: impl Into<String>,
        arguments: serde_json::Value,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            arguments,
        }
    }
}

/// The result of executing a tool
///
/// Tool results are sent back to the assistant after a tool is executed.
/// They include the original call ID for matching.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolResult {
    /// ID of the original tool call this is responding to
    pub call_id: ToolCallId,
    /// The tool's output (success case)
    pub output: Option<String>,
    /// Error message if the tool failed
    pub error: Option<String>,
}

impl ToolResult {
    /// Create a successful tool result
    pub fn success(call_id: impl Into<String>, output: impl Into<String>) -> Self {
        Self {
            call_id: call_id.into(),
            output: Some(output.into()),
            error: None,
        }
    }

    /// Create a failed tool result
    pub fn failure(call_id: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            call_id: call_id.into(),
            output: None,
            error: Some(error.into()),
        }
    }

    /// Returns true if this result represents a successful execution
    pub fn is_success(&self) -> bool {
        self.error.is_none()
    }
}

// ============================================================================
// ContentPart
// ============================================================================

/// A part of a message's content
///
/// Messages can contain multiple content parts, allowing for rich interactions:
/// - Text for regular conversation
/// - Tool calls when the assistant wants to use tools
/// - Tool results when reporting tool execution outcomes
///
/// # Why an enum?
///
/// Rust enums are "algebraic data types" - each variant can hold different data.
/// This is perfect for modeling the different types of content a message can have.
/// The compiler ensures we handle all cases.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    /// Plain text content
    Text {
        /// The text content
        text: String,
    },
    /// A request to execute a tool (from assistant)
    ToolCall(ToolCall),
    /// The result of a tool execution (from user, in response to tool call)
    ToolResult(ToolResult),
}

impl ContentPart {
    /// Create a text content part
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Create a tool call content part
    pub fn tool_call(
        id: impl Into<String>,
        name: impl Into<String>,
        arguments: serde_json::Value,
    ) -> Self {
        Self::ToolCall(ToolCall::new(id, name, arguments))
    }

    /// Create a successful tool result content part
    pub fn tool_result_success(call_id: impl Into<String>, output: impl Into<String>) -> Self {
        Self::ToolResult(ToolResult::success(call_id, output))
    }

    /// Create a failed tool result content part
    pub fn tool_result_failure(call_id: impl Into<String>, error: impl Into<String>) -> Self {
        Self::ToolResult(ToolResult::failure(call_id, error))
    }

    /// Returns true if this is a text part
    pub fn is_text(&self) -> bool {
        matches!(self, ContentPart::Text { .. })
    }

    /// Returns true if this is a tool call
    pub fn is_tool_call(&self) -> bool {
        matches!(self, ContentPart::ToolCall(_))
    }

    /// Returns true if this is a tool result
    pub fn is_tool_result(&self) -> bool {
        matches!(self, ContentPart::ToolResult(_))
    }

    /// Extract text content if this is a text part
    pub fn as_text(&self) -> Option<&str> {
        match self {
            ContentPart::Text { text } => Some(text),
            _ => None,
        }
    }

    /// Extract tool call if this is a tool call part
    pub fn as_tool_call(&self) -> Option<&ToolCall> {
        match self {
            ContentPart::ToolCall(call) => Some(call),
            _ => None,
        }
    }

    /// Extract tool result if this is a tool result part
    pub fn as_tool_result(&self) -> Option<&ToolResult> {
        match self {
            ContentPart::ToolResult(result) => Some(result),
            _ => None,
        }
    }
}

// ============================================================================
// Message
// ============================================================================

/// A unique identifier for a message
pub type MessageId = String;

/// A message in a conversation
///
/// Messages are the fundamental unit of conversation. Each message has:
/// - An ID for tracking and referencing
/// - A role (who sent it)
/// - Content (what was said/done)
/// - Timestamps for ordering and history
///
/// # Content Model
///
/// Messages contain a vector of [`ContentPart`]s, allowing for:
/// - Simple text-only messages
/// - Messages with multiple tool calls
/// - Mixed content (text + tool calls)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {
    /// Unique identifier for this message
    pub id: MessageId,
    /// Who sent this message
    pub role: Role,
    /// The message content (can have multiple parts)
    pub content: Vec<ContentPart>,
    /// When the message was created
    #[serde(with = "system_time_serde")]
    pub created_at: SystemTime,
}

impl Message {
    /// Create a new message with the given role and content
    pub fn new(role: Role, content: Vec<ContentPart>) -> Self {
        Self {
            id: generate_message_id(),
            role,
            content,
            created_at: SystemTime::now(),
        }
    }

    /// Create a user message with text content
    pub fn user(text: impl Into<String>) -> Self {
        Self::new(Role::User, vec![ContentPart::text(text)])
    }

    /// Create an assistant message with the given content parts
    pub fn assistant(content: Vec<ContentPart>) -> Self {
        Self::new(Role::Assistant, content)
    }

    /// Create an assistant message with just text
    pub fn assistant_text(text: impl Into<String>) -> Self {
        Self::assistant(vec![ContentPart::text(text)])
    }

    /// Create a user message containing tool results
    pub fn tool_results(results: Vec<ToolResult>) -> Self {
        Self::new(
            Role::User,
            results.into_iter().map(ContentPart::ToolResult).collect(),
        )
    }

    /// Get all text content concatenated
    ///
    /// Useful for simple display or when you only care about text.
    pub fn text_content(&self) -> String {
        self.content
            .iter()
            .filter_map(|part| part.as_text())
            .collect::<Vec<_>>()
            .join("")
    }

    /// Get all tool calls in this message
    pub fn tool_calls(&self) -> Vec<&ToolCall> {
        self.content
            .iter()
            .filter_map(|part| part.as_tool_call())
            .collect()
    }

    /// Returns true if this message contains any tool calls
    pub fn has_tool_calls(&self) -> bool {
        self.content.iter().any(|part| part.is_tool_call())
    }

    /// Returns true if this message is from the user
    pub fn is_user(&self) -> bool {
        self.role.is_user()
    }

    /// Returns true if this message is from the assistant
    pub fn is_assistant(&self) -> bool {
        self.role.is_assistant()
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Generate a unique message ID
///
/// Uses timestamp + atomic counter to ensure uniqueness even
/// when messages are created in rapid succession.
fn generate_message_id() -> MessageId {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64;
    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("msg_{}_{}", timestamp, counter)
}

/// Serde module for SystemTime
///
/// SystemTime doesn't have a default serde implementation,
/// so we serialize it as milliseconds since UNIX epoch.
mod system_time_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let millis = time
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;
        millis.serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
    where
        D: Deserializer<'de>,
    {
        let millis = u64::deserialize(deserializer)?;
        Ok(UNIX_EPOCH + Duration::from_millis(millis))
    }
}

// ============================================================================
// Tests
// ============================================================================

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

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

    #[test]
    fn test_role_deserialization() {
        let user: Role = serde_json::from_str("\"user\"").unwrap();
        let assistant: Role = serde_json::from_str("\"assistant\"").unwrap();
        assert_eq!(user, Role::User);
        assert_eq!(assistant, Role::Assistant);
    }

    #[test]
    fn test_role_helpers() {
        assert!(Role::User.is_user());
        assert!(!Role::User.is_assistant());
        assert!(Role::Assistant.is_assistant());
        assert!(!Role::Assistant.is_user());
    }

    #[test]
    fn test_content_part_text() {
        let part = ContentPart::text("Hello, world!");
        assert!(part.is_text());
        assert_eq!(part.as_text(), Some("Hello, world!"));
        assert!(!part.is_tool_call());
        assert!(!part.is_tool_result());
    }

    #[test]
    fn test_content_part_tool_call() {
        let part = ContentPart::tool_call(
            "call_1",
            "read_file",
            serde_json::json!({"path": "/tmp/test.txt"}),
        );
        assert!(part.is_tool_call());
        assert!(!part.is_text());

        let call = part.as_tool_call().unwrap();
        assert_eq!(call.name, "read_file");
        assert_eq!(call.id, "call_1");
    }

    #[test]
    fn test_content_part_tool_result() {
        let success = ContentPart::tool_result_success("call_1", "file contents here");
        assert!(success.is_tool_result());
        assert!(success.as_tool_result().unwrap().is_success());

        let failure = ContentPart::tool_result_failure("call_2", "file not found");
        assert!(failure.is_tool_result());
        assert!(!failure.as_tool_result().unwrap().is_success());
    }

    #[test]
    fn test_message_user() {
        let msg = Message::user("Hello, agent!");
        assert!(msg.is_user());
        assert!(!msg.is_assistant());
        assert_eq!(msg.text_content(), "Hello, agent!");
        assert!(!msg.has_tool_calls());
    }

    #[test]
    fn test_message_assistant_text() {
        let msg = Message::assistant_text("I can help with that.");
        assert!(msg.is_assistant());
        assert_eq!(msg.text_content(), "I can help with that.");
    }

    #[test]
    fn test_message_with_tool_calls() {
        let msg = Message::assistant(vec![
            ContentPart::text("Let me read that file."),
            ContentPart::tool_call(
                "call_1",
                "read_file",
                serde_json::json!({"path": "/tmp/test.txt"}),
            ),
        ]);

        assert!(msg.has_tool_calls());
        assert_eq!(msg.tool_calls().len(), 1);
        assert_eq!(msg.tool_calls()[0].name, "read_file");
        assert_eq!(msg.text_content(), "Let me read that file.");
    }

    #[test]
    fn test_message_serialization_roundtrip() {
        let original = Message::user("Test message");
        let json = serde_json::to_string(&original).unwrap();
        let restored: Message = serde_json::from_str(&json).unwrap();

        assert_eq!(original.id, restored.id);
        assert_eq!(original.role, restored.role);
        assert_eq!(original.text_content(), restored.text_content());
        // Note: created_at comparison might have slight precision loss
    }

    #[test]
    fn test_tool_call_serialization() {
        let call = ToolCall::new("call_123", "bash", serde_json::json!({"command": "ls -la"}));
        let json = serde_json::to_string(&call).unwrap();
        let restored: ToolCall = serde_json::from_str(&json).unwrap();

        assert_eq!(call.id, restored.id);
        assert_eq!(call.name, restored.name);
        assert_eq!(call.arguments, restored.arguments);
    }

    #[test]
    fn test_tool_result_success() {
        let result = ToolResult::success("call_1", "output text");
        assert!(result.is_success());
        assert_eq!(result.output, Some("output text".to_string()));
        assert_eq!(result.error, None);
    }

    #[test]
    fn test_tool_result_failure() {
        let result = ToolResult::failure("call_1", "something went wrong");
        assert!(!result.is_success());
        assert_eq!(result.output, None);
        assert_eq!(result.error, Some("something went wrong".to_string()));
    }

    #[test]
    fn test_content_part_serde_tagged() {
        // Verify the serde tag format
        let text = ContentPart::text("hello");
        let json = serde_json::to_string(&text).unwrap();
        assert!(json.contains("\"type\":\"text\""));

        let call = ContentPart::tool_call("id", "name", serde_json::json!({}));
        let json = serde_json::to_string(&call).unwrap();
        assert!(json.contains("\"type\":\"tool_call\""));
    }

    #[test]
    fn test_message_id_generation() {
        let msg1 = Message::user("first");
        let msg2 = Message::user("second");
        // IDs should be unique
        assert_ne!(msg1.id, msg2.id);
        // IDs should have our prefix
        assert!(msg1.id.starts_with("msg_"));
    }
}