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
//! AI Agent for System Analysis and Predictions
//!
//! Answers natural-language questions about system state by pairing live hardware
//! telemetry with an LLM backend.
//!
//! # How it works
//!
//! A question is parsed into a [`Query`] to classify intent and handed to the
//! configured model with read-only monitoring tools. A bounded loop executes
//! requested measurements and returns their evidence for follow-up reasoning.
//! Live answers are not cached.
//!
//! # Requirements and limitations
//!
//! Read these before building on this module — several are easy to assume otherwise.
//!
//! - **A backend is required.** There is no built-in offline inference. [`Agent::new`]
//!   fails with [`IronError::Configuration`] when no backend is configured. Set one
//!   explicitly, or use [`AgentConfig::auto_detect`] to discover a running local
//!   server.
//! - **Where your telemetry goes depends on the backend you choose.** A local backend
//!   (Ollama, vLLM, or TensorRT-LLM on localhost) keeps system state on the machine.
//!   A hosted backend (OpenAI, Anthropic) transmits the extracted system state to
//!   that provider — which includes hardware identifiers such as GPU UUIDs and PCI
//!   bus ids.
//! - **`--offline` is enforced here.** [`Agent::ask`] refuses any backend whose
//!   [`BackendType::runs_on_host`] is false when [`crate::consent::is_offline_mode`]
//!   is set. The check is on egress rather than on "makes a network call": a model
//!   served over loopback keeps data on the machine, while a local CLI tool that
//!   relays the prompt to its vendor does not.
//! - **Calls block the calling thread.** [`Agent::ask`] runs inference inline; nothing
//!   in this module spawns a thread. Never call it from a render or event loop —
//!   spawn a thread and deliver the result over a channel.
//!   [`Agent::ask_with_timeout`] bounds the tool loop and backend wait.
//! - **[`ModelSize`] is advisory metadata.** It records an intended model scale, and
//!   its `latency_estimate_ms` / `memory_mb` are fixed estimates rather than
//!   measurements. It does not select, download, or load a model — the model in use
//!   is whatever the configured backend is serving.
//!
//! # Question categories
//!
//! - **System State**: "What's my GPU utilization?", "Show memory usage"
//! - **Predictions**: "When will this training complete?", "ETA for disk copy"
//! - **Energy Analysis**: "How much power am I using?", "Cost per hour estimate"
//! - **Comparisons**: "Is my GPU faster than X?", "Compare temps across GPUs"
//! - **Recommendations**: "Should I upgrade RAM?", "Optimize settings"
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::agent::{Agent, AgentConfig};
//! use ironmonitor::UnifiedMonitor;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Discover a locally running inference server. Fails if none is available —
//! // the agent cannot run without a backend.
//! let config = AgentConfig::auto_detect()?;
//! let mut agent = Agent::new(config)?;
//!
//! let monitor = UnifiedMonitor::new()?;
//!
//! // Blocking call: run this off any UI thread.
//! let response = agent.ask("What's my GPU temperature and is it safe?", &monitor)?;
//!
//! println!("Agent: {}", response.response);
//! # Ok(())
//! # }
//! ```

pub mod backend;
pub mod engine;
pub mod inference;
pub mod local;
pub mod query;
pub mod remote;
pub mod state;
pub mod tool_runtime;

use crate::error::{IronError, Result};
use crate::UnifiedMonitor;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

pub use backend::{BackendCapabilities, BackendConfig, BackendDiscovery, BackendType};
pub use engine::InferenceEngine;
pub use local::{
    InferenceRequest, InferenceResponse, LocalInferenceClient, ModelInfo, OllamaClient,
};
pub use query::{Query, QueryType};
pub use remote::{RemoteClient, RemoteClientBuilder};
pub use state::SystemState;

/// The model to ask a hosted provider for when the caller named none.
///
/// These are the only place in the non-interactive path where ironmon picks a model
/// name, and a name is all a hosted provider will accept — unlike a local server,
/// there is nothing to ask "what are you serving?" without a credential. So they
/// are a starting point, not a claim about what is current: a provider ships a new
/// model and these age the same day. Anything that can enumerate the provider (the
/// GUI's model dropdown does) should prefer the live listing and treat these as the
/// answer of last resort. Set the model explicitly on [`BackendConfig`] to pin one.
pub const DEFAULT_OPENAI_MODEL: &str = "gpt-5.6-terra";
/// See [`DEFAULT_OPENAI_MODEL`].
pub const DEFAULT_ANTHROPIC_MODEL: &str = "claude-sonnet-5";
/// Formerly the default for GitHub Models, retained only so existing saved
/// configurations still resolve to something.
///
/// GitHub retired that service on 2026-07-30, so no id reaches it any more —
/// including this one. It keeps GitHub's publisher-qualified spelling because that
/// is what a stored config from before the shutdown will look like. See
/// [`BackendType::RemoteGitHub`].
#[deprecated(
    since = "2.1.0",
    note = "GitHub retired GitHub Models on 2026-07-30; no model id reaches it."
)]
pub const DEFAULT_GITHUB_MODEL: &str = "openai/gpt-4.1";

/// AI model size options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ModelSize {
    /// 100M parameters - Fastest, basic queries (~50-100ms latency)
    Small,
    /// 500M parameters - Balanced, good reasoning (~100-200ms latency)
    #[default]
    Medium,
    /// 1B parameters - Best reasoning, slower (~200-500ms latency)
    Large,
}

impl ModelSize {
    /// Get estimated inference latency in milliseconds
    pub fn latency_estimate_ms(&self) -> u64 {
        match self {
            Self::Small => 75,
            Self::Medium => 150,
            Self::Large => 350,
        }
    }

    /// Get memory requirement in MB
    pub fn memory_mb(&self) -> usize {
        match self {
            Self::Small => 200,   // ~100M params * 2 bytes (quantized)
            Self::Medium => 1000, // ~500M params * 2 bytes
            Self::Large => 2000,  // ~1B params * 2 bytes
        }
    }

    /// Get model description
    pub fn description(&self) -> &str {
        match self {
            Self::Small => "100M params - Fast responses, basic queries",
            Self::Medium => "500M params - Balanced speed and reasoning",
            Self::Large => "1B params - Advanced reasoning, slower",
        }
    }
}

impl std::fmt::Display for ModelSize {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Small => write!(f, "100M"),
            Self::Medium => write!(f, "500M"),
            Self::Large => write!(f, "1B"),
        }
    }
}

/// Agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Model size to use (for local models)
    pub model_size: ModelSize,

    /// Model cache directory
    pub model_dir: PathBuf,

    /// Maximum response length in tokens
    pub max_response_tokens: usize,

    /// Temperature for sampling (0.0 = deterministic, 1.0 = creative)
    pub temperature: f32,

    /// Enable response caching (reuse answers for identical queries)
    pub enable_caching: bool,

    /// Maximum cache size (number of query-response pairs)
    pub cache_size: usize,

    /// Timeout for inference in seconds
    pub timeout_seconds: u64,

    /// Backend configuration (optional, defaults to rule-based)
    pub backend: Option<BackendConfig>,
}

impl AgentConfig {
    /// Create new config with specified model size (rule-based backend)
    pub fn new(model_size: ModelSize) -> Self {
        Self {
            model_size,
            model_dir: Self::default_model_dir(),
            max_response_tokens: 256, // Keep responses concise
            temperature: 0.3,         // Prefer factual responses
            enable_caching: true,
            cache_size: 100,
            timeout_seconds: 5, // Prevent hanging
            backend: None,      // Use rule-based by default
        }
    }

    /// Create new config with backend
    pub fn with_backend(backend: BackendConfig) -> Self {
        Self {
            model_size: ModelSize::Medium, // Ignored for remote backends
            model_dir: Self::default_model_dir(),
            max_response_tokens: backend.max_tokens,
            temperature: backend.temperature,
            enable_caching: true,
            cache_size: 100,
            timeout_seconds: backend.timeout.as_secs(),
            backend: Some(backend),
        }
    }

    /// Get default model directory (~/.cache/ironmon/models)
    fn default_model_dir() -> PathBuf {
        #[cfg(unix)]
        {
            let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
            PathBuf::from(home).join(".cache/ironmon/models")
        }

        #[cfg(windows)]
        {
            let local_app_data =
                std::env::var("LOCALAPPDATA").unwrap_or_else(|_| "C:\\Temp".to_string());
            PathBuf::from(local_app_data).join("ironmon\\models")
        }
    }

    /// Set custom model directory
    pub fn with_model_dir(mut self, path: PathBuf) -> Self {
        self.model_dir = path;
        self
    }

    /// Set temperature (0.0-1.0)
    pub fn with_temperature(mut self, temp: f32) -> Self {
        self.temperature = temp.clamp(0.0, 1.0);
        self
    }

    /// Set max response tokens
    pub fn with_max_tokens(mut self, tokens: usize) -> Self {
        self.max_response_tokens = tokens;
        self
    }

    /// Disable caching
    pub fn without_caching(mut self) -> Self {
        self.enable_caching = false;
        self
    }

    /// Enable caching (on by default)
    pub fn with_caching(mut self, enabled: bool) -> Self {
        self.enable_caching = enabled;
        self
    }

    /// Set cache size
    pub fn with_cache_size(mut self, size: usize) -> Self {
        self.cache_size = size;
        self
    }

    /// Set timeout duration
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout_seconds = timeout.as_secs();
        self
    }

    /// Create config with automatic backend detection
    ///
    /// This will:
    /// 1. Discover available backends (local and remote)
    /// 2. Select the recommended backend
    /// 3. Configure with appropriate defaults
    #[allow(deprecated)]
    pub fn auto_detect() -> Result<Self> {
        let discovery = BackendDiscovery::discover();
        // A configured hosted key is usable here, as before the split, so the error
        // below is raised only when nothing is set up at all.
        if discovery.available().is_empty() && discovery.configured().is_empty() {
            return Err(IronError::Configuration(
                "No AI backends available. Please install Ollama (https://ollama.com), \
                configure an API key (OPENAI_API_KEY or GITHUB_TOKEN), or set up another backend."
                    .to_string(),
            ));
        }

        let backend_type = discovery.recommended();

        // Create backend config based on detected type
        let backend_config = match backend_type {
            BackendType::IronWorks => {
                // The server decides which model it serves; "default" asks for
                // whatever is loaded rather than pinning a name IronMonitor cannot know.
                BackendConfig::ironworks("default")
            }
            // CLI tools use whatever model they are already configured for;
            // "default" tells the client not to override it.
            BackendType::Cli(provider) => BackendConfig::cli(provider, "default"),
            BackendType::RemoteOpenAI => {
                BackendConfig::openai(DEFAULT_OPENAI_MODEL, None) // Uses OPENAI_API_KEY from env
            }
            BackendType::RemoteAnthropic => {
                BackendConfig::anthropic(DEFAULT_ANTHROPIC_MODEL, None) // Uses ANTHROPIC_API_KEY from env
            }
            BackendType::RemoteOllama => {
                BackendConfig::ollama("llama3.2:3b") // Default Ollama model
            }
            BackendType::RemoteMlx => BackendConfig::mlx("default_model"),
            BackendType::RemoteLMStudio => {
                BackendConfig::lm_studio("local-model") // LM Studio model
            }
            BackendType::RemoteGitHub => {
                BackendConfig::github_models(DEFAULT_GITHUB_MODEL, None) // Uses GITHUB_TOKEN from env
            }
            BackendType::RemoteVllm => {
                BackendConfig::vllm("local-model") // vLLM model
            }
            BackendType::RemoteTensorRT => {
                BackendConfig::tensorrt("local-model") // TensorRT model
            }
            _ => {
                return Err(IronError::Configuration(format!(
                    "Backend {} auto-detection not supported. Please configure manually.",
                    backend_type.display_name()
                )));
            }
        };

        // Validate the config
        backend_config.validate()?;

        Ok(Self::with_backend(backend_config))
    }

    /// Create config with specific backend type
    #[allow(deprecated)]
    pub fn with_backend_type(backend_type: BackendType) -> Result<Self> {
        let backend_config = match backend_type {
            BackendType::IronWorks => BackendConfig::ironworks("default"),
            // CLI tools use whatever model they are configured for; "default" tells
            // the client not to override it.
            BackendType::Cli(provider) => BackendConfig::cli(provider, "default"),
            BackendType::RemoteOpenAI => BackendConfig::openai(DEFAULT_OPENAI_MODEL, None),
            BackendType::RemoteAnthropic => BackendConfig::anthropic(DEFAULT_ANTHROPIC_MODEL, None),
            BackendType::RemoteOllama => BackendConfig::ollama("llama3.2:3b"),
            BackendType::RemoteMlx => BackendConfig::mlx("default_model"),
            BackendType::RemoteLMStudio => BackendConfig::lm_studio("local-model"),
            BackendType::RemoteGitHub => BackendConfig::github_models(DEFAULT_GITHUB_MODEL, None),
            BackendType::RemoteVllm => BackendConfig::vllm("local-model"),
            BackendType::RemoteTensorRT => BackendConfig::tensorrt("local-model"),
            _ => {
                return Err(IronError::Configuration(format!(
                    "Backend {} is not supported or requires manual configuration",
                    backend_type.display_name()
                )));
            }
        };

        backend_config.validate()?;
        Ok(Self::with_backend(backend_config))
    }

    /// List available backends
    pub fn list_available_backends() -> Vec<BackendType> {
        let discovery = BackendDiscovery::discover();
        discovery.available().to_vec()
    }

    /// Backends confirmed available, and those with only an API key set, from
    /// one discovery pass. A key-only backend is not in the first list because
    /// nothing probed it; callers that showed only the first list hid it.
    pub fn list_available_and_configured_backends() -> (Vec<BackendType>, Vec<BackendType>) {
        let discovery = BackendDiscovery::discover();
        (
            discovery.available().to_vec(),
            discovery.configured().to_vec(),
        )
    }
}

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

/// Query result with timing information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentResponse {
    /// The query that was asked
    pub query: String,

    /// Agent's response
    pub response: String,

    /// Query type detected
    pub query_type: QueryType,

    /// Time taken for inference (milliseconds)
    pub inference_time_ms: u64,

    /// Whether response came from cache
    pub from_cache: bool,

    /// Timestamp of response
    pub timestamp: u64,
}

impl std::fmt::Display for AgentResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.response)
    }
}

impl AgentResponse {
    /// Check if response indicates an error
    pub fn is_error(&self) -> bool {
        self.response.starts_with("Error:")
            || self.response.starts_with("Unable to")
            || self.response.contains("not available")
    }
}

/// Lightweight AI agent for system analysis
#[derive(Clone)]
pub struct Agent {
    config: AgentConfig,
    engine: Arc<Mutex<Option<InferenceEngine>>>,
    cache: Arc<Mutex<lru::LruCache<String, (String, QueryType)>>>,
    initialized: Arc<Mutex<bool>>,
}

impl Agent {
    /// Create new agent with configuration
    ///
    /// Note: Model loading happens lazily on first query to avoid startup latency
    pub fn new(config: AgentConfig) -> Result<Self> {
        let cache_size = if config.enable_caching {
            std::num::NonZeroUsize::new(config.cache_size.max(1))
                .expect("max(1) guarantees non-zero")
        } else {
            // SAFETY: literal 1 is always non-zero
            std::num::NonZeroUsize::new(1).expect("literal 1 is non-zero")
        };

        Ok(Self {
            config,
            engine: Arc::new(Mutex::new(None)),
            cache: Arc::new(Mutex::new(lru::LruCache::new(cache_size))),
            initialized: Arc::new(Mutex::new(false)),
        })
    }

    /// Get the agent's configuration
    pub fn config(&self) -> &AgentConfig {
        &self.config
    }

    /// Check if agent is initialized (model loaded)
    pub fn is_initialized(&self) -> bool {
        *self.initialized.lock().unwrap()
    }

    /// Initialize agent (load model) - called automatically on first query
    fn initialize(&self) -> Result<()> {
        let mut initialized = self.initialized.lock().unwrap();
        if *initialized {
            return Ok(());
        }

        // Initialize inference engine
        let mut engine_lock = self.engine.lock().unwrap();
        if engine_lock.is_none() {
            let engine = InferenceEngine::new(&self.config)?;
            *engine_lock = Some(engine);
        }

        *initialized = true;
        Ok(())
    }

    /// Ask agent a question about the system
    ///
    /// This is the main entry point for user queries. The agent will:
    /// 1. Parse the query and determine intent
    /// 2. Offer registered read-only tools to the configured model
    /// 3. Generate a contextual response using the reasoning model
    /// 4. Return fresh evidence without question-only caching
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ironmonitor::agent::{Agent, AgentConfig};
    /// # use ironmonitor::UnifiedMonitor;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut agent = Agent::new(AgentConfig::default())?;
    /// let monitor = UnifiedMonitor::new()?;
    ///
    /// let response = agent.ask("What's my GPU utilization?", &monitor)?;
    /// println!("Agent: {}", response.response);
    /// # Ok(())
    /// # }
    /// ```
    pub fn ask(&mut self, question: &str, _monitor: &UnifiedMonitor) -> Result<AgentResponse> {
        self.ask_with_control(question, &tool_runtime::RunControl::default())
    }

    /// Ask with live read-only tools, cancellation and optional progress events.
    /// Live answers are never reused from the question-only response cache.
    pub fn ask_with_control(
        &mut self,
        question: &str,
        control: &tool_runtime::RunControl,
    ) -> Result<AgentResponse> {
        self.ask_run(
            question,
            control,
            Duration::from_secs(self.config.timeout_seconds),
        )
    }

    fn ask_run(
        &mut self,
        question: &str,
        control: &tool_runtime::RunControl,
        budget: Duration,
    ) -> Result<AgentResponse> {
        self.ask_run_with_history(question, &[], control, budget)
    }

    /// Ask a follow-up with completed conversational exchanges. Prior readings
    /// are reference context; live questions still request fresh tool evidence.
    pub fn ask_with_history_and_control(
        &mut self,
        question: &str,
        history: &[tool_runtime::ConversationTurn],
        control: &tool_runtime::RunControl,
    ) -> Result<AgentResponse> {
        self.ask_run_with_history(
            question,
            history,
            control,
            Duration::from_secs(self.config.timeout_seconds),
        )
    }

    fn ask_run_with_history(
        &mut self,
        question: &str,
        history: &[tool_runtime::ConversationTurn],
        control: &tool_runtime::RunControl,
        budget: Duration,
    ) -> Result<AgentResponse> {
        self.refuse_if_offline_and_offhost()?;
        if control.is_cancelled() {
            return Err(IronError::Agent("Agent run cancelled".into()));
        }
        if question.trim().is_empty() {
            return Err(IronError::Agent("Question is empty".into()));
        }
        let start = Instant::now();
        self.initialize()?;
        let response_text = {
            let engine_lock = self
                .engine
                .try_lock()
                .map_err(|_| IronError::Agent("Agent is already running a query".into()))?;
            let engine = engine_lock
                .as_ref()
                .ok_or_else(|| IronError::Agent("Agent not initialized".into()))?;
            engine.generate_tool_response_with_history(
                question,
                history,
                budget.saturating_sub(start.elapsed()),
                control,
            )?
        };
        Ok(AgentResponse {
            query: question.to_string(),
            response: response_text,
            query_type: Query::parse(question).query_type,
            inference_time_ms: start.elapsed().as_millis() as u64,
            from_cache: false,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        })
    }
    /// Refuse to answer if `--offline` is set and the backend would send the
    /// question off this machine.
    ///
    /// `--offline` set an environment variable, printed that all network features
    /// were disabled, and enforced nothing: `is_offline_mode` had no callers outside
    /// its own module. A user who passed the flag and asked a hosted provider about
    /// their machine had their hardware inventory — GPU UUIDs and PCI bus ids
    /// included — sent to that vendor, while the tool told them it would not be.
    ///
    /// The check is on `runs_on_host` rather than on "is a network call", because
    /// the distinction that matters for privacy is whether data leaves the machine.
    /// A model served over loopback is not egress; a CLI tool that relays the prompt
    /// to its vendor is, even though it is a local process.
    fn refuse_if_offline_and_offhost(&self) -> Result<()> {
        if !crate::consent::is_offline_mode() {
            return Ok(());
        }
        let Some(backend) = self.config.backend.as_ref() else {
            return Ok(());
        };
        if backend.backend_type.runs_on_host() {
            return Ok(());
        }
        Err(crate::error::IronError::Other(format!(
            "refusing to query {:?} in offline mode: it would send this machine's \
             hardware details off-host. Use a backend that runs locally (IronWorks, \
             Ollama), or drop --offline if you intend the data to leave.",
            backend.backend_type
        )))
    }

    /// Ask with an explicit overall deadline for model rounds and tool waits.
    pub fn ask_with_timeout(
        &mut self,
        question: &str,
        monitor: &UnifiedMonitor,
        timeout: Duration,
    ) -> Result<AgentResponse> {
        let _ = monitor;
        self.ask_run(question, &tool_runtime::RunControl::default(), timeout)
    }

    /// Clear response cache
    pub fn clear_cache(&mut self) {
        let mut cache = self.cache.lock().unwrap();
        cache.clear();
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> (usize, usize) {
        let cache = self.cache.lock().unwrap();
        (cache.len(), cache.cap().get())
    }

    /// Get current cache size (number of entries)
    pub fn cache_size(&self) -> usize {
        let cache = self.cache.lock().unwrap();
        cache.len()
    }

    /// Preload model (warm start) - optional, to avoid first-query latency
    pub fn preload(&mut self) -> Result<()> {
        self.initialize()
    }
}

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

    #[test]
    fn test_model_size_properties() {
        assert_eq!(ModelSize::Small.latency_estimate_ms(), 75);
        assert_eq!(ModelSize::Medium.latency_estimate_ms(), 150);
        assert_eq!(ModelSize::Large.latency_estimate_ms(), 350);

        assert_eq!(ModelSize::Small.memory_mb(), 200);
        assert_eq!(ModelSize::Medium.memory_mb(), 1000);
        assert_eq!(ModelSize::Large.memory_mb(), 2000);
    }

    #[test]
    fn test_config_defaults() {
        let config = AgentConfig::default();
        assert_eq!(config.model_size, ModelSize::Medium);
        assert!(config.enable_caching);
        assert_eq!(config.temperature, 0.3);
        assert_eq!(config.max_response_tokens, 256);
    }

    #[test]
    fn test_config_builder() {
        let config = AgentConfig::new(ModelSize::Large)
            .with_temperature(0.7)
            .with_max_tokens(512)
            .without_caching();

        assert_eq!(config.model_size, ModelSize::Large);
        assert_eq!(config.temperature, 0.7);
        assert_eq!(config.max_response_tokens, 512);
        assert!(!config.enable_caching);
    }
}

#[cfg(test)]
mod offline_enforcement_tests {
    use super::*;
    use crate::agent::backend::BackendConfig;

    /// Serialised because these mutate a process-wide environment variable.
    pub(super) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn agent_with(backend: BackendConfig) -> Agent {
        let config = AgentConfig::with_backend(backend);
        Agent::new(config).expect("agent construction should not require a live backend")
    }

    /// The flag has to actually stop the send. It previously set an environment
    /// variable, announced that all network features were disabled, and enforced
    /// nothing — `is_offline_mode` had no callers.
    #[test]
    fn offline_refuses_a_backend_that_would_send_data_off_host() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("IRONMON_OFFLINE", "1");

        let agent = agent_with(BackendConfig::anthropic(
            DEFAULT_ANTHROPIC_MODEL,
            Some("test".into()),
        ));
        let err = agent
            .refuse_if_offline_and_offhost()
            .expect_err("a hosted provider must be refused in offline mode");
        let msg = err.to_string();
        assert!(
            msg.contains("offline mode"),
            "the refusal should say why: {msg}"
        );
        assert!(
            msg.contains("locally") || msg.contains("Ollama"),
            "the refusal should name a way forward: {msg}"
        );

        std::env::remove_var("IRONMON_OFFLINE");
    }

    /// Over-blocking would make the flag useless for the private path it exists to
    /// protect: a model served over loopback is not egress.
    #[test]
    fn offline_permits_a_backend_that_runs_on_this_machine() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        std::env::set_var("IRONMON_OFFLINE", "1");

        let agent = agent_with(BackendConfig::ironworks("test-model"));
        assert!(
            agent.refuse_if_offline_and_offhost().is_ok(),
            "on-host inference must remain usable in offline mode, or the flag \
             pushes users toward the hosted path it is meant to avoid"
        );

        std::env::remove_var("IRONMON_OFFLINE");
    }

    /// Without the flag nothing changes; the guard must not alter default behaviour.
    #[test]
    fn without_offline_a_hosted_backend_is_permitted() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        std::env::remove_var("IRONMON_OFFLINE");

        let agent = agent_with(BackendConfig::anthropic(
            DEFAULT_ANTHROPIC_MODEL,
            Some("test".into()),
        ));
        assert!(agent.refuse_if_offline_and_offhost().is_ok());
    }
}