1use serde::{Deserialize, Serialize};
28use std::time::SystemTime;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum Role {
45 User,
47 Assistant,
49}
50
51impl Role {
52 pub fn is_user(&self) -> bool {
54 matches!(self, Role::User)
55 }
56
57 pub fn is_assistant(&self) -> bool {
59 matches!(self, Role::Assistant)
60 }
61}
62
63pub type ToolCallId = String;
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct ToolCall {
79 pub id: ToolCallId,
81 pub name: String,
83 pub arguments: serde_json::Value,
85}
86
87impl ToolCall {
88 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct ToolResult {
108 pub call_id: ToolCallId,
110 pub output: Option<String>,
112 pub error: Option<String>,
114}
115
116impl ToolResult {
117 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 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 pub fn is_success(&self) -> bool {
137 self.error.is_none()
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(tag = "type", rename_all = "snake_case")]
159pub enum ContentPart {
160 Text {
162 text: String,
164 },
165 ToolCall(ToolCall),
167 ToolResult(ToolResult),
169}
170
171impl ContentPart {
172 pub fn text(text: impl Into<String>) -> Self {
174 Self::Text { text: text.into() }
175 }
176
177 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 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 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 pub fn is_text(&self) -> bool {
198 matches!(self, ContentPart::Text { .. })
199 }
200
201 pub fn is_tool_call(&self) -> bool {
203 matches!(self, ContentPart::ToolCall(_))
204 }
205
206 pub fn is_tool_result(&self) -> bool {
208 matches!(self, ContentPart::ToolResult(_))
209 }
210
211 pub fn as_text(&self) -> Option<&str> {
213 match self {
214 ContentPart::Text { text } => Some(text),
215 _ => None,
216 }
217 }
218
219 pub fn as_tool_call(&self) -> Option<&ToolCall> {
221 match self {
222 ContentPart::ToolCall(call) => Some(call),
223 _ => None,
224 }
225 }
226
227 pub fn as_tool_result(&self) -> Option<&ToolResult> {
229 match self {
230 ContentPart::ToolResult(result) => Some(result),
231 _ => None,
232 }
233 }
234}
235
236pub type MessageId = String;
242
243#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258pub struct Message {
259 pub id: MessageId,
261 pub role: Role,
263 pub content: Vec<ContentPart>,
265 #[serde(with = "system_time_serde")]
267 pub created_at: SystemTime,
268}
269
270impl Message {
271 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 pub fn user(text: impl Into<String>) -> Self {
283 Self::new(Role::User, vec![ContentPart::text(text)])
284 }
285
286 pub fn assistant(content: Vec<ContentPart>) -> Self {
288 Self::new(Role::Assistant, content)
289 }
290
291 pub fn assistant_text(text: impl Into<String>) -> Self {
293 Self::assistant(vec![ContentPart::text(text)])
294 }
295
296 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 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 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 pub fn has_tool_calls(&self) -> bool {
325 self.content.iter().any(|part| part.is_tool_call())
326 }
327
328 pub fn is_user(&self) -> bool {
330 self.role.is_user()
331 }
332
333 pub fn is_assistant(&self) -> bool {
335 self.role.is_assistant()
336 }
337}
338
339fn 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
359mod 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#[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 }
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 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 assert_ne!(msg1.id, msg2.id);
545 assert!(msg1.id.starts_with("msg_"));
547 }
548}