Skip to main content

paper/core/
config.rs

1use super::paths::{create_private_dir, Paths};
2use serde::{Deserialize, Serialize};
3use std::io::Write;
4use std::path::PathBuf;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7#[serde(default)]
8pub struct Config {
9    pub keyword_sufficiency_threshold: usize,
10    pub rerank_top: usize,
11    pub rrf_k: i32,
12    pub max_chunk_tokens: usize,
13    pub chunk_overlap: usize,
14    pub roots: Vec<PathBuf>,
15    /// Optional local, OpenAI-compatible server (Ollama, LM Studio, vLLM).
16    /// Only used by `paper answer --polish --engine local`.
17    pub local_engine: LocalEngineConfig,
18    /// Optional cloud fallback. Only used by `paper answer --polish
19    /// --engine openrouter`, and only when an API key is configured.
20    pub openrouter: OpenRouterConfig,
21}
22
23/// Local OpenAI-compatible server used for optional answer polishing.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25#[serde(default)]
26pub struct LocalEngineConfig {
27    /// Base URL of the server, e.g. `http://localhost:11434`.
28    pub base_url: String,
29    /// Model name as the server knows it, e.g. `llama3.1`.
30    pub model: String,
31    /// Request timeout in seconds.
32    pub timeout_secs: u64,
33}
34
35impl Default for LocalEngineConfig {
36    fn default() -> Self {
37        Self {
38            base_url: String::new(),
39            model: String::new(),
40            timeout_secs: 60,
41        }
42    }
43}
44
45/// OpenRouter settings for the opt-in cloud fallback.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(default)]
48pub struct OpenRouterConfig {
49    /// API key. When empty, `OPENROUTER_API_KEY` from the environment is used.
50    pub api_key: String,
51    /// Model slug, e.g. `anthropic/claude-sonnet-4-5`.
52    pub model: String,
53    /// Request timeout in seconds.
54    pub timeout_secs: u64,
55}
56
57impl Default for OpenRouterConfig {
58    fn default() -> Self {
59        Self {
60            api_key: String::new(),
61            model: String::new(),
62            timeout_secs: 120,
63        }
64    }
65}
66
67impl Default for Config {
68    fn default() -> Self {
69        Self {
70            keyword_sufficiency_threshold: 10,
71            rerank_top: 20,
72            rrf_k: 60,
73            max_chunk_tokens: 400,
74            chunk_overlap: 40,
75            roots: vec![],
76            local_engine: LocalEngineConfig::default(),
77            openrouter: OpenRouterConfig::default(),
78        }
79    }
80}
81
82impl Config {
83    pub fn load() -> anyhow::Result<Self> {
84        Self::load_from(&Paths::new().config_path())
85    }
86
87    pub fn load_from(path: &std::path::Path) -> anyhow::Result<Self> {
88        if path.exists() {
89            let content = std::fs::read_to_string(path)?;
90            match toml::from_str(&content) {
91                Ok(config) => Ok(config),
92                Err(e) => {
93                    tracing::warn!(
94                        "Config file at {} is corrupt ({e:#}); falling back to defaults",
95                        path.display()
96                    );
97                    Ok(Self::default())
98                }
99            }
100        } else {
101            Ok(Self::default())
102        }
103    }
104
105    pub fn save(&self) -> anyhow::Result<()> {
106        self.save_to(&Paths::new().config_path())
107    }
108
109    /// Owner-only on Unix: the file may hold the OpenRouter API key. Written to
110    /// a private temp file in the same directory and renamed over `path`, so a
111    /// reader (or a crash) never sees a half-written config, and the new file
112    /// is 0600 before any content lands in it (tempfile creates it `create_new`
113    /// with an unpredictable name; mode 0600 on Unix). A symlinked config is
114    /// written through, as before.
115    pub fn save_to(&self, path: &std::path::Path) -> anyhow::Result<()> {
116        let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
117        let parent = path.parent().unwrap_or(std::path::Path::new("."));
118        create_private_dir(parent)?;
119        let contents = toml::to_string_pretty(self)?;
120        let mut temp = tempfile::Builder::new()
121            .prefix(".config-")
122            .suffix(".tmp")
123            .tempfile_in(parent)?;
124        temp.write_all(contents.as_bytes())?;
125        temp.as_file().sync_all()?;
126        // Replaces an existing file (std's rename semantics; MoveFileEx on Windows).
127        // On Windows a replace can fail with "access denied" while another
128        // writer's replace of the same file is still completing, or while a
129        // scanner briefly holds it; that clears in milliseconds, so retry.
130        let mut attempt = 0;
131        loop {
132            match temp.persist(&path) {
133                Ok(_) => return Ok(()),
134                Err(e)
135                    if cfg!(windows)
136                        && e.error.kind() == std::io::ErrorKind::PermissionDenied
137                        && attempt < 50 =>
138                {
139                    temp = e.file;
140                    attempt += 1;
141                    std::thread::sleep(std::time::Duration::from_millis(10));
142                }
143                Err(e) => return Err(e.error.into()),
144            }
145        }
146    }
147
148    pub fn search(&self) -> SearchConfig {
149        SearchConfig {
150            keyword_sufficiency_threshold: self.keyword_sufficiency_threshold,
151            rerank_top: self.rerank_top,
152            rrf_k: self.rrf_k,
153            ..SearchConfig::default()
154        }
155    }
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
159#[serde(default)]
160pub struct SearchConfig {
161    pub keyword_sufficiency_threshold: usize,
162    pub rerank_top: usize,
163    pub rrf_k: i32,
164    pub keyword_limit: usize,
165    pub semantic_limit: usize,
166    pub fused_limit: usize,
167    /// Minimum cosine similarity for a semantic hit. Vector search always has a
168    /// nearest neighbour, so without a floor every query would "find" something.
169    pub semantic_min_score: f32,
170}
171
172impl Default for SearchConfig {
173    fn default() -> Self {
174        Self {
175            keyword_sufficiency_threshold: 10,
176            rerank_top: 20,
177            rrf_k: 60,
178            keyword_limit: 20,
179            semantic_limit: 20,
180            fused_limit: 50,
181            semantic_min_score: 0.25,
182        }
183    }
184}