1use std::path::PathBuf;
2use std::{fmt, str::FromStr};
3
4use serde::{Deserialize, Serialize};
5
6use crate::mode::AgentMode;
7
8#[derive(Debug, Clone, Serialize, Deserialize, Default)]
15pub struct ProjectSettings {
16 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub safe_command_prefixes: Option<Vec<String>>,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub denied_command_prefixes: Option<Vec<String>>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub auto_accept_safe_commands: Option<bool>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub context_limit: Option<u32>,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub project_md_files: Option<Vec<String>>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub preferred_mode: Option<AgentMode>,
36}
37
38pub fn discover_project_settings(
43 start_dir: &std::path::Path,
44) -> Option<Result<ProjectSettings, SettingsError>> {
45 let mut dir = start_dir.to_path_buf();
46
47 loop {
48 let candidate = dir.join(".tinyharness").join("config.json");
49 if candidate.is_file() {
50 let content = match std::fs::read_to_string(&candidate) {
51 Ok(c) => c,
52 Err(e) => return Some(Err(SettingsError::Io(e))),
53 };
54 let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
55 return Some(parsed);
56 }
57
58 if let Some(parent) = dir.parent() {
60 if parent == dir {
61 break;
62 }
63 dir = parent.to_path_buf();
64 } else {
65 break;
66 }
67 }
68
69 None
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum SettingSource {
75 Global,
77 Project,
79 Default,
81}
82
83impl std::fmt::Display for SettingSource {
84 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85 match self {
86 SettingSource::Global => f.write_str("global"),
87 SettingSource::Project => f.write_str("project"),
88 SettingSource::Default => f.write_str("default"),
89 }
90 }
91}
92
93#[derive(Debug, Clone)]
97pub struct MergedSettings {
98 pub safe_commands: Vec<String>,
100 pub safe_commands_source: SettingSource,
101 pub denied_commands: Vec<String>,
103 pub denied_commands_source: SettingSource,
104 pub auto_accept_safe_commands: bool,
105 pub auto_accept_source: SettingSource,
106 pub context_limit: Option<u32>,
107 pub context_limit_source: SettingSource,
108 pub project_md_files: Vec<String>,
109 pub project_md_files_source: SettingSource,
110 pub preferred_mode: AgentMode,
111 pub preferred_mode_source: SettingSource,
112}
113
114pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
120 let global = load_settings();
121
122 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
123 let project = match discover_project_settings(&cwd) {
124 Some(Ok(ps)) => Some(ps),
125 Some(Err(e)) => {
126 tracing::warn!(
127 "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
128 );
129 None
130 }
131 None => None,
132 };
133
134 let merged = merge_settings(&global, project.as_ref());
135 (global, project, merged)
136}
137
138fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
140 let global_safe = global.get_safe_commands();
141 let global_denied = global.get_denied_commands();
142
143 match project {
144 None => MergedSettings {
145 safe_commands: global_safe,
146 safe_commands_source: SettingSource::Default,
147 denied_commands: global_denied,
148 denied_commands_source: SettingSource::Default,
149 auto_accept_safe_commands: global.auto_accept_safe_commands,
150 auto_accept_source: SettingSource::Default,
151 context_limit: global.context_limit,
152 context_limit_source: SettingSource::Default,
153 project_md_files: Vec::new(),
154 project_md_files_source: SettingSource::Default,
155 preferred_mode: global.preferred_mode,
156 preferred_mode_source: SettingSource::Default,
157 },
158 Some(p) => {
159 let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
161 let mut combined = global_safe.clone();
162 for cmd in proj_safe {
163 if !combined.contains(cmd) {
164 combined.push(cmd.clone());
165 }
166 }
167 combined
168 } else {
169 global_safe
170 };
171 let safe_source = if p.safe_command_prefixes.is_some() {
172 SettingSource::Project
173 } else {
174 SettingSource::Default
175 };
176
177 let (denied_commands, denied_source) =
179 if let Some(ref proj_denied) = p.denied_command_prefixes {
180 (proj_denied.clone(), SettingSource::Project)
181 } else {
182 (global_denied, SettingSource::Default)
183 };
184
185 let (auto_accept, auto_source) = p
186 .auto_accept_safe_commands
187 .map(|v| (v, SettingSource::Project))
188 .unwrap_or((global.auto_accept_safe_commands, SettingSource::Default));
189
190 let (context_limit, ctx_source) = p
191 .context_limit
192 .map(|v| (Some(v), SettingSource::Project))
193 .unwrap_or((global.context_limit, SettingSource::Default));
194
195 let (project_md_files, md_source) = p
196 .project_md_files
197 .as_ref()
198 .map(|files| (files.clone(), SettingSource::Project))
199 .unwrap_or((Vec::new(), SettingSource::Default));
200
201 let (preferred_mode, mode_source) = p
202 .preferred_mode
203 .map(|m| (m, SettingSource::Project))
204 .unwrap_or((global.preferred_mode, SettingSource::Default));
205
206 MergedSettings {
207 safe_commands,
208 safe_commands_source: safe_source,
209 denied_commands,
210 denied_commands_source: denied_source,
211 auto_accept_safe_commands: auto_accept,
212 auto_accept_source: auto_source,
213 context_limit,
214 context_limit_source: ctx_source,
215 project_md_files,
216 project_md_files_source: md_source,
217 preferred_mode,
218 preferred_mode_source: mode_source,
219 }
220 }
221 }
222}
223
224pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
228 ProjectSettings {
229 safe_command_prefixes: settings.safe_command_prefixes.clone(),
230 denied_command_prefixes: settings.denied_command_prefixes.clone(),
231 auto_accept_safe_commands: Some(settings.auto_accept_safe_commands),
232 context_limit: settings.context_limit,
233 project_md_files: None, preferred_mode: Some(settings.preferred_mode),
235 }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
240pub enum ProviderKind {
241 Ollama,
242 LlamaCpp,
243 Vllm,
244}
245
246impl fmt::Display for ProviderKind {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 match self {
249 ProviderKind::Ollama => f.write_str("ollama"),
250 ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
251 ProviderKind::Vllm => f.write_str("vllm"),
252 }
253 }
254}
255
256impl FromStr for ProviderKind {
257 type Err = String;
258
259 fn from_str(s: &str) -> Result<Self, Self::Err> {
260 match s.trim().to_lowercase().as_str() {
261 "ollama" => Ok(ProviderKind::Ollama),
262 "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
263 "vllm" => Ok(ProviderKind::Vllm),
264 _ => Err(format!("Unknown provider '{}'", s)),
265 }
266 }
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
276pub enum OllamaThinkType {
277 Off,
279 Low,
281 Medium,
283 High,
285}
286
287impl fmt::Display for OllamaThinkType {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 match self {
290 OllamaThinkType::Off => f.write_str("off"),
291 OllamaThinkType::Low => f.write_str("low"),
292 OllamaThinkType::Medium => f.write_str("medium"),
293 OllamaThinkType::High => f.write_str("high"),
294 }
295 }
296}
297
298impl FromStr for OllamaThinkType {
299 type Err = String;
300
301 fn from_str(s: &str) -> Result<Self, Self::Err> {
302 match s.trim().to_lowercase().as_str() {
303 "off" | "false" | "0" => Ok(OllamaThinkType::Off),
304 "low" => Ok(OllamaThinkType::Low),
305 "medium" | "mid" => Ok(OllamaThinkType::Medium),
306 "high" => Ok(OllamaThinkType::High),
307 _ => Err(format!(
308 "Unknown think type '{}'. Valid values: off, low, medium, high",
309 s
310 )),
311 }
312 }
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct Settings {
320 pub last_provider: ProviderKind,
321 #[serde(default)]
325 pub last_provider_url: Option<String>,
326 pub last_model: Option<String>,
327 pub preferred_mode: AgentMode,
328 pub ollama_api_key: Option<String>,
329 pub ollama_timeout_secs: u64,
331 pub ollama_max_retries: u32,
333 pub ollama_think_type: OllamaThinkType,
335 pub show_thinking: bool,
337 pub context_limit: Option<u32>,
339 pub auto_accept_safe_commands: bool,
341 pub safe_command_prefixes: Option<Vec<String>>,
343 pub denied_command_prefixes: Option<Vec<String>>,
346 #[serde(default)]
351 pub project_md_files: Option<Vec<String>>,
352}
353
354impl Default for Settings {
355 fn default() -> Self {
356 Settings {
357 last_provider: ProviderKind::Ollama,
358 last_provider_url: None,
359 last_model: None,
360 preferred_mode: AgentMode::Casual,
361 ollama_api_key: None,
362 ollama_timeout_secs: 5,
363 ollama_max_retries: 3,
364 ollama_think_type: OllamaThinkType::Medium,
365 show_thinking: false,
366 context_limit: None,
367 auto_accept_safe_commands: true,
368 safe_command_prefixes: None,
369 denied_command_prefixes: None,
370 project_md_files: None,
371 }
372 }
373}
374
375pub fn get_default_safe_commands() -> Vec<String> {
378 vec![
379 "cd".to_string(),
380 "ls".to_string(),
381 "grep".to_string(),
382 "glob".to_string(),
383 "find".to_string(),
384 "cat".to_string(),
385 "head".to_string(),
386 "tail".to_string(),
387 "wc".to_string(),
388 "pwd".to_string(),
389 "echo".to_string(),
390 "printf".to_string(),
391 "tree".to_string(),
392 "file".to_string(),
393 "stat".to_string(),
394 "du".to_string(),
395 "df".to_string(),
396 "free".to_string(),
397 "uptime".to_string(),
398 "whoami".to_string(),
399 "hostname".to_string(),
400 "uname".to_string(),
401 "date".to_string(),
402 "cal".to_string(),
403 "ps".to_string(),
404 "env".to_string(),
405 "printenv".to_string(),
406 "which".to_string(),
407 "whereis".to_string(),
408 "type".to_string(),
409 "git status".to_string(),
410 "git diff".to_string(),
411 "git log".to_string(),
412 "git show".to_string(),
413 "git branch".to_string(),
414 "git remote".to_string(),
415 "git tag".to_string(),
416 "git describe".to_string(),
417 "git rev-parse".to_string(),
418 "cargo tree".to_string(),
419 "cargo metadata".to_string(),
420 "cargo doc".to_string(),
421 "rustc --version".to_string(),
422 "cargo --version".to_string(),
423 ]
424}
425
426impl Settings {
427 pub fn get_safe_commands(&self) -> Vec<String> {
429 self.safe_command_prefixes
430 .clone()
431 .unwrap_or_else(get_default_safe_commands)
432 }
433
434 pub fn get_denied_commands(&self) -> Vec<String> {
439 self.denied_command_prefixes.clone().unwrap_or_default()
440 }
441}
442
443#[derive(Debug)]
447pub enum SettingsError {
448 Io(std::io::Error),
449 Parse(serde_json::Error),
450}
451
452impl std::fmt::Display for SettingsError {
453 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454 match self {
455 SettingsError::Io(e) => write!(f, "I/O error: {}", e),
456 SettingsError::Parse(e) => write!(f, "parse error: {}", e),
457 }
458 }
459}
460
461impl std::error::Error for SettingsError {
462 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
463 match self {
464 SettingsError::Io(e) => Some(e),
465 SettingsError::Parse(e) => Some(e),
466 }
467 }
468}
469
470impl From<std::io::Error> for SettingsError {
471 fn from(e: std::io::Error) -> Self {
472 SettingsError::Io(e)
473 }
474}
475
476impl From<serde_json::Error> for SettingsError {
477 fn from(e: serde_json::Error) -> Self {
478 SettingsError::Parse(e)
479 }
480}
481
482pub struct SettingsStore {
489 path: std::path::PathBuf,
490}
491
492impl SettingsStore {
493 pub fn default_path() -> Self {
496 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
497 let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
498 SettingsStore { path }
499 }
500
501 pub fn new(path: std::path::PathBuf) -> Self {
503 SettingsStore { path }
504 }
505
506 pub fn load(&self) -> Result<Settings, SettingsError> {
511 if !self.path.exists() {
512 return Ok(Settings::default());
513 }
514 let content = std::fs::read_to_string(&self.path)?;
515 let settings = serde_json::from_str(&content)?;
516 Ok(settings)
517 }
518
519 pub fn load_or_default(&self) -> Settings {
524 self.load().unwrap_or_else(|e| {
525 tracing::warn!("Failed to load settings: {e}. Using defaults.");
526 Settings::default()
527 })
528 }
529
530 pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
532 let dir = self.path.parent().ok_or_else(|| {
533 SettingsError::Io(std::io::Error::new(
534 std::io::ErrorKind::InvalidInput,
535 "settings path has no parent directory",
536 ))
537 })?;
538 std::fs::create_dir_all(dir)?;
539
540 let json = serde_json::to_string_pretty(settings)?;
541 let tmp_path = dir.join("settings.json.tmp");
542
543 {
544 let mut file = std::fs::File::create(&tmp_path)?;
545 std::io::Write::write_all(&mut file, json.as_bytes())?;
546 std::io::Write::flush(&mut file)?;
547 }
548
549 std::fs::rename(&tmp_path, &self.path)?;
550 Ok(())
551 }
552
553 pub fn path(&self) -> &std::path::Path {
555 &self.path
556 }
557}
558
559pub fn load_settings() -> Settings {
565 SettingsStore::default_path().load_or_default()
566}
567
568pub fn save_settings(settings: &Settings) {
573 let store = SettingsStore::default_path();
574 if let Err(e) = store.save(settings) {
575 tracing::warn!("Failed to save settings: {e}");
576 }
577}
578
579pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
588 if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
590 let files: Vec<String> = env
591 .split(',')
592 .map(|s| s.trim().to_string())
593 .filter(|s| !s.is_empty())
594 .collect();
595 if !files.is_empty() {
596 return files;
597 }
598 }
599
600 if let Some(s) = settings
602 && let Some(ref configured) = s.project_md_files
603 && !configured.is_empty()
604 {
605 return configured.clone();
606 }
607
608 crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
610 .iter()
611 .map(|s| s.to_string())
612 .collect()
613}
614
615pub fn prompts_dir() -> PathBuf {
619 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
620 PathBuf::from(home)
621 .join(".config")
622 .join("tinyharness")
623 .join("prompts")
624}
625
626pub fn ensure_prompts_initialized() -> PathBuf {
635 let dir = prompts_dir();
636 if !dir.exists() {
637 std::fs::create_dir_all(&dir).ok();
638 }
639
640 {
642 let header_path = dir.join("header.md");
643 if !header_path.exists() {
644 let header_text = include_str!("../prompts/header.md");
645 if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
646 tracing::warn!(
647 "Failed to write default header to {}: {e}",
648 header_path.display(),
649 );
650 }
651 }
652 }
653
654 let modes = [
655 AgentMode::Casual,
656 AgentMode::Planning,
657 AgentMode::Agent,
658 AgentMode::Research,
659 ];
660
661 for mode in &modes {
662 let file_path = dir.join(mode.prompts_filename());
663 if !file_path.exists() {
664 let default_text = mode.default_system_prompt();
665 if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
667 tracing::warn!(
668 "Failed to write default prompt to {}: {e}",
669 file_path.display(),
670 );
671 }
672 }
673 }
674
675 dir
676}