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
103                .reranker_if_installed()
104                .map(std::sync::Arc::new),
105            self.config.search(),
106        ))
107    }
108
109    pub fn embedding_model_installed(&self) -> bool {
110        if !cfg!(feature = "embeddings") {
111            // A keyword-only build can never load a model, so it must not
112            // advertise one as installed.
113            return false;
114        }
115        let manager = &self.model_manager;
116        manager.is_installed(DEFAULT_EMBEDDING) || manager.is_installed(MULTILINGUAL_EMBEDDING)
117    }
118
119    pub fn reranker_installed(&self) -> bool {
120        self.model_manager.is_installed(OPTIONAL_RERANKER)
121    }
122}
123
124#[derive(Args)]
125pub struct SearchArgs {
126    pub query: String,
127    #[arg(long, short)]
128    pub root: Vec<String>,
129    #[arg(long, short, default_value = "10")]
130    pub limit: usize,
131    #[arg(long)]
132    pub json: bool,
133    /// Fail with exit code 3 if the embedding model is not installed.
134    #[arg(long)]
135    pub semantic: bool,
136    /// Only files modified on or after this date (`YYYY-MM-DD`).
137    #[arg(long)]
138    pub after: Option<String>,
139    /// Only files modified on or before this date (`YYYY-MM-DD`).
140    #[arg(long)]
141    pub before: Option<String>,
142    /// Only these extensions, comma-separated (`pdf,docx`).
143    #[arg(long, value_delimiter = ',')]
144    pub ext: Vec<String>,
145    /// Only paths containing this substring.
146    #[arg(long)]
147    pub path: Option<String>,
148}
149
150impl SearchArgs {
151    pub fn filters(&self) -> Result<SearchFilters> {
152        SearchFilters::from_parts(
153            self.after.as_deref(),
154            self.before.as_deref(),
155            &self.ext,
156            self.path.clone(),
157        )
158    }
159}
160
161#[derive(Args)]
162pub struct AnswerArgs {
163    pub question: String,
164    #[arg(long, short)]
165    pub root: Vec<String>,
166    #[arg(long)]
167    pub polish: bool,
168    /// Which engine polishes the answer: `local` (an OpenAI-compatible server
169    /// on this machine) or `openrouter` (opt-in cloud fallback).
170    #[arg(long, default_value = "local", value_parser = ["local", "openrouter"])]
171    pub engine: String,
172    #[arg(long)]
173    pub json: bool,
174    #[arg(long)]
175    pub after: Option<String>,
176    #[arg(long)]
177    pub before: Option<String>,
178    #[arg(long, value_delimiter = ',')]
179    pub ext: Vec<String>,
180    #[arg(long)]
181    pub path: Option<String>,
182}
183
184impl AnswerArgs {
185    pub fn filters(&self) -> Result<SearchFilters> {
186        SearchFilters::from_parts(
187            self.after.as_deref(),
188            self.before.as_deref(),
189            &self.ext,
190            self.path.clone(),
191        )
192    }
193}
194
195#[derive(Args)]
196pub struct IndexArgs {
197    #[arg(long, short)]
198    pub root: Vec<String>,
199    #[arg(long)]
200    pub watch: bool,
201    #[arg(long)]
202    pub file: Option<String>,
203    /// Also load the embedding model so semantic search covers new chunks.
204    #[arg(long)]
205    pub embeddings: bool,
206    /// Force OCR for scanned pages and images (on by default when the OCR
207    /// models are installed).
208    #[arg(long)]
209    pub ocr: bool,
210    /// Skip OCR even when the models are installed.
211    #[arg(long)]
212    pub no_ocr: bool,
213}
214
215#[derive(Args)]
216pub struct ModelsArgs {
217    #[command(subcommand)]
218    pub command: ModelsCommand,
219}
220
221#[derive(Subcommand)]
222pub enum ModelsCommand {
223    List,
224    Install { model: String },
225    Remove { model: String },
226}
227
228pub async fn run_search(args: SearchArgs) -> Result<i32> {
229    search::run(args).await
230}
231
232pub async fn run_answer(args: AnswerArgs) -> Result<i32> {
233    answer::run(args).await
234}
235
236pub async fn run_index(args: IndexArgs) -> Result<i32> {
237    index::run(args).await
238}
239
240pub async fn run_models(args: ModelsArgs) -> Result<i32> {
241    models::run(args).await
242}
243
244pub async fn run_aggregate(args: aggregate::AggregateArgs) -> Result<i32> {
245    aggregate::run(args).await
246}
247
248pub async fn run_doctor() -> Result<i32> {
249    doctor::run().await
250}
251
252#[cfg(feature = "daemon")]
253pub async fn run_daemon_control(args: DaemonControlArgs) -> Result<i32> {
254    daemon::run(args).await
255}
256
257/// Drop control characters (C0, DEL, C1) except `\n` and `\t` from text
258/// headed for a terminal, so an indexed document cannot inject escape
259/// sequences. Same filter as `polish::sanitize`, without the trim.
260fn terminal_safe(text: &str) -> String {
261    text.chars()
262        .filter(|c| !c.is_control() || *c == '\n' || *c == '\t')
263        .collect()
264}
265
266#[cfg(test)]
267mod tests {
268    use super::terminal_safe;
269
270    #[test]
271    fn terminal_safe_drops_control_characters_and_keeps_printable_text() {
272        let raw = "a\x1b[2Jb\x1b]0;pwned\x07c\u{9b}31md\x7fe\r\nf\tg  ";
273        assert_eq!(terminal_safe(raw), "a[2Jb]0;pwnedc31mde\nf\tg  ");
274        assert_eq!(terminal_safe("Grüße, 世界"), "Grüße, 世界");
275    }
276}