1use crate::agent::Agent; 2use crate::paths; 3use serde::{Deserialize, Serialize}; 4use std::os::unix::fs::PermissionsExt; 5use std::path::{Path, PathBuf}; 6 7pub const CLAUDE_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN"; 8pub const OPENCODE_ENV: &str = "OPENCODE_API_KEY"; 9const DEFAULT_MODEL: &str = "opencode/claude-sonnet-5-5"; 10 11#[derive(Serialize, Deserialize, Default, Clone)] 12#[serde(default)] 13pub struct Config { 14 pub default_agent: Agent, 15 pub claude_token: String, 16 pub opencode_key: String, 17 pub opencode_model: String, 18 pub recents: Vec<PathBuf>, 19} 20 21pub struct Secret { 22 pub value: String, 23 pub from_env: bool, 24} 25 26impl Config { 27 pub fn load() -> Config { 28 std::fs::read(paths::config_file()) 29 .ok() 30 .and_then(|b| serde_json::from_slice(&b).ok()) 31 .unwrap_or_default() 32 } 33 34 pub fn save(&self) { 35 let path = paths::config_file(); 36 let _ = std::fs::create_dir_all(path.parent().unwrap_or(Path::new("/"))); 37 if std::fs::write(&path, serde_json::to_vec_pretty(self).unwrap_or_default()).is_ok() { 38 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); 39 } 40 } 41 42 pub fn claude_token(&self) -> Option<Secret> { 43 secret(&self.claude_token, CLAUDE_ENV) 44 } 45 46 pub fn opencode_key(&self) -> Option<Secret> { 47 secret(&self.opencode_key, OPENCODE_ENV) 48 } 49 50 pub fn model(&self) -> &str { 51 if self.opencode_model.is_empty() { 52 DEFAULT_MODEL 53 } else { 54 &self.opencode_model 55 } 56 } 57 58 pub fn touch_recent(&mut self, dir: &Path) { 59 self.recents.retain(|d| d != dir); 60 self.recents.insert(0, dir.to_path_buf()); 61 self.recents.truncate(8); 62 self.save(); 63 } 64} 65 66fn secret(stored: &str, env: &str) -> Option<Secret> { 67 if !stored.is_empty() { 68 return Some(Secret { 69 value: stored.to_string(), 70 from_env: false, 71 }); 72 } 73 std::env::var(env) 74 .ok() 75 .filter(|v| !v.is_empty()) 76 .map(|value| Secret { 77 value, 78 from_env: true, 79 }) 80}