Skip to main content

paper/cli/
mod.rs

1pub mod aggregate;
2pub mod answer;
3#[cfg(feature = "daemon")]
4pub mod daemon;
5pub mod doctor;
6pub mod index;
7pub mod model_downloader;
8pub mod models;
9pub mod search;
10pub mod uninstall;
11pub mod update;
12
13#[cfg(feature = "daemon")]
14pub use daemon::{DaemonControlArgs, DaemonControlCommand};
15pub use uninstall::UninstallArgs;
16pub use update::UpdateArgs;
17
18use crate::core::config::Config;
19use crate::core::effective::{load_live_remote, resolve, Effective};
20use crate::core::index::{init_db, Connection};
21use crate::core::models::{ModelManager, DEFAULT_EMBEDDING, MULTILINGUAL_EMBEDDING};
22use crate::core::paths::Paths;
23use crate::core::remote_config::RemoteConfig;
24use crate::core::search::{SearchFilters, SearchPipeline, SharedEmbedder};
25use anyhow::Result;
26use clap::{Args, Subcommand};
27use std::path::PathBuf;
28
29pub const EXIT_FOUND: i32 = 0;
30pub const EXIT_NOT_FOUND: i32 = 1;
31pub const EXIT_ERROR: i32 = 2;
32pub const EXIT_MODEL_MISSING: i32 = 3;
33
34/// Shared state for every subcommand: where things live and what is indexed.
35pub struct Workspace {
36    pub paths: Paths,
37    pub config: Config,
38    /// Single `ModelManager`, constructed once so search/model checks don't
39    /// rebuild the client and spec list on every call (M2).
40    pub model_manager: ModelManager,
41    /// Verified, unexpired remote config from the local cache (never fetched here).
42    pub remote: Option<RemoteConfig>,
43    pub effective: Effective,
44}
45
46impl Default for Workspace {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52impl Workspace {
53    pub fn new() -> Self {
54        let config = Config::load().unwrap_or_default();
55        let today = chrono::Local::now().date_naive();
56        let remote = load_live_remote(today);
57        Self {
58            paths: Paths::new(),
59            effective: resolve(&config, remote.as_ref(), today),
60            model_manager: ModelManager::new().with_remote(remote.as_ref()),
61            config,
62            remote,
63        }
64    }
65
66    /// One stderr line when the daemon is still setting up (stdout stays clean).
67    pub fn note_setup_in_progress(&self) {
68        if let Some(phase) = self.setup_status() {
69            eprintln!(
70                "note: Paper is still setting up in the background: {phase}. Results will fill in when it finishes."
71            );
72        }
73    }
74
75    /// Background-setup phase; the status file belongs to the daemon feature.
76    pub fn setup_status(&self) -> Option<String> {
77        #[cfg(feature = "daemon")]
78        return crate::bootstrap::setup_status(&self.paths);
79        #[cfg(not(feature = "daemon"))]
80        None
81    }
82
83    /// Search scope: `--root` flags, then the config file, then *everything* in
84    /// the index. Searching must not silently depend on the current directory.
85    pub fn search_roots(&self, flags: &[String]) -> Vec<PathBuf> {
86        if !flags.is_empty() {
87            return flags.iter().map(PathBuf::from).collect();
88        }
89        self.config.roots.clone()
90    }
91
92    /// CLI `--root` flags win, then the config file, then the current directory.
93    pub fn roots(&self, flags: &[String]) -> Vec<PathBuf> {
94        if !flags.is_empty() {
95            return flags.iter().map(PathBuf::from).collect();
96        }
97        if !self.config.roots.is_empty() {
98            return self.config.roots.clone();
99        }
100        std::env::current_dir().map(|d| vec![d]).unwrap_or_default()
101    }
102
103    pub fn open_index(&self) -> Result<Connection> {
104        let conn = Connection::open(&self.paths.db_path())?;
105        init_db(&conn)?;
106        Ok(conn)
107    }
108
109    /// Load the embedder only when it is already on disk: searching must never
110    /// trigger a surprise download. The effective embedder is tried first, then
111    /// any other installed one (multilingual before English-only).
112    pub fn embedder(&self) -> Option<SharedEmbedder> {
113        let manager = &self.model_manager;
114        for candidate in [
115            self.effective.embedder.as_str(),
116            MULTILINGUAL_EMBEDDING,
117            DEFAULT_EMBEDDING,
118        ] {
119            if !manager.is_installed(candidate) {
120                continue;
121            }
122            if let Some(embedder) = manager.embedder_if_installed(candidate) {
123                return Some(std::sync::Arc::new(embedder) as SharedEmbedder);
124            }
125        }
126        None
127    }
128
129    pub fn pipeline(&self) -> Result<SearchPipeline> {
130        Ok(SearchPipeline::new(
131            self.open_index()?,
132            self.embedder(),
133            self.model_manager
134                .reranker_if_installed(&self.effective.reranker)
135                .map(std::sync::Arc::new),
136            self.config.search(self.remote.as_ref()),
137        ))
138    }
139
140    pub fn embedding_model_installed(&self) -> bool {
141        if !cfg!(feature = "embeddings") {
142            // A keyword-only build can never load a model, so it must not
143            // advertise one as installed.
144            return false;
145        }
146        let manager = &self.model_manager;
147        manager.is_installed(DEFAULT_EMBEDDING) || manager.is_installed(MULTILINGUAL_EMBEDDING)
148    }
149
150    pub fn reranker_installed(&self) -> bool {
151        self.model_manager.is_installed(&self.effective.reranker)
152    }
153}
154
155#[derive(Args)]
156pub struct SearchArgs {
157    pub query: String,
158    #[arg(long, short)]
159    pub root: Vec<String>,
160    #[arg(long, short, default_value = "10")]
161    pub limit: usize,
162    #[arg(long)]
163    pub json: bool,
164    /// Fail with exit code 3 if the embedding model is not installed.
165    #[arg(long)]
166    pub semantic: bool,
167    /// Only files modified on or after this date (`YYYY-MM-DD`).
168    #[arg(long)]
169    pub after: Option<String>,
170    /// Only files modified on or before this date (`YYYY-MM-DD`).
171    #[arg(long)]
172    pub before: Option<String>,
173    /// Only these extensions, comma-separated (`pdf,docx`).
174    #[arg(long, value_delimiter = ',')]
175    pub ext: Vec<String>,
176    /// Only paths containing this substring.
177    #[arg(long)]
178    pub path: Option<String>,
179}
180
181impl SearchArgs {
182    pub fn filters(&self) -> Result<SearchFilters> {
183        SearchFilters::from_parts(
184            self.after.as_deref(),
185            self.before.as_deref(),
186            &self.ext,
187            self.path.clone(),
188        )
189    }
190}
191
192#[derive(Args)]
193pub struct AnswerArgs {
194    pub question: String,
195    #[arg(long, short)]
196    pub root: Vec<String>,
197    #[arg(long)]
198    pub polish: bool,
199    /// Which engine polishes the answer: `local` (an OpenAI-compatible server
200    /// on this machine) or `openrouter` (opt-in cloud fallback).
201    #[arg(long, default_value = "local", value_parser = ["local", "openrouter"])]
202    pub engine: String,
203    #[arg(long)]
204    pub json: bool,
205    #[arg(long)]
206    pub after: Option<String>,
207    #[arg(long)]
208    pub before: Option<String>,
209    #[arg(long, value_delimiter = ',')]
210    pub ext: Vec<String>,
211    #[arg(long)]
212    pub path: Option<String>,
213}
214
215impl AnswerArgs {
216    pub fn filters(&self) -> Result<SearchFilters> {
217        SearchFilters::from_parts(
218            self.after.as_deref(),
219            self.before.as_deref(),
220            &self.ext,
221            self.path.clone(),
222        )
223    }
224}
225
226#[derive(Args)]
227pub struct IndexArgs {
228    #[arg(long, short)]
229    pub root: Vec<String>,
230    #[arg(long)]
231    pub watch: bool,
232    #[arg(long)]
233    pub file: Option<String>,
234    /// Also load the embedding model so semantic search covers new chunks.
235    #[arg(long)]
236    pub embeddings: bool,
237    /// Force OCR for scanned pages and images (on by default when the OCR
238    /// models are installed).
239    #[arg(long)]
240    pub ocr: bool,
241    /// Skip OCR even when the models are installed.
242    #[arg(long)]
243    pub no_ocr: bool,
244}
245
246#[derive(Args)]
247pub struct ModelsArgs {
248    #[command(subcommand)]
249    pub command: ModelsCommand,
250}
251
252#[derive(Subcommand)]
253pub enum ModelsCommand {
254    List,
255    Install { model: String },
256    Remove { model: String },
257}
258
259pub async fn run_search(args: SearchArgs) -> Result<i32> {
260    search::run(args).await
261}
262
263pub async fn run_answer(args: AnswerArgs) -> Result<i32> {
264    answer::run(args).await
265}
266
267pub async fn run_index(args: IndexArgs) -> Result<i32> {
268    index::run(args).await
269}
270
271pub async fn run_models(args: ModelsArgs) -> Result<i32> {
272    models::run(args).await
273}
274
275pub async fn run_aggregate(args: aggregate::AggregateArgs) -> Result<i32> {
276    aggregate::run(args).await
277}
278
279pub async fn run_doctor() -> Result<i32> {
280    doctor::run().await
281}
282
283#[cfg(feature = "daemon")]
284pub async fn run_daemon_control(args: DaemonControlArgs) -> Result<i32> {
285    daemon::run(args).await
286}
287
288/// Drop control characters (C0, DEL, C1) except `\n` and `\t` from text
289/// headed for a terminal, so an indexed document cannot inject escape
290/// sequences. Same filter as `polish::sanitize`, without the trim.
291fn terminal_safe(text: &str) -> String {
292    text.chars()
293        .filter(|c| !c.is_control() || *c == '\n' || *c == '\t')
294        .collect()
295}
296
297#[cfg(test)]
298mod tests {
299    use super::terminal_safe;
300
301    #[test]
302    fn terminal_safe_drops_control_characters_and_keeps_printable_text() {
303        let raw = "a\x1b[2Jb\x1b]0;pwned\x07c\u{9b}31md\x7fe\r\nf\tg  ";
304        assert_eq!(terminal_safe(raw), "a[2Jb]0;pwnedc31mde\nf\tg  ");
305        assert_eq!(terminal_safe("Grüße, 世界"), "Grüße, 世界");
306    }
307}