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
//! # Performance Optimization for Agent Skills
//!
//! This module provides performance optimizations for large-scale skill operations,
//! including indexing, caching, and batch processing.

use crate::skills::tags::TagFilter;
use crate::skills::types::SkillPackage;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::time::{Duration, Instant};
use tracing::debug;

/// Performance statistics for operations
#[derive(Debug, Clone, Default)]
pub struct PerformanceStats {
    /// Number of operations performed
    pub operations: usize,

    /// Total time spent
    pub total_duration: Duration,

    /// Cache hits
    pub cache_hits: usize,

    /// Cache misses
    pub cache_misses: usize,

    /// Items processed
    pub items_processed: usize,
}

impl PerformanceStats {
    /// Create new statistics
    pub fn new() -> Self {
        Self::default()
    }

    /// Calculate average time per operation
    pub fn avg_time_per_operation(&self) -> Option<Duration> {
        if self.operations > 0 {
            Some(self.total_duration / self.operations as u32)
        } else {
            None
        }
    }

    /// Calculate cache hit rate
    pub fn cache_hit_rate(&self) -> f64 {
        let total = self.cache_hits + self.cache_misses;
        if total > 0 {
            self.cache_hits as f64 / total as f64
        } else {
            0.0
        }
    }

    /// Calculate throughput (items per second)
    pub fn throughput(&self) -> f64 {
        let seconds = self.total_duration.as_secs_f64();
        if seconds > 0.0 {
            self.items_processed as f64 / seconds
        } else {
            0.0
        }
    }
}

/// Simple LRU cache implementation
#[derive(Debug, Clone)]
pub struct LruCache<K, V>
where
    K: Hash + Eq + Clone,
    V: Clone,
{
    capacity: usize,
    map: HashMap<K, V>,
    access_order: Vec<K>,
}

impl<K, V> LruCache<K, V>
where
    K: Hash + Eq + Clone,
    V: Clone,
{
    /// Create a new LRU cache with the given capacity
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity,
            map: HashMap::new(),
            access_order: Vec::with_capacity(capacity),
        }
    }

    /// Get a value from the cache
    pub fn get(&mut self, key: &K) -> Option<&V> {
        if self.map.contains_key(key) {
            // Move to end (most recently used)
            if let Some(pos) = self.access_order.iter().position(|k| k == key) {
                self.access_order.remove(pos);
                self.access_order.push(key.clone());
            }
            self.map.get(key)
        } else {
            None
        }
    }

    /// Insert a value into the cache
    pub fn put(&mut self, key: K, value: V) {
        // Remove existing if present
        if self.map.contains_key(&key) {
            if let Some(pos) = self.access_order.iter().position(|k| k == &key) {
                self.access_order.remove(pos);
            }
        }

        // Evict oldest if at capacity
        if self.access_order.len() >= self.capacity {
            if let Some(old_key) = self.access_order.first() {
                self.map.remove(old_key);
                self.access_order.remove(0);
            }
        }

        // Insert new
        self.map.insert(key.clone(), value);
        self.access_order.push(key);
    }

    /// Check if cache contains a key
    pub fn contains_key(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }

    /// Clear the cache
    pub fn clear(&mut self) {
        self.map.clear();
        self.access_order.clear();
    }

    /// Get current size
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Check if cache is empty
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }
}

/// Multi-indexed skill collection for fast queries
#[derive(Debug, Clone)]
pub struct IndexedSkillCollection {
    /// All skills
    skills: Vec<SkillPackage>,

    /// Index by name
    by_name: HashMap<String, usize>,

    /// Index by tags (tag -> skill indices)
    by_tag: HashMap<String, Vec<usize>>,

    /// Cache for query results
    query_cache: LruCache<String, Vec<usize>>,
}

impl Default for IndexedSkillCollection {
    fn default() -> Self {
        Self::new()
    }
}

impl IndexedSkillCollection {
    /// Create a new indexed collection
    pub fn new() -> Self {
        Self {
            skills: Vec::new(),
            by_name: HashMap::new(),
            by_tag: HashMap::new(),
            query_cache: LruCache::new(100),
        }
    }

    /// Create with capacity hint
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            skills: Vec::with_capacity(capacity),
            by_name: HashMap::with_capacity(capacity),
            by_tag: HashMap::new(),
            query_cache: LruCache::new(100),
        }
    }

    /// Add a skill to the collection
    pub fn add(&mut self, skill: SkillPackage) {
        let index = self.skills.len();

        // Index by name
        self.by_name.insert(skill.metadata.name.clone(), index);

        // Index by tags
        for tag in &skill.metadata.tags {
            self.by_tag
                .entry(tag.clone())
                .or_default()
                .push(index);
        }

        self.skills.push(skill);
    }

    /// Add multiple skills in batch
    pub fn add_batch(&mut self, skills: Vec<SkillPackage>) {
        let start = Instant::now();
        let initial_count = self.skills.len();

        for skill in skills {
            self.add(skill);
        }

        let added = self.skills.len() - initial_count;
        debug!("Added {} skills in {:?}", added, start.elapsed());
    }

    /// Get a skill by name (O(1))
    pub fn get_by_name(&self, name: &str) -> Option<&SkillPackage> {
        self.by_name.get(name).map(|&index| &self.skills[index])
    }

    /// Get all skills with a specific tag (O(1) average)
    pub fn get_by_tag(&self, tag: &str) -> Vec<&SkillPackage> {
        self.by_tag
            .get(tag)
            .map(|indices| indices.iter().map(|&i| &self.skills[i]).collect())
            .unwrap_or_default()
    }

    /// Query skills using a tag filter with caching
    pub fn query(&mut self, filter: &TagFilter) -> Vec<&SkillPackage> {
        let cache_key = format!("{:?}", filter);

        // Check cache
        if let Some(indices) = self.query_cache.get(&cache_key) {
            debug!("Cache hit for query: {}", cache_key);
            return indices.iter().map(|&i| &self.skills[i]).collect();
        }

        // Perform query and collect indices first
        let indices: Vec<usize> = self
            .skills
            .iter()
            .enumerate()
            .filter(|(_, skill)| {
                let tags: HashSet<String> = skill.metadata.tags.iter().cloned().collect();
                filter.matches(&tags)
            })
            .map(|(i, _)| i)
            .collect();

        // Cache the indices
        self.query_cache.put(cache_key, indices.clone());

        // Return references using indices
        indices.iter().map(|&i| &self.skills[i]).collect()
    }

    /// Get all skills
    pub fn all(&self) -> Vec<&SkillPackage> {
        self.skills.iter().collect()
    }

    /// Count of skills
    pub fn len(&self) -> usize {
        self.skills.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.skills.is_empty()
    }

    /// Clear the collection
    pub fn clear(&mut self) {
        self.skills.clear();
        self.by_name.clear();
        self.by_tag.clear();
        self.query_cache.clear();
    }

    /// Rebuild all indexes
    pub fn rebuild_indexes(&mut self) {
        let skills = std::mem::take(&mut self.skills);
        self.clear();
        self.add_batch(skills);
    }
}

/// Batch operations for efficient processing
pub struct BatchOperations;

impl BatchOperations {
    /// Batch filter skills
    pub fn filter_skills(
        skills: &[SkillPackage],
        predicate: impl Fn(&SkillPackage) -> bool,
    ) -> Vec<SkillPackage> {
        skills.iter().filter(|s| predicate(s)).cloned().collect()
    }

    /// Batch map skills
    pub fn map_skills(
        skills: Vec<SkillPackage>,
        mapper: impl Fn(SkillPackage) -> SkillPackage,
    ) -> Vec<SkillPackage> {
        skills.into_iter().map(mapper).collect()
    }

    /// Batch filter and map
    pub fn filter_map_skills(
        skills: Vec<SkillPackage>,
        predicate: impl Fn(&SkillPackage) -> bool,
        mapper: impl Fn(SkillPackage) -> SkillPackage,
    ) -> Vec<SkillPackage> {
        skills
            .into_iter()
            .filter(|s| predicate(s))
            .map(mapper)
            .collect()
    }

    /// Partition skills into two groups
    pub fn partition_skills(
        skills: Vec<SkillPackage>,
        predicate: impl Fn(&SkillPackage) -> bool,
    ) -> (Vec<SkillPackage>, Vec<SkillPackage>) {
        skills.into_iter().partition(predicate)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::skills::types::SkillMetadata;

    fn create_test_skill(name: &str, tags: Vec<&str>) -> SkillPackage {
        SkillPackage {
            metadata: SkillMetadata {
                id: uuid::Uuid::new_v4().to_string(),
                name: name.to_string(),
                description: String::new(),
                version: "1.0.0".to_string(),
                author: None,
                dependencies: Vec::new(),
                tags: tags.into_iter().map(String::from).collect(),
            },
            instructions: String::new(),
            scripts: Vec::new(),
            resources: Default::default(),
        }
    }

    #[test]
    fn test_performance_stats_default() {
        let stats = PerformanceStats::new();
        assert_eq!(stats.operations, 0);
        assert_eq!(stats.cache_hits, 0);
        assert_eq!(stats.cache_misses, 0);
    }

    #[test]
    fn test_performance_stats_avg_time() {
        let mut stats = PerformanceStats::new();
        stats.operations = 10;
        stats.total_duration = Duration::from_secs(1);

        let avg = stats.avg_time_per_operation();
        assert_eq!(avg, Some(Duration::from_millis(100)));
    }

    #[test]
    fn test_performance_stats_cache_hit_rate() {
        let mut stats = PerformanceStats::new();
        stats.cache_hits = 80;
        stats.cache_misses = 20;

        let rate = stats.cache_hit_rate();
        assert!((rate - 0.8).abs() < 0.01);
    }

    #[test]
    fn test_performance_stats_throughput() {
        let mut stats = PerformanceStats::new();
        stats.items_processed = 1000;
        stats.total_duration = Duration::from_secs(2);

        let throughput = stats.throughput();
        assert!((throughput - 500.0).abs() < 1.0);
    }

    #[test]
    fn test_lru_cache_basic() {
        let mut cache = LruCache::new(2);

        cache.put("key1", "value1");
        cache.put("key2", "value2");

        assert_eq!(cache.get(&"key1"), Some(&"value1"));
        assert_eq!(cache.get(&"key2"), Some(&"value2"));
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_lru_cache_eviction() {
        let mut cache = LruCache::new(2);

        cache.put("key1", "value1");
        cache.put("key2", "value2");
        cache.put("key3", "value3"); // Should evict key1

        assert_eq!(cache.get(&"key1"), None);
        assert_eq!(cache.get(&"key2"), Some(&"value2"));
        assert_eq!(cache.get(&"key3"), Some(&"value3"));
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_lru_cache_access_order() {
        let mut cache = LruCache::new(2);

        cache.put("key1", "value1");
        cache.put("key2", "value2");
        cache.get(&"key1"); // Access key1
        cache.put("key3", "value3"); // Should evict key2

        assert_eq!(cache.get(&"key1"), Some(&"value1"));
        assert_eq!(cache.get(&"key2"), None);
        assert_eq!(cache.get(&"key3"), Some(&"value3"));
    }

    #[test]
    fn test_indexed_collection_add() {
        let mut collection = IndexedSkillCollection::new();
        let skill = create_test_skill("skill1", vec!["tag1", "tag2"]);

        collection.add(skill);

        assert_eq!(collection.len(), 1);
        assert!(collection.get_by_name("skill1").is_some());
    }

    #[test]
    fn test_indexed_collection_by_name() {
        let mut collection = IndexedSkillCollection::new();
        collection.add(create_test_skill("skill1", vec!["tag1"]));
        collection.add(create_test_skill("skill2", vec!["tag2"]));

        assert_eq!(
            collection.get_by_name("skill1").unwrap().metadata.name,
            "skill1"
        );
        assert_eq!(
            collection.get_by_name("skill2").unwrap().metadata.name,
            "skill2"
        );
        assert!(collection.get_by_name("skill3").is_none());
    }

    #[test]
    fn test_indexed_collection_by_tag() {
        let mut collection = IndexedSkillCollection::new();
        collection.add(create_test_skill("skill1", vec!["rust", "web"]));
        collection.add(create_test_skill("skill2", vec!["rust", "cli"]));
        collection.add(create_test_skill("skill3", vec!["python", "web"]));

        let rust_skills = collection.get_by_tag("rust");
        assert_eq!(rust_skills.len(), 2);

        let web_skills = collection.get_by_tag("web");
        assert_eq!(web_skills.len(), 2);

        let python_skills = collection.get_by_tag("python");
        assert_eq!(python_skills.len(), 1);
    }

    #[test]
    fn test_indexed_collection_query() {
        let mut collection = IndexedSkillCollection::new();
        collection.add(create_test_skill("skill1", vec!["rust", "web"]));
        collection.add(create_test_skill("skill2", vec!["rust", "cli"]));
        collection.add(create_test_skill("skill3", vec!["python", "web"]));

        let filter = TagFilter::new().has("rust");
        let results = collection.query(&filter);

        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_indexed_collection_query_cache() {
        let mut collection = IndexedSkillCollection::new();
        collection.add(create_test_skill("skill1", vec!["rust"]));
        collection.add(create_test_skill("skill2", vec!["python"]));

        let filter = TagFilter::new().has("rust");

        // First query - cache miss
        let results1 = collection.query(&filter);
        assert_eq!(results1.len(), 1);

        // Second query - cache hit
        let results2 = collection.query(&filter);
        assert_eq!(results2.len(), 1);
    }

    #[test]
    fn test_indexed_collection_batch_add() {
        let mut collection = IndexedSkillCollection::new();
        let skills = vec![
            create_test_skill("skill1", vec!["tag1"]),
            create_test_skill("skill2", vec!["tag2"]),
            create_test_skill("skill3", vec!["tag3"]),
        ];

        collection.add_batch(skills);

        assert_eq!(collection.len(), 3);
    }

    #[test]
    fn test_batch_operations_filter() {
        let skills = vec![
            create_test_skill("skill1", vec!["rust"]),
            create_test_skill("skill2", vec!["python"]),
            create_test_skill("skill3", vec!["rust"]),
        ];

        let filtered = BatchOperations::filter_skills(&skills, |s| {
            s.metadata.tags.contains(&"rust".to_string())
        });

        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_batch_operations_partition() {
        let skills = vec![
            create_test_skill("skill1", vec!["rust"]),
            create_test_skill("skill2", vec!["python"]),
            create_test_skill("skill3", vec!["go"]),
        ];

        let (rust_skills, other_skills) = BatchOperations::partition_skills(skills, |s| {
            s.metadata.tags.contains(&"rust".to_string())
        });

        assert_eq!(rust_skills.len(), 1);
        assert_eq!(other_skills.len(), 2);
    }

    #[test]
    fn test_indexed_collection_rebuild() {
        let mut collection = IndexedSkillCollection::new();
        collection.add(create_test_skill("skill1", vec!["tag1"]));
        collection.add(create_test_skill("skill2", vec!["tag2"]));

        assert_eq!(collection.by_tag.len(), 2);

        collection.rebuild_indexes();

        assert_eq!(collection.len(), 2);
        assert!(collection.get_by_name("skill1").is_some());
        assert!(collection.get_by_name("skill2").is_some());
    }
}