Skip to main content

tinyharness_lib/config/
mod.rs

1use std::path::PathBuf;
2use std::{fmt, str::FromStr};
3
4use serde::{Deserialize, Serialize};
5
6use crate::mode::AgentMode;
7
8/// Identifies which provider backend was used last.
9#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
10pub enum ProviderKind {
11    Ollama,
12    LlamaCpp,
13    Vllm,
14}
15
16impl fmt::Display for ProviderKind {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        match self {
19            ProviderKind::Ollama => f.write_str("ollama"),
20            ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
21            ProviderKind::Vllm => f.write_str("vllm"),
22        }
23    }
24}
25
26impl FromStr for ProviderKind {
27    type Err = String;
28
29    fn from_str(s: &str) -> Result<Self, Self::Err> {
30        match s.trim().to_lowercase().as_str() {
31            "ollama" => Ok(ProviderKind::Ollama),
32            "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
33            "vllm" => Ok(ProviderKind::Vllm),
34            _ => Err(format!("Unknown provider '{}'", s)),
35        }
36    }
37}
38
39/// Controls the "think" (reasoning) level for Ollama models that support it
40/// (e.g. qwen2.5 variants). Affects how much internal reasoning the model does
41/// before responding.
42///
43/// Corresponds to Ollama's `think` parameter. Only meaningful for Ollama;
44/// other providers ignore this setting.
45#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
46pub enum OllamaThinkType {
47    /// Disable thinking entirely (fastest, lowest quality).
48    Off,
49    /// Minimal reasoning (faster, lower latency).
50    Low,
51    /// Balanced reasoning (good default).
52    Medium,
53    /// Maximum reasoning (slowest, highest quality).
54    High,
55}
56
57impl fmt::Display for OllamaThinkType {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            OllamaThinkType::Off => f.write_str("off"),
61            OllamaThinkType::Low => f.write_str("low"),
62            OllamaThinkType::Medium => f.write_str("medium"),
63            OllamaThinkType::High => f.write_str("high"),
64        }
65    }
66}
67
68impl FromStr for OllamaThinkType {
69    type Err = String;
70
71    fn from_str(s: &str) -> Result<Self, Self::Err> {
72        match s.trim().to_lowercase().as_str() {
73            "off" | "false" | "0" => Ok(OllamaThinkType::Off),
74            "low" => Ok(OllamaThinkType::Low),
75            "medium" | "mid" => Ok(OllamaThinkType::Medium),
76            "high" => Ok(OllamaThinkType::High),
77            _ => Err(format!(
78                "Unknown think type '{}'. Valid values: off, low, medium, high",
79                s
80            )),
81        }
82    }
83}
84
85/// Persisted application settings — pure data type with no I/O.
86///
87/// Use `SettingsStore` to load and save instances of this type.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Settings {
90    pub last_provider: ProviderKind,
91    pub last_model: Option<String>,
92    pub preferred_mode: AgentMode,
93    pub ollama_api_key: Option<String>,
94    /// Timeout in seconds for Ollama requests (default: 5)
95    pub ollama_timeout_secs: u64,
96    /// Maximum number of retries for Ollama requests (default: 3)
97    pub ollama_max_retries: u32,
98    /// Controls the think/reasoning level for Ollama (default: Medium)
99    pub ollama_think_type: OllamaThinkType,
100    /// Show the model's thinking/reasoning chain inline during streaming (default: false)
101    pub show_thinking: bool,
102    /// Context limit for warning calculations only (default: None, uses model default)
103    pub context_limit: Option<u32>,
104    /// Automatically accept safe read-only commands in the run tool (default: true)
105    pub auto_accept_safe_commands: bool,
106    /// List of command prefixes considered safe for auto-accept (default: see get_default_safe_commands)
107    pub safe_command_prefixes: Option<Vec<String>>,
108    /// List of command prefixes that are always denied auto-accept, even if they
109    /// match a safe prefix. Takes priority over the safe list. (default: empty)
110    pub denied_command_prefixes: Option<Vec<String>>,
111}
112
113impl Default for Settings {
114    fn default() -> Self {
115        Settings {
116            last_provider: ProviderKind::Ollama,
117            last_model: None,
118            preferred_mode: AgentMode::Casual,
119            ollama_api_key: None,
120            ollama_timeout_secs: 5,
121            ollama_max_retries: 3,
122            ollama_think_type: OllamaThinkType::Medium,
123            show_thinking: false,
124            context_limit: None,
125            auto_accept_safe_commands: true,
126            safe_command_prefixes: None,
127            denied_command_prefixes: None,
128        }
129    }
130}
131
132/// Returns the default list of safe command prefixes.
133/// These are read-only commands that don't modify the filesystem.
134pub fn get_default_safe_commands() -> Vec<String> {
135    vec![
136        "cd".to_string(),
137        "ls".to_string(),
138        "grep".to_string(),
139        "glob".to_string(),
140        "find".to_string(),
141        "cat".to_string(),
142        "head".to_string(),
143        "tail".to_string(),
144        "wc".to_string(),
145        "pwd".to_string(),
146        "echo".to_string(),
147        "printf".to_string(),
148        "tree".to_string(),
149        "file".to_string(),
150        "stat".to_string(),
151        "du".to_string(),
152        "df".to_string(),
153        "free".to_string(),
154        "uptime".to_string(),
155        "whoami".to_string(),
156        "hostname".to_string(),
157        "uname".to_string(),
158        "date".to_string(),
159        "cal".to_string(),
160        "ps".to_string(),
161        "env".to_string(),
162        "printenv".to_string(),
163        "which".to_string(),
164        "whereis".to_string(),
165        "type".to_string(),
166        "git status".to_string(),
167        "git diff".to_string(),
168        "git log".to_string(),
169        "git show".to_string(),
170        "git branch".to_string(),
171        "git remote".to_string(),
172        "git tag".to_string(),
173        "git describe".to_string(),
174        "git rev-parse".to_string(),
175        "cargo tree".to_string(),
176        "cargo metadata".to_string(),
177        "cargo doc".to_string(),
178        "rustc --version".to_string(),
179        "cargo --version".to_string(),
180    ]
181}
182
183impl Settings {
184    /// Returns the list of safe command prefixes, using defaults if not configured.
185    pub fn get_safe_commands(&self) -> Vec<String> {
186        self.safe_command_prefixes
187            .clone()
188            .unwrap_or_else(get_default_safe_commands)
189    }
190
191    /// Returns the list of always-denied command prefixes.
192    /// These take priority over the safe list — if a command matches both
193    /// a safe prefix and a denied prefix, it is denied.
194    /// Defaults to an empty list (nothing denied).
195    pub fn get_denied_commands(&self) -> Vec<String> {
196        self.denied_command_prefixes.clone().unwrap_or_default()
197    }
198}
199
200// ── Errors ──────────────────────────────────────────────────────────────────
201
202/// Error type for settings I/O operations.
203#[derive(Debug)]
204pub enum SettingsError {
205    Io(std::io::Error),
206    Parse(serde_json::Error),
207}
208
209impl std::fmt::Display for SettingsError {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        match self {
212            SettingsError::Io(e) => write!(f, "I/O error: {}", e),
213            SettingsError::Parse(e) => write!(f, "parse error: {}", e),
214        }
215    }
216}
217
218impl std::error::Error for SettingsError {
219    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
220        match self {
221            SettingsError::Io(e) => Some(e),
222            SettingsError::Parse(e) => Some(e),
223        }
224    }
225}
226
227impl From<std::io::Error> for SettingsError {
228    fn from(e: std::io::Error) -> Self {
229        SettingsError::Io(e)
230    }
231}
232
233impl From<serde_json::Error> for SettingsError {
234    fn from(e: serde_json::Error) -> Self {
235        SettingsError::Parse(e)
236    }
237}
238
239// ── Settings store ─────────────────────────────────────────────────────────
240
241/// Handles persistence of [`Settings`] to disk.
242///
243/// By default, uses `~/.config/tinyharness/settings.json`. This can be
244/// overridden with [`SettingsStore::new`] for testing or alternative paths.
245pub struct SettingsStore {
246    path: std::path::PathBuf,
247}
248
249impl SettingsStore {
250    /// Create a store that reads/writes from the default path
251    /// (`~/.config/tinyharness/settings.json`).
252    pub fn default_path() -> Self {
253        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
254        let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
255        SettingsStore { path }
256    }
257
258    /// Create a store that reads/writes from a custom path.
259    pub fn new(path: std::path::PathBuf) -> Self {
260        SettingsStore { path }
261    }
262
263    /// Load settings from disk.
264    ///
265    /// Returns `Ok(Settings)` with defaults if the file doesn't exist,
266    /// or an error if the file exists but cannot be parsed.
267    pub fn load(&self) -> Result<Settings, SettingsError> {
268        if !self.path.exists() {
269            return Ok(Settings::default());
270        }
271        let content = std::fs::read_to_string(&self.path)?;
272        let settings = serde_json::from_str(&content)?;
273        Ok(settings)
274    }
275
276    /// Load settings from disk, returning defaults on any error.
277    ///
278    /// This matches the original behaviour and is suitable for application
279    /// startup where you don't want to fail on corrupt settings files.
280    pub fn load_or_default(&self) -> Settings {
281        self.load().unwrap_or_else(|e| {
282            eprintln!("Warning: Failed to load settings: {}. Using defaults.", e);
283            Settings::default()
284        })
285    }
286
287    /// Save settings to disk atomically (write to temp file, then rename).
288    pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
289        let dir = self.path.parent().ok_or_else(|| {
290            SettingsError::Io(std::io::Error::new(
291                std::io::ErrorKind::InvalidInput,
292                "settings path has no parent directory",
293            ))
294        })?;
295        std::fs::create_dir_all(dir)?;
296
297        let json = serde_json::to_string_pretty(settings)?;
298        let tmp_path = dir.join("settings.json.tmp");
299
300        {
301            let mut file = std::fs::File::create(&tmp_path)?;
302            std::io::Write::write_all(&mut file, json.as_bytes())?;
303            std::io::Write::flush(&mut file)?;
304        }
305
306        std::fs::rename(&tmp_path, &self.path)?;
307        Ok(())
308    }
309
310    /// Returns the path where settings are stored.
311    pub fn path(&self) -> &std::path::Path {
312        &self.path
313    }
314}
315
316// ── Free convenience functions ─────────────────────────────────────────────
317
318/// Load settings from the default path, returning defaults on any error.
319///
320/// This is a convenience wrapper around [`SettingsStore::default_path().load_or_default()`].
321pub fn load_settings() -> Settings {
322    SettingsStore::default_path().load_or_default()
323}
324
325/// Save settings to the default path atomically.
326///
327/// This is a convenience wrapper around [`SettingsStore::default_path().save()`].
328/// On error, prints a warning to stderr (matching the original behaviour).
329pub fn save_settings(settings: &Settings) {
330    let store = SettingsStore::default_path();
331    if let Err(e) = store.save(settings) {
332        eprintln!("Warning: Failed to save settings: {}", e);
333    }
334}
335
336// ── Prompt file management ──────────────────────────────────────────────────
337
338/// Returns the directory where per-mode prompt `.md` files are stored.
339///
340/// Default: `~/.config/tinyharness/prompts/`
341pub fn prompts_dir() -> PathBuf {
342    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
343    PathBuf::from(home)
344        .join(".config")
345        .join("tinyharness")
346        .join("prompts")
347}
348
349/// Ensure the prompts directory exists and is seeded with `.md` files
350/// containing the hardcoded defaults for each mode.
351///
352/// On first launch, this creates `~/.config/tinyharness/prompts/` and writes
353/// `casual.md`, `planning.md`, `agent.md`, and `research.md`.  Existing files
354/// are **never** overwritten — users can safely customize them.
355///
356/// Returns the prompts directory path.
357pub fn ensure_prompts_initialized() -> PathBuf {
358    let dir = prompts_dir();
359    if !dir.exists() {
360        std::fs::create_dir_all(&dir).ok();
361    }
362
363    let modes = [
364        AgentMode::Casual,
365        AgentMode::Planning,
366        AgentMode::Agent,
367        AgentMode::Research,
368    ];
369
370    for mode in &modes {
371        let file_path = dir.join(mode.prompts_filename());
372        if !file_path.exists() {
373            let default_text = mode.default_system_prompt();
374            // Write the default, trimming leading/trailing whitespace/newlines
375            if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
376                eprintln!(
377                    "Warning: Failed to write default prompt to {}: {}",
378                    file_path.display(),
379                    e
380                );
381            }
382        }
383    }
384
385    dir
386}