1use super::{terminal_safe, AnswerArgs, Workspace, EXIT_FOUND, EXIT_NOT_FOUND};
2use crate::core::answer::Answer;
3use crate::core::config::Config;
4use crate::core::models::chat::ChatClient;
5use crate::core::models::polish::{self, Extract, PolishEngine};
6use anyhow::Result;
7use std::time::Duration;
8
9const MAX_POLISH_EXTRACTS: usize = 5;
11
12pub async fn run(args: AnswerArgs) -> Result<i32> {
13 let ws = Workspace::new();
14 let roots = ws.search_roots(&args.root);
15 let filters = args.filters()?;
16 let hits = ws
17 .pipeline()?
18 .search_with(&args.question, &roots, &filters)?;
19 let mut answer = Answer::from_hits(&args.question, &hits);
20 ws.note_setup_in_progress();
21
22 if args.polish && !answer.not_found {
23 match polish_answer(&args, &hits).await {
24 Ok((text, engine)) => {
25 answer.text = text;
26 answer.engine = engine;
27 }
28 Err(err) => {
29 eprintln!("note: polish failed ({err:#}); returning the verbatim extract");
32 }
33 }
34 } else if args.polish {
35 eprintln!("note: nothing to polish; returning the verbatim extract");
36 }
37
38 if args.json {
39 println!("{}", serde_json::to_string_pretty(&answer)?);
40 } else {
41 println!("{}", terminal_safe(&answer.render()));
42 }
43 Ok(if answer.not_found {
44 EXIT_NOT_FOUND
45 } else {
46 EXIT_FOUND
47 })
48}
49
50async fn polish_answer(
55 args: &AnswerArgs,
56 hits: &[crate::core::search::Hit],
57) -> Result<(String, String)> {
58 if offline() {
59 anyhow::bail!("PAPER_OFFLINE is set, so no engine may be contacted");
60 }
61 let engine = PolishEngine::parse(&args.engine)?;
62 let config = Config::load()?;
63
64 let (base_url, api_key, model, timeout) = match engine {
65 PolishEngine::Local => (
66 config.local_engine.base_url.clone(),
67 None,
68 config.local_engine.model.clone(),
69 config.local_engine.timeout_secs,
70 ),
71 PolishEngine::OpenRouter => {
72 let key = if config.openrouter.api_key.is_empty() {
73 std::env::var("OPENROUTER_API_KEY").unwrap_or_default()
74 } else {
75 config.openrouter.api_key.clone()
76 };
77 if key.is_empty() {
78 anyhow::bail!(
79 "no OpenRouter API key: set OPENROUTER_API_KEY or [openrouter] api_key in the config"
80 );
81 }
82 (
83 "https://openrouter.ai".to_string(),
84 Some(key),
85 config.openrouter.model.clone(),
86 config.openrouter.timeout_secs,
87 )
88 }
89 };
90
91 if model.trim().is_empty() {
92 anyhow::bail!("no model configured for the {} engine", engine.as_str());
93 }
94
95 let extracts: Vec<Extract> = hits
98 .iter()
99 .filter(|hit| !matches!(hit.confidence, crate::core::search::Confidence::Low))
100 .take(MAX_POLISH_EXTRACTS)
101 .map(|hit| Extract {
102 reference: citation_reference(hit),
103 text: hit.content.clone(),
104 })
105 .collect();
106 if extracts.is_empty() {
107 anyhow::bail!("no extract with enough confidence to polish");
108 }
109
110 let client = ChatClient::new(
111 &base_url,
112 api_key,
113 &model,
114 Duration::from_secs(timeout.max(1)),
115 )?;
116 let text = polish::polish(&client, engine, &args.question, &extracts).await?;
117 let label = format!("{}/{}", engine.as_str(), client.model());
118 Ok((text, label))
119}
120
121fn citation_reference(hit: &crate::core::search::Hit) -> String {
123 let mut reference = hit.path.clone();
124 if let Some(anchor) = &hit.anchor {
125 reference.push_str(&format!(" [{anchor}]"));
126 }
127 if hit.line_start > 0 {
128 reference.push_str(&format!(":{}-{}", hit.line_start, hit.line_end));
129 } else if hit.page > 0 {
130 reference.push_str(&format!(":p.{}", hit.page));
131 }
132 reference
133}
134
135fn offline() -> bool {
136 std::env::var("PAPER_OFFLINE")
137 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
138 .unwrap_or(false)
139}