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