mermaid-cli 0.14.1

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
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
use crate::constants::{DEFAULT_MAX_TOKENS, DEFAULT_OLLAMA_PORT, DEFAULT_TEMPERATURE};
use crate::models::ReasoningLevel;
use crate::runtime::{PolicyOverride, SafetyMode};
use anyhow::{Context, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Main configuration structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    /// Last used model (persisted between sessions)
    #[serde(default)]
    pub last_used_model: Option<String>,

    /// Default model configuration
    #[serde(default)]
    pub default_model: ModelSettings,

    /// Ollama configuration
    #[serde(default)]
    pub ollama: OllamaConfig,

    /// Non-interactive mode configuration
    #[serde(default)]
    pub non_interactive: NonInteractiveConfig,

    /// MCP server configurations
    #[serde(default)]
    pub mcp_servers: HashMap<String, McpServerConfig>,

    /// User overrides + custom OpenAI-compatible providers. Keys are
    /// provider names; matching a built-in registry entry overrides its
    /// defaults, anything else defines a fully custom provider.
    /// Example:
    /// ```toml
    /// [providers.groq]
    /// api_key_env = "MY_GROQ_KEY"  # override default GROQ_API_KEY
    ///
    /// [providers.my-vllm]
    /// base_url = "http://192.168.1.42:8000/v1"
    /// api_key_env = "VLLM_KEY"
    /// compat = "openai-effort"
    /// ```
    #[serde(default)]
    pub providers: HashMap<String, UserProviderConfig>,

    /// Per-model reasoning preferences keyed by full model ID
    /// (`provider/name`). Set when the user runs `/reasoning <level>` or
    /// Alt+T cycles while using a specific model — the new value sticks
    /// for that model until changed. Falls back to
    /// `default_model.reasoning` when no entry exists.
    /// Example:
    /// ```toml
    /// [reasoning_per_model]
    /// "<provider>/<model>" = "high"
    /// "ollama/qwen3-coder:30b" = "low"
    /// ```
    #[serde(default)]
    pub reasoning_per_model: HashMap<String, ReasoningLevel>,

    /// Per-model Ollama `num_ctx` override set via `/context <n>`/`max`. Beats
    /// auto-fit; cleared by `/context auto`. Keyed by model id.
    ///
    /// Example:
    /// ```toml
    /// [ollama_num_ctx_per_model]
    /// "ollama/ornith:9b" = 131072
    /// ```
    #[serde(default)]
    pub ollama_num_ctx_per_model: HashMap<String, u32>,

    /// Named model profiles that agents/plugins can request without
    /// hardcoding a concrete provider model. Values are full model IDs.
    /// Example:
    /// ```toml
    /// [model_profiles]
    /// fast = "ollama/qwen3-coder:14b"
    /// large-context = "openai/<model>"
    /// tool-strong = "anthropic/<model>"
    /// vision = "gemini/gemini-2.5-pro"
    /// cheap = "groq/llama-3.3-70b-versatile"
    /// ```
    #[serde(default)]
    pub model_profiles: HashMap<String, String>,

    /// Runtime safety policy. Defaults to `Ask` so mutations / shell /
    /// network actions require approval out of the box; users opt into
    /// `Auto` (LLM-vetted) or `FullAccess` deliberately.
    #[serde(default)]
    pub safety: SafetyConfig,

    /// Durable semantic memory settings.
    #[serde(default)]
    pub memory: MemoryConfig,

    /// Context-compaction settings.
    #[serde(default)]
    pub compaction: CompactionConfig,

    /// Computer-use (desktop control) preferences.
    #[serde(default)]
    pub computer_use: ComputerUseConfig,

    /// Runtime-only prompt customizations supplied by CLI flags. These are
    /// deliberately skipped when saving config so one-off agent personas do
    /// not pollute the user's persistent Mermaid settings.
    #[serde(skip)]
    pub prompt: PromptConfig,
}

#[derive(Debug, Clone, Default)]
pub struct PromptConfig {
    pub system_prompt: Option<String>,
    pub append_system_prompt: Vec<String>,
}

impl PromptConfig {
    pub fn render_system_prompt(&self, default_prompt: &str) -> String {
        let mut rendered = self
            .system_prompt
            .as_deref()
            .unwrap_or(default_prompt)
            .trim_end()
            .to_string();

        for extra in &self.append_system_prompt {
            let extra = extra.trim();
            if extra.is_empty() {
                continue;
            }
            if !rendered.is_empty() {
                rendered.push_str("\n\n");
            }
            rendered.push_str(extra);
        }

        rendered
    }

    pub fn is_customized(&self) -> bool {
        self.system_prompt.is_some() || !self.append_system_prompt.is_empty()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SafetyConfig {
    pub mode: SafetyMode,
    pub checkpoint_on_mutation: bool,
    #[serde(default)]
    pub overrides: Vec<PolicyOverride>,
    /// Model id the `Auto`-mode safety classifier uses to vet borderline
    /// actions. `None` ⇒ vet with the session's active model. Set this to
    /// point the vet at a cheaper/faster model than the one driving the work.
    #[serde(default)]
    pub auto_classifier_model: Option<String>,
    /// Headless escape hatch: when true, non-replayable tools (web/mcp/
    /// subagent/computer_use) are allowed to PROCEED on an `Ask` decision in a
    /// headless run (no approval UI) instead of being blocked. Default `false`
    /// — `mermaid run` in `ask` mode otherwise refuses these. Set via
    /// `--allow-untrusted-tools` or config for CI that needs them.
    #[serde(default)]
    pub allow_untrusted_headless_tools: bool,
}

impl Default for SafetyConfig {
    fn default() -> Self {
        Self {
            // Safe-by-default: the first run prompts for approval on
            // mutations / shell / network rather than silently auto-allowing
            // everything. FullAccess remains available via config.
            mode: SafetyMode::Ask,
            checkpoint_on_mutation: true,
            overrides: Vec::new(),
            auto_classifier_model: None,
            allow_untrusted_headless_tools: false,
        }
    }
}

/// Durable semantic memory settings (v0.10.0).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryConfig {
    /// Master switch for agent memory (the tool, the always-loaded index, and
    /// the slash commands). On by default.
    pub enabled: bool,
    /// Byte cap on the always-loaded memory index before it's truncated.
    pub index_cap_bytes: usize,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            index_cap_bytes: crate::constants::MAX_MEMORY_INDEX_BYTES,
        }
    }
}

/// Context-compaction settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CompactionConfig {
    /// Cap on consecutive auto-compact-and-continue recoveries after a
    /// context-window truncation, before the run stops and shows the manual
    /// levers (`/context max`, `/context offload on`). The counter resets
    /// whenever the run makes progress, so this bounds only no-progress
    /// thrashing on a too-small window. `0` means uncapped.
    ///
    /// Example:
    /// ```toml
    /// [compaction]
    /// max_truncation_recoveries = 0  # never give up on its own
    /// ```
    pub max_truncation_recoveries: u8,
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            max_truncation_recoveries: crate::constants::COMPACTION_MAX_TRUNCATION_RECOVERIES,
        }
    }
}

/// Computer-use (desktop control) preferences.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ComputerUseConfig {
    /// After a successful click / type_text / press_key, auto-capture the
    /// focused window and attach it inline so the model can verify the result.
    /// On by default (non-breaking); set false to cut the per-action capture
    /// cost + image tokens when visual feedback isn't needed. The model can
    /// still call `screenshot` explicitly.
    pub auto_screenshot: bool,
}

impl Default for ComputerUseConfig {
    fn default() -> Self {
        Self {
            auto_screenshot: true,
        }
    }
}

/// User-supplied OpenAI-compatible provider configuration. All fields are
/// optional — when matching a built-in registry entry, only the supplied
/// fields override; the rest fall back to the registry defaults. For
/// fully custom providers, `base_url` and `api_key_env` are required.
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct UserProviderConfig {
    /// Override base URL for `/chat/completions` (None = use built-in
    /// registry default; required for fully custom providers).
    #[serde(default)]
    pub base_url: Option<String>,
    /// Env var name to read the API key from (None = use the built-in
    /// registry default like `GROQ_API_KEY`; required for fully custom
    /// providers).
    #[serde(default)]
    pub api_key_env: Option<String>,
    /// Extra HTTP headers sent on every request to this provider.
    #[serde(default)]
    pub extra_headers: HashMap<String, String>,
    /// For fully custom providers (no built-in registry entry), declares
    /// which OpenAI-compatible shape the endpoint speaks. Ignored when
    /// the provider name matches a built-in registry entry. Values:
    /// `"openai"` (no reasoning), `"openai-effort"` (`reasoning_effort`
    /// field), `"openrouter"` (nested `reasoning: {effort}` object).
    #[serde(default)]
    pub compat: Option<String>,
    /// Optional preferred model — surfaced by `mermaid status` and used
    /// as the default when the user picks this provider with no model
    /// suffix.
    #[serde(default)]
    pub default_model: Option<String>,
}

/// MCP server configuration
#[derive(Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Command to execute (e.g., "npx", "node", "python")
    pub command: String,
    /// Command-line arguments
    #[serde(default)]
    pub args: Vec<String>,
    /// Environment variables for the server process
    #[serde(default)]
    pub env: HashMap<String, String>,
}

/// Mask a header/env map for `Debug`: keys are kept (so you can still see which
/// vars are set) but values are never rendered — they hold secrets like API keys
/// and `Authorization` tokens (#F12). A `BTreeMap` keeps the output deterministic.
fn debug_masked_map(
    map: &HashMap<String, String>,
) -> std::collections::BTreeMap<&str, &'static str> {
    map.keys().map(|k| (k.as_str(), "[REDACTED]")).collect()
}

// Manual `Debug` for the secret-bearing config structs so a `{:?}` (into
// tracing, a panic, or an error) cannot dump provider keys / Authorization
// headers / MCP env secrets. `Config` keeps its derived `Debug`, which now
// recurses through these redacting impls (#F12).
impl std::fmt::Debug for McpServerConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpServerConfig")
            .field("command", &self.command)
            // args may carry an inline secret (e.g. `--api-key=sk-...`).
            .field(
                "args",
                &self
                    .args
                    .iter()
                    .map(|a| crate::utils::redact_secrets(a))
                    .collect::<Vec<_>>(),
            )
            .field("env", &debug_masked_map(&self.env))
            .finish()
    }
}

impl std::fmt::Debug for UserProviderConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UserProviderConfig")
            .field("base_url", &self.base_url)
            .field("api_key_env", &self.api_key_env)
            .field("extra_headers", &debug_masked_map(&self.extra_headers))
            .field("compat", &self.compat)
            .field("default_model", &self.default_model)
            .finish()
    }
}

/// Default model settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ModelSettings {
    /// Model provider (ollama, openai, anthropic)
    pub provider: String,
    /// Model name
    pub name: String,
    /// Temperature for generation
    pub temperature: f32,
    /// Maximum tokens to generate
    pub max_tokens: usize,
    /// Default reasoning depth used for new sessions when no `--reasoning`
    /// flag is given. Each adapter snaps this onto the closest level the
    /// model actually supports via `nearest_effort()`.
    pub reasoning: ReasoningLevel,
}

impl Default for ModelSettings {
    fn default() -> Self {
        Self {
            provider: String::new(),
            name: String::new(),
            temperature: DEFAULT_TEMPERATURE,
            max_tokens: DEFAULT_MAX_TOKENS,
            reasoning: ReasoningLevel::default(),
        }
    }
}

/// Ollama configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct OllamaConfig {
    /// Ollama server host
    pub host: String,
    /// Ollama server port
    pub port: u16,
    /// Number of GPU layers to offload (None = auto, 0 = CPU only, positive = specific count)
    /// Lower values free up VRAM for larger models at the cost of speed
    pub num_gpu: Option<i32>,
    /// Number of CPU threads for processing offloaded layers
    /// Higher values improve CPU inference speed for large models
    pub num_thread: Option<i32>,
    /// Context window size (number of tokens)
    /// Larger values allow longer conversations but use more memory
    pub num_ctx: Option<i32>,
    /// Enable NUMA optimization for multi-CPU systems
    pub numa: Option<bool>,
    /// Allow Ollama to offload the model/KV cache to system RAM when it doesn't
    /// fit VRAM. **Disabled by default**: RAM offload is 5–20× slower, so by
    /// default Mermaid auto-fits `num_ctx` to VRAM (keeping the model on the
    /// GPU). Enable to trade speed for a larger context window. Toggle in-app
    /// with `/context offload on|off`.
    pub allow_ram_offload: bool,
    /// Optional hard cap on the auto-fitted context window (in tokens). `None`
    /// lets auto-fit use the full memory budget up to the model's max; set this
    /// to bound it (e.g. to leave VRAM headroom for other apps).
    pub max_auto_num_ctx: Option<usize>,
}

impl Default for OllamaConfig {
    fn default() -> Self {
        Self {
            host: String::from("localhost"),
            port: DEFAULT_OLLAMA_PORT,
            num_gpu: None,            // Let Ollama auto-detect
            num_thread: None,         // Let Ollama auto-detect
            num_ctx: None,            // Use model default (overrides auto-fit)
            numa: None,               // Auto-detect
            allow_ram_offload: false, // VRAM-only by default (RAM is slow)
            max_auto_num_ctx: None,   // No cap; auto-fit to the memory budget
        }
    }
}

/// Non-interactive mode configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct NonInteractiveConfig {
    /// Output format (text, json, markdown)
    pub output_format: String,
    /// Maximum tokens to generate
    pub max_tokens: usize,
    /// Don't execute agent actions (dry run)
    pub no_execute: bool,
}

impl Default for NonInteractiveConfig {
    fn default() -> Self {
        Self {
            output_format: String::from("text"),
            max_tokens: DEFAULT_MAX_TOKENS,
            no_execute: false,
        }
    }
}

/// Load configuration from single config file
/// Priority: config file > defaults (that's it - no merging, no env vars)
pub fn load_config() -> Result<Config> {
    let config_path = get_config_path()?;

    if config_path.exists() {
        let toml_str = std::fs::read_to_string(&config_path)
            .with_context(|| format!("Failed to read {}", config_path.display()))?;
        let config: Config = toml::from_str(&toml_str).with_context(|| {
            format!(
                "Failed to parse {}. Run 'mermaid init' to regenerate.",
                config_path.display()
            )
        })?;
        Ok(config)
    } else {
        Ok(Config::default())
    }
}

/// Like [`load_config`] but never fails: if a config file exists yet is
/// malformed, warn on stderr and fall back to defaults — instead of silently
/// swallowing the error (#111). An *absent* file is not an error (`load_config`
/// returns defaults for it), so the warning fires only for a genuine
/// read/parse failure the user should know about.
pub fn load_config_or_warn() -> Config {
    match load_config() {
        Ok(config) => config,
        Err(e) => {
            // A TOML parse error renders the offending source line, which can be
            // a secret-bearing one (`extra_headers`/`env`/`api_key_env`); scrub
            // credential-shaped content before it reaches stderr (#F13).
            eprintln!(
                "mermaid: {}",
                crate::utils::redact_secrets(&format!("{e:#}"))
            );
            Config::default()
        },
    }
}

/// Get the path to the single config file
pub fn get_config_path() -> Result<PathBuf> {
    Ok(get_config_dir()?.join("config.toml"))
}

/// Get the configuration directory
pub fn get_config_dir() -> Result<PathBuf> {
    if let Some(proj_dirs) = ProjectDirs::from("", "", "mermaid") {
        let config_dir = proj_dirs.config_dir();
        std::fs::create_dir_all(config_dir)?;
        Ok(config_dir.to_path_buf())
    } else {
        // Fallback to home directory
        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .context("Could not determine home directory")?;
        let config_dir = PathBuf::from(home).join(".config").join("mermaid");
        std::fs::create_dir_all(&config_dir)?;
        Ok(config_dir)
    }
}

/// Save configuration to file
pub fn save_config(config: &Config, path: Option<PathBuf>) -> Result<()> {
    let path = if let Some(p) = path {
        p
    } else {
        get_config_dir()?.join("config.toml")
    };

    let toml_string = toml::to_string_pretty(config)?;

    // The config can carry literal secrets — `mcp_servers[].env`,
    // `mcp_servers[].args`, and `providers[].extra_headers` all accept inline
    // credential values — so it must not be left world-readable at umask. On
    // Unix, create it 0600 from the start (and tighten an already-existing
    // file, whose perms a fresh `mode()` would not touch). Windows uses ACLs;
    // leave its default.
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&path)
            .with_context(|| format!("Failed to write config to {}", path.display()))?;
        // `mode()` only applies on create; tighten a pre-existing config too.
        let _ = file.set_permissions(std::fs::Permissions::from_mode(0o600));
        file.write_all(toml_string.as_bytes())
            .with_context(|| format!("Failed to write config to {}", path.display()))?;
    }
    #[cfg(not(unix))]
    {
        std::fs::write(&path, toml_string)
            .with_context(|| format!("Failed to write config to {}", path.display()))?;
    }

    Ok(())
}

/// Create a default configuration file if it doesn't exist
pub fn init_config() -> Result<()> {
    let config_file = get_config_path()?;

    if config_file.exists() {
        println!("Configuration already exists at: {}", config_file.display());
    } else {
        let default_config = Config::default();
        save_config(&default_config, Some(config_file.clone()))?;
        println!("Created configuration at: {}", config_file.display());
    }

    Ok(())
}

/// Serializes the read-modify-write persistence path. The `persist_*` helpers
/// run as concurrent detached tasks (dispatched by the effect runner) that all
/// load → mutate → save the same file; without a lock two quick toggles
/// (`/model` then Alt+T) can interleave their loads and lose one write. Held
/// only across the synchronous fs work — never across an `.await`.
static PERSIST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Load the config, apply `mutate`, and save it back — under `PERSIST_LOCK` so
/// concurrent persists can't clobber each other. On a malformed config the error
/// propagates (the caller drops it) rather than overwriting the file with
/// defaults (#111).
fn update_config(mutate: impl FnOnce(&mut Config)) -> Result<()> {
    let _guard = PERSIST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let mut config = load_config()?;
    mutate(&mut config);
    save_config(&config, None)
}

/// Persist the last used model to config file.
pub fn persist_last_model(model: &str) -> Result<()> {
    update_config(|config| config.last_used_model = Some(model.to_string()))
}

/// Persist the user's default reasoning level to config file. Used by the
/// `/reasoning` slash command and the Alt+T cycle handler so the choice survives
/// across sessions.
pub fn persist_default_reasoning(level: ReasoningLevel) -> Result<()> {
    update_config(|config| config.default_model.reasoning = level)
}

/// Persist a reasoning level for a specific model ID
/// (e.g. `<provider>/<model>`). The TUI calls this from Alt+T,
/// `/reasoning <level>`, and the does-not-support-thinking auto-snap so
/// the choice sticks per-model rather than bleeding into other models on
/// next session start.
pub fn persist_reasoning_for_model(model_id: &str, level: ReasoningLevel) -> Result<()> {
    update_config(|config| {
        config
            .reasoning_per_model
            .insert(model_id.to_string(), level);
    })
}

/// Persist (or clear) a per-model Ollama `num_ctx` override. `Some(n)` sets it,
/// `None` removes the entry (returning that model to auto-fit).
pub fn persist_ollama_num_ctx_for_model(model_id: &str, num_ctx: Option<u32>) -> Result<()> {
    update_config(|config| match num_ctx {
        Some(n) => {
            config
                .ollama_num_ctx_per_model
                .insert(model_id.to_string(), n);
        },
        None => {
            config.ollama_num_ctx_per_model.remove(model_id);
        },
    })
}

/// Persist the Ollama RAM-offload toggle (`/context offload on|off`).
pub fn persist_ollama_allow_ram_offload(enabled: bool) -> Result<()> {
    update_config(|config| config.ollama.allow_ram_offload = enabled)
}

/// Resolve which model to use: CLI arg > last_used > default_model > any available
pub async fn resolve_model_id(cli_model: Option<&str>, config: &Config) -> anyhow::Result<String> {
    if let Some(model) = cli_model {
        if let Some(resolved) = resolve_model_profile_alias(model, config)? {
            return Ok(resolved);
        }
        return Ok(model.to_string());
    }
    if let Some(last_model) = &config.last_used_model {
        if let Some(resolved) = resolve_model_profile_alias(last_model, config)? {
            return Ok(resolved);
        }
        return Ok(last_model.clone());
    }
    if !config.default_model.provider.is_empty() && !config.default_model.name.is_empty() {
        return Ok(format!(
            "{}/{}",
            config.default_model.provider, config.default_model.name
        ));
    }
    let available = crate::ollama::require_any_model(config).await?;
    // `require_any_model` already errors on empty, so this `.first()` is
    // never `None` in practice. Use `.first()` over `[0]` so the precondition
    // is enforced by the type system instead of by a comment.
    let first = available
        .first()
        .ok_or_else(|| anyhow::anyhow!("require_any_model returned empty list"))?;
    Ok(format!("ollama/{}", first))
}

fn resolve_model_profile_alias(requested: &str, config: &Config) -> anyhow::Result<Option<String>> {
    let profile = requested.strip_prefix("profile:").unwrap_or(requested);
    if let Some(model) = config.model_profiles.get(profile) {
        anyhow::ensure!(
            !model.trim().is_empty(),
            "model profile `{}` is configured with an empty model id",
            profile
        );
        return Ok(Some(model.clone()));
    }
    if requested.starts_with("profile:") {
        anyhow::bail!(
            "model profile `{}` is not configured; add it under [model_profiles]",
            profile
        );
    }
    Ok(None)
}

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

    /// Configs persisted before Step 4 don't have a `reasoning` field on
    /// `[default_model]`. Loading them must succeed and yield the
    /// `Medium` default — otherwise existing user configs break on
    /// upgrade.
    #[test]
    fn model_settings_deserializes_without_reasoning_field() {
        let toml_blob = r#"
            provider = "ollama"
            name = "qwen3-coder:30b"
            temperature = 0.7
            max_tokens = 4096
        "#;
        let settings: ModelSettings = toml::from_str(toml_blob).expect("backward compat");
        assert_eq!(settings.reasoning, ReasoningLevel::Medium);
        assert_eq!(settings.provider, "ollama");
    }

    #[test]
    fn model_settings_round_trips_reasoning_high() {
        let original = ModelSettings {
            provider: "anthropic".to_string(),
            name: "claude-sonnet-4-6".to_string(),
            temperature: 0.5,
            max_tokens: 8192,
            reasoning: ReasoningLevel::High,
        };
        let toml_blob = toml::to_string(&original).expect("serialize");
        let back: ModelSettings = toml::from_str(&toml_blob).expect("deserialize");
        assert_eq!(back.reasoning, ReasoningLevel::High);
        assert_eq!(back.name, "claude-sonnet-4-6");
    }

    #[test]
    fn configured_model_profile_resolves_explicit_alias() {
        let mut config = Config::default();
        config
            .model_profiles
            .insert("fast".to_string(), "ollama/qwen3-coder:14b".to_string());
        assert_eq!(
            resolve_model_profile_alias("fast", &config).unwrap(),
            Some("ollama/qwen3-coder:14b".to_string())
        );
        assert_eq!(
            resolve_model_profile_alias("profile:fast", &config).unwrap(),
            Some("ollama/qwen3-coder:14b".to_string())
        );
    }

    #[test]
    fn profile_prefix_requires_configuration() {
        let config = Config::default();
        assert!(resolve_model_profile_alias("profile:vision", &config).is_err());
        assert_eq!(
            resolve_model_profile_alias("vision", &config).unwrap(),
            None
        );
    }

    /// `persist_default_reasoning` writes to the real config path, so
    /// this test goes through `save_config(_, Some(path))` directly to
    /// avoid clobbering the user's actual `~/.config/mermaid/config.toml`.
    /// Uses `std::env::temp_dir` (matching the pattern in
    /// `session::conversation` and `utils::logger`) — no external
    /// `tempfile` crate dependency.
    #[test]
    fn save_and_reload_preserves_reasoning_field() {
        let dir = std::env::temp_dir().join("mermaid_test_config_reasoning");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");

        let mut cfg = Config::default();
        cfg.default_model.provider = "ollama".to_string();
        cfg.default_model.name = "qwen3-coder:30b".to_string();
        cfg.default_model.reasoning = ReasoningLevel::Low;

        save_config(&cfg, Some(path.clone())).expect("save");

        let blob = std::fs::read_to_string(&path).expect("read");
        let loaded: Config = toml::from_str(&blob).expect("parse back");
        assert_eq!(loaded.default_model.reasoning, ReasoningLevel::Low);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Per-model entries serialize as a TOML table with quoted keys (the
    /// model IDs contain `/`). This test verifies the round-trip works
    /// through both serialization and deserialization, matching what
    /// `persist_reasoning_for_model` would produce in real use.
    #[test]
    fn save_and_reload_preserves_reasoning_per_model_table() {
        let dir = std::env::temp_dir().join("mermaid_test_config_per_model_reasoning");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");

        let mut cfg = Config::default();
        cfg.reasoning_per_model.insert(
            "anthropic/claude-sonnet-4-6".to_string(),
            ReasoningLevel::High,
        );
        cfg.reasoning_per_model
            .insert("ollama/qwen3-coder:30b".to_string(), ReasoningLevel::Low);

        save_config(&cfg, Some(path.clone())).expect("save");

        let blob = std::fs::read_to_string(&path).expect("read");
        let loaded: Config = toml::from_str(&blob).expect("parse back");
        assert_eq!(
            loaded
                .reasoning_per_model
                .get("anthropic/claude-sonnet-4-6"),
            Some(&ReasoningLevel::High)
        );
        assert_eq!(
            loaded.reasoning_per_model.get("ollama/qwen3-coder:30b"),
            Some(&ReasoningLevel::Low)
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `/context <n>` overrides round-trip through the per-model TOML table, and
    /// the offload toggle persists on `[ollama]`.
    #[test]
    fn save_and_reload_preserves_ollama_context_overrides() {
        let dir = std::env::temp_dir().join("mermaid_test_config_ollama_ctx");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");

        let mut cfg = Config::default();
        cfg.ollama_num_ctx_per_model
            .insert("ollama/ornith:9b".to_string(), 131_072);
        cfg.ollama.allow_ram_offload = true;
        cfg.ollama.max_auto_num_ctx = Some(65_536);

        save_config(&cfg, Some(path.clone())).expect("save");
        let blob = std::fs::read_to_string(&path).expect("read");
        let loaded: Config = toml::from_str(&blob).expect("parse back");

        assert_eq!(
            loaded.ollama_num_ctx_per_model.get("ollama/ornith:9b"),
            Some(&131_072)
        );
        assert!(loaded.ollama.allow_ram_offload);
        assert_eq!(loaded.ollama.max_auto_num_ctx, Some(65_536));

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Older configs have neither the per-model num_ctx table nor the new
    /// `[ollama]` keys; loading must default cleanly (empty map, offload off).
    #[test]
    fn config_deserializes_without_ollama_context_keys() {
        let toml_blob = r#"
[ollama]
host = "localhost"
port = 11434
"#;
        let cfg: Config = toml::from_str(toml_blob).expect("parse");
        assert!(cfg.ollama_num_ctx_per_model.is_empty());
        assert!(!cfg.ollama.allow_ram_offload);
        assert_eq!(cfg.ollama.max_auto_num_ctx, None);
    }

    /// Configs from before Step 5b don't have a `reasoning_per_model`
    /// section. Loading them must succeed with an empty map — otherwise
    /// upgrade breaks every existing user.
    #[test]
    fn config_deserializes_without_reasoning_per_model() {
        let toml_blob = r#"
            last_used_model = "ollama/qwen3-coder:30b"

            [default_model]
            provider = "ollama"
            name = "qwen3-coder:30b"
            temperature = 0.7
            max_tokens = 4096
        "#;
        let cfg: Config = toml::from_str(toml_blob).expect("backward compat");
        assert!(cfg.reasoning_per_model.is_empty());
        assert!(!cfg.prompt.is_customized());
    }

    /// Config holds inline-secret-capable fields (`mcp_servers[].env`, `args`,
    /// `providers[].extra_headers`), so it must be written owner-only rather
    /// than inheriting a world-readable umask.
    #[cfg(unix)]
    #[test]
    fn save_config_writes_owner_only_perms() {
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join("mermaid_test_config_perms");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let path = dir.join("config.toml");
        // Pre-create a world-readable file to prove we also tighten existing.
        std::fs::write(&path, "stale").expect("seed");
        let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644));

        save_config(&Config::default(), Some(path.clone())).expect("save");
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "config must be written owner-only");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn config_defaults_computer_use_auto_screenshot_on() {
        // An empty/legacy config must keep the auto-screenshot behavior (#98).
        let cfg: Config = toml::from_str("").expect("empty config");
        assert!(cfg.computer_use.auto_screenshot);
    }

    #[test]
    fn prompt_config_replaces_and_appends_without_persisting() {
        let mut cfg = Config::default();
        cfg.prompt.system_prompt = Some("base".to_string());
        cfg.prompt
            .append_system_prompt
            .push("extra instructions".to_string());

        assert_eq!(
            cfg.prompt.render_system_prompt("default"),
            "base\n\nextra instructions"
        );

        let blob = toml::to_string(&cfg).expect("serialize");
        assert!(!blob.contains("extra instructions"));
        let loaded: Config = toml::from_str(&blob).expect("deserialize");
        assert!(!loaded.prompt.is_customized());
    }
}