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;
10
11#[cfg(feature = "daemon")]
12pub use daemon::{DaemonControlArgs, DaemonControlCommand};
13
14use crate::core::config::Config;
15use crate::core::index::{init_db, Connection};
16use crate::core::models::{
17    ModelManager, DEFAULT_EMBEDDING, MULTILINGUAL_EMBEDDING, OPTIONAL_RERANKER,
18};
19use crate::core::paths::Paths;
20use crate::core::search::{SearchFilters, SearchPipeline, SharedEmbedder};
21use anyhow::Result;
22use clap::{Args, Subcommand};
23use std::path::PathBuf;
24
25pub const EXIT_FOUND: i32 = 0;
26pub const EXIT_NOT_FOUND: i32 = 1;
27pub const EXIT_ERROR: i32 = 2;
28pub const EXIT_MODEL_MISSING: i32 = 3;
29
30/// Shared state for every subcommand: where things live and what is indexed.
31pub struct Workspace {
32    pub paths: Paths,
33    pub config: Config,
34}
35
36impl Default for Workspace {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl Workspace {
43    pub fn new() -> Self {
44        Self {
45            paths: Paths::new(),
46            config: Config::load().unwrap_or_default(),
47        }
48    }
49
50    /// Search scope: `--root` flags, then the config file, then *everything* in
51    /// the index. Searching must not silently depend on the current directory.
52    pub fn search_roots(&self, flags: &[String]) -> Vec<PathBuf> {
53        if !flags.is_empty() {
54            return flags.iter().map(PathBuf::from).collect();
55        }
56        self.config.roots.clone()
57    }
58
59    /// CLI `--root` flags win, then the config file, then the current directory.
60    pub fn roots(&self, flags: &[String]) -> Vec<PathBuf> {
61        if !flags.is_empty() {
62            return flags.iter().map(PathBuf::from).collect();
63        }
64        if !self.config.roots.is_empty() {
65            return self.config.roots.clone();
66        }
67        std::env::current_dir().map(|d| vec![d]).unwrap_or_default()
68    }
69
70    pub fn open_index(&self) -> Result<Connection> {
71        let conn = Connection::open(&self.paths.db_path())?;
72        init_db(&conn)?;
73        Ok(conn)
74    }
75
76    /// Load the embedder only when it is already on disk: searching must never
77    /// trigger a surprise download. If both embedding models are present the
78    /// multilingual one wins, since it also covers English.
79    pub fn embedder(&self) -> Option<SharedEmbedder> {
80        let manager = ModelManager::new();
81        for candidate in [MULTILINGUAL_EMBEDDING, DEFAULT_EMBEDDING] {
82            if !manager.is_installed(candidate) {
83                continue;
84            }
85            if let Some(embedder) = manager.embedder_if_installed(candidate) {
86                return Some(std::sync::Arc::new(embedder) as SharedEmbedder);
87            }
88        }
89        None
90    }
91
92    pub fn pipeline(&self) -> Result<SearchPipeline> {
93        Ok(SearchPipeline::new(
94            self.open_index()?,
95            self.embedder(),
96            ModelManager::new().reranker_if_installed(),
97            self.config.search(),
98        ))
99    }
100
101    pub fn embedding_model_installed(&self) -> bool {
102        if !cfg!(feature = "embeddings") {
103            // A keyword-only build can never load a model, so it must not
104            // advertise one as installed.
105            return false;
106        }
107        let manager = ModelManager::new();
108        manager.is_installed(DEFAULT_EMBEDDING) || manager.is_installed(MULTILINGUAL_EMBEDDING)
109    }
110
111    pub fn reranker_installed(&self) -> bool {
112        ModelManager::new().is_installed(OPTIONAL_RERANKER)
113    }
114}
115
116#[derive(Args)]
117pub struct SearchArgs {
118    pub query: String,
119    #[arg(long, short)]
120    pub root: Vec<String>,
121    #[arg(long, short, default_value = "10")]
122    pub limit: usize,
123    #[arg(long)]
124    pub json: bool,
125    /// Fail with exit code 3 if the embedding model is not installed.
126    #[arg(long)]
127    pub semantic: bool,
128    /// Only files modified on or after this date (`YYYY-MM-DD`).
129    #[arg(long)]
130    pub after: Option<String>,
131    /// Only files modified on or before this date (`YYYY-MM-DD`).
132    #[arg(long)]
133    pub before: Option<String>,
134    /// Only these extensions, comma-separated (`pdf,docx`).
135    #[arg(long, value_delimiter = ',')]
136    pub ext: Vec<String>,
137    /// Only paths containing this substring.
138    #[arg(long)]
139    pub path: Option<String>,
140}
141
142impl SearchArgs {
143    pub fn filters(&self) -> Result<SearchFilters> {
144        SearchFilters::from_parts(
145            self.after.as_deref(),
146            self.before.as_deref(),
147            &self.ext,
148            self.path.clone(),
149        )
150    }
151}
152
153#[derive(Args)]
154pub struct AnswerArgs {
155    pub question: String,
156    #[arg(long, short)]
157    pub root: Vec<String>,
158    #[arg(long)]
159    pub polish: bool,
160    /// Which engine polishes the answer: `local` (an OpenAI-compatible server
161    /// on this machine) or `openrouter` (opt-in cloud fallback).
162    #[arg(long, default_value = "local", value_parser = ["local", "openrouter"])]
163    pub engine: String,
164    #[arg(long)]
165    pub json: bool,
166    #[arg(long)]
167    pub after: Option<String>,
168    #[arg(long)]
169    pub before: Option<String>,
170    #[arg(long, value_delimiter = ',')]
171    pub ext: Vec<String>,
172    #[arg(long)]
173    pub path: Option<String>,
174}
175
176impl AnswerArgs {
177    pub fn filters(&self) -> Result<SearchFilters> {
178        SearchFilters::from_parts(
179            self.after.as_deref(),
180            self.before.as_deref(),
181            &self.ext,
182            self.path.clone(),
183        )
184    }
185}
186
187#[derive(Args)]
188pub struct IndexArgs {
189    #[arg(long, short)]
190    pub root: Vec<String>,
191    #[arg(long)]
192    pub watch: bool,
193    #[arg(long)]
194    pub file: Option<String>,
195    /// Also load the embedding model so semantic search covers new chunks.
196    #[arg(long)]
197    pub embeddings: bool,
198    /// Enable OCR for scanned PDF pages (requires `ocr` feature and tesseract/pdftoppm).
199    #[arg(long)]
200    pub ocr: bool,
201}
202
203#[derive(Args)]
204pub struct ModelsArgs {
205    #[command(subcommand)]
206    pub command: ModelsCommand,
207}
208
209#[derive(Subcommand)]
210pub enum ModelsCommand {
211    List,
212    Install { model: String },
213    Remove { model: String },
214}
215
216pub async fn run_search(args: SearchArgs) -> Result<i32> {
217    search::run(args).await
218}
219
220pub async fn run_answer(args: AnswerArgs) -> Result<i32> {
221    answer::run(args).await
222}
223
224pub async fn run_index(args: IndexArgs) -> Result<i32> {
225    index::run(args).await
226}
227
228pub async fn run_models(args: ModelsArgs) -> Result<i32> {
229    models::run(args).await
230}
231
232pub async fn run_aggregate(args: aggregate::AggregateArgs) -> Result<i32> {
233    aggregate::run(args).await
234}
235
236pub async fn run_doctor() -> Result<i32> {
237    doctor::run().await
238}
239
240#[cfg(feature = "daemon")]
241pub async fn run_daemon_control(args: DaemonControlArgs) -> Result<i32> {
242    daemon::run(args).await
243}