vtcode_core/commands/
ask.rs1use crate::cli::input_hardening::validate_agent_safe_text;
4use crate::config::types::AgentConfig;
5use crate::llm::collect_single_response;
6use crate::llm::factory::{ProviderConfig, create_provider_with_config, infer_provider_from_model};
7use crate::llm::provider::{LLMRequest, Message};
8use crate::prompts::system::lightweight_instruction_text;
9use anyhow::Result;
10use std::io::IsTerminal;
11use std::sync::Arc;
12
13#[cfg_attr(feature = "profiling", hotpath::measure)]
15pub async fn handle_ask_command(
16 config: AgentConfig,
17 prompt: Vec<String>,
18 options: crate::cli::AskCommandOptions,
19) -> Result<()> {
20 let prompt_text = prompt.join(" ");
21 validate_agent_safe_text("prompt", &prompt_text)?;
22
23 if config.verbose {
24 tracing::debug!(model = %config.model, prompt = %prompt_text, "Sending prompt");
25 }
26
27 let request = LLMRequest {
28 messages: Arc::new(vec![Message::user(prompt_text)]),
29 system_prompt: Some(Arc::from(lightweight_instruction_text())),
30 model: config.model.clone(),
31 ..Default::default()
32 };
33 let provider_name = if config.provider.trim().is_empty() {
34 infer_provider_from_model(&request.model)
35 .map(|provider| provider.to_string())
36 .ok_or_else(|| anyhow::anyhow!("Cannot determine provider for model: {}", request.model))?
37 } else {
38 config.provider.to_lowercase()
39 };
40 let provider = create_provider_with_config(
41 &provider_name,
42 ProviderConfig {
43 api_key: Some(config.api_key.clone()),
44 openai_chatgpt_auth: config.openai_chatgpt_auth.clone(),
45 copilot_auth: None,
46 base_url: None,
47 model: Some(request.model.clone()),
48 prompt_cache: None,
49 timeouts: None,
50 openai: None,
51 anthropic: None,
52 openrouter: None,
53 model_behavior: config.model_behavior.clone(),
54 workspace_root: Some(config.workspace.clone()),
55 },
56 )?;
57 let backend_kind = provider.name().to_string();
58 let response = collect_single_response(provider.as_ref(), request).await?;
59 let response_model = if response.model.is_empty() {
60 config.model.clone()
61 } else {
62 response.model.clone()
63 };
64
65 if let Some(crate::cli::args::AskOutputFormat::Json) = options.output_format {
67 let output = serde_json::json!({
69 "response": response,
70 "provider": {
71 "kind": backend_kind,
72 "model": response_model,
73 }
74 });
75 use std::io::Write;
76 let mut stdout = std::io::stdout().lock();
77 serde_json::to_writer_pretty(&mut stdout, &output)?;
78 writeln!(stdout)?;
79 } else {
80 use std::io::Write;
81 let mut stdout = std::io::stdout().lock();
82 if is_pipe_output() {
83 if let Some(code_only) = extract_code_only(response.content_text()) {
84 write!(stdout, "{code_only}")?;
85 } else {
86 writeln!(stdout, "{}", response.content_text())?;
87 }
88 } else {
89 writeln!(stdout, "{}", response.content_text())?;
91 }
92 }
93
94 Ok(())
95}
96
97fn is_pipe_output() -> bool {
98 !std::io::stdout().is_terminal()
99}
100
101fn extract_code_only(text: &str) -> Option<String> {
102 let blocks = extract_code_fence_blocks(text);
103 let block = select_best_code_block(&blocks)?;
104 let mut output = block.lines.join("\n");
105 if !output.ends_with('\n') {
106 output.push('\n');
107 }
108 Some(output)
109}
110
111#[cfg(test)]
112mod tests {
113 use super::*;
114
115 #[test]
116 fn code_only_returns_none_without_fences() {
117 assert_eq!(extract_code_only("plain response text"), None);
118 }
119
120 #[test]
121 fn code_only_returns_none_for_unclosed_fence() {
122 assert_eq!(extract_code_only("```rust\nlet x = 1;\n"), None);
123 }
124
125 #[test]
126 fn code_only_returns_none_for_empty_block() {
127 assert_eq!(extract_code_only("```\n```"), None);
128 }
129
130 #[test]
131 fn code_only_terminates_output_with_newline() {
132 assert_eq!(extract_code_only("```\ncode\n```").as_deref(), Some("code\n"));
133 }
134
135 #[test]
136 fn code_only_strips_carriage_returns() {
137 assert_eq!(extract_code_only("```\r\ncode\r\n```\r\n").as_deref(), Some("code\n"));
138 }
139
140 #[test]
141 fn code_only_prefers_more_lines_over_language_tag() {
142 let text = "```rust\nlet x = 1;\n```\n\n```\nline one\nline two\nline three\n```";
143 assert_eq!(extract_code_only(text).as_deref(), Some("line one\nline two\nline three\n"));
144 }
145
146 #[test]
147 fn code_only_prefers_language_tag_on_line_tie_regardless_of_order() {
148 let plain_first = "```\nplain one\nplain two\n```\n\n```python\npy one\npy two\n```";
149 assert_eq!(extract_code_only(plain_first).as_deref(), Some("py one\npy two\n"));
150
151 let tagged_first = "```python\npy one\npy two\n```\n\n```\nplain one\nplain two\n```";
152 assert_eq!(extract_code_only(tagged_first).as_deref(), Some("py one\npy two\n"));
153 }
154
155 #[test]
156 fn code_only_ignores_blank_lines_when_scoring() {
157 let text = "```\n\n\n```\n\n```\ncode\n```";
158 assert_eq!(extract_code_only(text).as_deref(), Some("code\n"));
159 }
160}
161
162fn extract_code_fence_blocks(text: &str) -> Vec<CodeFenceBlock> {
163 let mut blocks = Vec::new();
164 let mut current_language: Option<String> = None;
165 let mut current_lines: Vec<String> = Vec::new();
166
167 for raw_line in text.lines() {
168 let trimmed_start = raw_line.trim_start();
169 if let Some(rest) = trimmed_start.strip_prefix("```") {
170 let rest_clean = rest.trim_matches('\r');
171 let rest_trimmed = rest_clean.trim();
172 if current_language.is_some() {
173 if rest_trimmed.is_empty() {
174 let language = current_language.take().and_then(|lang| {
175 let cleaned = lang.trim_matches(|ch| matches!(ch, '"' | '\'' | '`'));
176 let cleaned = cleaned.trim();
177 if cleaned.is_empty() {
178 None
179 } else {
180 Some(cleaned.to_string())
181 }
182 });
183 let block_lines = std::mem::take(&mut current_lines);
184 blocks.push(CodeFenceBlock { language, lines: block_lines });
185 continue;
186 }
187 } else {
188 let token = rest_trimmed.split_whitespace().next().unwrap_or_default();
189 let normalized = token.trim_matches(|ch| matches!(ch, '"' | '\'' | '`')).trim();
190 current_language = Some(normalized.to_ascii_lowercase());
191 current_lines.clear();
192 continue;
193 }
194 }
195
196 if current_language.is_some() {
197 current_lines.push(raw_line.trim_end_matches('\r').to_string());
198 }
199 }
200
201 blocks
202}
203
204fn select_best_code_block(blocks: &[CodeFenceBlock]) -> Option<&CodeFenceBlock> {
205 let mut best = None;
206 let mut best_score = (0usize, 0u8);
207 for block in blocks {
208 let score = score_code_block(block);
209 if score > best_score {
210 best_score = score;
211 best = Some(block);
212 }
213 }
214 best
215}
216
217fn score_code_block(block: &CodeFenceBlock) -> (usize, u8) {
218 let line_count = block.lines.iter().filter(|line| !line.trim().is_empty()).count();
219 let has_language = block.language.as_ref().is_some_and(|lang| !lang.trim().is_empty());
220 (line_count, if has_language { 1 } else { 0 })
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
224struct CodeFenceBlock {
225 language: Option<String>,
226 lines: Vec<String>,
227}