Skip to main content

vtcode_core/tools/registry/
dual_output.rs

1//! Dual-channel tool execution helpers.
2
3use anyhow::Result;
4use serde_json::Value;
5use tracing::{debug, warn};
6use vtcode_commons::serde_helpers::json_to_string_pretty;
7
8use crate::config::constants::tools;
9use crate::tools::summarizers::{
10    Summarizer,
11    execution::BashSummarizer,
12    file_ops::{EditSummarizer, ReadSummarizer},
13};
14use crate::tools::tool_intent;
15
16use super::{SplitToolResult, ToolRegistry};
17
18impl ToolRegistry {
19    /// Execute tool with dual-channel output (Phase 4: Split Tool Results).
20    ///
21    /// This method enables significant token savings by separating:
22    /// - `llm_content`: Concise summary sent to LLM context (token-optimized)
23    /// - `ui_content`: Rich output displayed to user (full details)
24    ///
25    /// For tools with registered summarizers, this can achieve 90-97% token reduction
26    /// on tool outputs while preserving full details for the UI.
27    ///
28    /// # Example
29    /// This snippet is illustrative; registry setup and argument construction are
30    /// omitted because they depend on the caller's tool inventory.
31    /// ```rust,ignore
32    /// let result = registry.execute_tool_dual("grep_file", args).await?;
33    /// // result.llm_content: "Found 127 matches in 15 files. Key: src/tools/grep.rs (3)"
34    /// // result.ui_content: [Full formatted output with all 127 matches]
35    /// // Savings: ~98% token reduction
36    /// ```
37    #[expect(clippy::cognitive_complexity, reason = "dual-output projection; split per surface")]
38    pub async fn execute_tool_dual(&self, name: &str, args: Value) -> Result<SplitToolResult> {
39        // Execute the tool using existing infrastructure
40        let result = self.execute_tool_ref(name, &args).await?;
41
42        // Convert Value to string for UI content
43        let ui_content = if result.is_string() {
44            result.as_str().unwrap_or("").to_string()
45        } else {
46            json_to_string_pretty(&result)
47        };
48
49        // Get canonical tool name for summarizer lookup
50        // Resolve alias through registration lookup first
51        let tool_name = if let Some(registration) = self.inventory.registration_for(name) {
52            registration.name().to_string()
53        } else {
54            name.to_string() // Fallback to original name if not found
55        };
56
57        // Check if we have a summarizer for this tool
58        match tool_name.as_str() {
59            tools::CODE_SEARCH => Ok(SplitToolResult::simple(tool_name.as_str(), ui_content)),
60            tools::UNIFIED_FILE => match tool_intent::file_operation_action(&args).unwrap_or("read") {
61                "read" => {
62                    let mut metadata = args.clone();
63                    if let Value::Object(map) = &mut metadata
64                        && !map.contains_key("file_path")
65                    {
66                        let inferred_path = args
67                            .get("path")
68                            .or_else(|| args.get("file_path"))
69                            .or_else(|| args.get("filepath"))
70                            .or_else(|| args.get("target_path"))
71                            .and_then(Value::as_str)
72                            .map(str::to_string);
73                        if let Some(path) = inferred_path {
74                            map.insert("file_path".to_string(), Value::String(path));
75                        }
76                    }
77
78                    let summarizer = ReadSummarizer::default();
79                    match summarizer.summarize(&ui_content, Some(&metadata)) {
80                        Ok(llm_content) => {
81                            let savings = summarizer.estimate_savings(&ui_content, &llm_content);
82                            debug!(
83                                tool = tools::UNIFIED_FILE,
84                                action = "read",
85                                ui_tokens = %savings.ui_tokens,
86                                llm_tokens = %savings.llm_tokens,
87                                savings_pct = %savings.savings_percent,
88                                "Applied file_operation read summarization"
89                            );
90                            Ok(SplitToolResult::new(tool_name.as_str(), llm_content, ui_content))
91                        }
92                        Err(e) => {
93                            warn!(
94                                tool = tools::UNIFIED_FILE,
95                                action = "read",
96                                error = %e,
97                                "Failed to summarize file_operation read output, using simple result"
98                            );
99                            Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
100                        }
101                    }
102                }
103                "write" | "edit" | "patch" | "move" | "copy" | "delete" => {
104                    let summarizer = EditSummarizer::default();
105                    match summarizer.summarize(&ui_content, None) {
106                        Ok(llm_content) => {
107                            let savings = summarizer.estimate_savings(&ui_content, &llm_content);
108                            debug!(
109                                tool = tools::UNIFIED_FILE,
110                                action = "mutate",
111                                ui_tokens = %savings.ui_tokens,
112                                llm_tokens = %savings.llm_tokens,
113                                savings_pct = %savings.savings_percent,
114                                "Applied file_operation mutation summarization"
115                            );
116                            Ok(SplitToolResult::new(tool_name.as_str(), llm_content, ui_content))
117                        }
118                        Err(e) => {
119                            warn!(
120                                tool = tools::UNIFIED_FILE,
121                                action = "mutate",
122                                error = %e,
123                                "Failed to summarize file_operation mutation output, using simple result"
124                            );
125                            Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
126                        }
127                    }
128                }
129                _ => Ok(SplitToolResult::simple(tool_name.as_str(), ui_content)),
130            },
131            tools::UNIFIED_EXEC | tools::EXEC_COMMAND => {
132                match tool_intent::command_session_action(&args).unwrap_or("run") {
133                    "run" | "code" => {
134                        let summarizer = BashSummarizer::default();
135                        let metadata = args.as_object().map(|_| args.clone());
136                        match summarizer.summarize(&ui_content, metadata.as_ref()) {
137                            Ok(llm_content) => {
138                                let savings = summarizer.estimate_savings(&ui_content, &llm_content);
139                                debug!(
140                                    tool = tools::UNIFIED_EXEC,
141                                    action = "run",
142                                    ui_tokens = %savings.ui_tokens,
143                                    llm_tokens = %savings.llm_tokens,
144                                    savings_pct = %savings.savings_percent,
145                                    "Applied command_session summarization"
146                                );
147                                Ok(SplitToolResult::new(tool_name.as_str(), llm_content, ui_content))
148                            }
149                            Err(e) => {
150                                warn!(
151                                    tool = tools::UNIFIED_EXEC,
152                                    action = "run",
153                                    error = %e,
154                                    "Failed to summarize command_session output, using simple result"
155                                );
156                                Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
157                            }
158                        }
159                    }
160                    _ => Ok(SplitToolResult::simple(tool_name.as_str(), ui_content)),
161                }
162            }
163            tools::READ_FILE => {
164                // Apply read file summarization
165                let summarizer = ReadSummarizer::default();
166                // Extract file path from args if available for better summary
167                let metadata = args.as_object().map(|_| args.clone());
168                match summarizer.summarize(&ui_content, metadata.as_ref()) {
169                    Ok(llm_content) => {
170                        let savings = summarizer.estimate_savings(&ui_content, &llm_content);
171                        debug!(
172                            tool = tools::READ_FILE,
173                            ui_tokens = %savings.ui_tokens,
174                            llm_tokens = %savings.llm_tokens,
175                            savings_pct = %savings.savings_percent,
176                            "Applied read file summarization"
177                        );
178                        Ok(SplitToolResult::new(tool_name.as_str(), llm_content, ui_content))
179                    }
180                    Err(e) => {
181                        warn!(
182                            tool = tools::READ_FILE,
183                            error = %e,
184                            "Failed to summarize read output, using simple result"
185                        );
186                        Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
187                    }
188                }
189            }
190            tools::RUN_PTY_CMD => {
191                // Apply bash execution summarization
192                let summarizer = BashSummarizer::default();
193                // Pass command info from args if available
194                let metadata = args.as_object().map(|_| args.clone());
195                match summarizer.summarize(&ui_content, metadata.as_ref()) {
196                    Ok(llm_content) => {
197                        let savings = summarizer.estimate_savings(&ui_content, &llm_content);
198                        debug!(
199                            tool = tools::RUN_PTY_CMD,
200                            ui_tokens = %savings.ui_tokens,
201                            llm_tokens = %savings.llm_tokens,
202                            savings_pct = %savings.savings_percent,
203                            "Applied bash summarization"
204                        );
205                        Ok(SplitToolResult::new(tool_name.as_str(), llm_content, ui_content))
206                    }
207                    Err(e) => {
208                        warn!(
209                            tool = tools::RUN_PTY_CMD,
210                            error = %e,
211                            "Failed to summarize bash output, using simple result"
212                        );
213                        Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
214                    }
215                }
216            }
217            tools::WRITE_FILE | tools::EDIT_FILE | tools::APPLY_PATCH => {
218                // Apply edit/write file summarization
219                let summarizer = EditSummarizer::default();
220                match summarizer.summarize(&ui_content, None) {
221                    Ok(llm_content) => {
222                        let savings = summarizer.estimate_savings(&ui_content, &llm_content);
223                        debug!(
224                            tool = tool_name.as_str(),
225                            ui_tokens = %savings.ui_tokens,
226                            llm_tokens = %savings.llm_tokens,
227                            savings_pct = %savings.savings_percent,
228                            "Applied edit summarization"
229                        );
230                        Ok(SplitToolResult::new(tool_name.as_str(), llm_content, ui_content))
231                    }
232                    Err(e) => {
233                        warn!(
234                            tool = tool_name.as_str(),
235                            error = %e,
236                            "Failed to summarize edit output, using simple result"
237                        );
238                        Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
239                    }
240                }
241            }
242            _ => {
243                // No summarizer registered, use same content for both channels
244                Ok(SplitToolResult::simple(tool_name.as_str(), ui_content))
245            }
246        }
247    }
248}