1use std::path::PathBuf;
2use std::{fmt, str::FromStr};
3
4use serde::{Deserialize, Serialize};
5
6use crate::mode::AgentMode;
7
8#[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#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
46pub enum OllamaThinkType {
47 Off,
49 Low,
51 Medium,
53 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#[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 pub ollama_timeout_secs: u64,
96 pub ollama_max_retries: u32,
98 pub ollama_think_type: OllamaThinkType,
100 pub show_thinking: bool,
102 pub context_limit: Option<u32>,
104 pub auto_accept_safe_commands: bool,
106 pub safe_command_prefixes: Option<Vec<String>>,
108 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
132pub 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 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 pub fn get_denied_commands(&self) -> Vec<String> {
196 self.denied_command_prefixes.clone().unwrap_or_default()
197 }
198}
199
200#[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
239pub struct SettingsStore {
246 path: std::path::PathBuf,
247}
248
249impl SettingsStore {
250 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 pub fn new(path: std::path::PathBuf) -> Self {
260 SettingsStore { path }
261 }
262
263 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 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 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 pub fn path(&self) -> &std::path::Path {
312 &self.path
313 }
314}
315
316pub fn load_settings() -> Settings {
322 SettingsStore::default_path().load_or_default()
323}
324
325pub 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
336pub 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
349pub 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 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}