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