use std::path::PathBuf;
use std::{fmt, str::FromStr};
use serde::{Deserialize, Serialize};
use crate::mode::AgentMode;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProjectSettings {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub safe_command_prefixes: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub denied_command_prefixes: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_accept_safe_commands: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_limit: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project_md_files: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preferred_mode: Option<AgentMode>,
}
pub fn discover_project_settings(
start_dir: &std::path::Path,
) -> Option<Result<ProjectSettings, SettingsError>> {
let mut dir = start_dir.to_path_buf();
loop {
let candidate = dir.join(".tinyharness").join("config.json");
if candidate.is_file() {
let content = match std::fs::read_to_string(&candidate) {
Ok(c) => c,
Err(e) => return Some(Err(SettingsError::Io(e))),
};
let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
return Some(parsed);
}
if let Some(parent) = dir.parent() {
if parent == dir {
break;
}
dir = parent.to_path_buf();
} else {
break;
}
}
None
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingSource {
Global,
Project,
Default,
}
impl std::fmt::Display for SettingSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SettingSource::Global => f.write_str("global"),
SettingSource::Project => f.write_str("project"),
SettingSource::Default => f.write_str("default"),
}
}
}
#[derive(Debug, Clone)]
pub struct MergedSettings {
pub safe_commands: Vec<String>,
pub safe_commands_source: SettingSource,
pub denied_commands: Vec<String>,
pub denied_commands_source: SettingSource,
pub auto_accept_safe_commands: bool,
pub auto_accept_source: SettingSource,
pub context_limit: Option<u32>,
pub context_limit_source: SettingSource,
pub project_md_files: Vec<String>,
pub project_md_files_source: SettingSource,
pub preferred_mode: AgentMode,
pub preferred_mode_source: SettingSource,
}
pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
let global = load_settings();
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let project = match discover_project_settings(&cwd) {
Some(Ok(ps)) => Some(ps),
Some(Err(e)) => {
tracing::warn!(
"Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
);
None
}
None => None,
};
let merged = merge_settings(&global, project.as_ref());
(global, project, merged)
}
fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
let global_safe = global.get_safe_commands();
let global_denied = global.get_denied_commands();
match project {
None => MergedSettings {
safe_commands: global_safe,
safe_commands_source: SettingSource::Default,
denied_commands: global_denied,
denied_commands_source: SettingSource::Default,
auto_accept_safe_commands: global.auto_accept_safe_commands,
auto_accept_source: SettingSource::Default,
context_limit: global.context_limit,
context_limit_source: SettingSource::Default,
project_md_files: Vec::new(),
project_md_files_source: SettingSource::Default,
preferred_mode: global.preferred_mode,
preferred_mode_source: SettingSource::Default,
},
Some(p) => {
let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
let mut combined = global_safe.clone();
for cmd in proj_safe {
if !combined.contains(cmd) {
combined.push(cmd.clone());
}
}
combined
} else {
global_safe
};
let safe_source = if p.safe_command_prefixes.is_some() {
SettingSource::Project
} else {
SettingSource::Default
};
let (denied_commands, denied_source) =
if let Some(ref proj_denied) = p.denied_command_prefixes {
(proj_denied.clone(), SettingSource::Project)
} else {
(global_denied, SettingSource::Default)
};
let (auto_accept, auto_source) = p
.auto_accept_safe_commands
.map(|v| (v, SettingSource::Project))
.unwrap_or((global.auto_accept_safe_commands, SettingSource::Default));
let (context_limit, ctx_source) = p
.context_limit
.map(|v| (Some(v), SettingSource::Project))
.unwrap_or((global.context_limit, SettingSource::Default));
let (project_md_files, md_source) = p
.project_md_files
.as_ref()
.map(|files| (files.clone(), SettingSource::Project))
.unwrap_or((Vec::new(), SettingSource::Default));
let (preferred_mode, mode_source) = p
.preferred_mode
.map(|m| (m, SettingSource::Project))
.unwrap_or((global.preferred_mode, SettingSource::Default));
MergedSettings {
safe_commands,
safe_commands_source: safe_source,
denied_commands,
denied_commands_source: denied_source,
auto_accept_safe_commands: auto_accept,
auto_accept_source: auto_source,
context_limit,
context_limit_source: ctx_source,
project_md_files,
project_md_files_source: md_source,
preferred_mode,
preferred_mode_source: mode_source,
}
}
}
}
pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
ProjectSettings {
safe_command_prefixes: settings.safe_command_prefixes.clone(),
denied_command_prefixes: settings.denied_command_prefixes.clone(),
auto_accept_safe_commands: Some(settings.auto_accept_safe_commands),
context_limit: settings.context_limit,
project_md_files: None, preferred_mode: Some(settings.preferred_mode),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ProviderKind {
Ollama,
LlamaCpp,
Vllm,
OpenAiCompat,
Sockudo,
}
impl fmt::Display for ProviderKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProviderKind::Ollama => f.write_str("ollama"),
ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
ProviderKind::Vllm => f.write_str("vllm"),
ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
ProviderKind::Sockudo => f.write_str("sockudo"),
}
}
}
impl FromStr for ProviderKind {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"ollama" => Ok(ProviderKind::Ollama),
"llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
"vllm" => Ok(ProviderKind::Vllm),
"openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
"sockudo" => Ok(ProviderKind::Sockudo),
_ => Err(format!("Unknown provider '{}'", s)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum OllamaThinkType {
Off,
Low,
Medium,
High,
}
impl fmt::Display for OllamaThinkType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OllamaThinkType::Off => f.write_str("off"),
OllamaThinkType::Low => f.write_str("low"),
OllamaThinkType::Medium => f.write_str("medium"),
OllamaThinkType::High => f.write_str("high"),
}
}
}
impl FromStr for OllamaThinkType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_str() {
"off" | "false" | "0" => Ok(OllamaThinkType::Off),
"low" => Ok(OllamaThinkType::Low),
"medium" | "mid" => Ok(OllamaThinkType::Medium),
"high" => Ok(OllamaThinkType::High),
_ => Err(format!(
"Unknown think type '{}'. Valid values: off, low, medium, high",
s
)),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
pub last_provider: ProviderKind,
#[serde(default)]
pub last_provider_url: Option<String>,
pub last_model: Option<String>,
pub preferred_mode: AgentMode,
pub ollama_api_key: Option<String>,
#[serde(default)]
pub openai_compat_api_key: Option<String>,
#[serde(default)]
pub sockudo_app_id: Option<String>,
#[serde(default)]
pub sockudo_app_key: Option<String>,
#[serde(default)]
pub sockudo_app_secret: Option<String>,
pub ollama_timeout_secs: u64,
pub ollama_max_retries: u32,
pub ollama_think_type: OllamaThinkType,
pub show_thinking: bool,
pub context_limit: Option<u32>,
pub auto_accept_safe_commands: bool,
#[serde(default)]
pub skip_health_check: bool,
pub safe_command_prefixes: Option<Vec<String>>,
pub denied_command_prefixes: Option<Vec<String>>,
#[serde(default)]
pub project_md_files: Option<Vec<String>>,
}
impl Default for Settings {
fn default() -> Self {
Settings {
last_provider: ProviderKind::Ollama,
last_provider_url: None,
last_model: None,
preferred_mode: AgentMode::Casual,
ollama_api_key: None,
openai_compat_api_key: None,
sockudo_app_id: None,
sockudo_app_key: None,
sockudo_app_secret: None,
ollama_timeout_secs: 5,
ollama_max_retries: 3,
ollama_think_type: OllamaThinkType::Medium,
show_thinking: false,
context_limit: None,
auto_accept_safe_commands: true,
skip_health_check: false,
safe_command_prefixes: None,
denied_command_prefixes: None,
project_md_files: None,
}
}
}
pub fn get_default_safe_commands() -> Vec<String> {
vec![
"cd".to_string(),
"ls".to_string(),
"grep".to_string(),
"glob".to_string(),
"find".to_string(),
"cat".to_string(),
"head".to_string(),
"tail".to_string(),
"wc".to_string(),
"pwd".to_string(),
"echo".to_string(),
"printf".to_string(),
"tree".to_string(),
"file".to_string(),
"stat".to_string(),
"du".to_string(),
"df".to_string(),
"free".to_string(),
"uptime".to_string(),
"whoami".to_string(),
"hostname".to_string(),
"uname".to_string(),
"date".to_string(),
"cal".to_string(),
"ps".to_string(),
"env".to_string(),
"printenv".to_string(),
"which".to_string(),
"whereis".to_string(),
"type".to_string(),
"git status".to_string(),
"git diff".to_string(),
"git log".to_string(),
"git show".to_string(),
"git branch".to_string(),
"git remote".to_string(),
"git tag".to_string(),
"git describe".to_string(),
"git rev-parse".to_string(),
"cargo tree".to_string(),
"cargo metadata".to_string(),
"cargo doc".to_string(),
"rustc --version".to_string(),
"cargo --version".to_string(),
]
}
impl Settings {
pub fn get_safe_commands(&self) -> Vec<String> {
self.safe_command_prefixes
.clone()
.unwrap_or_else(get_default_safe_commands)
}
pub fn get_denied_commands(&self) -> Vec<String> {
self.denied_command_prefixes.clone().unwrap_or_default()
}
}
#[derive(Debug)]
pub enum SettingsError {
Io(std::io::Error),
Parse(serde_json::Error),
}
impl std::fmt::Display for SettingsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SettingsError::Io(e) => write!(f, "I/O error: {}", e),
SettingsError::Parse(e) => write!(f, "parse error: {}", e),
}
}
}
impl std::error::Error for SettingsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
SettingsError::Io(e) => Some(e),
SettingsError::Parse(e) => Some(e),
}
}
}
impl From<std::io::Error> for SettingsError {
fn from(e: std::io::Error) -> Self {
SettingsError::Io(e)
}
}
impl From<serde_json::Error> for SettingsError {
fn from(e: serde_json::Error) -> Self {
SettingsError::Parse(e)
}
}
pub struct SettingsStore {
path: std::path::PathBuf,
}
impl SettingsStore {
pub fn default_path() -> Self {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
let path = std::path::PathBuf::from(home).join(".config/tinyharness/settings.json");
SettingsStore { path }
}
pub fn new(path: std::path::PathBuf) -> Self {
SettingsStore { path }
}
pub fn load(&self) -> Result<Settings, SettingsError> {
if !self.path.exists() {
return Ok(Settings::default());
}
let content = std::fs::read_to_string(&self.path)?;
let settings = serde_json::from_str(&content)?;
Ok(settings)
}
pub fn load_or_default(&self) -> Settings {
self.load().unwrap_or_else(|e| {
tracing::warn!("Failed to load settings: {e}. Using defaults.");
Settings::default()
})
}
pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
let dir = self.path.parent().ok_or_else(|| {
SettingsError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"settings path has no parent directory",
))
})?;
std::fs::create_dir_all(dir)?;
let json = serde_json::to_string_pretty(settings)?;
let tmp_path = dir.join("settings.json.tmp");
{
let mut file = std::fs::File::create(&tmp_path)?;
std::io::Write::write_all(&mut file, json.as_bytes())?;
std::io::Write::flush(&mut file)?;
}
std::fs::rename(&tmp_path, &self.path)?;
Ok(())
}
pub fn path(&self) -> &std::path::Path {
&self.path
}
}
pub fn load_settings() -> Settings {
SettingsStore::default_path().load_or_default()
}
pub fn save_settings(settings: &Settings) {
let store = SettingsStore::default_path();
if let Err(e) = store.save(settings) {
tracing::warn!("Failed to save settings: {e}");
}
}
pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
let files: Vec<String> = env
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if !files.is_empty() {
return files;
}
}
if let Some(s) = settings
&& let Some(ref configured) = s.project_md_files
&& !configured.is_empty()
{
return configured.clone();
}
crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
.iter()
.map(|s| s.to_string())
.collect()
}
pub fn prompts_dir() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
PathBuf::from(home)
.join(".config")
.join("tinyharness")
.join("prompts")
}
pub fn ensure_prompts_initialized() -> PathBuf {
let dir = prompts_dir();
if !dir.exists() {
std::fs::create_dir_all(&dir).ok();
}
{
let header_path = dir.join("header.md");
if !header_path.exists() {
let header_text = include_str!("../prompts/header.md");
if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
tracing::warn!(
"Failed to write default header to {}: {e}",
header_path.display(),
);
}
}
}
let modes = [
AgentMode::Casual,
AgentMode::Planning,
AgentMode::Agent,
AgentMode::Research,
];
for mode in &modes {
let file_path = dir.join(mode.prompts_filename());
if !file_path.exists() {
let default_text = mode.default_system_prompt();
if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
tracing::warn!(
"Failed to write default prompt to {}: {e}",
file_path.display(),
);
}
}
}
dir
}