Skip to main content

paper/core/
config.rs

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    /// Pins a model: remote defaults never move it. Unset means follow defaults.
11    #[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    /// Search values are `Option`s so only what the user wrote overrides remote
16    /// config; the built-ins live in `SearchConfig::default()`.
17    #[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    /// `false` stops the daemon installing approved updates.
26    #[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    /// Optional local, OpenAI-compatible server (Ollama, LM Studio, vLLM).
32    /// Only used by `paper answer --polish --engine local`.
33    pub local_engine: LocalEngineConfig,
34    /// Optional cloud fallback. Only used by `paper answer --polish
35    /// --engine openrouter`, and only when an API key is configured.
36    pub openrouter: OpenRouterConfig,
37}
38
39/// Local OpenAI-compatible server used for optional answer polishing.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(default)]
42pub struct LocalEngineConfig {
43    /// Base URL of the server, e.g. `http://localhost:11434`.
44    pub base_url: String,
45    /// Model name as the server knows it, e.g. `llama3.1`.
46    pub model: String,
47    /// Request timeout in seconds.
48    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/// OpenRouter settings for the opt-in cloud fallback.
62#[derive(Debug, Clone, Serialize, Deserialize)]
63#[serde(default)]
64pub struct OpenRouterConfig {
65    /// API key. When empty, `OPENROUTER_API_KEY` from the environment is used.
66    pub api_key: String,
67    /// Model slug, e.g. `anthropic/claude-sonnet-4-5`.
68    pub model: String,
69    /// Request timeout in seconds.
70    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    /// Owner-only on Unix: the file may hold the OpenRouter API key. Written to
130    /// a private temp file in the same directory and renamed over `path`, so a
131    /// reader (or a crash) never sees a half-written config, and the new file
132    /// is 0600 before any content lands in it (tempfile creates it `create_new`
133    /// with an unpredictable name; mode 0600 on Unix). A symlinked config is
134    /// written through, as before.
135    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        // Replaces an existing file (std's rename semantics; MoveFileEx on Windows).
147        // On Windows a replace can fail with "access denied" while another
148        // writer's replace of the same file is still completing, or while a
149        // scanner briefly holds it; that clears in milliseconds, so retry.
150        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    /// Local value > remote value > built-in default. The caller passes only an
169    /// unexpired remote config.
170    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    /// Minimum cosine similarity for a semantic hit. Vector search always has a
200    /// nearest neighbour, so without a floor every query would "find" something.
201    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}