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 crate::core::effective::note_deprecations(ws.remote.as_ref(), &ws.effective);
22 if let Some(n) = crate::core::update_state::UpdateSummary::load(
23 &ws.paths.base_dir(),
24 &ws.config,
25 ws.remote.as_ref(),
26 )
27 .cli_note()
28 {
29 eprintln!("{n}");
30 }
31
32 if args.polish && !answer.not_found {
33 match polish_answer(&args, &hits).await {
34 Ok((text, engine)) => {
35 answer.text = text;
36 answer.engine = engine;
37 }
38 Err(err) => {
39 eprintln!("note: polish failed ({err:#}); returning the verbatim extract");
42 }
43 }
44 } else if args.polish {
45 eprintln!("note: nothing to polish; returning the verbatim extract");
46 }
47
48 if args.json {
49 println!("{}", serde_json::to_string_pretty(&answer)?);
50 } else {
51 println!("{}", terminal_safe(&answer.render()));
52 }
53 Ok(if answer.not_found {
54 EXIT_NOT_FOUND
55 } else {
56 EXIT_FOUND
57 })
58}
59
60async fn polish_answer(
65 args: &AnswerArgs,
66 hits: &[crate::core::search::Hit],
67) -> Result<(String, String)> {
68 if offline() {
69 anyhow::bail!("PAPER_OFFLINE is set, so no engine may be contacted");
70 }
71 let engine = PolishEngine::parse(&args.engine)?;
72 let config = Config::load()?;
73
74 let (base_url, api_key, model, timeout) = match engine {
75 PolishEngine::Local => (
76 config.local_engine.base_url.clone(),
77 None,
78 config.local_engine.model.clone(),
79 config.local_engine.timeout_secs,
80 ),
81 PolishEngine::OpenRouter => {
82 let key = if config.openrouter.api_key.is_empty() {
83 std::env::var("OPENROUTER_API_KEY").unwrap_or_default()
84 } else {
85 config.openrouter.api_key.clone()
86 };
87 if key.is_empty() {
88 anyhow::bail!(
89 "no OpenRouter API key: set OPENROUTER_API_KEY or [openrouter] api_key in the config"
90 );
91 }
92 (
93 "https://openrouter.ai".to_string(),
94 Some(key),
95 config.openrouter.model.clone(),
96 config.openrouter.timeout_secs,
97 )
98 }
99 };
100
101 if model.trim().is_empty() {
102 anyhow::bail!("no model configured for the {} engine", engine.as_str());
103 }
104
105 let extracts: Vec<Extract> = hits
108 .iter()
109 .filter(|hit| !matches!(hit.confidence, crate::core::search::Confidence::Low))
110 .take(MAX_POLISH_EXTRACTS)
111 .map(|hit| Extract {
112 reference: citation_reference(hit),
113 text: hit.content.clone(),
114 })
115 .collect();
116 if extracts.is_empty() {
117 anyhow::bail!("no extract with enough confidence to polish");
118 }
119
120 let client = ChatClient::new(
121 &base_url,
122 api_key,
123 &model,
124 Duration::from_secs(timeout.max(1)),
125 )?;
126 let text = polish::polish(&client, engine, &args.question, &extracts).await?;
127 let label = format!("{}/{}", engine.as_str(), client.model());
128 Ok((text, label))
129}
130
131fn citation_reference(hit: &crate::core::search::Hit) -> String {
133 let mut reference = hit.path.clone();
134 if let Some(anchor) = &hit.anchor {
135 reference.push_str(&format!(" [{anchor}]"));
136 }
137 if hit.line_start > 0 {
138 reference.push_str(&format!(":{}-{}", hit.line_start, hit.line_end));
139 } else if hit.page > 0 {
140 reference.push_str(&format!(":p.{}", hit.page));
141 }
142 reference
143}
144
145fn offline() -> bool {
146 std::env::var("PAPER_OFFLINE")
147 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
148 .unwrap_or(false)
149}