Skip to main content

vtcode_core/tools/
builder.rs

1//! Unified builder for tool responses
2//!
3//! Provides a consistent way to construct tool execution results with
4//! support for dual-channel output, structured metadata, and standardized error reporting.
5
6use hashbrown::HashMap;
7use serde_json::{Value, json};
8use std::path::PathBuf;
9
10use crate::tools::result::{ToolMetadataBuilder, ToolResult};
11
12/// Builder for standardized tool responses
13#[must_use = "build the response before discarding the builder"]
14pub struct ToolResponseBuilder {
15    tool_name: String,
16    success: bool,
17    message: Option<String>,
18    content: Option<String>,
19    stdout: Option<String>,
20    modified_files: Vec<String>,
21    has_more: bool,
22    llm_content: Option<String>,
23    ui_content: Option<String>,
24    error: Option<String>,
25    metadata: ToolMetadataBuilder,
26    custom_fields: HashMap<String, Value>,
27}
28
29impl ToolResponseBuilder {
30    /// Create a new builder for the given tool
31    pub fn new(tool_name: impl Into<String>) -> Self {
32        Self {
33            tool_name: tool_name.into(),
34            success: true,
35            message: None,
36            content: None,
37            stdout: None,
38            modified_files: Vec::new(),
39            has_more: false,
40            llm_content: None,
41            ui_content: None,
42            error: None,
43            metadata: ToolMetadataBuilder::new(),
44            custom_fields: HashMap::new(),
45        }
46    }
47
48    /// Mark the execution as successful
49    pub fn success(mut self) -> Self {
50        self.success = true;
51        self
52    }
53
54    /// Mark the execution as failed with an error message
55    pub fn failure(mut self, error: impl Into<String>) -> Self {
56        self.success = false;
57        self.error = Some(error.into());
58        self
59    }
60
61    /// Set a user-friendly status message
62    pub fn message(mut self, message: impl Into<String>) -> Self {
63        self.message = Some(message.into());
64        self
65    }
66
67    /// Set the main content (used for both LLM and UI if not overridden)
68    pub fn content(mut self, content: impl Into<String>) -> Self {
69        self.content = Some(content.into());
70        self
71    }
72
73    /// Set standard output from a process
74    pub fn stdout(mut self, stdout: impl Into<String>) -> Self {
75        self.stdout = Some(stdout.into());
76        self
77    }
78
79    /// Add a modified file to the list
80    pub fn modified_file(mut self, path: impl Into<String>) -> Self {
81        self.modified_files.push(path.into());
82        self
83    }
84
85    /// Add multiple modified files
86    pub fn modified_files(mut self, paths: Vec<String>) -> Self {
87        self.modified_files.extend(paths);
88        self
89    }
90
91    /// Set whether there are more results available
92    pub fn has_more(mut self, has_more: bool) -> Self {
93        self.has_more = has_more;
94        self
95    }
96
97    /// Set explicit dual-channel content
98    pub fn dual_content(mut self, llm: impl Into<String>, ui: impl Into<String>) -> Self {
99        self.llm_content = Some(llm.into());
100        self.ui_content = Some(ui.into());
101        self
102    }
103
104    /// Add a file reference to the metadata (for UI linking)
105    pub fn file(mut self, path: impl Into<PathBuf>) -> Self {
106        self.metadata = self.metadata.file(path.into());
107        self
108    }
109
110    /// Add multiple file references
111    pub fn files(mut self, paths: Vec<PathBuf>) -> Self {
112        self.metadata = self.metadata.files(paths);
113        self
114    }
115
116    /// Add structured data to the metadata
117    pub fn data(mut self, key: impl Into<String>, value: Value) -> Self {
118        self.metadata = self.metadata.data(key, value);
119        self
120    }
121
122    /// Add a custom top-level field to the final JSON response
123    pub fn field(mut self, key: impl Into<String>, value: Value) -> Self {
124        self.custom_fields.insert(key.into(), value);
125        self
126    }
127
128    /// Build the legacy JSON Value response
129    #[must_use]
130    pub fn build_json(self) -> Value {
131        let mut res = json!({
132            "success": self.success,
133            "status": if self.success { "success" } else { "error" },
134        });
135
136        let Some(obj) = res.as_object_mut() else {
137            return res;
138        };
139
140        if let Some(msg) = self.message {
141            obj.insert("message".to_string(), json!(msg));
142        }
143
144        if let Some(err) = self.error {
145            obj.insert("error".to_string(), json!(err));
146        }
147
148        let content_value = self.content;
149        if let Some(c) = content_value.as_ref() {
150            obj.insert("content".to_string(), json!(c));
151        }
152
153        if let Some(s) = self.stdout {
154            let duplicates_content = content_value.as_deref() == Some(s.as_str());
155            if !duplicates_content {
156                obj.insert("stdout".to_string(), json!(s));
157            }
158        }
159
160        if !self.modified_files.is_empty() {
161            obj.insert("modified_files".to_string(), json!(self.modified_files));
162        }
163
164        if self.has_more {
165            obj.insert("has_more".to_string(), json!(true));
166        }
167
168        // Build and merge metadata. Keys already surfaced as top-level custom
169        // fields stay top-level only: duplicating them inside `metadata.data`
170        // re-serializes the same values on every tool result (read_file paid
171        // that tax for `content_kind`/`encoding` on every call). Only explicit
172        // `.field()` twins dedup — a `.data()` entry sharing a name with a
173        // builder-structural key (success/status/message/...) must survive.
174        let mut meta = self.metadata.build();
175        meta.data.retain(|key, _| !self.custom_fields.contains_key(key));
176        if !meta.data.is_empty() || !meta.files.is_empty() || !meta.lines.is_empty() {
177            obj.insert("metadata".to_string(), json!(meta));
178        }
179
180        // Add custom top-level fields
181        for (k, v) in self.custom_fields {
182            obj.insert(k, v);
183        }
184
185        res
186    }
187
188    /// Build the modern dual-channel ToolResult
189    #[must_use]
190    pub fn build_result(self) -> ToolResult {
191        if !self.success {
192            return ToolResult::error(self.tool_name, self.error.unwrap_or_else(|| "Unknown error".to_string()));
193        }
194
195        let llm = self.llm_content.or_else(|| self.content.clone()).unwrap_or_default();
196        let ui = self.ui_content.or_else(|| self.content.clone()).unwrap_or_default();
197
198        let mut res = ToolResult::new(self.tool_name, llm, ui);
199        res.metadata = self.metadata.build();
200
201        // Add custom fields to metadata data map
202        for (k, v) in self.custom_fields {
203            res.metadata.data.insert(k, v);
204        }
205
206        res
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::ToolResponseBuilder;
213    use serde_json::json;
214
215    #[test]
216    fn build_json_omits_stdout_when_same_as_content() {
217        let value = ToolResponseBuilder::new("test").content("same").stdout("same").build_json();
218
219        assert_eq!(value.get("content").and_then(|v| v.as_str()), Some("same"));
220        assert!(value.get("stdout").is_none());
221    }
222
223    #[test]
224    fn build_json_keeps_metadata_only_keys_and_deduplicates_field_keys() {
225        let value = ToolResponseBuilder::new("read_file")
226            .field("content_kind", json!("text"))
227            .field("encoding", json!("utf8"))
228            .data("content_kind", json!("text"))
229            .data("encoding", json!("utf8"))
230            .data("size_bytes", json!(1024))
231            .build_json();
232
233        // Duplicated keys stay top-level only; metadata-only keys survive.
234        assert_eq!(value["content_kind"], json!("text"));
235        assert_eq!(value["encoding"], json!("utf8"));
236        assert_eq!(value["metadata"]["data"]["size_bytes"], json!(1024));
237        assert!(value["metadata"]["data"].get("content_kind").is_none());
238        assert!(value["metadata"]["data"].get("encoding").is_none());
239    }
240
241    #[test]
242    fn build_json_omits_metadata_object_when_all_data_keys_are_duplicates() {
243        let value = ToolResponseBuilder::new("read_file")
244            .field("content_kind", json!("text"))
245            .data("content_kind", json!("text"))
246            .build_json();
247
248        assert_eq!(value["content_kind"], json!("text"));
249        assert!(value.get("metadata").is_none());
250    }
251
252    #[test]
253    fn build_json_keeps_data_keys_colliding_with_structural_names() {
254        // A `.data()` entry must not vanish because it shares a name with a
255        // builder-structural key; only explicit `.field()` twins dedup.
256        let value = ToolResponseBuilder::new("read_file")
257            .message("done")
258            .field("kind", json!("top"))
259            .data("message", json!("from data"))
260            .data("kind", json!("from data"))
261            .build_json();
262
263        assert_eq!(value["message"], json!("done"));
264        assert_eq!(value["kind"], json!("top"));
265        assert_eq!(value["metadata"]["data"]["message"], json!("from data"));
266        assert!(value["metadata"]["data"].get("kind").is_none());
267    }
268}