1use super::paths::{create_private_dir, Paths};
2use super::remote_config::RemoteConfig;
3use serde::{Deserialize, Serialize};
4use std::io::Write;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8#[serde(default)]
9pub struct Config {
10 #[serde(skip_serializing_if = "Option::is_none")]
12 pub embedder: Option<String>,
13 #[serde(skip_serializing_if = "Option::is_none")]
14 pub reranker: Option<String>,
15 #[serde(skip_serializing_if = "Option::is_none")]
18 pub keyword_sufficiency_threshold: Option<usize>,
19 #[serde(skip_serializing_if = "Option::is_none")]
20 pub rerank_top: Option<usize>,
21 #[serde(skip_serializing_if = "Option::is_none")]
22 pub rrf_k: Option<i32>,
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub semantic_min_score: Option<f32>,
25 #[serde(skip_serializing_if = "Option::is_none")]
27 pub auto_update: Option<bool>,
28 pub max_chunk_tokens: usize,
29 pub chunk_overlap: usize,
30 pub roots: Vec<PathBuf>,
31 pub local_engine: LocalEngineConfig,
34 pub openrouter: OpenRouterConfig,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(default)]
42pub struct LocalEngineConfig {
43 pub base_url: String,
45 pub model: String,
47 pub timeout_secs: u64,
49}
50
51impl Default for LocalEngineConfig {
52 fn default() -> Self {
53 Self {
54 base_url: String::new(),
55 model: String::new(),
56 timeout_secs: 60,
57 }
58 }
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
63#[serde(default)]
64pub struct OpenRouterConfig {
65 pub api_key: String,
67 pub model: String,
69 pub timeout_secs: u64,
71}
72
73impl Default for OpenRouterConfig {
74 fn default() -> Self {
75 Self {
76 api_key: String::new(),
77 model: String::new(),
78 timeout_secs: 120,
79 }
80 }
81}
82
83impl Default for Config {
84 fn default() -> Self {
85 Self {
86 embedder: None,
87 reranker: None,
88 keyword_sufficiency_threshold: None,
89 rerank_top: None,
90 rrf_k: None,
91 semantic_min_score: None,
92 auto_update: None,
93 max_chunk_tokens: 400,
94 chunk_overlap: 40,
95 roots: vec![],
96 local_engine: LocalEngineConfig::default(),
97 openrouter: OpenRouterConfig::default(),
98 }
99 }
100}
101
102impl Config {
103 pub fn load() -> anyhow::Result<Self> {
104 Self::load_from(&Paths::new().config_path())
105 }
106
107 pub fn load_from(path: &std::path::Path) -> anyhow::Result<Self> {
108 if path.exists() {
109 let content = std::fs::read_to_string(path)?;
110 match toml::from_str(&content) {
111 Ok(config) => Ok(config),
112 Err(e) => {
113 tracing::warn!(
114 "Config file at {} is corrupt ({e:#}); falling back to defaults",
115 path.display()
116 );
117 Ok(Self::default())
118 }
119 }
120 } else {
121 Ok(Self::default())
122 }
123 }
124
125 pub fn save(&self) -> anyhow::Result<()> {
126 self.save_to(&Paths::new().config_path())
127 }
128
129 pub fn save_to(&self, path: &std::path::Path) -> anyhow::Result<()> {
136 let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
137 let parent = path.parent().unwrap_or(std::path::Path::new("."));
138 create_private_dir(parent)?;
139 let contents = toml::to_string_pretty(self)?;
140 let mut temp = tempfile::Builder::new()
141 .prefix(".config-")
142 .suffix(".tmp")
143 .tempfile_in(parent)?;
144 temp.write_all(contents.as_bytes())?;
145 temp.as_file().sync_all()?;
146 let mut attempt = 0;
151 loop {
152 match temp.persist(&path) {
153 Ok(_) => return Ok(()),
154 Err(e)
155 if cfg!(windows)
156 && e.error.kind() == std::io::ErrorKind::PermissionDenied
157 && attempt < 50 =>
158 {
159 temp = e.file;
160 attempt += 1;
161 std::thread::sleep(std::time::Duration::from_millis(10));
162 }
163 Err(e) => return Err(e.error.into()),
164 }
165 }
166 }
167
168 pub fn search(&self, remote: Option<&RemoteConfig>) -> SearchConfig {
171 let d = SearchConfig::default();
172 SearchConfig {
173 keyword_sufficiency_threshold: self
174 .keyword_sufficiency_threshold
175 .unwrap_or(d.keyword_sufficiency_threshold),
176 rerank_top: self
177 .rerank_top
178 .or(remote.and_then(|r| r.search.rerank_top))
179 .unwrap_or(d.rerank_top),
180 rrf_k: self.rrf_k.unwrap_or(d.rrf_k),
181 semantic_min_score: self
182 .semantic_min_score
183 .or(remote.and_then(|r| r.search.semantic_min_score))
184 .unwrap_or(d.semantic_min_score),
185 ..d
186 }
187 }
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
191#[serde(default)]
192pub struct SearchConfig {
193 pub keyword_sufficiency_threshold: usize,
194 pub rerank_top: usize,
195 pub rrf_k: i32,
196 pub keyword_limit: usize,
197 pub semantic_limit: usize,
198 pub fused_limit: usize,
199 pub semantic_min_score: f32,
202}
203
204impl Default for SearchConfig {
205 fn default() -> Self {
206 Self {
207 keyword_sufficiency_threshold: 10,
208 rerank_top: 20,
209 rrf_k: 60,
210 keyword_limit: 20,
211 semantic_limit: 20,
212 fused_limit: 50,
213 semantic_min_score: 0.25,
214 }
215 }
216}