cc-agent-sdk 0.1.7

claude agent sdk
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! Todo List management for Claude Agent SDK
//!
//! This module provides functionality for managing todo lists within the SDK,
//! allowing agents and users to track tasks and their completion status.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Todo status
///
/// Represents the completion status of a todo item.
///
/// # Variants
///
/// * `Pending` - Todo item is not yet started
/// * `InProgress` - Todo item is currently being worked on
/// * `Completed` - Todo item has been completed
///
/// # Example
///
/// ```
/// use claude_agent_sdk::todos::TodoStatus;
///
/// let status = TodoStatus::Pending;
/// assert_eq!(status, TodoStatus::Pending);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TodoStatus {
    /// Todo item is not yet started
    Pending,

    /// Todo item is currently being worked on
    InProgress,

    /// Todo item has been completed
    Completed,
}

impl TodoStatus {
    /// Check if the status is a completed state
    ///
    /// # Returns
    ///
    /// `true` if status is `Completed`, `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoStatus;
    /// assert!(!TodoStatus::Pending.is_completed());
    /// assert!(TodoStatus::Completed.is_completed());
    /// ```
    pub fn is_completed(&self) -> bool {
        matches!(self, TodoStatus::Completed)
    }

    /// Check if the status is an active state
    ///
    /// # Returns
    ///
    /// `true` if status is `Pending` or `InProgress`, `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoStatus;
    /// assert!(TodoStatus::Pending.is_active());
    /// assert!(TodoStatus::InProgress.is_active());
    /// assert!(!TodoStatus::Completed.is_active());
    /// ```
    pub fn is_active(&self) -> bool {
        matches!(self, TodoStatus::Pending | TodoStatus::InProgress)
    }
}

/// A todo item in a todo list
///
/// Represents a single task with content and status.
///
/// # Example
///
/// ```
/// use claude_agent_sdk::todos::TodoItem;
/// use std::str::FromStr;
///
/// let item = TodoItem {
///     id: "123".to_string(),
///     content: "Write documentation".to_string(),
///     status: claude_agent_sdk::todos::TodoStatus::Pending,
///     created_at: chrono::Utc::now(),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TodoItem {
    /// Unique identifier for the todo item
    pub id: String,

    /// Content/description of the todo item
    pub content: String,

    /// Current status of the todo item
    pub status: TodoStatus,

    /// Timestamp when the todo item was created
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl TodoItem {
    /// Create a new todo item
    ///
    /// # Arguments
    ///
    /// * `id` - Unique identifier for the todo item
    /// * `content` - Content/description of the todo item
    ///
    /// # Returns
    ///
    /// A new TodoItem with Pending status
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoItem;
    /// let item = TodoItem::new("123", "Write docs");
    /// assert_eq!(item.status, claude_agent_sdk::todos::TodoStatus::Pending);
    /// ```
    pub fn new(id: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            content: content.into(),
            status: TodoStatus::Pending,
            created_at: chrono::Utc::now(),
        }
    }

    /// Mark the todo item as completed
    ///
    /// # Returns
    ///
    /// A modified TodoItem with Completed status
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoItem;
    /// let mut item = TodoItem::new("123", "Write docs");
    /// item.complete();
    /// assert!(item.status.is_completed());
    /// ```
    pub fn complete(&mut self) {
        self.status = TodoStatus::Completed;
    }

    /// Mark the todo item as in progress
    ///
    /// # Returns
    ///
    /// A modified TodoItem with InProgress status
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoItem;
    /// let mut item = TodoItem::new("123", "Write docs");
    /// item.start();
    /// assert_eq!(item.status, claude_agent_sdk::todos::TodoStatus::InProgress);
    /// ```
    pub fn start(&mut self) {
        self.status = TodoStatus::InProgress;
    }

    /// Reset the todo item to pending
    ///
    /// # Returns
    ///
    /// A modified TodoItem with Pending status
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoItem;
    /// let mut item = TodoItem::new("123", "Write docs");
    /// item.complete();
    /// item.reset();
    /// assert_eq!(item.status, claude_agent_sdk::todos::TodoStatus::Pending);
    /// ```
    pub fn reset(&mut self) {
        self.status = TodoStatus::Pending;
    }
}

/// A todo list containing multiple todo items
///
/// # Example
///
/// ```
/// use claude_agent_sdk::todos::TodoList;
///
/// let mut list = TodoList::new("Project Tasks");
/// list.add("Task 1");
/// list.add("Task 2");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TodoList {
    /// Unique identifier for the todo list
    pub id: String,

    /// Name of the todo list
    pub name: String,

    /// Todo items in the list
    pub items: Vec<TodoItem>,
}

impl TodoList {
    /// Create a new todo list
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the todo list
    ///
    /// # Returns
    ///
    /// A new TodoList with a unique ID
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// let list = TodoList::new("My Tasks");
    /// assert!(!list.id.is_empty());
    /// assert_eq!(list.name, "My Tasks");
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            name: name.into(),
            items: Vec::new(),
        }
    }

    /// Add a new todo item to the list
    ///
    /// # Arguments
    ///
    /// * `content` - Content/description for the new todo item
    ///
    /// # Returns
    ///
    /// Reference to the newly added todo item
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// let item = list.add("Write documentation");
    /// assert_eq!(item.content, "Write documentation");
    /// ```
    pub fn add(&mut self, content: impl Into<String>) -> &TodoItem {
        let item = TodoItem::new(uuid::Uuid::new_v4().to_string(), content);
        self.items.push(item);
        self.items.last().unwrap()
    }

    /// Complete a todo item by ID
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the todo item to complete
    ///
    /// # Returns
    ///
    /// Ok(()) if successful, Err(TodoError) if item not found
    ///
    /// # Errors
    ///
    /// Returns `TodoError::NotFound` if the item doesn't exist
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # let id = list.add("Write docs").id.clone();
    /// // Complete the item
    /// # let result = list.complete(&id);
    /// # assert!(result.is_ok());
    /// ```
    pub fn complete(&mut self, id: &str) -> Result<(), TodoError> {
        let item = self
            .items
            .iter_mut()
            .find(|item| item.id == id)
            .ok_or_else(|| TodoError::NotFound(id.to_string()))?;

        item.complete();
        Ok(())
    }

    /// Start a todo item by ID
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the todo item to start
    ///
    /// # Returns
    ///
    /// Ok(()) if successful, Err(TodoError) if item not found
    ///
    /// # Errors
    ///
    /// Returns `TodoError::NotFound` if the item doesn't exist
    pub fn start(&mut self, id: &str) -> Result<(), TodoError> {
        let item = self
            .items
            .iter_mut()
            .find(|item| item.id == id)
            .ok_or_else(|| TodoError::NotFound(id.to_string()))?;

        item.start();
        Ok(())
    }

    /// Reset a todo item to pending by ID
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the todo item to reset
    ///
    /// # Returns
    ///
    /// Ok(()) if successful, Err(TodoError) if item not found
    ///
    /// # Errors
    ///
    /// Returns `TodoError::NotFound` if the item doesn't exist
    pub fn reset(&mut self, id: &str) -> Result<(), TodoError> {
        let item = self
            .items
            .iter_mut()
            .find(|item| item.id == id)
            .ok_or_else(|| TodoError::NotFound(id.to_string()))?;

        item.reset();
        Ok(())
    }

    /// Remove a todo item by ID
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the todo item to remove
    ///
    /// # Returns
    ///
    /// Ok(()) if successful, Err(TodoError) if item not found
    ///
    /// # Errors
    ///
    /// Returns `TodoError::NotFound` if the item doesn't exist
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # let id = list.add("Write docs").id.clone();
    /// // Remove the item
    /// # let result = list.remove(&id);
    /// # assert!(result.is_ok());
    /// # assert_eq!(list.items.len(), 0);
    /// ```
    pub fn remove(&mut self, id: &str) -> Result<(), TodoError> {
        let index = self
            .items
            .iter()
            .position(|item| item.id == id)
            .ok_or_else(|| TodoError::NotFound(id.to_string()))?;

        self.items.remove(index);
        Ok(())
    }

    /// Get a todo item by ID
    ///
    /// # Arguments
    ///
    /// * `id` - ID of the todo item to retrieve
    ///
    /// # Returns
    ///
    /// Some(item) if found, None otherwise
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # let id = list.add("Write docs").id.clone();
    /// let found = list.get(&id);
    /// assert!(found.is_some());
    /// ```
    pub fn get(&self, id: &str) -> Option<&TodoItem> {
        self.items.iter().find(|item| item.id == id)
    }

    /// Get all todo items with a specific status
    ///
    /// # Arguments
    ///
    /// * `status` - Status to filter by
    ///
    /// # Returns
    ///
    /// Vector of todo items with the specified status
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::{TodoList, TodoStatus};
    /// # let mut list = TodoList::new("My Tasks");
    /// # list.add("Task 1");
    /// # list.add("Task 2");
    /// # let pending = list.filter_by_status(TodoStatus::Pending);
    /// # assert_eq!(pending.len(), 2);
    /// ```
    pub fn filter_by_status(&self, status: TodoStatus) -> Vec<&TodoItem> {
        self.items
            .iter()
            .filter(|item| item.status == status)
            .collect()
    }

    /// Get the count of items by status
    ///
    /// # Returns
    ///
    /// HashMap mapping status to count
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # list.add("Task 1");
    /// # list.add("Task 2");
    /// let counts = list.count_by_status();
    /// # assert_eq!(counts.get(&claude_agent_sdk::todos::TodoStatus::Pending).copied(), Some(2));
    /// ```
    pub fn count_by_status(&self) -> HashMap<TodoStatus, usize> {
        let mut counts = HashMap::new();
        for item in &self.items {
            *counts.entry(item.status).or_insert(0) += 1;
        }
        counts
    }

    /// Get the total number of todo items
    ///
    /// # Returns
    ///
    /// Total count of todo items
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # assert_eq!(list.len(), 0);
    /// # list.add("Task 1");
    /// # assert_eq!(list.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Check if the todo list is empty
    ///
    /// # Returns
    ///
    /// `true` if there are no items, `false` otherwise
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # assert!(list.is_empty());
    /// # list.add("Task 1");
    /// # assert!(!list.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Get the number of completed items
    ///
    /// # Returns
    ///
    /// Count of completed todo items
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # let id = list.add("Task 1").id.clone();
    /// # list.complete(&id);
    /// # assert_eq!(list.completed_count(), 1);
    /// ```
    pub fn completed_count(&self) -> usize {
        self.items.iter().filter(|item| item.status.is_completed()).count()
    }

    /// Calculate completion percentage
    ///
    /// # Returns
    ///
    /// Percentage of completed items (0-100), or 0 if empty
    ///
    /// # Example
    ///
    /// ```
    /// # use claude_agent_sdk::todos::TodoList;
    /// # let mut list = TodoList::new("My Tasks");
    /// # let id1 = list.add("Task 1").id.clone();
    /// # let id2 = list.add("Task 2").id.clone();
    /// # list.complete(&id1);
    /// # assert_eq!(list.completion_percentage(), 50.0);
    /// ```
    pub fn completion_percentage(&self) -> f64 {
        if self.is_empty() {
            return 0.0;
        }
        (self.completed_count() as f64 / self.len() as f64) * 100.0
    }
}

/// Errors that can occur in todo operations
///
/// # Variants
///
/// * `NotFound` - Todo item not found
/// * `InvalidInput` - Invalid input provided
///
/// # Example
///
/// ```
/// use claude_agent_sdk::todos::TodoError;
///
/// let error = TodoError::NotFound("123".to_string());
/// assert_eq!(format!("{}", error), "Todo item not found: 123");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TodoError {
    /// Todo item not found
    NotFound(String),

    /// Invalid input provided
    InvalidInput(String),
}

impl std::fmt::Display for TodoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TodoError::NotFound(id) => write!(f, "Todo item not found: {}", id),
            TodoError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
        }
    }
}

impl std::error::Error for TodoError {}

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

    #[test]
    fn test_todo_status() {
        let status = TodoStatus::Pending;
        assert!(!status.is_completed());
        assert!(status.is_active());

        let status = TodoStatus::InProgress;
        assert!(!status.is_completed());
        assert!(status.is_active());

        let status = TodoStatus::Completed;
        assert!(status.is_completed());
        assert!(!status.is_active());
    }

    #[test]
    fn test_todo_item_creation() {
        let item = TodoItem::new("123", "Test task");
        assert_eq!(item.id, "123");
        assert_eq!(item.content, "Test task");
        assert_eq!(item.status, TodoStatus::Pending);
    }

    #[test]
    fn test_todo_item_complete() {
        let mut item = TodoItem::new("123", "Test task");
        item.complete();
        assert!(item.status.is_completed());
    }

    #[test]
    fn test_todo_item_start() {
        let mut item = TodoItem::new("123", "Test task");
        item.start();
        assert_eq!(item.status, TodoStatus::InProgress);
    }

    #[test]
    fn test_todo_item_reset() {
        let mut item = TodoItem::new("123", "Test task");
        item.complete();
        item.reset();
        assert_eq!(item.status, TodoStatus::Pending);
    }

    #[test]
    fn test_todo_list_creation() {
        let list = TodoList::new("My Tasks");
        assert_eq!(list.name, "My Tasks");
        assert!(!list.id.is_empty());
        assert!(list.is_empty());
    }

    #[test]
    fn test_todo_list_add() {
        let mut list = TodoList::new("My Tasks");
        let item = list.add("Task 1");
        assert_eq!(item.content, "Task 1");
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_todo_list_complete() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        let id = list.items[0].id.clone();

        let result = list.complete(&id);
        assert!(result.is_ok());
        assert!(list.items[0].status.is_completed());
    }

    #[test]
    fn test_todo_list_complete_not_found() {
        let mut list = TodoList::new("My Tasks");
        let result = list.complete("nonexistent");
        assert!(matches!(result, Err(TodoError::NotFound(_))));
    }

    #[test]
    fn test_todo_list_remove() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        let id = list.items[0].id.clone();

        let result = list.remove(&id);
        assert!(result.is_ok());
        assert!(list.is_empty());
    }

    #[test]
    fn test_todo_list_get() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        let id = list.items[0].id.clone();

        let item = list.get(&id);
        assert!(item.is_some());
        assert_eq!(item.unwrap().content, "Task 1");

        let not_found = list.get("nonexistent");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_todo_list_filter_by_status() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        list.add("Task 2");
        let id = list.items[0].id.clone();
        list.complete(&id).unwrap();

        let pending = list.filter_by_status(TodoStatus::Pending);
        assert_eq!(pending.len(), 1);

        let completed = list.filter_by_status(TodoStatus::Completed);
        assert_eq!(completed.len(), 1);
    }

    #[test]
    fn test_todo_list_count_by_status() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        list.add("Task 2");
        list.add("Task 3");
        let id = list.items[0].id.clone();
        list.complete(&id).unwrap();

        let counts = list.count_by_status();
        assert_eq!(*counts.get(&TodoStatus::Pending).unwrap_or(&0), 2);
        assert_eq!(*counts.get(&TodoStatus::Completed).unwrap_or(&0), 1);
    }

    #[test]
    fn test_todo_list_completed_count() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        list.add("Task 2");
        assert_eq!(list.completed_count(), 0);

        let id = list.items[0].id.clone();
        list.complete(&id).unwrap();
        assert_eq!(list.completed_count(), 1);
    }

    #[test]
    fn test_todo_list_completion_percentage() {
        let mut list = TodoList::new("My Tasks");
        assert_eq!(list.completion_percentage(), 0.0);

        list.add("Task 1");
        list.add("Task 2");
        let id = list.items[0].id.clone();
        list.complete(&id).unwrap();
        assert_eq!(list.completion_percentage(), 50.0);
    }

    #[test]
    fn test_todo_error_display() {
        let error = TodoError::NotFound("123".to_string());
        assert_eq!(format!("{}", error), "Todo item not found: 123");

        let error = TodoError::InvalidInput("test".to_string());
        assert_eq!(format!("{}", error), "Invalid input: test");
    }

    #[test]
    fn test_todo_list_start() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        let id = list.items[0].id.clone();

        let result = list.start(&id);
        assert!(result.is_ok());
        assert_eq!(list.items[0].status, TodoStatus::InProgress);
    }

    #[test]
    fn test_todo_list_reset() {
        let mut list = TodoList::new("My Tasks");
        list.add("Task 1");
        let id = list.items[0].id.clone();

        list.complete(&id).unwrap();
        assert!(list.items[0].status.is_completed());

        list.reset(&id).unwrap();
        assert_eq!(list.items[0].status, TodoStatus::Pending);
    }
}