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