Skip to main content

vtcode_core/tools/
result.rs

1//! Split tool results: Dual-channel output for LLM and UI
2//!
3//! Implements Phase 4 of pi-coding-agent integration:
4//! - LLM content: Concise summaries optimized for token efficiency
5//! - UI content: Rich output with full details for user display
6//!
7//! Expected savings: 20-30% on tool-heavy sessions (97% on tool output tokens)
8
9use hashbrown::HashMap;
10use serde::{Deserialize, Serialize};
11use std::path::PathBuf;
12
13#[cfg(test)]
14use crate::config::constants::tools;
15use crate::utils::tokens::estimate_tokens;
16
17/// Result from tool execution with dual-channel output
18///
19/// Tools return two versions of their output:
20/// 1. `llm_content` - Concise summary for model context (token-optimized)
21/// 2. `ui_content` - Rich output for user display (full details)
22///
23/// This enables significant token savings while preserving user experience.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ToolResult {
26    /// Tool name that produced this result
27    pub tool_name: String,
28
29    /// Concise summary for LLM context (token-optimized)
30    ///
31    /// Example: "Found 127 matches in 15 files. Key: src/tools/grep.rs (3), src/tools/list.rs (1)"
32    /// vs full output which might be 2,500 tokens
33    pub llm_content: String,
34
35    /// Rich output for UI display (full details)
36    ///
37    /// Can include ANSI codes, formatting, full listings, etc.
38    /// Not sent to LLM, only displayed to user
39    pub ui_content: String,
40
41    /// Whether the tool execution succeeded
42    pub success: bool,
43
44    /// Error message if execution failed
45    pub error: Option<String>,
46
47    /// Structured metadata for both channels
48    pub metadata: ToolMetadata,
49}
50
51/// Metadata accompanying tool results
52///
53/// Provides structured data that can be used by both LLM and UI
54/// without being embedded in content strings
55#[derive(Debug, Clone, Default, Serialize, Deserialize)]
56pub struct ToolMetadata {
57    /// File paths referenced by this tool (for UI linking, LLM context)
58    pub files: Vec<PathBuf>,
59
60    /// Line numbers referenced (for UI jump-to-line)
61    pub lines: Vec<usize>,
62
63    /// Key-value pairs for structured data
64    ///
65    /// Examples:
66    /// - match_count: 127
67    /// - files_searched: 50
68    /// - execution_time_ms: 234
69    pub data: HashMap<String, serde_json::Value>,
70
71    /// Token counts for observability
72    pub token_counts: TokenCounts,
73}
74
75/// Token counting for split tool results
76#[derive(Debug, Clone, Default, Serialize, Deserialize)]
77pub struct TokenCounts {
78    /// Tokens in LLM content (what we send to model)
79    pub llm_tokens: usize,
80
81    /// Tokens in UI content (what we DON'T send to model)
82    pub ui_tokens: usize,
83
84    /// Tokens saved by splitting (ui_tokens - llm_tokens)
85    pub savings_tokens: usize,
86
87    /// Percentage saved (0-100)
88    pub savings_percent: f32,
89}
90
91impl ToolResult {
92    /// Create a new tool result with dual content
93    pub fn new(tool_name: impl Into<String>, llm_content: impl Into<String>, ui_content: impl Into<String>) -> Self {
94        let llm_str = llm_content.into();
95        let ui_str = ui_content.into();
96
97        let llm_tokens = estimate_tokens(&llm_str);
98        let ui_tokens = estimate_tokens(&ui_str);
99        let savings = ui_tokens.saturating_sub(llm_tokens);
100        let savings_pct = if ui_tokens > 0 {
101            (savings as f32 / ui_tokens as f32) * 100.0
102        } else {
103            0.0
104        };
105
106        Self {
107            tool_name: tool_name.into(),
108            llm_content: llm_str,
109            ui_content: ui_str,
110            success: true,
111            error: None,
112            metadata: ToolMetadata {
113                token_counts: TokenCounts {
114                    llm_tokens,
115                    ui_tokens,
116                    savings_tokens: savings,
117                    savings_percent: savings_pct,
118                },
119                ..Default::default()
120            },
121        }
122    }
123
124    /// Create an error result
125    pub fn error(tool_name: impl Into<String>, error: impl Into<String>) -> Self {
126        let error_msg = error.into();
127        Self {
128            tool_name: tool_name.into(),
129            llm_content: format!("Tool failed: {error_msg}"),
130            ui_content: format!("Error: {error_msg}"),
131            success: false,
132            error: Some(error_msg),
133            metadata: ToolMetadata::default(),
134        }
135    }
136
137    /// Create a simple result with same content for both channels
138    ///
139    /// Use this for backward compatibility or when splitting doesn't make sense
140    pub fn simple(tool_name: impl Into<String>, content: impl Into<String>) -> Self {
141        let content_str = content.into();
142        Self::new(tool_name, content_str.clone(), content_str)
143    }
144
145    /// Add metadata to the result
146    #[must_use]
147    pub fn with_metadata(mut self, metadata: ToolMetadata) -> Self {
148        // Preserve token counts from construction
149        let token_counts = std::mem::take(&mut self.metadata.token_counts);
150        self.metadata = metadata;
151        self.metadata.token_counts = token_counts;
152        self
153    }
154
155    /// Add file references to metadata
156    #[must_use]
157    pub fn with_files(mut self, files: Vec<PathBuf>) -> Self {
158        self.metadata.files = files;
159        self
160    }
161
162    /// Add data to metadata
163    #[must_use]
164    pub fn with_data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
165        self.metadata.data.insert(key.into(), value);
166        self
167    }
168
169    /// Get token savings summary for logging
170    pub fn savings_summary(&self) -> String {
171        let counts = &self.metadata.token_counts;
172        format!("{} → {} tokens ({:.1}% saved)", counts.ui_tokens, counts.llm_tokens, counts.savings_percent)
173    }
174
175    /// Check if this result has significant savings (>50%)
176    pub fn has_significant_savings(&self) -> bool {
177        self.metadata.token_counts.savings_percent > 50.0
178    }
179}
180
181/// Builder for ToolMetadata
182#[must_use = "build the metadata before discarding the builder"]
183#[derive(Default)]
184pub struct ToolMetadataBuilder {
185    files: Vec<PathBuf>,
186    lines: Vec<usize>,
187    data: HashMap<String, serde_json::Value>,
188}
189
190impl ToolMetadataBuilder {
191    pub fn new() -> Self {
192        Self::default()
193    }
194
195    pub fn file(mut self, path: PathBuf) -> Self {
196        self.files.push(path);
197        self
198    }
199
200    pub fn files(mut self, paths: Vec<PathBuf>) -> Self {
201        self.files.extend(paths);
202        self
203    }
204
205    pub fn line(mut self, line: usize) -> Self {
206        self.lines.push(line);
207        self
208    }
209
210    pub fn lines(mut self, lines: Vec<usize>) -> Self {
211        self.lines.extend(lines);
212        self
213    }
214
215    pub fn data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
216        self.data.insert(key.into(), value);
217        self
218    }
219
220    #[must_use]
221    pub fn build(self) -> ToolMetadata {
222        ToolMetadata {
223            files: self.files,
224            lines: self.lines,
225            data: self.data,
226            token_counts: TokenCounts::default(), // Will be filled by ToolResult
227        }
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn test_tool_result_creation() {
237        let result = ToolResult::new(
238            tools::GREP_FILE,
239            "Found 127 matches in 15 files",
240            "Very long output with 127 full match listings...",
241        );
242
243        assert_eq!(result.tool_name, tools::GREP_FILE);
244        assert!(result.success);
245        assert!(result.error.is_none());
246        assert!(result.metadata.token_counts.llm_tokens > 0);
247        assert!(result.metadata.token_counts.ui_tokens > 0);
248        assert!(result.metadata.token_counts.savings_tokens > 0);
249    }
250
251    #[test]
252    fn test_error_result() {
253        let result = ToolResult::error(tools::GREP_FILE, "Pattern invalid");
254
255        assert_eq!(result.tool_name, tools::GREP_FILE);
256        assert!(!result.success);
257        assert_eq!(result.error, Some("Pattern invalid".to_string()));
258        assert!(result.llm_content.contains("failed"));
259    }
260
261    #[test]
262    fn test_simple_result() {
263        let result = ToolResult::simple("test_tool", "Same content");
264
265        assert_eq!(result.llm_content, result.ui_content);
266        assert_eq!(result.metadata.token_counts.savings_tokens, 0);
267    }
268
269    #[test]
270    fn test_token_estimation() {
271        let text = "Hello world";
272        let tokens = estimate_tokens(text);
273        // tiktoken cl100k_base BPE tokenizes "Hello world" as 2 tokens
274        assert_eq!(tokens, 2);
275
276        let long_text = "a".repeat(1000);
277        let long_tokens = estimate_tokens(&long_text);
278        // Repeated single chars: ~8 chars/token for 'a' in cl100k_base
279        assert_eq!(long_tokens, 125);
280    }
281
282    #[test]
283    fn test_metadata_builder() {
284        let metadata = ToolMetadataBuilder::new()
285            .file(PathBuf::from("src/main.rs"))
286            .file(PathBuf::from("src/lib.rs"))
287            .line(42)
288            .line(100)
289            .data("match_count", serde_json::json!(127))
290            .data("files_searched", serde_json::json!(50))
291            .build();
292
293        assert_eq!(metadata.files.len(), 2);
294        assert_eq!(metadata.lines.len(), 2);
295        assert_eq!(metadata.data.len(), 2);
296        assert_eq!(metadata.data["match_count"], 127);
297    }
298
299    #[test]
300    fn test_with_methods() {
301        let result = ToolResult::new("test", "llm", "ui")
302            .with_files(vec![PathBuf::from("test.rs")])
303            .with_data("key", serde_json::json!("value"));
304
305        assert_eq!(result.metadata.files.len(), 1);
306        assert_eq!(result.metadata.data["key"], "value");
307    }
308
309    #[test]
310    fn test_savings_calculation() {
311        let result = ToolResult::new(
312            "grep",
313            "Short summary",  // ~2 tokens
314            "a".repeat(1000), // ~125 tokens (repeated chars: ~8 chars/token)
315        );
316
317        assert!(result.metadata.token_counts.savings_tokens > 100);
318        assert!(result.metadata.token_counts.savings_percent > 90.0);
319        assert!(result.has_significant_savings());
320    }
321
322    #[test]
323    fn test_savings_summary() {
324        let result = ToolResult::new("grep", "Short", "Long content here");
325
326        let summary = result.savings_summary();
327        assert!(summary.contains("→"));
328        assert!(summary.contains("tokens"));
329        assert!(summary.contains("%"));
330    }
331}