claude-sdk-rs 1.0.0

Rust SDK for Claude AI with CLI integration - type-safe async API for Claude Code and direct SDK usage
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
//! Real-time dashboard functionality for analytics visualization
//!
//! This module provides comprehensive dashboard capabilities for monitoring
//! Claude AI Interactive usage, costs, and performance in real-time.
//!
//! # Features
//!
//! - **Live Updates**: Real-time data streaming via async channels
//! - **Customizable Widgets**: Modular widget system for flexible layouts
//! - **Time Series Visualization**: Historical data tracking and charting
//! - **System Health Monitoring**: Track system status and resource usage
//! - **Interactive Controls**: Dynamic filtering and time range selection
//!
//! # Architecture
//!
//! The dashboard system follows a pub-sub pattern where:
//! 1. Data sources publish updates to the dashboard manager
//! 2. Dashboard manager aggregates and transforms data
//! 3. Subscribers receive formatted updates for display
//!
//! # Example
//!
//! ```no_run
//! use crate_interactive::analytics::{DashboardManager, DashboardConfig};
//!
//! # async fn example(analytics_engine: std::sync::Arc<AnalyticsEngine>) -> Result<(), Box<dyn std::error::Error>> {
//! // Create dashboard with custom config
//! let config = DashboardConfig {
//!     refresh_interval_seconds: 5,
//!     max_recent_entries: 50,
//!     enable_live_updates: true,
//!     chart_time_range_hours: 24,
//! };
//!
//! let dashboard = DashboardManager::new(analytics_engine, config);
//!
//! // Start live updates
//! dashboard.start_live_updates().await?;
//!
//! // Get current dashboard data
//! let data = dashboard.get_live_data().await?;
//! println!("Today's cost: ${:.2}", data.current_metrics.today_cost);
//! # Ok(())
//! # }
//! ```

use super::{AnalyticsEngine, DashboardData};
use crate::cli::error::Result;
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use sysinfo::{Disks, System};
use tokio::sync::broadcast;

/// Dashboard configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardConfig {
    pub refresh_interval_seconds: u64,
    pub max_recent_entries: usize,
    pub enable_live_updates: bool,
    pub chart_time_range_hours: u32,
    pub enable_real_system_monitoring: bool,
}

impl Default for DashboardConfig {
    fn default() -> Self {
        Self {
            refresh_interval_seconds: 30,
            max_recent_entries: 20,
            enable_live_updates: true,
            chart_time_range_hours: 24,
            enable_real_system_monitoring: true,
        }
    }
}

/// Real-time dashboard data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiveDashboardData {
    pub timestamp: DateTime<Utc>,
    pub current_metrics: DashboardData,
    pub time_series: TimeSeriesData,
    pub system_status: SystemStatus,
}

/// Time series data for charts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeSeriesData {
    pub cost_over_time: Vec<(DateTime<Utc>, f64)>,
    pub commands_over_time: Vec<(DateTime<Utc>, usize)>,
    pub success_rate_over_time: Vec<(DateTime<Utc>, f64)>,
    pub response_time_over_time: Vec<(DateTime<Utc>, f64)>,
}

/// System health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStatus {
    pub health: HealthStatus,
    pub uptime_hours: f64,
    pub active_sessions: usize,
    pub memory_usage_mb: f64,
    pub disk_usage_percent: f64,
    pub last_error: Option<DateTime<Utc>>,
}

/// Health status levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum HealthStatus {
    Healthy,
    Warning,
    Critical,
    Unknown,
}

/// Dashboard widget configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetConfig {
    pub widget_type: WidgetType,
    pub title: String,
    pub position: (u32, u32), // (row, column)
    pub size: (u32, u32),     // (width, height)
    pub refresh_interval: Option<u64>,
    pub settings: HashMap<String, serde_json::Value>,
}

/// Available widget types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WidgetType {
    CostSummary,
    CommandActivity,
    SuccessRate,
    ResponseTime,
    TopCommands,
    RecentAlerts,
    SessionList,
    ErrorLog,
    CustomChart,
}

/// Dashboard layout configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardLayout {
    pub name: String,
    pub widgets: Vec<WidgetConfig>,
    pub created_at: DateTime<Utc>,
    pub last_modified: DateTime<Utc>,
}

/// Live dashboard manager
pub struct DashboardManager {
    analytics_engine: AnalyticsEngine,
    config: DashboardConfig,
    layouts: HashMap<String, DashboardLayout>,
    update_sender: broadcast::Sender<LiveDashboardData>,
    _update_receiver: broadcast::Receiver<LiveDashboardData>,
    cache: Option<Arc<super::dashboard_cache::DashboardCache>>,
}

impl DashboardManager {
    /// Create a new dashboard manager
    pub fn new(analytics_engine: AnalyticsEngine, config: DashboardConfig) -> Self {
        let (update_sender, update_receiver) = broadcast::channel(100);

        Self {
            analytics_engine,
            config,
            layouts: HashMap::new(),
            update_sender,
            _update_receiver: update_receiver,
            cache: None,
        }
    }

    /// Create a new dashboard manager with caching enabled
    pub fn with_cache(
        analytics_engine: AnalyticsEngine,
        config: DashboardConfig,
        cache_config: super::dashboard_cache::CacheConfig,
    ) -> Self {
        let (update_sender, update_receiver) = broadcast::channel(100);
        let cache = Arc::new(super::dashboard_cache::DashboardCache::new(cache_config));

        Self {
            analytics_engine,
            config,
            layouts: HashMap::new(),
            update_sender,
            _update_receiver: update_receiver,
            cache: Some(cache),
        }
    }

    /// Start the dashboard update loop
    pub async fn start_update_loop(&self) -> Result<()> {
        let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(
            self.config.refresh_interval_seconds,
        ));

        loop {
            interval.tick().await;

            if let Ok(dashboard_data) = self.generate_live_data().await {
                // Send update to subscribers
                let _ = self.update_sender.send(dashboard_data);
            }
        }
    }

    /// Generate live dashboard data
    pub async fn generate_live_data(&self) -> Result<LiveDashboardData> {
        use super::dashboard_cache::CacheKey;

        // Check cache first if caching is enabled
        if let Some(cache) = &self.cache {
            let cache_key = CacheKey::live_dashboard_data();
            if let Some(cached_data) = cache.get_live_dashboard_data(&cache_key).await {
                return Ok(cached_data);
            }
        }

        // Generate fresh data
        let current_metrics = self.analytics_engine.get_dashboard_data().await?;
        let time_series = self.generate_time_series().await?;
        let system_status = self.get_system_status().await?;

        let live_data = LiveDashboardData {
            timestamp: Utc::now(),
            current_metrics,
            time_series,
            system_status,
        };

        // Cache the result if caching is enabled
        if let Some(cache) = &self.cache {
            let cache_key = CacheKey::live_dashboard_data();
            cache
                .set_live_dashboard_data(cache_key, live_data.clone(), Some(30))
                .await; // 30 second TTL
        }

        Ok(live_data)
    }

    /// Subscribe to live dashboard updates
    pub fn subscribe_to_updates(&self) -> broadcast::Receiver<LiveDashboardData> {
        self.update_sender.subscribe()
    }

    /// Create a custom dashboard layout
    pub fn create_layout(&mut self, name: String, widgets: Vec<WidgetConfig>) -> Result<()> {
        let layout = DashboardLayout {
            name: name.clone(),
            widgets,
            created_at: Utc::now(),
            last_modified: Utc::now(),
        };

        self.layouts.insert(name, layout);
        Ok(())
    }

    /// Get available dashboard layouts
    pub fn get_layouts(&self) -> Vec<&DashboardLayout> {
        self.layouts.values().collect()
    }

    /// Generate default dashboard layout
    pub fn create_default_layout(&mut self) -> Result<()> {
        let widgets = vec![
            WidgetConfig {
                widget_type: WidgetType::CostSummary,
                title: "Cost Overview".to_string(),
                position: (0, 0),
                size: (2, 1),
                refresh_interval: None,
                settings: HashMap::new(),
            },
            WidgetConfig {
                widget_type: WidgetType::CommandActivity,
                title: "Command Activity".to_string(),
                position: (0, 2),
                size: (2, 1),
                refresh_interval: None,
                settings: HashMap::new(),
            },
            WidgetConfig {
                widget_type: WidgetType::SuccessRate,
                title: "Success Rate".to_string(),
                position: (1, 0),
                size: (1, 1),
                refresh_interval: None,
                settings: HashMap::new(),
            },
            WidgetConfig {
                widget_type: WidgetType::ResponseTime,
                title: "Response Time".to_string(),
                position: (1, 1),
                size: (1, 1),
                refresh_interval: None,
                settings: HashMap::new(),
            },
            WidgetConfig {
                widget_type: WidgetType::TopCommands,
                title: "Top Commands".to_string(),
                position: (2, 0),
                size: (2, 1),
                refresh_interval: None,
                settings: HashMap::new(),
            },
            WidgetConfig {
                widget_type: WidgetType::RecentAlerts,
                title: "Recent Alerts".to_string(),
                position: (2, 2),
                size: (2, 1),
                refresh_interval: None,
                settings: HashMap::new(),
            },
        ];

        self.create_layout("default".to_string(), widgets)
    }

    /// Export dashboard data for external visualization
    pub async fn export_dashboard_data(&self, format: DashboardExportFormat) -> Result<String> {
        let data = self.generate_live_data().await?;

        match format {
            DashboardExportFormat::Json => Ok(serde_json::to_string_pretty(&data)?),
            DashboardExportFormat::Prometheus => self.export_prometheus_metrics(&data).await,
            DashboardExportFormat::InfluxDB => self.export_influxdb_line_protocol(&data).await,
        }
    }

    /// Generate chart data for specific metrics
    pub async fn generate_chart_data(
        &self,
        metric: ChartMetric,
        hours: u32,
    ) -> Result<Vec<(DateTime<Utc>, f64)>> {
        let start_time = Utc::now() - Duration::hours(hours as i64);
        let end_time = Utc::now();

        match metric {
            ChartMetric::CostOverTime => {
                self.generate_cost_time_series(start_time, end_time, hours)
                    .await
            }
            ChartMetric::CommandsOverTime => {
                self.generate_commands_time_series(start_time, end_time, hours)
                    .await
            }
            ChartMetric::SuccessRate => {
                self.generate_success_rate_time_series(start_time, end_time, hours)
                    .await
            }
            ChartMetric::ResponseTime => {
                self.generate_response_time_time_series(start_time, end_time, hours)
                    .await
            }
        }
    }

    // Private helper methods

    async fn generate_time_series(&self) -> Result<TimeSeriesData> {
        let hours = self.config.chart_time_range_hours;
        let start_time = Utc::now() - Duration::hours(hours as i64);
        let end_time = Utc::now();

        // Use optimized time series generation
        use super::time_series_optimizer::{TimeSeriesOptimizer, TimeSeriesType};

        let optimizer = TimeSeriesOptimizer::new(self.analytics_engine.clone());
        let types = vec![
            TimeSeriesType::Cost,
            TimeSeriesType::Commands,
            TimeSeriesType::SuccessRate,
            TimeSeriesType::ResponseTime,
        ];

        let optimized_data = optimizer
            .generate_optimized_time_series(start_time, end_time, types)
            .await?;

        // Convert to legacy format for compatibility
        Ok(TimeSeriesOptimizer::to_legacy_format(&optimized_data))
    }

    async fn get_system_status(&self) -> Result<SystemStatus> {
        // Get actual system information where possible
        let mut health = HealthStatus::Healthy;
        let mut last_error = None;

        // Check for recent errors in the last hour
        let one_hour_ago = Utc::now() - Duration::hours(1);
        let recent_search = crate::cli::history::HistorySearch {
            since: Some(one_hour_ago),
            until: Some(Utc::now()),
            ..Default::default()
        };

        let recent_entries = self
            .analytics_engine
            .history_store
            .read()
            .await
            .search(&recent_search)
            .await?;

        let error_count = recent_entries.iter().filter(|e| !e.success).count();
        let total_count = recent_entries.len();

        // Determine health based on error rate
        if total_count > 0 {
            let error_rate = (error_count as f64 / total_count as f64) * 100.0;
            health = match error_rate {
                r if r > 50.0 => HealthStatus::Critical,
                r if r > 25.0 => HealthStatus::Warning,
                _ => HealthStatus::Healthy,
            };

            // Set last error if there were any
            if error_count > 0 {
                last_error = recent_entries
                    .iter()
                    .filter(|e| !e.success)
                    .map(|e| e.timestamp)
                    .max();
            }
        }

        // Get real system metrics if enabled, otherwise use "no data available" state
        let (memory_usage_mb, uptime_hours, disk_usage_percent) =
            if self.config.enable_real_system_monitoring {
                self.get_real_system_metrics().await
            } else {
                // Return clear "no data available" indicators
                (f64::NAN, f64::NAN, f64::NAN)
            };

        // Count active sessions (unique sessions in recent data)
        let active_sessions = recent_entries
            .iter()
            .map(|e| e.session_id)
            .collect::<std::collections::HashSet<_>>()
            .len();

        Ok(SystemStatus {
            health,
            uptime_hours,
            active_sessions,
            memory_usage_mb,
            disk_usage_percent,
            last_error,
        })
    }

    /// Get real system metrics using sysinfo crate
    async fn get_real_system_metrics(&self) -> (f64, f64, f64) {
        // Use tokio::task::spawn_blocking to handle potentially blocking sysinfo calls
        tokio::task::spawn_blocking(|| {
            let mut system = System::new_all();
            system.refresh_all();

            // Get memory usage in MB
            let used_memory = system.used_memory() as f64 / 1024.0 / 1024.0; // Convert bytes to MB

            // Get system uptime in hours
            let uptime_seconds = System::uptime();
            let uptime_hours = uptime_seconds as f64 / 3600.0;

            // Get disk usage percentage for the root disk
            let disks = Disks::new_with_refreshed_list();
            let disk_usage_percent = disks
                .first()
                .map(|disk| {
                    let total = disk.total_space();
                    let available = disk.available_space();
                    if total > 0 {
                        ((total - available) as f64 / total as f64) * 100.0
                    } else {
                        0.0
                    }
                })
                .unwrap_or(0.0);

            (used_memory, uptime_hours, disk_usage_percent)
        })
        .await
        .unwrap_or((f64::NAN, f64::NAN, f64::NAN)) // Fallback on error
    }

    async fn export_prometheus_metrics(&self, data: &LiveDashboardData) -> Result<String> {
        let mut metrics = String::new();

        metrics.push_str(&format!(
            "claude_interactive_cost_total {:.2}\n",
            data.current_metrics.today_cost
        ));

        metrics.push_str(&format!(
            "claude_interactive_commands_total {}\n",
            data.current_metrics.today_commands
        ));

        metrics.push_str(&format!(
            "claude_interactive_success_rate {:.2}\n",
            data.current_metrics.success_rate
        ));

        metrics.push_str(&format!(
            "claude_interactive_active_sessions {}\n",
            data.system_status.active_sessions
        ));

        metrics.push_str(&format!(
            "claude_interactive_memory_usage_mb {:.2}\n",
            data.system_status.memory_usage_mb
        ));

        Ok(metrics)
    }

    async fn export_influxdb_line_protocol(&self, data: &LiveDashboardData) -> Result<String> {
        let timestamp = data.timestamp.timestamp_nanos_opt().unwrap_or(0);
        let mut lines = String::new();

        lines.push_str(&format!(
            "claude_interactive,metric=cost value={:.2} {}\n",
            data.current_metrics.today_cost, timestamp
        ));

        lines.push_str(&format!(
            "claude_interactive,metric=commands value={} {}\n",
            data.current_metrics.today_commands, timestamp
        ));

        lines.push_str(&format!(
            "claude_interactive,metric=success_rate value={:.2} {}\n",
            data.current_metrics.success_rate, timestamp
        ));

        Ok(lines)
    }

    /// Generate cost time series data
    async fn generate_cost_time_series(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
        _hours: u32,
    ) -> Result<Vec<(DateTime<Utc>, f64)>> {
        use crate::cli::cost::CostFilter;

        let mut data = Vec::new();
        let interval = Duration::hours(1);
        let mut current_time = start_time;

        while current_time < end_time {
            let next_time = current_time + interval;

            // Query cost data for this hour
            let filter = CostFilter {
                since: Some(current_time),
                until: Some(next_time),
                ..Default::default()
            };

            let cost_summary = self
                .analytics_engine
                .cost_tracker
                .read()
                .await
                .get_filtered_summary(&filter)
                .await?;

            data.push((current_time, cost_summary.total_cost));
            current_time = next_time;
        }

        Ok(data)
    }

    /// Generate commands count time series data
    async fn generate_commands_time_series(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
        _hours: u32,
    ) -> Result<Vec<(DateTime<Utc>, f64)>> {
        use crate::cli::history::HistorySearch;

        let mut data = Vec::new();
        let interval = Duration::hours(1);
        let mut current_time = start_time;

        while current_time < end_time {
            let next_time = current_time + interval;

            // Query history data for this hour
            let search = HistorySearch {
                since: Some(current_time),
                until: Some(next_time),
                ..Default::default()
            };

            let entries = self
                .analytics_engine
                .history_store
                .read()
                .await
                .search(&search)
                .await?;

            data.push((current_time, entries.len() as f64));
            current_time = next_time;
        }

        Ok(data)
    }

    /// Generate success rate time series data
    async fn generate_success_rate_time_series(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
        _hours: u32,
    ) -> Result<Vec<(DateTime<Utc>, f64)>> {
        use crate::cli::history::HistorySearch;

        let mut data = Vec::new();
        let interval = Duration::hours(1);
        let mut current_time = start_time;

        while current_time < end_time {
            let next_time = current_time + interval;

            // Query history data for this hour
            let search = HistorySearch {
                since: Some(current_time),
                until: Some(next_time),
                ..Default::default()
            };

            let entries = self
                .analytics_engine
                .history_store
                .read()
                .await
                .search(&search)
                .await?;

            let success_rate = if entries.is_empty() {
                f64::NAN // No data available - return NaN instead of misleading 100%
            } else {
                let successful = entries.iter().filter(|e| e.success).count();
                (successful as f64 / entries.len() as f64) * 100.0
            };

            data.push((current_time, success_rate));
            current_time = next_time;
        }

        Ok(data)
    }

    /// Generate response time time series data
    async fn generate_response_time_time_series(
        &self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
        _hours: u32,
    ) -> Result<Vec<(DateTime<Utc>, f64)>> {
        use crate::cli::history::HistorySearch;

        let mut data = Vec::new();
        let interval = Duration::hours(1);
        let mut current_time = start_time;

        while current_time < end_time {
            let next_time = current_time + interval;

            // Query history data for this hour
            let search = HistorySearch {
                since: Some(current_time),
                until: Some(next_time),
                ..Default::default()
            };

            let entries = self
                .analytics_engine
                .history_store
                .read()
                .await
                .search(&search)
                .await?;

            let avg_response_time = if entries.is_empty() {
                f64::NAN // No data available - return NaN instead of misleading default
            } else {
                let total_duration: u64 = entries.iter().map(|e| e.duration_ms).sum();
                total_duration as f64 / entries.len() as f64
            };

            data.push((current_time, avg_response_time));
            current_time = next_time;
        }

        Ok(data)
    }
}

/// Chart metric types
#[derive(Debug, Clone)]
pub enum ChartMetric {
    CostOverTime,
    CommandsOverTime,
    SuccessRate,
    ResponseTime,
}

/// Dashboard export formats
#[derive(Debug, Clone)]
pub enum DashboardExportFormat {
    Json,
    Prometheus,
    InfluxDB,
}