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 OpenAiCompat,
250 Sockudo,
251}
252
253impl fmt::Display for ProviderKind {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 match self {
256 ProviderKind::Ollama => f.write_str("ollama"),
257 ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
258 ProviderKind::Vllm => f.write_str("vllm"),
259 ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
260 ProviderKind::Sockudo => f.write_str("sockudo"),
261 }
262 }
263}
264
265impl FromStr for ProviderKind {
266 type Err = String;
267
268 fn from_str(s: &str) -> Result<Self, Self::Err> {
269 match s.trim().to_lowercase().as_str() {
270 "ollama" => Ok(ProviderKind::Ollama),
271 "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
272 "vllm" => Ok(ProviderKind::Vllm),
273 "openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
274 "sockudo" => Ok(ProviderKind::Sockudo),
275 _ => Err(format!("Unknown provider '{}'", s)),
276 }
277 }
278}
279
280#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
287pub enum OllamaThinkType {
288 Off,
290 Low,
292 Medium,
294 High,
296}
297
298impl fmt::Display for OllamaThinkType {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 match self {
301 OllamaThinkType::Off => f.write_str("off"),
302 OllamaThinkType::Low => f.write_str("low"),
303 OllamaThinkType::Medium => f.write_str("medium"),
304 OllamaThinkType::High => f.write_str("high"),
305 }
306 }
307}
308
309impl FromStr for OllamaThinkType {
310 type Err = String;
311
312 fn from_str(s: &str) -> Result<Self, Self::Err> {
313 match s.trim().to_lowercase().as_str() {
314 "off" | "false" | "0" => Ok(OllamaThinkType::Off),
315 "low" => Ok(OllamaThinkType::Low),
316 "medium" | "mid" => Ok(OllamaThinkType::Medium),
317 "high" => Ok(OllamaThinkType::High),
318 _ => Err(format!(
319 "Unknown think type '{}'. Valid values: off, low, medium, high",
320 s
321 )),
322 }
323 }
324}
325
326#[derive(Debug, Clone, Serialize, Deserialize)]
330pub struct Settings {
331 pub last_provider: ProviderKind,
332 #[serde(default)]
336 pub last_provider_url: Option<String>,
337 pub last_model: Option<String>,
338 pub preferred_mode: AgentMode,
339 pub ollama_api_key: Option<String>,
340 #[serde(default)]
344 pub openai_compat_api_key: Option<String>,
345 #[serde(default)]
347 pub sockudo_app_id: Option<String>,
348 #[serde(default)]
350 pub sockudo_app_key: Option<String>,
351 #[serde(default)]
353 pub sockudo_app_secret: Option<String>,
354 pub ollama_timeout_secs: u64,
356 pub ollama_max_retries: u32,
358 pub ollama_think_type: OllamaThinkType,
360 pub show_thinking: bool,
362 pub context_limit: Option<u32>,
364 pub auto_accept_safe_commands: bool,
366 #[serde(default)]
372 pub skip_health_check: bool,
373 pub safe_command_prefixes: Option<Vec<String>>,
375 pub denied_command_prefixes: Option<Vec<String>>,
378 #[serde(default)]
383 pub project_md_files: Option<Vec<String>>,
384}
385
386impl Default for Settings {
387 fn default() -> Self {
388 Settings {
389 last_provider: ProviderKind::Ollama,
390 last_provider_url: None,
391 last_model: None,
392 preferred_mode: AgentMode::Casual,
393 ollama_api_key: None,
394 openai_compat_api_key: None,
395 sockudo_app_id: None,
396 sockudo_app_key: None,
397 sockudo_app_secret: None,
398 ollama_timeout_secs: 5,
399 ollama_max_retries: 3,
400 ollama_think_type: OllamaThinkType::Medium,
401 show_thinking: false,
402 context_limit: None,
403 auto_accept_safe_commands: true,
404 skip_health_check: false,
405 safe_command_prefixes: None,
406 denied_command_prefixes: None,
407 project_md_files: None,
408 }
409 }
410}
411
412pub fn get_default_safe_commands() -> Vec<String> {
415 vec![
416 "cd".to_string(),
417 "ls".to_string(),
418 "grep".to_string(),
419 "glob".to_string(),
420 "find".to_string(),
421 "cat".to_string(),
422 "head".to_string(),
423 "tail".to_string(),
424 "wc".to_string(),
425 "pwd".to_string(),
426 "echo".to_string(),
427 "printf".to_string(),
428 "tree".to_string(),
429 "file".to_string(),
430 "stat".to_string(),
431 "du".to_string(),
432 "df".to_string(),
433 "free".to_string(),
434 "uptime".to_string(),
435 "whoami".to_string(),
436 "hostname".to_string(),
437 "uname".to_string(),
438 "date".to_string(),
439 "cal".to_string(),
440 "ps".to_string(),
441 "env".to_string(),
442 "printenv".to_string(),
443 "which".to_string(),
444 "whereis".to_string(),
445 "type".to_string(),
446 "git status".to_string(),
447 "git diff".to_string(),
448 "git log".to_string(),
449 "git show".to_string(),
450 "git branch".to_string(),
451 "git remote".to_string(),
452 "git tag".to_string(),
453 "git describe".to_string(),
454 "git rev-parse".to_string(),
455 "cargo tree".to_string(),
456 "cargo metadata".to_string(),
457 "cargo doc".to_string(),
458 "rustc --version".to_string(),
459 "cargo --version".to_string(),
460 ]
461}
462
463impl Settings {
464 pub fn get_safe_commands(&self) -> Vec<String> {
466 self.safe_command_prefixes
467 .clone()
468 .unwrap_or_else(get_default_safe_commands)
469 }
470
471 pub fn get_denied_commands(&self) -> Vec<String> {
476 self.denied_command_prefixes.clone().unwrap_or_default()
477 }
478}
479
480#[derive(Debug)]
484pub enum SettingsError {
485 Io(std::io::Error),
486 Parse(serde_json::Error),
487}
488
489impl std::fmt::Display for SettingsError {
490 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491 match self {
492 SettingsError::Io(e) => write!(f, "I/O error: {}", e),
493 SettingsError::Parse(e) => write!(f, "parse error: {}", e),
494 }
495 }
496}
497
498impl std::error::Error for SettingsError {
499 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
500 match self {
501 SettingsError::Io(e) => Some(e),
502 SettingsError::Parse(e) => Some(e),
503 }
504 }
505}
506
507impl From<std::io::Error> for SettingsError {
508 fn from(e: std::io::Error) -> Self {
509 SettingsError::Io(e)
510 }
511}
512
513impl From<serde_json::Error> for SettingsError {
514 fn from(e: serde_json::Error) -> Self {
515 SettingsError::Parse(e)
516 }
517}
518
519pub struct SettingsStore {
526 path: std::path::PathBuf,
527}
528
529impl SettingsStore {
530 pub fn default_path() -> Self {
533 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
534 let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
535 SettingsStore { path }
536 }
537
538 pub fn new(path: std::path::PathBuf) -> Self {
540 SettingsStore { path }
541 }
542
543 pub fn load(&self) -> Result<Settings, SettingsError> {
548 if !self.path.exists() {
549 return Ok(Settings::default());
550 }
551 let content = std::fs::read_to_string(&self.path)?;
552 let settings = serde_json::from_str(&content)?;
553 Ok(settings)
554 }
555
556 pub fn load_or_default(&self) -> Settings {
561 self.load().unwrap_or_else(|e| {
562 tracing::warn!("Failed to load settings: {e}. Using defaults.");
563 Settings::default()
564 })
565 }
566
567 pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
569 let dir = self.path.parent().ok_or_else(|| {
570 SettingsError::Io(std::io::Error::new(
571 std::io::ErrorKind::InvalidInput,
572 "settings path has no parent directory",
573 ))
574 })?;
575 std::fs::create_dir_all(dir)?;
576
577 let json = serde_json::to_string_pretty(settings)?;
578 let tmp_path = dir.join("settings.json.tmp");
579
580 {
581 let mut file = std::fs::File::create(&tmp_path)?;
582 std::io::Write::write_all(&mut file, json.as_bytes())?;
583 std::io::Write::flush(&mut file)?;
584 }
585
586 std::fs::rename(&tmp_path, &self.path)?;
587 Ok(())
588 }
589
590 pub fn path(&self) -> &std::path::Path {
592 &self.path
593 }
594}
595
596pub fn load_settings() -> Settings {
602 SettingsStore::default_path().load_or_default()
603}
604
605pub fn save_settings(settings: &Settings) {
610 let store = SettingsStore::default_path();
611 if let Err(e) = store.save(settings) {
612 tracing::warn!("Failed to save settings: {e}");
613 }
614}
615
616pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
625 if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
627 let files: Vec<String> = env
628 .split(',')
629 .map(|s| s.trim().to_string())
630 .filter(|s| !s.is_empty())
631 .collect();
632 if !files.is_empty() {
633 return files;
634 }
635 }
636
637 if let Some(s) = settings
639 && let Some(ref configured) = s.project_md_files
640 && !configured.is_empty()
641 {
642 return configured.clone();
643 }
644
645 crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
647 .iter()
648 .map(|s| s.to_string())
649 .collect()
650}
651
652pub fn prompts_dir() -> PathBuf {
656 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
657 PathBuf::from(home)
658 .join(".config")
659 .join("tinyharness")
660 .join("prompts")
661}
662
663pub fn ensure_prompts_initialized() -> PathBuf {
672 let dir = prompts_dir();
673 if !dir.exists() {
674 std::fs::create_dir_all(&dir).ok();
675 }
676
677 {
679 let header_path = dir.join("header.md");
680 if !header_path.exists() {
681 let header_text = include_str!("../prompts/header.md");
682 if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
683 tracing::warn!(
684 "Failed to write default header to {}: {e}",
685 header_path.display(),
686 );
687 }
688 }
689 }
690
691 let modes = [
692 AgentMode::Casual,
693 AgentMode::Planning,
694 AgentMode::Agent,
695 AgentMode::Research,
696 ];
697
698 for mode in &modes {
699 let file_path = dir.join(mode.prompts_filename());
700 if !file_path.exists() {
701 let default_text = mode.default_system_prompt();
702 if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
704 tracing::warn!(
705 "Failed to write default prompt to {}: {e}",
706 file_path.display(),
707 );
708 }
709 }
710 }
711
712 dir
713}