vtcode_core/tools/source_inspection/
exposure.rs1use super::*;
2use crate::config::constants::tools;
3use crate::llm::provider::{Message, MessageRole};
4use crate::tools::registry::ToolRegistry;
5
6fn output_text(value: &Value) -> Option<&str> {
7 ["content", "output", "stdout"]
8 .iter()
9 .find_map(|key| value.get(key).and_then(Value::as_str))
10}
11
12fn complete_shell_output(args: &Value, output: &Value, text: &str, content: &str) -> bool {
13 if text != content
14 || output.get("exit_code").and_then(Value::as_i64) != Some(0)
15 || output.get("success").and_then(Value::as_bool) == Some(false)
16 || [
17 "cancelled",
18 "blocked",
19 "not_executed",
20 "termination_requested",
21 "truncated",
22 "result_ref_only",
23 ]
24 .iter()
25 .any(|key| output.get(key).and_then(Value::as_bool) == Some(true))
26 || output.get("output_truncated").and_then(Value::as_bool) == Some(true)
27 || output.get("spool_path").is_some()
28 {
29 return false;
30 }
31 let Some(command) = crate::tools::command_args::shell_command_text_with_args(args) else {
32 return false;
33 };
34 let Some(commands) = crate::tools::tool_intent::readonly::static_shell_command_words(&command) else {
35 return false;
36 };
37 let Ok(Some(words)) = crate::tools::command_args::command_words(args) else {
38 return false;
39 };
40 commands.as_slice() == [words]
41}
42
43fn read_support(name: &str, args: &Value, output: &Value) -> Option<String> {
44 let digest = if name == tools::CODE_SEARCH {
46 revision(&output.get("results")?.to_string())
47 } else {
48 revision(output_text(output)?)
49 };
50 Some(format!("{}:{digest}", call_key(name, args)))
51}
52
53struct RetainedSignatures {
54 by_call_id: HashMap<String, Vec<String>>,
55 call_ids: HashSet<String>,
56}
57
58struct SourceReadTarget {
59 path: PathBuf,
60 raw_start: Option<usize>,
61}
62
63fn retained_signatures(messages: &[Message]) -> RetainedSignatures {
64 let calls: HashMap<_, _> = messages
65 .iter()
66 .filter(|message| message.role == MessageRole::Assistant)
67 .flat_map(|message| message.tool_calls.iter().flatten())
68 .map(|call| (call.id.as_str(), call))
69 .collect();
70 let mut signatures = HashMap::new();
71 let mut current_calls = HashSet::new();
72 for message in messages.iter().filter(|message| message.role == MessageRole::Tool) {
73 let Some(call) = message.tool_call_id.as_deref().and_then(|id| calls.get(id)) else {
74 continue;
75 };
76 current_calls.insert(call.id.clone());
77 let Some(function) = call.function.as_ref() else {
78 continue;
79 };
80 let text = message.content.as_text();
81 let Ok(output) = serde_json::from_str::<Value>(&text) else {
82 continue;
83 };
84 if output.get("cleared").and_then(Value::as_str) == Some("tool_result")
85 || output.get("error").is_some()
86 || output.get("success").and_then(Value::as_bool) == Some(false)
87 || output.get("conflict_detected").and_then(Value::as_bool) == Some(true)
88 {
89 continue;
90 }
91 let args = serde_json::from_str::<Value>(&function.arguments)
92 .unwrap_or_else(|_| Value::String(function.arguments.clone()));
93 let mut call_signatures = vec![call_key(&function.name, &args)];
94 if let Some(support) = read_support(&function.name, &args, &output) {
95 call_signatures.push(support);
96 }
97 signatures.insert(call.id.clone(), call_signatures);
98 }
99 RetainedSignatures { by_call_id: signatures, call_ids: current_calls }
100}
101
102impl SourceInspection {
103 pub fn reconcile(&self, messages: &[Message]) {
106 let RetainedSignatures { by_call_id: signatures, call_ids: current_calls } = retained_signatures(messages);
107 let mut ledger = self.0.lock();
108 let previous_calls = ledger.previous_calls.clone();
109 let mut active = HashSet::new();
110 for (key, support) in &mut ledger.supports {
111 if support.call_id.is_none() {
112 support.call_id = signatures
113 .iter()
114 .find(|(id, values)| !previous_calls.contains(*id) && values.contains(&support.signature))
115 .map(|(id, _)| id.clone());
116 }
117 if support
118 .call_id
119 .as_ref()
120 .and_then(|id| signatures.get(id))
121 .is_some_and(|values| values.contains(&support.signature))
122 {
123 active.insert(key.clone());
124 }
125 }
126 ledger.previous_calls = current_calls;
127 ledger.active = active;
128 let active = ledger.active.clone();
129 for file in ledger.files.values_mut() {
130 file.lines
131 .retain(|_, credit| credit.iter().all(|support| active.contains(support)));
132 if file
133 .empty
134 .as_ref()
135 .is_some_and(|credit| !credit.iter().all(|support| active.contains(support)))
136 {
137 file.empty = None;
138 }
139 }
140 }
141 pub fn reconcile_projection_change(&self, before: &[Message], after: &[Message]) {
144 let affected = retained_signatures(before).call_ids;
145 let signatures = retained_signatures(after).by_call_id;
146 let mut ledger = self.0.lock();
147 let mut active = ledger.active.clone();
148 active.retain(|key| {
149 ledger.supports.get(key).is_some_and(|support| {
150 support.call_id.as_ref().is_some_and(|id| {
151 !affected.contains(id)
152 || signatures.get(id).is_some_and(|values| values.contains(&support.signature))
153 })
154 })
155 });
156 ledger.active = active.clone();
157 for file in ledger.files.values_mut() {
158 file.lines.retain(|_, credit| credit.iter().all(|key| active.contains(key)));
159 if file
160 .empty
161 .as_ref()
162 .is_some_and(|credit| !credit.iter().all(|key| active.contains(key)))
163 {
164 file.empty = None;
165 }
166 }
167 }
168}
169
170impl ToolRegistry {
171 pub fn reconcile_source_inspection(&self, messages: &[Message]) {
173 self.edited_file_monitor_ref().source_inspection().reconcile(messages);
174 }
175
176 pub fn reconcile_source_projection_change(&self, before: &[Message], after: &[Message]) {
177 self.edited_file_monitor_ref()
178 .source_inspection()
179 .reconcile_projection_change(before, after);
180 }
181
182 pub fn set_inspection_mode(&self, mode: InspectionMode) {
183 self.edited_file_monitor_ref().source_inspection().set_mode(mode);
184 }
185
186 pub fn inspection_mode(&self) -> InspectionMode {
187 self.edited_file_monitor_ref().source_inspection().mode()
188 }
189
190 pub(crate) async fn observe_source_output(&self, name: &str, args: &Value, output: &Value) {
191 let inspection = self.edited_file_monitor_ref().source_inspection();
192 let inspection_enabled = inspection.mode() != InspectionMode::Off;
193 if output.get("error").is_some() {
194 return;
195 }
196 if name == tools::CODE_SEARCH {
197 if !inspection_enabled {
198 return;
199 }
200 let Some(support) = read_support(name, args, output) else {
201 return;
202 };
203 if let Some(results) = output.get("results").and_then(Value::as_array) {
204 for result in results {
205 let (Some(path), Some(line), Some(snippet)) = (
206 result.get("path").and_then(Value::as_str),
207 result.get("line").and_then(Value::as_u64),
208 result.get("snippet").and_then(Value::as_str),
209 ) else {
210 continue;
211 };
212 let Ok(path) = self.file_ops_tool().normalize_user_path(path).await else {
213 continue;
214 };
215 let Ok(content) = tokio::fs::read_to_string(&path).await else {
216 continue;
217 };
218 let source_lines: Vec<_> = content.lines().collect();
219 let Some(start) = usize::try_from(line).ok().and_then(|line| line.checked_sub(1)) else {
220 continue;
221 };
222 let exposed = snippet
223 .lines()
224 .enumerate()
225 .filter_map(|(offset, text)| {
226 let index = start + offset;
227 (source_lines.get(index).copied() == Some(text)).then_some(index)
228 })
229 .collect();
230 let support = inspection.register_support(support.clone());
231 inspection.insert_lines(path, &content, exposed, support, false);
232 }
233 }
234 return;
235 }
236 let Some(text) = output_text(output) else { return };
237 let Some(support) = read_support(name, args, output) else {
238 return;
239 };
240 let file_read = name == tools::READ_FILE
241 || (name == tools::UNIFIED_FILE && crate::tools::tool_intent::file_operation_action(args) == Some("read"));
242 if file_read && !inspection_enabled {
243 return;
244 }
245 let target = if file_read {
246 output.get("path").and_then(Value::as_str).map(|path| SourceReadTarget {
247 path: PathBuf::from(path),
248 raw_start: crate::tools::file_ops::source_line_offset(args),
249 })
250 } else {
251 self.verbatim_shell_read(name, args)
252 };
253 let Some(SourceReadTarget { path, raw_start }) = target else {
254 return;
255 };
256 let Some(path_text) = path.to_str() else { return };
257 let Ok(path) = self.file_ops_tool().normalize_user_path(path_text).await else {
258 return;
259 };
260 let Ok(content) = tokio::fs::read_to_string(&path).await else {
263 return;
264 };
265 if !file_read
266 && complete_shell_output(args, output, text, &content)
267 && let Err(error) = self.edited_file_monitor_ref().record_read_text(&path, &content)
268 {
269 tracing::warn!(path = %path.display(), %error, "failed to record complete shell read");
270 }
271 if !inspection_enabled {
272 return;
273 }
274 let source_lines: Vec<_> = content.lines().collect();
275 let lines = if let Some(start) = raw_start {
276 text.lines()
277 .enumerate()
278 .map_while(|(index, line)| {
279 let index = start + index;
280 (source_lines.get(index).copied() == Some(line)).then_some(index)
281 })
282 .collect()
283 } else if text == content
284 || crate::tools::file_ops::restore_exact_text_content(text, content.len() as u64).as_deref()
285 == Some(&content)
286 {
287 (0..source_lines.len()).collect()
288 } else {
289 text.lines()
290 .filter_map(|line| {
291 let (number, body) = line.split_once(": ")?;
292 let index = number.parse::<usize>().ok()?.checked_sub(1)?;
293 (source_lines.get(index).copied() == Some(body)).then_some(index)
294 })
295 .collect()
296 };
297 let empty = content.is_empty() && text.is_empty() && file_read;
298 let support = inspection.register_support(support);
299 inspection.insert_lines(path, &content, lines, support, empty);
300 }
301
302 fn verbatim_shell_read(&self, name: &str, args: &Value) -> Option<SourceReadTarget> {
303 if !crate::tools::tool_intent::is_command_run_tool_call(name, args) {
304 return None;
305 }
306 let words = crate::tools::command_args::command_words(args).ok()??;
307 let (path, start) = match words.as_slice() {
308 [command, path] if command == "cat" && !path.starts_with('-') => (path, 0),
309 [command, option, script, path] if command == "sed" && option == "-n" => {
310 let range = script.strip_suffix('p')?;
311 let (start, end) = range.split_once(',').unwrap_or((range, range));
312 let start = start.parse::<usize>().ok()?.checked_sub(1)?;
313 let end = end.parse::<usize>().ok()?;
314 if end <= start {
315 return None;
316 }
317 (path, start)
318 }
319 _ => return None,
320 };
321 let cwd = self
322 .pty_manager()
323 .working_dir_candidate(crate::tools::command_args::working_dir_text(args))
324 .ok()?;
325 Some(SourceReadTarget { path: cwd.join(path), raw_start: Some(start) })
326 }
327}