ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//! AI Data API - Full System Visibility for AI Agents
//!
//! This module provides a comprehensive API that gives AI systems full visibility
//! into hardware monitoring data. It exposes "tools" that AI agents can call to
//! query specific aspects of the system.
//!
//! # Architecture
//!
//! The API is organized around "tools" that mirror how AI agents think:
//! - Each tool has a name, description, and parameters
//! - Tools return structured JSON-serializable data
//! - The system maintains state to calculate rates and deltas
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::ai_api::{AiDataApi, ToolCall, ToolResult};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut api = AiDataApi::new()?;
//!
//! // List available tools
//! let tools = api.list_tools();
//! for tool in &tools {
//!     println!("{}: {}", tool.name, tool.description);
//! }
//!
//! // Call a tool
//! let result = api.call_tool("get_gpu_status", serde_json::json!({}))?;
//! println!("{}", serde_json::to_string_pretty(&result)?);
//! # Ok(())
//! # }
//! ```

mod diagnostic_tools;
mod endpoint_tools;
pub mod formats;
pub mod mcp_server;
pub(crate) mod observation_tools;
pub mod ontology;
pub mod tools;
pub mod types;

use crate::error::{IronError, Result};
use crate::gpu::GpuCollection;
use crate::NetworkMonitor;
use crate::ProcessMonitor;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;

pub use formats::*;
pub use mcp_server::{McpServer, MCP_PROTOCOL_VERSION};
pub use ontology::*;
pub use tools::*;
pub use types::*;

/// Tool definition for AI systems
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// Tool name (identifier)
    pub name: String,
    /// Human-readable description
    pub description: String,
    /// Parameter schema (JSON Schema format)
    pub parameters: serde_json::Value,
    /// Category for organization
    pub category: ToolCategory,
    /// Example usage
    pub example: Option<String>,
}

/// Tool categories
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ToolCategory {
    /// GPU monitoring tools
    Gpu,
    /// CPU monitoring tools
    Cpu,
    /// Memory monitoring tools
    Memory,
    /// Disk monitoring tools
    Disk,
    /// Network monitoring tools
    Network,
    /// Process monitoring tools
    Process,
    /// System-wide tools
    System,
    /// Motherboard/hardware tools
    Hardware,
    /// Audio device tools
    Audio,
    /// Bluetooth device tools
    Bluetooth,
    /// Display/monitor tools
    Display,
    /// USB device tools
    Usb,
}

impl std::fmt::Display for ToolCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ToolCategory::Gpu => write!(f, "GPU"),
            ToolCategory::Cpu => write!(f, "CPU"),
            ToolCategory::Memory => write!(f, "Memory"),
            ToolCategory::Disk => write!(f, "Disk"),
            ToolCategory::Network => write!(f, "Network"),
            ToolCategory::Process => write!(f, "Process"),
            ToolCategory::System => write!(f, "System"),
            ToolCategory::Hardware => write!(f, "Hardware"),
            ToolCategory::Audio => write!(f, "Audio"),
            ToolCategory::Bluetooth => write!(f, "Bluetooth"),
            ToolCategory::Display => write!(f, "Display"),
            ToolCategory::Usb => write!(f, "USB"),
        }
    }
}

/// Result from a tool call
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// Whether the call succeeded
    pub success: bool,
    /// Result data (if successful)
    pub data: Option<serde_json::Value>,
    /// Error message (if failed)
    pub error: Option<String>,
    /// Execution time in milliseconds
    pub execution_time_ms: u64,
    /// Tool that was called
    pub tool_name: String,
}

impl ToolResult {
    /// Create a successful result
    pub fn success(tool_name: &str, data: serde_json::Value, exec_time_ms: u64) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            execution_time_ms: exec_time_ms,
            tool_name: tool_name.to_string(),
        }
    }

    /// Create a failed result
    pub fn error(tool_name: &str, error: impl ToString, exec_time_ms: u64) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(error.to_string()),
            execution_time_ms: exec_time_ms,
            tool_name: tool_name.to_string(),
        }
    }
}

/// A request to call a tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// Tool name to call
    pub name: String,
    /// Parameters to pass
    pub parameters: serde_json::Value,
}

/// Replace values that name an absence with `null`, in place.
///
/// The ontology has rejected `"Unknown"`-as-a-value since the absence-word guard
/// went into `push_str_as`; the agent tool surface never had the equivalent. On
/// one machine `get_usb_devices` returned `"speed": "Unknown"` for thirty-odd
/// devices, `get_bluetooth_devices` returned `"type": "Unknown"` for nine and an
/// empty `"address"` for one — seventy values in total, each of which an agent
/// reads as a fact about the hardware. `null` says the same thing truthfully.
///
/// This is weaker than what the ontology does, and deliberately so: a `Reading`
/// carries *why* it is unavailable, and a `null` here carries nothing but the
/// absence. Getting the reason onto this surface means giving each tool the
/// `Reading` shape, which is a larger change than this one. Until then, `null`
/// beats a string that looks like a measurement and is not.
///
/// The predicate is `ontology::resolve::names_an_absence` rather than a second
/// copy of the word list, so the two surfaces cannot drift apart.
fn null_out_absence_words(v: &mut serde_json::Value) {
    use serde_json::Value;
    match v {
        Value::String(s) => {
            if s.trim().is_empty() || crate::ontology::resolve::names_an_absence(s) {
                *v = Value::Null;
            }
        }
        Value::Object(m) => {
            for val in m.values_mut() {
                null_out_absence_words(val);
            }
        }
        Value::Array(a) => {
            for val in a.iter_mut() {
                null_out_absence_words(val);
            }
        }
        _ => {}
    }
}

/// AI Data API - Main interface for AI system data access
pub struct AiDataApi {
    observations: Option<Arc<observation_tools::ObservationService>>,
    /// GPU collection for GPU queries
    gpus: Option<GpuCollection>,
    /// Process monitor with GPU attribution
    process_monitor: Option<ProcessMonitor>,
    /// Network monitor
    network_monitor: Option<NetworkMonitor>,
    /// Cache for expensive operations
    cache: Arc<Mutex<ApiCache>>,
    /// Last update times for rate calculations
    #[allow(dead_code)]
    last_update: Instant,
    /// Historical data context (injected from GUI)
    historical_context: Option<String>,
    /// Why GPU detection failed, when it did. `gpus` is `None` in that case and
    /// no GPU was ever enumerated, so the two must not read alike.
    gpu_error: Option<String>,
    /// Why the process monitor could not be created, when it could not.
    process_monitor_error: Option<String>,
    /// Why the network monitor could not be created, when it could not.
    network_monitor_error: Option<String>,
}

/// Cache for API data
struct ApiCache {
    /// Cached system summary
    system_summary: Option<(Instant, SystemSummary)>,
    /// Cache TTL in milliseconds
    ttl_ms: u64,
}

impl ApiCache {
    fn new() -> Self {
        Self {
            system_summary: None,
            ttl_ms: 1000, // 1 second default TTL
        }
    }

    fn is_valid(&self, cached_at: Instant) -> bool {
        cached_at.elapsed().as_millis() < self.ttl_ms as u128
    }
}

impl AiDataApi {
    /// Create a new AI Data API instance
    pub fn new() -> Result<Self> {
        // Try to initialize components, but don't fail if some aren't available
        // A failure is kept with its reason rather than dropped. Dropping it made
        // the component look as if it had been found absent.
        let (gpus, gpu_error) = match GpuCollection::auto_detect() {
            Ok(gpus) => (Some(gpus), None),
            Err(e) => (None, Some(e.to_string())),
        };

        // Create process monitor (without GPU integration for now, as GpuCollection doesn't implement Clone)
        // Primed here, so the first tool call reports CPU% over the interval
        // since startup rather than each process's lifetime average.
        let (process_monitor, process_monitor_error) = match ProcessMonitor::new() {
            Ok(mut m) => {
                let _ = m.sample_cpu_times();
                (Some(m), None)
            }
            Err(e) => (None, Some(e.to_string())),
        };
        let (network_monitor, network_monitor_error) = match NetworkMonitor::new() {
            Ok(m) => (Some(m), None),
            Err(e) => (None, Some(e.to_string())),
        };

        Ok(Self {
            observations: None,
            gpus,
            process_monitor,
            network_monitor,
            cache: Arc::new(Mutex::new(ApiCache::new())),
            last_update: Instant::now(),
            historical_context: None,
            gpu_error,
            process_monitor_error,
            network_monitor_error,
        })
    }

    /// The error for a GPU tool when GPU detection did not succeed. It names the
    /// detection failure. It used to say "No GPUs detected", which was a claim
    /// about the machine that nothing had established.
    fn gpu_unavailable(&self) -> IronError {
        IronError::HardwareError(format!(
            "GPU detection failed: {}",
            self.gpu_error
                .as_deref()
                .unwrap_or("no GPU monitor was created")
        ))
    }

    /// Create API with pre-initialized components
    pub fn with_components(
        gpus: Option<GpuCollection>,
        process_monitor: Option<ProcessMonitor>,
        network_monitor: Option<NetworkMonitor>,
    ) -> Self {
        Self {
            observations: None,
            gpus,
            process_monitor,
            network_monitor,
            cache: Arc::new(Mutex::new(ApiCache::new())),
            last_update: Instant::now(),
            historical_context: None,
            gpu_error: None,
            process_monitor_error: None,
            network_monitor_error: None,
        }
    }

    /// Set historical data context from the GUI
    pub fn set_historical_context(&mut self, context: Option<String>) {
        self.historical_context = context;
    }

    /// List all available tools
    pub fn list_tools(&self) -> Vec<ToolDefinition> {
        tools::get_all_tool_definitions()
    }

    /// List tools by category
    pub fn list_tools_by_category(&self, category: ToolCategory) -> Vec<ToolDefinition> {
        self.list_tools()
            .into_iter()
            .filter(|t| t.category == category)
            .collect()
    }

    /// Get a tool definition by name
    pub fn get_tool(&self, name: &str) -> Option<ToolDefinition> {
        self.list_tools().into_iter().find(|t| t.name == name)
    }

    /// Call a tool by name with parameters
    pub fn call_tool(&mut self, name: &str, params: serde_json::Value) -> Result<ToolResult> {
        let start = Instant::now();

        let result = match name {
            "describe_entities" => self.tool_describe_entities(params),
            "list_connections" => self.tool_list_connections(params),
            "inspect_services" => self.tool_inspect_services(params),
            "query_os_events" => self.tool_query_os_events(params),
            "get_observation_snapshot" => self.tool_observation_snapshot(params),
            "get_collector_health" => self.tool_collector_health(params),
            "query_metric_history" => self.tool_metric_history(params),
            "query_events" => self.tool_observation_events(params),
            "inspect_process" => self.tool_inspect_process(params),
            "check_endpoint" => self.tool_check_endpoint(params),
            // System tools
            "get_system_summary" => self.tool_get_system_summary(params),
            "get_system_info" => self.tool_get_system_info(params),
            "get_platform_info" => self.tool_get_platform_info(params),

            // GPU tools
            "get_gpu_status" => self.tool_get_gpu_status(params),
            "get_gpu_list" => self.tool_get_gpu_list(params),
            "get_gpu_details" => self.tool_get_gpu_details(params),
            "get_gpu_processes" => self.tool_get_gpu_processes(params),
            "get_gpu_utilization" => self.tool_get_gpu_utilization(params),
            "get_gpu_memory" => self.tool_get_gpu_memory(params),
            "get_gpu_temperature" => self.tool_get_gpu_temperature(params),
            "get_gpu_power" => self.tool_get_gpu_power(params),

            // CPU tools
            "get_cpu_status" => self.tool_get_cpu_status(params),
            "get_cpu_cores" => self.tool_get_cpu_cores(params),
            "get_cpu_frequency" => self.tool_get_cpu_frequency(params),

            // Memory tools
            "get_memory_status" => self.tool_get_memory_status(params),
            "get_memory_breakdown" => self.tool_get_memory_breakdown(params),
            "get_swap_status" => self.tool_get_swap_status(params),

            // Disk tools
            "get_disk_list" => self.tool_get_disk_list(params),
            "get_disk_details" => self.tool_get_disk_details(params),
            "get_disk_io" => self.tool_get_disk_io(params),
            "get_disk_health" => self.tool_get_disk_health(params),

            // Network tools
            "get_network_interfaces" => self.tool_get_network_interfaces(params),
            "get_network_bandwidth" => self.tool_get_network_bandwidth(params),
            "get_interface_details" => self.tool_get_interface_details(params),

            // Process tools
            "get_process_list" => self.tool_get_process_list(params),
            "get_process_details" => self.tool_get_process_details(params),
            "get_top_cpu_processes" => self.tool_get_top_cpu_processes(params),
            "get_top_memory_processes" => self.tool_get_top_memory_processes(params),
            "get_top_gpu_processes" => self.tool_get_top_gpu_processes(params),
            "search_processes" => self.tool_search_processes(params),

            // Hardware tools
            "get_motherboard_sensors" => self.tool_get_motherboard_sensors(params),
            "get_system_temperatures" => self.tool_get_system_temperatures(params),
            "get_fan_speeds" => self.tool_get_fan_speeds(params),
            "get_voltage_rails" => self.tool_get_voltage_rails(params),
            "get_driver_info" => self.tool_get_driver_info(params),

            // Audio tools
            "get_audio_devices" => self.tool_get_audio_devices(params),
            "get_audio_status" => self.tool_get_audio_status(params),

            // Bluetooth tools
            "get_bluetooth_adapters" => self.tool_get_bluetooth_adapters(params),
            "get_bluetooth_devices" => self.tool_get_bluetooth_devices(params),

            // Display tools
            "get_display_list" => self.tool_get_display_list(params),
            "get_display_details" => self.tool_get_display_details(params),

            // USB tools
            "get_usb_devices" => self.tool_get_usb_devices(params),
            "get_usb_device_details" => self.tool_get_usb_device_details(params),

            // Profile inspector tools
            "list_profile_subsystems" => self.tool_list_profile_subsystems(params),
            "get_profile_settings" => self.tool_get_profile_settings(params),
            "search_profile_settings" => self.tool_search_profile_settings(params),
            "get_active_app_profiles" => self.tool_get_active_app_profiles(params),
            "get_profile_deviations" => self.tool_get_profile_deviations(params),
            "explain_profile_setting" => self.tool_explain_profile_setting(params),
            "benchmark_profile_providers" => self.tool_benchmark_profile_providers(params),
            "list_writable_profile_settings" => self.tool_list_writable_profile_settings(params),
            "apply_profile_setting" => self.tool_apply_profile_setting(params),

            _ => Err(IronError::NotImplemented(format!("Unknown tool: {}", name))),
        };

        let exec_time = start.elapsed().as_millis() as u64;

        match result {
            Ok(mut data) => {
                null_out_absence_words(&mut data);
                Ok(ToolResult::success(name, data, exec_time))
            }
            Err(e) => Ok(ToolResult::error(name, e, exec_time)),
        }
    }

    /// Execute multiple tool calls in sequence
    pub fn call_tools(&mut self, calls: Vec<ToolCall>) -> Vec<ToolResult> {
        calls
            .into_iter()
            .map(|call| {
                self.call_tool(&call.name, call.parameters)
                    .unwrap_or_else(|e| ToolResult::error(&call.name, e, 0))
            })
            .collect()
    }

    /// Get a compact system summary (cached)
    pub fn system_summary(&mut self) -> Result<SystemSummary> {
        // Check cache
        {
            let cache = self.cache.lock().unwrap();
            if let Some((cached_at, ref summary)) = cache.system_summary {
                if cache.is_valid(cached_at) {
                    return Ok(summary.clone());
                }
            }
        }

        // Generate fresh summary
        let summary = self.generate_system_summary()?;

        // Update cache
        {
            let mut cache = self.cache.lock().unwrap();
            cache.system_summary = Some((Instant::now(), summary.clone()));
        }

        Ok(summary)
    }

    /// Generate a fresh system summary
    fn generate_system_summary(&mut self) -> Result<SystemSummary> {
        let mut summary = SystemSummary::default();
        // Every section that could not be read is named here with its reason.
        // Its list is `None` (not empty) in the summary, so an agent cannot
        // mistake a failed read for a machine with nothing in that section.
        let mut errors: Vec<String> = Vec::new();

        // GPU info
        match self.gpus.as_ref() {
            None => errors.push(format!(
                "gpus: {}",
                self.gpu_error
                    .as_deref()
                    .unwrap_or("GPU detection did not run")
            )),
            Some(gpus) => match gpus.snapshot_all() {
                Err(e) => errors.push(format!("gpus: {e}")),
                Ok(snapshots) => {
                    summary.gpu_count = Some(snapshots.len());
                    let mut gpu_list = Vec::with_capacity(snapshots.len());
                    for snapshot in snapshots {
                        gpu_list.push(GpuSummary {
                            name: snapshot.static_info.name.clone(),
                            vendor: format!("{:?}", snapshot.static_info.vendor),
                            utilization_percent: snapshot.dynamic_info.utilization.map(f32::from),
                            memory_used_mb: snapshot
                                .dynamic_info
                                .memory
                                .used
                                .map(|v| v / 1024 / 1024),
                            memory_total_mb: snapshot
                                .dynamic_info
                                .memory
                                .total
                                .map(|v| v / 1024 / 1024),
                            temperature_c: snapshot.dynamic_info.thermal.temperature,
                            power_watts: snapshot
                                .dynamic_info
                                .power
                                .draw
                                .map(|p| p as f32 / 1000.0),
                        });
                    }
                    summary.gpus = Some(gpu_list);
                }
            },
        }

        // Process info
        match self.process_monitor.as_mut() {
            None => errors.push(format!(
                "processes: {}",
                self.process_monitor_error
                    .as_deref()
                    .unwrap_or("process monitor did not start")
            )),
            Some(proc_mon) => {
                match proc_mon.processes() {
                    Err(e) => errors.push(format!("processes: {e}")),
                    Ok(procs) => {
                        summary.process_count = Some(procs.len());

                        // Calculate total CPU usage. `None` if any process's figure is unknown.
                        summary.total_cpu_percent =
                            procs.iter().map(|p| p.cpu_percent).sum::<Option<f32>>();

                        // Get top CPU consumers
                        let mut by_cpu = procs.clone();
                        by_cpu.sort_by(|a, b| {
                            b.cpu_percent
                                .partial_cmp(&a.cpu_percent)
                                .unwrap_or(std::cmp::Ordering::Equal)
                        });
                        summary.top_cpu_processes = Some(
                            by_cpu
                                .iter()
                                .take(5)
                                .map(|p| ProcessSummary {
                                    pid: p.pid,
                                    name: p.name.clone(),
                                    cpu_percent: p.cpu_percent,
                                    memory_mb: (p.memory_bytes / 1024 / 1024),
                                    gpu_memory_mb: p
                                        .total_gpu_memory_bytes
                                        .map(|b| b / 1024 / 1024),
                                })
                                .collect(),
                        );

                        // Get top memory consumers
                        let mut by_mem = procs.clone();
                        by_mem.sort_by_key(|p| std::cmp::Reverse(p.memory_bytes));
                        summary.top_memory_processes = Some(
                            by_mem
                                .iter()
                                .take(5)
                                .map(|p| ProcessSummary {
                                    pid: p.pid,
                                    name: p.name.clone(),
                                    cpu_percent: p.cpu_percent,
                                    memory_mb: (p.memory_bytes / 1024 / 1024),
                                    gpu_memory_mb: p
                                        .total_gpu_memory_bytes
                                        .map(|b| b / 1024 / 1024),
                                })
                                .collect(),
                        );
                    }
                }

                // GPU processes
                match proc_mon.gpu_processes() {
                    Err(e) => errors.push(format!("gpu_processes: {e}")),
                    Ok(gpu_procs) => {
                        summary.gpu_process_count = Some(gpu_procs.len());
                        summary.top_gpu_processes = Some(
                            gpu_procs
                                .iter()
                                .take(5)
                                .map(|p| ProcessSummary {
                                    pid: p.pid,
                                    name: p.name.clone(),
                                    cpu_percent: p.cpu_percent,
                                    memory_mb: (p.memory_bytes / 1024 / 1024),
                                    gpu_memory_mb: p
                                        .total_gpu_memory_bytes
                                        .map(|b| b / 1024 / 1024),
                                })
                                .collect(),
                        );
                    }
                }
            }
        }

        // Network info
        match self.network_monitor.as_mut() {
            None => errors.push(format!(
                "network: {}",
                self.network_monitor_error
                    .as_deref()
                    .unwrap_or("network monitor did not start")
            )),
            Some(net_mon) => match net_mon.active_interfaces() {
                Err(e) => errors.push(format!("network: {e}")),
                Ok(interfaces) => {
                    summary.active_network_interfaces = Some(interfaces.len());
                    let mut net_list = Vec::with_capacity(interfaces.len());
                    for iface in interfaces {
                        let rate = net_mon.bandwidth_rate(&iface.name, &iface);
                        net_list.push(NetworkSummary {
                            name: iface.name.clone(),
                            rx_bytes_per_sec: rate.map(|(rx, _)| rx as u64),
                            tx_bytes_per_sec: rate.map(|(_, tx)| tx as u64),
                            rx_total_mb: (iface.rx_bytes / 1024 / 1024),
                            tx_total_mb: (iface.tx_bytes / 1024 / 1024),
                            is_up: iface.is_up,
                        });
                    }
                    summary.network_interfaces = Some(net_list);
                }
            },
        }

        // Memory info (platform-specific)
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::memory;
            match memory::read_memory_stats() {
                Ok(mem) => {
                    summary.memory = Some(MemorySummary {
                        total_mb: (mem.ram.total / 1024),
                        used_mb: (mem.ram.used / 1024),
                        free_mb: mem.ram.free.map(|v| v / 1024),
                        cached_mb: mem.ram.cached.map(|v| v / 1024),
                        swap_total_mb: mem.swap.total.map(|v| v / 1024),
                        swap_used_mb: mem.swap.used.map(|v| v / 1024),
                        usage_percent: mem.ram_usage_percent(),
                    });
                }
                Err(e) => errors.push(format!("memory: {e}")),
            }
        }
        #[cfg(not(target_os = "linux"))]
        {
            errors.push("memory: this summary reads memory on Linux only".to_string());
        }

        // Disk info. `disk_count` and `disks` cover the disks that were read;
        // a disk whose info failed is counted in `unreadable_disk_count` and its
        // error goes to `errors`. It used to be counted in `disk_count` and then
        // silently left out of the list.
        match crate::disk::enumerate_disks() {
            Err(e) => errors.push(format!("disks: {e}")),
            Ok(disks) => {
                let mut disk_list = Vec::with_capacity(disks.len());
                let mut unreadable = 0usize;
                for (index, disk) in disks.iter().enumerate() {
                    match disk.info() {
                        Ok(info) => disk_list.push(DiskSummary {
                            name: info.name.clone(),
                            model: info.model.clone(),
                            // Integer division truncated every drive under a
                            // gibibyte to 0 GB, which reads as a zero-size disk.
                            size_gb: info.capacity.map(|c| c as f64 / 1024.0 / 1024.0 / 1024.0),
                            // `Unknown` is null, not the word "Unknown".
                            disk_type: (info.disk_type != crate::disk::DiskType::Unknown)
                                .then(|| format!("{:?}", info.disk_type)),
                            temperature_c: disk.temperature().ok().flatten(),
                        }),
                        Err(e) => {
                            unreadable += 1;
                            errors.push(format!("disk {index}: {e}"));
                        }
                    }
                }
                summary.disk_count = Some(disk_list.len());
                summary.unreadable_disk_count = Some(unreadable);
                summary.disks = Some(disk_list);
            }
        }

        summary.errors = errors;
        summary.timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| {
                IronError::HardwareError(format!("system clock is before the Unix epoch: {e}"))
            })?
            .as_secs();

        Ok(summary)
    }

    /// Format the tool list as a prompt for AI systems
    pub fn tools_as_prompt(&self) -> String {
        let tools = self.list_tools();
        let mut prompt = String::from("# Available System Monitoring Tools\n\n");
        prompt.push_str("You have access to the following tools to query system information:\n\n");

        let mut by_category: HashMap<ToolCategory, Vec<&ToolDefinition>> = HashMap::new();
        for tool in &tools {
            by_category.entry(tool.category).or_default().push(tool);
        }

        for (category, tools) in by_category {
            prompt.push_str(&format!("## {} Tools\n\n", category));
            for tool in tools {
                prompt.push_str(&format!("### `{}`\n", tool.name));
                prompt.push_str(&format!("{}\n\n", tool.description));
                if let Some(ref example) = tool.example {
                    prompt.push_str(&format!("**Example:** `{}`\n\n", example));
                }
            }
        }

        prompt
    }

    /// Get tools in OpenAI function calling format
    pub fn tools_as_openai_functions(&self) -> Vec<serde_json::Value> {
        self.list_tools()
            .into_iter()
            .map(|tool| {
                serde_json::json!({
                    "type": "function",
                    "function": {
                        "name": tool.name,
                        "description": tool.description,
                        "parameters": tool.parameters
                    }
                })
            })
            .collect()
    }

    /// Get tools in Anthropic tool format
    pub fn tools_as_anthropic_tools(&self) -> Vec<serde_json::Value> {
        self.list_tools()
            .into_iter()
            .map(|tool| {
                serde_json::json!({
                    "name": tool.name,
                    "description": tool.description,
                    "input_schema": tool.parameters
                })
            })
            .collect()
    }

    /// Analyze a user query and automatically call relevant tools
    ///
    /// Returns a context string with the results of all relevant tool calls
    /// that can be injected into the AI system prompt.
    pub fn auto_query(&mut self, user_query: &str) -> String {
        let query_lower = user_query.to_lowercase();
        let mut results: Vec<String> = Vec::new();
        let mut tools_called: Vec<&str> = Vec::new();

        // GPU-related queries
        if query_lower.contains("gpu")
            || query_lower.contains("graphics")
            || query_lower.contains("nvidia")
            || query_lower.contains("amd")
            || query_lower.contains("cuda")
            || query_lower.contains("vram")
        {
            tools_called.push("get_gpu_status");
            if let Ok(result) = self.call_tool("get_gpu_status", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## GPU Status\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }

            // If asking about GPU processes or utilization
            if query_lower.contains("process")
                || query_lower.contains("using")
                || query_lower.contains("utiliz")
            {
                tools_called.push("get_gpu_processes");
                if let Ok(result) = self.call_tool("get_gpu_processes", serde_json::json!({})) {
                    if result.success {
                        if let Some(data) = result.data {
                            results.push(format!(
                                "## GPU Processes\n```json\n{}\n```",
                                serde_json::to_string_pretty(&data).unwrap_or_default()
                            ));
                        }
                    }
                }
            }
        }

        // CPU-related queries
        if query_lower.contains("cpu")
            || query_lower.contains("processor")
            || query_lower.contains("core")
            || query_lower.contains("thread")
        {
            tools_called.push("get_cpu_status");
            if let Ok(result) = self.call_tool("get_cpu_status", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## CPU Status\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Memory-related queries
        if query_lower.contains("memory")
            || query_lower.contains("ram")
            || query_lower.contains("swap")
        {
            tools_called.push("get_memory_status");
            if let Ok(result) = self.call_tool("get_memory_status", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## Memory Status\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Disk-related queries
        if query_lower.contains("disk")
            || query_lower.contains("storage")
            || query_lower.contains("ssd")
            || query_lower.contains("nvme")
            || query_lower.contains("hdd")
            || query_lower.contains("drive")
        {
            tools_called.push("get_disk_list");
            if let Ok(result) = self.call_tool("get_disk_list", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## Disk Information\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Network-related queries
        if query_lower.contains("network")
            || query_lower.contains("bandwidth")
            || query_lower.contains("ethernet")
            || query_lower.contains("wifi")
            || query_lower.contains("interface")
            || query_lower.contains("internet")
        {
            tools_called.push("get_network_interfaces");
            if let Ok(result) = self.call_tool("get_network_interfaces", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## Network Interfaces\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Process-related queries
        if query_lower.contains("process")
            || query_lower.contains("program")
            || query_lower.contains("running")
            || query_lower.contains("application")
        {
            // Determine which process info to get
            if query_lower.contains("cpu") || query_lower.contains("processor") {
                tools_called.push("get_top_cpu_processes");
                if let Ok(result) =
                    self.call_tool("get_top_cpu_processes", serde_json::json!({"count": 10}))
                {
                    if result.success {
                        if let Some(data) = result.data {
                            results.push(format!(
                                "## Top CPU Processes\n```json\n{}\n```",
                                serde_json::to_string_pretty(&data).unwrap_or_default()
                            ));
                        }
                    }
                }
            } else if query_lower.contains("memory") || query_lower.contains("ram") {
                tools_called.push("get_top_memory_processes");
                if let Ok(result) =
                    self.call_tool("get_top_memory_processes", serde_json::json!({"count": 10}))
                {
                    if result.success {
                        if let Some(data) = result.data {
                            results.push(format!(
                                "## Top Memory Processes\n```json\n{}\n```",
                                serde_json::to_string_pretty(&data).unwrap_or_default()
                            ));
                        }
                    }
                }
            } else if query_lower.contains("gpu") {
                tools_called.push("get_top_gpu_processes");
                if let Ok(result) =
                    self.call_tool("get_top_gpu_processes", serde_json::json!({"count": 10}))
                {
                    if result.success {
                        if let Some(data) = result.data {
                            results.push(format!(
                                "## Top GPU Processes\n```json\n{}\n```",
                                serde_json::to_string_pretty(&data).unwrap_or_default()
                            ));
                        }
                    }
                }
            } else {
                // General process list
                tools_called.push("get_process_list");
                if let Ok(result) =
                    self.call_tool("get_process_list", serde_json::json!({"count": 15}))
                {
                    if result.success {
                        if let Some(data) = result.data {
                            results.push(format!(
                                "## Running Processes\n```json\n{}\n```",
                                serde_json::to_string_pretty(&data).unwrap_or_default()
                            ));
                        }
                    }
                }
            }
        }

        // Temperature-related queries
        if query_lower.contains("temp")
            || query_lower.contains("heat")
            || query_lower.contains("hot")
            || query_lower.contains("thermal")
        {
            tools_called.push("get_system_temperatures");
            if let Ok(result) = self.call_tool("get_system_temperatures", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## System Temperatures\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Power-related queries
        if query_lower.contains("power")
            || query_lower.contains("watt")
            || query_lower.contains("energy")
            || query_lower.contains("consumption")
        {
            tools_called.push("get_gpu_power");
            if let Ok(result) = self.call_tool("get_gpu_power", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## GPU Power\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // System/overview queries - provide general summary
        if query_lower.contains("system")
            || query_lower.contains("overview")
            || query_lower.contains("status")
            || query_lower.contains("summary")
            || query_lower.contains("hardware")
            || query_lower.contains("specs")
            || query_lower.contains("what do i have")
            || query_lower.contains("my computer")
        {
            tools_called.push("get_system_summary");
            if let Ok(result) = self.call_tool("get_system_summary", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## System Summary\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Fan-related queries
        if query_lower.contains("fan") {
            tools_called.push("get_fan_speeds");
            if let Ok(result) = self.call_tool("get_fan_speeds", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## Fan Speeds\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // If no specific tools matched, provide a general system summary
        if results.is_empty() {
            tools_called.push("get_system_summary");
            if let Ok(result) = self.call_tool("get_system_summary", serde_json::json!({})) {
                if result.success {
                    if let Some(data) = result.data {
                        results.push(format!(
                            "## System Summary\n```json\n{}\n```",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        ));
                    }
                }
            }
        }

        // Historical data queries (injected from GUI if available)
        if (query_lower.contains("minute")
            || query_lower.contains("ago")
            || query_lower.contains("earlier")
            || query_lower.contains("before")
            || query_lower.contains("history")
            || query_lower.contains("historical")
            || query_lower.contains("was"))
            && self.historical_context.is_some()
        {
            if let Some(ref context) = self.historical_context {
                tools_called.push("get_historical_data");
                results.push(format!("## Historical Data\n{}", context));
            }
        }

        // Build the context string
        if results.is_empty() {
            String::from("No system data available.")
        } else {
            let header = format!(
                "# Real-time System Data\n\n*Tools called: {}*\n\n",
                tools_called.join(", ")
            );
            format!("{}{}", header, results.join("\n\n"))
        }
    }

    /// Analyze a user query and automatically call relevant tools
    ///
    /// Returns a tuple of (context string, tools called) with the results of all
    /// relevant tool calls that can be injected into the AI system prompt.
    pub fn auto_query_with_tools(&mut self, user_query: &str) -> (String, Vec<String>) {
        let context = self.auto_query(user_query);

        // Parse tools from the context header
        let tools = if context.contains("*Tools called:") {
            context
                .lines()
                .find(|line| line.contains("*Tools called:"))
                .and_then(|line| {
                    line.trim_start_matches("*Tools called: ")
                        .trim_end_matches("*")
                        .split(", ")
                        .map(|s| s.to_string())
                        .filter(|s| !s.is_empty())
                        .collect::<Vec<_>>()
                        .into()
                })
                .unwrap_or_default()
        } else {
            Vec::new()
        };

        (context, tools)
    }
}