Skip to main content

vtcode_core/core/agent/
result_reducers.rs

1//! Token-efficient tool result reducers.
2//!
3//! When tool results are too large for the context window, reducers truncate
4//! them to keep only high-signal information. This follows the context
5//! engineering principle: "return only summaries or a small number of results
6//! to the model."
7
8use std::borrow::Cow;
9
10use serde_json::Value;
11
12use crate::config::constants::tools;
13use crate::mcp::{MCP_APP_DISCLOSURE_KEY, MCP_APP_SUPPRESSED_KEY};
14use crate::tools::tool_intent;
15
16/// Reduce a tool result to be more token-efficient.
17///
18/// Dispatches to the appropriate reducer based on the tool name.
19pub fn reduce_tool_result(tool_name: &str, result: Value) -> Value {
20    let canonical_tool_name = tool_intent::canonical_command_session_tool_name(tool_name).unwrap_or(tool_name);
21    match canonical_tool_name {
22        tools::READ_FILE => reduce_read_file_result(result),
23        tools::UNIFIED_EXEC => reduce_command_result(result),
24        _ => result,
25    }
26}
27
28/// Strip TUI-only display fields from a tool result before it enters model
29/// context.
30///
31/// The `view` field produced by `task_tracker` (and its planning-workflow
32/// variant) is rendered only by the TUI — branch symbols, status icons, and
33/// per-item display lines that duplicate the structured `checklist` already
34/// present in the same payload. Sending it to the model wastes tokens on every
35/// tracker call, and the waste grows as items accumulate `outcome`/`verify`
36/// metadata (observed growing from ~5 KB to ~12 KB per call in session logs,
37/// with `view` accounting for ~3 KB of each).
38///
39/// The TUI reads `view` from the original tool-output `Value` via the
40/// pipeline-output / event path, not from the model-facing string this is
41/// applied to, so removing it here is display-safe.
42///
43/// The MCP app-disclosure object (`uiDisclosure`, derived from server `_meta`)
44/// is likewise display-only: SEP-1865 states `_meta` is "not intended for
45/// model context", and the URIs, origins, and permission requests it carries
46/// are server-controlled. The `off`-tier suppression marker (`uiSuppressed`)
47/// is display-only for the same reason. The event path keeps both for
48/// TUI/desktop rendering; only the model projection drops them.
49///
50/// Returns a borrowed value when no stripping is needed so the common path
51/// pays zero allocation.
52pub fn strip_tui_display_fields<'a>(tool_name: &str, value: &'a Value) -> Cow<'a, Value> {
53    let Some(obj) = value.as_object() else {
54        return Cow::Borrowed(value);
55    };
56    let canonical = tool_intent::canonical_command_session_tool_name(tool_name).unwrap_or(tool_name);
57    let strip_view = (canonical == tools::TASK_TRACKER || canonical == tools::MATRIX) && obj.contains_key("view");
58    // Both app keys are namespaced to the MCP execution path; no other tool
59    // writes them, so their presence alone marks them for stripping.
60    let strip_disclosure = obj.contains_key(MCP_APP_DISCLOSURE_KEY);
61    let strip_suppressed = obj.contains_key(MCP_APP_SUPPRESSED_KEY);
62    if !strip_view && !strip_disclosure && !strip_suppressed {
63        return Cow::Borrowed(value);
64    }
65    let mut stripped = obj.clone();
66    if strip_view {
67        stripped.remove("view");
68    }
69    if strip_disclosure {
70        stripped.remove(MCP_APP_DISCLOSURE_KEY);
71    }
72    if strip_suppressed {
73        stripped.remove(MCP_APP_SUPPRESSED_KEY);
74    }
75    Cow::Owned(Value::Object(stripped))
76}
77
78/// Project an indexed tracker update without repeating unchanged task details.
79/// Full results remain available to persistence, events, and explicit list calls.
80pub fn project_model_tool_result<'a>(tool_name: &str, args: &Value, value: &'a Value) -> Cow<'a, Value> {
81    let mut projected = strip_tui_display_fields(tool_name, value);
82    if tool_name != tools::TASK_TRACKER
83        || args.get("action").and_then(Value::as_str) != Some("update")
84        || args.get("items").is_some()
85    {
86        return projected;
87    }
88    let index_path = args
89        .get("index_path")
90        .and_then(Value::as_str)
91        .map(str::to_owned)
92        .or_else(|| args.get("index").and_then(Value::as_u64).map(|index| index.to_string()));
93    let Some(index_path) = index_path else {
94        return projected;
95    };
96    let Some(changed_item) = value
97        .get("checklist")
98        .and_then(|checklist| checklist.get("items"))
99        .and_then(Value::as_array)
100        .and_then(|items| {
101            items.iter().find(|item| {
102                item.get("index_path")
103                    .and_then(Value::as_str)
104                    .is_some_and(|path| path == index_path)
105                    || item
106                        .get("index")
107                        .and_then(Value::as_u64)
108                        .is_some_and(|index| index.to_string() == index_path)
109            })
110        })
111        .cloned()
112    else {
113        return projected;
114    };
115    if let Some(object) = projected.to_mut().as_object_mut() {
116        if let Some(checklist) = object.get_mut("checklist").and_then(Value::as_object_mut) {
117            checklist.remove("items");
118        }
119        object.insert("changed_item".to_owned(), changed_item);
120    }
121    projected
122}
123
124/// Hard byte cap on model-visible content. Line truncation alone does not
125/// bound output with very long lines (minified bundles, generated data), so
126/// the provider-visible preview contract needs a byte budget as well.
127const MAX_RESULT_BYTES: usize = 32 * 1024;
128
129fn truncate_utf8_bytes(text: &str, max_bytes: usize) -> (String, bool) {
130    if text.len() <= max_bytes {
131        return (text.to_string(), false);
132    }
133    (vtcode_commons::formatting::truncate_utf8_prefix(text, max_bytes).to_string(), true)
134}
135
136fn reduce_read_file_result(result: Value) -> Value {
137    const MAX_FILE_LINES: usize = 2000;
138
139    let Some(obj) = result.as_object() else {
140        return result;
141    };
142    let Some(content) = obj.get("content").and_then(Value::as_str) else {
143        return result;
144    };
145
146    let (line_truncated, content) = match truncate_lines(content, MAX_FILE_LINES) {
147        Some((truncated, _)) => (true, truncated),
148        None => (false, content.to_string()),
149    };
150    let (content, byte_truncated) = truncate_utf8_bytes(&content, MAX_RESULT_BYTES);
151    let is_truncated = line_truncated || byte_truncated;
152    if !is_truncated {
153        // Keep the full payload: read results carry continuation fields
154        // (`has_more`, `next_read_args`, `spool_path`, …) that a whitelist
155        // rebuild would drop and break paging.
156        return result;
157    }
158
159    let mut reduced = obj.clone();
160    reduced.insert("content".to_string(), Value::String(content));
161    reduced.insert("is_truncated".to_string(), Value::Bool(true));
162    // next_read_args.offset still points past the *original* chunk. Without
163    // this flag the model would assume the page is complete and skip the
164    // byte-capped tail.
165    if reduced.contains_key("next_read_args") || reduced.get("has_more").and_then(Value::as_bool) == Some(true) {
166        reduced.insert("chunk_tail_omitted".to_string(), Value::Bool(true));
167    }
168    if line_truncated {
169        reduced.insert("note".to_string(), Value::String("File content truncated for context economy.".to_string()));
170    }
171
172    Value::Object(reduced)
173}
174
175fn reduce_command_result(result: Value) -> Value {
176    const MAX_FILE_LINES: usize = 2000;
177
178    let Some(obj) = result.as_object() else {
179        return result;
180    };
181    let stream_key = if obj.get("stdout").and_then(Value::as_str).is_some() {
182        "stdout"
183    } else {
184        "output"
185    };
186    let Some(stream) = obj.get(stream_key).and_then(Value::as_str) else {
187        return result;
188    };
189
190    let (line_truncated, lines_count, stream) = match truncate_lines(stream, MAX_FILE_LINES) {
191        Some((truncated, lines_count)) => (true, lines_count, truncated),
192        None => (false, 0, stream.to_string()),
193    };
194    let (stream, byte_truncated) = truncate_utf8_bytes(&stream, MAX_RESULT_BYTES);
195    if !line_truncated && !byte_truncated {
196        return result;
197    }
198
199    let mut reduced = obj.clone();
200    reduced.insert(stream_key.to_string(), Value::String(stream));
201    reduced.insert("is_truncated".to_string(), Value::Bool(true));
202    if line_truncated {
203        reduced.insert("original_lines".to_string(), Value::Number(serde_json::Number::from(lines_count as u64)));
204    }
205    reduced.insert("note".to_string(), Value::String("Command output truncated for context economy.".to_string()));
206    Value::Object(reduced)
207}
208
209pub fn truncate_lines(text: &str, max_lines: usize) -> Option<(String, usize)> {
210    if max_lines == 0 {
211        return Some((String::new(), text.lines().count()));
212    }
213
214    let mut lines = text.lines();
215    let mut total = 0usize;
216    let mut out = String::new();
217    while let Some(line) = lines.next() {
218        total += 1;
219        if total <= max_lines {
220            if total > 1 {
221                out.push('\n');
222            }
223            out.push_str(line);
224            continue;
225        }
226        total += lines.count();
227        return Some((out, total));
228    }
229    None
230}
231
232#[cfg(test)]
233mod tests {
234    #[test]
235    fn tracker_projection_keeps_only_the_changed_hierarchical_item() {
236        let original = serde_json::json!({
237            "status": "updated",
238            "checklist": {"total": 2, "completed": 1, "items": [
239                {"index_path": "1", "description": "Parent", "status": "pending"},
240                {"index_path": "1.1", "description": "Child", "status": "completed", "verify": ["cargo check"]}
241            ]},
242            "view": {"lines": ["Parent", "Child"]}
243        });
244        let projected = project_model_tool_result(
245            "task_tracker",
246            &serde_json::json!({"action": "update", "index_path": "1.1"}),
247            &original,
248        );
249        assert_eq!(projected["changed_item"]["description"], "Child");
250        assert_eq!(projected["changed_item"]["verify"], serde_json::json!(["cargo check"]));
251        assert_eq!(projected["checklist"]["total"], 2);
252        assert!(projected["checklist"].get("items").is_none());
253        assert!(projected.get("view").is_none());
254        assert_eq!(original["checklist"]["items"].as_array().unwrap().len(), 2);
255        assert!(original.get("view").is_some());
256        assert!(projected.to_string().len() < original.to_string().len());
257        for args in [
258            serde_json::json!({"action": "list"}),
259            serde_json::json!({"action": "create"}),
260            serde_json::json!({"action": "update", "items": ["Replacement"]}),
261            serde_json::json!({"action": "update", "index_path": "9"}),
262        ] {
263            let projected = project_model_tool_result("task_tracker", &args, &original);
264            assert_eq!(projected["checklist"]["items"], original["checklist"]["items"]);
265            assert!(projected.get("changed_item").is_none());
266        }
267    }
268
269    #[test]
270    fn tracker_projection_supports_standard_indices() {
271        let result = serde_json::json!({"checklist": {"items": [
272            {"index": 1, "description": "First"}, {"index": 2, "description": "Second"}
273        ]}});
274        let projected =
275            project_model_tool_result("task_tracker", &serde_json::json!({"action": "update", "index": 2}), &result);
276        assert_eq!(projected["changed_item"]["description"], "Second");
277        assert_eq!(project_model_tool_result("exec_command", &serde_json::json!({}), &result).as_ref(), &result);
278    }
279    use super::*;
280    use serde_json::json;
281
282    #[test]
283    fn strip_view_removes_view_from_task_tracker_result() {
284        let result = json!({
285            "status": "updated",
286            "message": "Item 1 status changed: pending → completed",
287            "checklist": { "title": "Demo", "total": 2, "completed": 1, "items": [] },
288            "view": { "title": "Demo", "lines": [{ "display": "└ [x] step one" }] },
289        });
290        let stripped = strip_tui_display_fields("task_tracker", &result);
291        assert!(stripped.get("view").is_none(), "view should be removed");
292        assert!(stripped.get("checklist").is_some(), "checklist must remain for the model");
293        assert_eq!(stripped["status"], "updated");
294    }
295
296    #[test]
297    fn strip_view_borrows_non_tracker_tools_unchanged() {
298        let result = json!({ "status": "ok", "output": "hello" });
299        let stripped = strip_tui_display_fields("exec_command", &result);
300        assert!(matches!(stripped, Cow::Borrowed(_)), "non-tracker tools should borrow without allocation");
301        assert_eq!(stripped.as_ref(), &result);
302    }
303
304    #[test]
305    fn strip_view_borrows_tracker_result_without_view_field() {
306        let result = json!({ "status": "empty", "message": "No active checklist." });
307        let stripped = strip_tui_display_fields("task_tracker", &result);
308        assert!(
309            matches!(stripped, Cow::Borrowed(_)),
310            "tracker results without `view` should borrow without allocation"
311        );
312        assert_eq!(stripped.as_ref(), &result);
313    }
314
315    #[test]
316    fn strip_view_preserves_checklist_items_and_metadata() {
317        let result = json!({
318            "status": "ok",
319            "checklist": {
320                "title": "Plan",
321                "total": 2,
322                "completed": 0,
323                "items": [
324                    { "index": 1, "description": "Step A", "status": "pending", "files": ["a.rs"], "outcome": null, "verify": ["cargo check"] },
325                    { "index": 2, "description": "Step B", "status": "pending" },
326                ],
327            },
328            "view": { "title": "Plan", "lines": [{ "display": "├ [ ] Step A" }] },
329        });
330        let stripped = strip_tui_display_fields("task_tracker", &result);
331        let items = stripped["checklist"]["items"].as_array().unwrap();
332        assert_eq!(items.len(), 2);
333        assert_eq!(items[0]["verify"][0], "cargo check");
334        assert_eq!(items[1]["description"], "Step B");
335        assert!(stripped.get("view").is_none());
336    }
337
338    #[test]
339    fn strip_view_handles_non_object_result() {
340        let result = json!("not an object");
341        let stripped = strip_tui_display_fields("task_tracker", &result);
342        assert_eq!(stripped.as_ref(), &result);
343    }
344
345    #[test]
346    fn reduce_read_file_preserves_continuation_fields_when_not_truncated() {
347        let result = json!({
348            "success": true,
349            "content": "short body",
350            "path": "src/lib.rs",
351            "has_more": true,
352            "next_read_args": { "path": "src/lib.rs", "offset": 80 },
353            "spool_path": ".vtcode/context/tool_outputs/x",
354            "spooled_bytes": 999,
355        });
356        let reduced = reduce_tool_result("read_file", result.clone());
357        assert_eq!(reduced, result, "untruncated read results must stay intact for paging");
358    }
359
360    #[test]
361    fn reduce_read_file_truncates_large_content_but_keeps_next_read_args() {
362        let content = "a\n".repeat(2_500);
363        let result = json!({
364            "success": true,
365            "content": content,
366            "path": "src/lib.rs",
367            "has_more": true,
368            "next_read_args": { "path": "src/lib.rs", "offset": 2500 },
369        });
370        let reduced = reduce_tool_result("read_file", result);
371        assert_eq!(reduced["is_truncated"], json!(true));
372        assert!(reduced["content"].as_str().unwrap().lines().count() < 2_500, "content must be line-capped");
373        assert_eq!(reduced["has_more"], json!(true), "paging fields survive truncation");
374        assert!(reduced.get("next_read_args").is_some(), "next_read_args must survive truncation");
375        assert_eq!(
376            reduced["chunk_tail_omitted"],
377            json!(true),
378            "byte-capped page must warn that the chunk tail is not in content"
379        );
380    }
381
382    #[test]
383    fn strip_disclosure_removes_server_meta_from_mcp_result() {
384        let result = json!({
385            "content": [{"type": "text", "text": "12:00"}],
386            "spool_path": ".vtcode/context/tool_outputs/mcp",
387            "uiDisclosure": {
388                "ui://demo/app.html": {"sandbox": "allow", "mimeType": "text/html;profile=mcp-app"},
389                "ui://demo/blocked.html": {"sandbox": "deny", "reason": "CSP violation"},
390            },
391        });
392        let stripped = strip_tui_display_fields("mcp__demo__get_time", &result);
393        assert!(stripped.get("uiDisclosure").is_none(), "server _meta must not reach the model");
394        assert_eq!(stripped["content"][0]["text"], "12:00", "text fallback must survive stripping");
395        assert_eq!(stripped["spool_path"], ".vtcode/context/tool_outputs/mcp");
396        assert!(result.get("uiDisclosure").is_some(), "event path keeps the original disclosure");
397    }
398
399    #[test]
400    fn strip_disclosure_removes_empty_disclosure_object() {
401        let result = json!({"content": [{"type": "text", "text": "ok"}], "uiDisclosure": {}});
402        let stripped = strip_tui_display_fields("mcp__demo__get_time", &result);
403        assert!(stripped.get("uiDisclosure").is_none(), "even an empty disclosure key must go");
404        assert_eq!(stripped["content"][0]["text"], "ok");
405    }
406
407    #[test]
408    fn strip_suppressed_removes_off_tier_marker() {
409        let result = json!({
410            "content": [{"type": "text", "text": "ok"}],
411            "uiSuppressed": ["ui://demo/app.html"],
412        });
413        let stripped = strip_tui_display_fields("mcp__demo__get_time", &result);
414        assert!(stripped.get("uiSuppressed").is_none(), "suppression marker must not reach the model");
415        assert_eq!(stripped["content"][0]["text"], "ok");
416        assert!(result.get("uiSuppressed").is_some(), "event path keeps the marker");
417    }
418
419    #[test]
420    fn model_projection_strips_disclosure_for_mcp_tools() {
421        let result = json!({
422            "content": [{"type": "text", "text": "12:00"}],
423            "uiDisclosure": {"ui://demo/app.html": {"sandbox": "allow"}},
424        });
425        let projected = project_model_tool_result("mcp__demo__get_time", &json!({}), &result);
426        assert!(projected.get("uiDisclosure").is_none());
427        assert_eq!(projected["content"][0]["text"], "12:00");
428    }
429}