1use std::collections::HashMap;
13
14use serde_json::Value;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ToolResultKind {
19 FileRead,
21 Shell,
23 Search,
25 Other,
27}
28
29pub fn classify_tool_name(name: &str) -> ToolResultKind {
34 let n = name.to_ascii_lowercase();
35
36 const FILE_READ: &[&str] = &[
38 "read_file",
39 "readfile",
40 "file_read",
41 "fsread",
42 "fs_read",
43 "view_file",
44 "viewfile",
45 "open_file",
46 "notebookread",
47 "notebook_read",
48 "cat_file",
49 "get_file",
50 "fetch_file",
51 "ctx_read",
52 "ctx_multi_read",
53 "multi_read",
54 "multiread",
55 "read_many", "read_files",
57 "str_replace_editor", "ctx_patch", "ctx_refactor", "ctx_callgraph", ];
62 if FILE_READ.iter().any(|k| n.contains(k)) {
63 return ToolResultKind::FileRead;
64 }
65 if matches!(n.as_str(), "read" | "view" | "cat" | "open") {
67 return ToolResultKind::FileRead;
68 }
69
70 const SEARCH: &[&str] = &[
71 "grep",
72 "ripgrep",
73 "search",
74 "find",
75 "glob",
76 "list_dir",
77 "listdir",
78 "list_files",
79 "listfiles",
80 "ls",
81 "codebase_search",
82 "ctx_search",
83 "ctx_tree",
84 ];
85 if SEARCH.iter().any(|k| n.contains(k)) {
86 return ToolResultKind::Search;
87 }
88
89 const SHELL: &[&str] = &[
90 "bash",
91 "shell",
92 "terminal",
93 "run_command",
94 "run_terminal",
95 "runterminal",
96 "execute_command",
97 "exec_command",
98 "command_exec",
99 "ctx_shell",
100 ];
101 if SHELL.iter().any(|k| n.contains(k)) {
102 return ToolResultKind::Shell;
103 }
104 if matches!(n.as_str(), "run" | "exec" | "execute" | "command" | "sh") {
105 return ToolResultKind::Shell;
106 }
107
108 for seg in n.split(|c: char| !c.is_ascii_alphanumeric()) {
115 match seg {
116 "read" | "view" | "cat" | "open" => return ToolResultKind::FileRead,
117 "grep" | "search" | "find" | "glob" | "ls" | "rg" => return ToolResultKind::Search,
118 "shell" | "bash" | "exec" | "run" | "terminal" | "cmd" => return ToolResultKind::Shell,
119 _ => {}
120 }
121 }
122
123 ToolResultKind::Other
124}
125
126pub fn anthropic_tool_names(messages: &[Value]) -> HashMap<String, String> {
130 let mut map = HashMap::new();
131 for msg in messages {
132 let Some(blocks) = msg.get("content").and_then(|c| c.as_array()) else {
133 continue;
134 };
135 for block in blocks {
136 if block.get("type").and_then(|t| t.as_str()) != Some("tool_use") {
137 continue;
138 }
139 if let (Some(id), Some(name)) = (
140 block.get("id").and_then(|v| v.as_str()),
141 block.get("name").and_then(|v| v.as_str()),
142 ) {
143 map.insert(id.to_string(), name.to_string());
144 }
145 }
146 }
147 map
148}
149
150pub fn openai_tool_names(messages: &[Value]) -> HashMap<String, String> {
153 let mut map = HashMap::new();
154 for msg in messages {
155 let Some(calls) = msg.get("tool_calls").and_then(|c| c.as_array()) else {
156 continue;
157 };
158 for call in calls {
159 let id = call.get("id").and_then(|v| v.as_str());
160 let name = call
161 .get("function")
162 .and_then(|f| f.get("name"))
163 .and_then(|v| v.as_str());
164 if let (Some(id), Some(name)) = (id, name) {
165 map.insert(id.to_string(), name.to_string());
166 }
167 }
168 }
169 map
170}
171
172pub fn responses_tool_names(input: &[Value]) -> HashMap<String, String> {
175 let mut map = HashMap::new();
176 for item in input {
177 if item.get("type").and_then(|t| t.as_str()) != Some("function_call") {
178 continue;
179 }
180 if let (Some(id), Some(name)) = (
181 item.get("call_id").and_then(|v| v.as_str()),
182 item.get("name").and_then(|v| v.as_str()),
183 ) {
184 map.insert(id.to_string(), name.to_string());
185 }
186 }
187 map
188}
189
190fn command_of(arguments: &Value) -> Option<String> {
194 let arguments = match arguments {
195 Value::String(raw) => &serde_json::from_str::<Value>(raw).ok()?,
196 other => other,
197 };
198 let command = arguments.get("command").or_else(|| arguments.get("cmd"))?;
199 match command {
200 Value::String(command) => Some(command.clone()),
201 Value::Array(argv) => {
202 let argv: Vec<&str> = argv.iter().filter_map(Value::as_str).collect();
203 match argv.as_slice() {
204 [] => None,
205 [shell, flag, script]
206 if matches!(
207 shell.rsplit('/').next(),
208 Some("sh" | "bash" | "zsh" | "dash" | "ksh")
209 ) && flag.starts_with('-')
210 && flag.ends_with('c') =>
211 {
212 Some((*script).to_string())
213 }
214 parts => Some(parts.join(" ")),
215 }
216 }
217 _ => None,
218 }
219}
220
221pub fn anthropic_tool_commands(messages: &[Value]) -> HashMap<String, String> {
224 let mut map = HashMap::new();
225 for msg in messages {
226 let Some(blocks) = msg.get("content").and_then(|c| c.as_array()) else {
227 continue;
228 };
229 for block in blocks {
230 if block.get("type").and_then(|t| t.as_str()) != Some("tool_use") {
231 continue;
232 }
233 if let (Some(id), Some(command)) = (
234 block.get("id").and_then(|v| v.as_str()),
235 block.get("input").and_then(command_of),
236 ) {
237 map.insert(id.to_string(), command);
238 }
239 }
240 }
241 map
242}
243
244pub fn openai_tool_commands(messages: &[Value]) -> HashMap<String, String> {
247 let mut map = HashMap::new();
248 for msg in messages {
249 let Some(calls) = msg.get("tool_calls").and_then(|c| c.as_array()) else {
250 continue;
251 };
252 for call in calls {
253 let id = call.get("id").and_then(|v| v.as_str());
254 let command = call
255 .get("function")
256 .and_then(|f| f.get("arguments"))
257 .and_then(command_of);
258 if let (Some(id), Some(command)) = (id, command) {
259 map.insert(id.to_string(), command);
260 }
261 }
262 }
263 map
264}
265
266pub fn responses_tool_commands(input: &[Value]) -> HashMap<String, String> {
270 let mut map = HashMap::new();
271 for item in input {
272 let command = match item.get("type").and_then(|t| t.as_str()) {
273 Some("function_call") => item.get("arguments").and_then(command_of),
274 Some("local_shell_call") => item.get("action").and_then(command_of),
275 _ => None,
276 };
277 if let (Some(id), Some(command)) = (item.get("call_id").and_then(|v| v.as_str()), command) {
278 map.insert(id.to_string(), command);
279 }
280 }
281 map
282}
283
284pub fn gemini_tool_commands(contents: &[Value]) -> HashMap<(usize, usize), String> {
298 let mut by_id: HashMap<&str, Option<String>> = HashMap::new();
299 let mut by_name: HashMap<&str, std::collections::VecDeque<Option<String>>> = HashMap::new();
300 let mut map = HashMap::new();
301 for (content_idx, content) in contents.iter().enumerate() {
302 let Some(parts) = content.get("parts").and_then(Value::as_array) else {
303 continue;
304 };
305 for (part_idx, part) in parts.iter().enumerate() {
306 if let Some(call) = part.get("functionCall") {
307 let command = call.get("args").and_then(command_of);
308 if let Some(id) = call.get("id").and_then(Value::as_str) {
309 by_id.insert(id, command);
310 } else if let Some(name) = call.get("name").and_then(Value::as_str) {
311 by_name.entry(name).or_default().push_back(command);
312 }
313 } else if let Some(response) = part.get("functionResponse") {
314 let command = match response.get("id").and_then(Value::as_str) {
315 Some(id) => by_id.remove(id).flatten(),
316 None => response
317 .get("name")
318 .and_then(Value::as_str)
319 .and_then(|name| by_name.get_mut(name))
320 .and_then(std::collections::VecDeque::pop_front)
321 .flatten(),
322 };
323 if let Some(command) = command {
324 map.insert((content_idx, part_idx), command);
325 }
326 }
327 }
328 }
329 map
330}
331
332pub fn should_protect(kind: ToolResultKind, content: &str) -> bool {
339 match kind {
340 ToolResultKind::FileRead => true,
341 ToolResultKind::Other => looks_like_source_code(content),
342 ToolResultKind::Shell | ToolResultKind::Search => false,
343 }
344}
345
346pub fn looks_like_source_code(content: &str) -> bool {
361 let mut code_signals = 0usize;
362 let mut shell_signals = 0usize;
363 let mut considered = 0usize;
364
365 for raw in content.lines().take(200) {
366 let line = raw.trim_end();
367 let trimmed = line.trim_start();
368 if trimmed.is_empty() {
369 continue;
370 }
371
372 if trimmed.starts_with("//")
380 || trimmed.starts_with("/*")
381 || trimmed.starts_with("*/")
382 || trimmed.starts_with("* ")
383 {
384 continue;
385 }
386
387 considered += 1;
388
389 if trimmed.starts_with("$ ")
391 || trimmed.starts_with("% ")
392 || trimmed.starts_with(">>> ")
393 || trimmed.starts_with("warning:")
394 || trimmed.starts_with("error:")
395 || trimmed.starts_with("error[")
396 || trimmed.starts_with("INFO ")
397 || trimmed.starts_with("WARN ")
398 || trimmed.starts_with("DEBUG ")
399 || trimmed.starts_with("ERROR ")
400 || trimmed.starts_with("Compiling ")
401 || trimmed.starts_with("Downloaded ")
402 || trimmed.starts_with("test result:")
403 {
404 shell_signals += 1;
405 continue;
406 }
407
408 let is_indented = line.len() != trimmed.len();
410 let has_code_punct = trimmed.ends_with('{')
411 || trimmed.ends_with('}')
412 || trimmed.ends_with(';')
413 || trimmed.ends_with("=>")
414 || trimmed.ends_with("->")
415 || trimmed.ends_with(':');
416 let is_call_or_closer = (trimmed.contains('(') && trimmed.contains(')'))
423 || trimmed.starts_with('}')
424 || trimmed.starts_with(')');
425 let has_keyword = [
426 "fn ",
427 "def ",
428 "class ",
429 "import ",
430 "from ",
431 "function ",
432 "func ",
433 "pub ",
434 "const ",
435 "let ",
436 "var ",
437 "package ",
438 "public ",
439 "private ",
440 "struct ",
441 "enum ",
442 "impl ",
443 "#include",
444 "return ",
445 "async ",
446 "export ",
447 ]
448 .iter()
449 .any(|k| trimmed.starts_with(k) || trimmed.contains(k));
450
451 let has_code_shape = has_code_punct && (is_indented || is_call_or_closer);
454 if has_code_shape || has_keyword {
455 code_signals += 1;
456 }
457 }
458
459 if considered < 5 || shell_signals > 0 {
460 return false;
461 }
462 code_signals * 2 >= considered
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469
470 #[test]
471 fn classifies_file_read_tools() {
472 for name in [
473 "Read",
474 "read_file",
475 "view_file",
476 "ctx_read",
477 "mcp__fs__readFile",
478 "ctx_multi_read",
480 "read_many_files",
481 ] {
482 assert_eq!(
483 classify_tool_name(name),
484 ToolResultKind::FileRead,
485 "{name} should be FileRead"
486 );
487 }
488 }
489
490 #[test]
491 fn classifies_shell_and_search() {
492 assert_eq!(classify_tool_name("Bash"), ToolResultKind::Shell);
493 assert_eq!(
494 classify_tool_name("run_terminal_cmd"),
495 ToolResultKind::Shell
496 );
497 assert_eq!(classify_tool_name("Grep"), ToolResultKind::Search);
498 assert_eq!(
499 classify_tool_name("codebase_search"),
500 ToolResultKind::Search
501 );
502 }
503
504 #[test]
505 fn unknown_tool_is_other() {
506 assert_eq!(classify_tool_name("submit_pr"), ToolResultKind::Other);
507 }
508
509 #[test]
510 fn classifies_vendor_prefixed_foreign_tools() {
511 assert_eq!(classify_tool_name("forge_read"), ToolResultKind::FileRead);
515 assert_eq!(classify_tool_name("pi.read"), ToolResultKind::FileRead);
516 assert_eq!(classify_tool_name("forge_shell"), ToolResultKind::Shell);
517 assert_eq!(classify_tool_name("forge_exec"), ToolResultKind::Shell);
518 assert_eq!(classify_tool_name("fs:grep"), ToolResultKind::Search);
519 }
520
521 #[test]
522 fn segment_fallback_has_no_substring_false_positives() {
523 assert_eq!(classify_tool_name("thread_create"), ToolResultKind::Other);
526 assert_eq!(classify_tool_name("spread_values"), ToolResultKind::Other);
527 assert_eq!(
528 classify_tool_name("readme_generator"),
529 ToolResultKind::Other
530 );
531 assert_eq!(classify_tool_name("submit_pull"), ToolResultKind::Other);
532 }
533
534 #[test]
535 fn anthropic_names_resolve_from_tool_use() {
536 let messages = vec![
537 serde_json::json!({
538 "role": "assistant",
539 "content": [
540 {"type": "text", "text": "reading"},
541 {"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {}}
542 ]
543 }),
544 serde_json::json!({
545 "role": "user",
546 "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "x"}]
547 }),
548 ];
549 let names = anthropic_tool_names(&messages);
550 assert_eq!(names.get("toolu_1").map(String::as_str), Some("Read"));
551 }
552
553 #[test]
554 fn openai_names_resolve_from_tool_calls() {
555 let messages = vec![serde_json::json!({
556 "role": "assistant",
557 "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "read_file"}}]
558 })];
559 let names = openai_tool_names(&messages);
560 assert_eq!(names.get("call_1").map(String::as_str), Some("read_file"));
561 }
562
563 #[test]
564 fn responses_names_resolve_from_function_call() {
565 let input = vec![serde_json::json!({
566 "type": "function_call", "call_id": "call_1", "name": "Read", "arguments": "{}"
567 })];
568 let names = responses_tool_names(&input);
569 assert_eq!(names.get("call_1").map(String::as_str), Some("Read"));
570 }
571
572 #[test]
573 fn source_code_detected() {
574 let code = "pub fn build(cfg: &Config) -> Result<App> {\n let mut app = App::new();\n app.configure(cfg);\n for route in cfg.routes() {\n app.register(route);\n }\n Ok(app)\n}";
575 assert!(looks_like_source_code(code));
576 }
577
578 #[test]
579 fn command_output_not_code() {
580 let log = "$ cargo build\n Compiling foo v0.1.0\n Compiling bar v0.2.0\nwarning: unused variable\n Finished dev target\nerror: could not compile";
581 assert!(!looks_like_source_code(log));
582 }
583
584 #[test]
585 fn plain_prose_not_code() {
586 let prose = "This is a normal paragraph of text.\nIt has several sentences.\nNone of them are code.\nThey are just words on lines.\nMore words follow here.";
587 assert!(!looks_like_source_code(prose));
588 }
589
590 #[test]
597 fn test_file_with_separator_comments_is_source() {
598 let code = "import { describe, it, expect } from \"vitest\";\n\
599 \n\
600 // ————————————————————————————————————————————————————————\n\
601 // Section: arithmetic\n\
602 // ————————————————————————————————————————————————————————\n\
603 describe(\"add\", () => {\n\
604 \x20 it(\"adds\", () => {\n\
605 \x20 expect(1 + 1).toBe(2);\n\
606 \x20 });\n\
607 });\n\
608 \n\
609 // ----------------------------------------------------------\n\
610 // Section: strings\n\
611 // ----------------------------------------------------------\n\
612 describe(\"concat\", () => {\n\
613 \x20 it(\"joins\", () => {\n\
614 \x20 expect(\"a\" + \"b\").toBe(\"ab\");\n\
615 \x20 });\n\
616 });\n";
617 assert!(
618 looks_like_source_code(code),
619 "a .test.ts with decorative separator comments must read as source"
620 );
621 assert!(
622 should_protect(ToolResultKind::Other, code),
623 "an unrecognized tool returning this source must still be protected"
624 );
625 }
626
627 #[test]
630 fn comment_heavy_source_still_detected() {
631 let code = "/*\n\
632 \x20* Copyright (c) 2026. All rights reserved.\n\
633 \x20* This module wires the request pipeline.\n\
634 \x20*/\n\
635 export function build(cfg) {\n\
636 \x20 const app = create();\n\
637 \x20 app.use(cfg);\n\
638 \x20 return app;\n\
639 }\n";
640 assert!(looks_like_source_code(code));
641 }
642
643 #[test]
647 fn parenthesized_log_output_still_not_code() {
648 let log = "INFO starting worker (pid=4211)\n\
649 processing batch (size=128) ok\n\
650 processing batch (size=64) ok\n\
651 WARN slow response (842ms) from upstream\n\
652 done in 3.2s (0 errors)\n";
653 assert!(!looks_like_source_code(log));
654 }
655
656 #[test]
659 fn ctx_patch_and_refactor_classified_as_file_read() {
660 assert_eq!(classify_tool_name("ctx_patch"), ToolResultKind::FileRead);
661 assert_eq!(classify_tool_name("ctx_refactor"), ToolResultKind::FileRead);
662 assert_eq!(
663 classify_tool_name("ctx_callgraph"),
664 ToolResultKind::FileRead
665 );
666 }
667
668 #[test]
670 fn diff_preview_is_protected_when_kind_is_file_read() {
671 let diff = "--- src/main.rs\n\
672 - fn check_all_segments(command: &str, allowlist: &[String]) -> Result<(), ShellError> {\n\
673 - if allowlist.is_empty() {\n\
674 - return Ok(());\n\
675 + fn check_all_segments(cmd: &str, list: &[String]) -> Result<(), ShellError> {\n\
676 + if list.is_empty() {\n\
677 + return Ok(());\n";
678 assert!(
679 should_protect(ToolResultKind::FileRead, diff),
680 "diff preview must be protected when kind is FileRead"
681 );
682 }
683}