Skip to main content

vtcode_core/tools/tool_intent/
classify.rs

1use serde_json::Value;
2
3use crate::config::constants::tools;
4use crate::tools::command_args::interactive_input_text;
5use crate::tools::names::canonical_tool_name;
6use crate::tools::tool_intent::actions::{
7    action_matches_any, command_session_action_in, command_session_action_is, file_operation_action,
8    file_operation_action_is,
9};
10use crate::tools::tool_intent::readonly::{
11    is_parallel_safe_command_session_command, is_readonly_command_session_command,
12};
13use crate::tools::tool_intent::types::{ToolBehavior, ToolIntent, ToolMutationModel};
14
15/// Returns the subset of actions that are allowed for a multi-action tool
16/// when planning mode is active. Returns `None` for tools that are not
17/// multi-action or have no action-level restrictions.
18pub fn planning_allowed_actions(tool_name: &str) -> Option<&'static [&'static str]> {
19    let canonical = canonical_tool_name(tool_name);
20    match canonical {
21        tools::UNIFIED_FILE => Some(&["read"]),
22        tools::UNIFIED_EXEC => Some(&["run", "poll", "wait", "list", "inspect", "continue"]),
23        // `code`, `write`, and `close` are always mutating and excluded.
24        _ => None,
25    }
26}
27
28pub fn builtin_tool_behavior(tool_name: &str) -> Option<ToolBehavior> {
29    let canonical = canonical_tool_name(tool_name);
30    builtin_tool_behavior_canonical(canonical)
31}
32
33pub fn is_parallel_safe_call(tool_name: &str, args: &Value) -> bool {
34    is_parallel_safe_call_with_intent(tool_name, args, &classify_tool_intent(tool_name, args))
35}
36
37/// [`is_parallel_safe_call`] for a call whose [`ToolIntent`] was already
38/// computed on the same args. The non-command branches reuse `intent.mutating`
39/// (identical to re-classifying: `builtin_tool_behavior.classify(args)` IS
40/// `classify_tool_intent`), so preflight paths avoid re-classifying the same
41/// args — a second shell parse for command payloads. The command-run
42/// branch still re-parses: parallel safety for command sessions is a separate
43/// predicate from the read-only intent.
44pub fn is_parallel_safe_call_with_intent(tool_name: &str, args: &Value, intent: &ToolIntent) -> bool {
45    let canonical = canonical_tool_name(tool_name);
46    if matches!(canonical, tools::EXEC_COMMAND | tools::UNIFIED_EXEC) && is_command_run_tool_call(canonical, args) {
47        return is_parallel_safe_command_session_command(args);
48    }
49    if let Some(behavior) = builtin_tool_behavior_canonical(canonical) {
50        return behavior.supports_parallel_calls && !intent.mutating;
51    }
52
53    !intent.mutating
54}
55
56pub fn classify_tool_intent(tool_name: &str, args: &Value) -> ToolIntent {
57    let canonical = canonical_tool_name(tool_name);
58    builtin_tool_behavior_canonical(canonical)
59        .map(|behavior| behavior.classify(args))
60        .unwrap_or_else(ToolIntent::mutating)
61}
62
63pub fn is_edited_file_conflict_guarded_call(tool_name: &str, args: &Value) -> bool {
64    let canonical = canonical_tool_name(tool_name);
65    match canonical {
66        tools::WRITE_FILE | tools::CREATE_FILE | tools::EDIT_FILE | tools::APPLY_PATCH => true,
67        tools::UNIFIED_FILE => file_operation_action(args)
68            .map(is_edited_file_conflict_guarded_file_operation_action)
69            .unwrap_or(false),
70        _ => false,
71    }
72}
73
74fn is_edited_file_conflict_guarded_file_operation_action(action: &str) -> bool {
75    action_matches_any(Some(action), &["write", "create", "edit", "patch"])
76}
77
78pub use tools::{canonical_command_session_tool_name, is_command_session_tool};
79
80pub fn should_use_spool_reference_only(tool_name: Option<&str>, output: &Value) -> bool {
81    let Some(obj) = output.as_object() else {
82        return false;
83    };
84
85    let has_spool_path = obj
86        .get("spool_path")
87        .and_then(Value::as_str)
88        .is_some_and(|path| !path.trim().is_empty());
89    if !has_spool_path {
90        return false;
91    }
92
93    if obj.get("loop_detected").and_then(Value::as_bool) == Some(true) {
94        return false;
95    }
96
97    if tool_name.is_some_and(is_command_session_tool) {
98        return true;
99    }
100
101    if obj
102        .get("content_type")
103        .and_then(Value::as_str)
104        .is_some_and(|content_type| content_type == "exec_inspect")
105    {
106        return true;
107    }
108
109    if tool_name.is_some_and(|name| {
110        name == tools::CODE_SEARCH
111            || name == tools::UNIFIED_SEARCH
112            || name == "code_search"
113            || name == "search_dispatch_internal"
114    }) {
115        return true;
116    }
117
118    ["command", "id", "session_id", "process_id", "is_exited", "exit_code"]
119        .iter()
120        .any(|key| obj.contains_key(*key))
121}
122
123/// Returns `true` if `tool_name` refers to a command/PTY execution tool.
124///
125/// This includes PTY session tools and all unified exec aliases.
126#[must_use]
127pub fn is_command_tool(tool_name: &str) -> bool {
128    tool_name == tools::CREATE_PTY_SESSION || tool_name == tools::SEND_PTY_INPUT || is_command_session_tool(tool_name)
129}
130
131/// Returns `true` if `tool_name` is a direct command-run tool whose output is
132/// rendered inline as a terminal panel and whose raw process output (including
133/// ANSI) should be preserved rather than stripped/line-styled.
134///
135/// This is the stable set shared by the TUI display gates (terminal-panel
136/// dispatch, ANSI preservation, and command-text summary). New command-run
137/// tools MUST be added here so the display stays in sync; the args-aware
138/// [`is_command_run_tool_call`] covers call-site routing.
139#[must_use]
140pub fn is_command_run_tool(tool_name: &str) -> bool {
141    matches!(tool_name, tools::RUN_PTY_CMD | tools::EXEC_COMMAND)
142}
143
144pub fn is_command_run_tool_call(tool_name: &str, args: &Value) -> bool {
145    match tool_name {
146        tools::RUN_PTY_CMD | tools::CREATE_PTY_SESSION | tools::SHELL | "bash" => true,
147        tools::EXEC_COMMAND => crate::tools::command_args::command_text(args).ok().flatten().is_some(),
148        tools::UNIFIED_EXEC | tools::EXEC_PTY_CMD | "exec" | "container.exec" => command_session_action_is(args, "run"),
149        _ => false,
150    }
151}
152
153/// Cleanup stops or releases an owned execution session, never starts work.
154pub fn is_exec_session_cleanup_call(tool_name: &str, args: &Value) -> bool {
155    tool_name == tools::WRITE_STDIN
156        && matches!(
157            crate::tools::command_args::write_stdin_dispatch(args),
158            Ok(crate::tools::command_args::WriteStdinDispatch::Terminate
159                | crate::tools::command_args::WriteStdinDispatch::Close)
160        )
161}
162
163pub fn remap_file_operation_command_args_to_command_session(args: &Value) -> Option<Value> {
164    let obj = args.as_object()?;
165    let command = obj
166        .get("command")
167        .or_else(|| obj.get("cmd"))
168        .or_else(|| obj.get("raw_command"))
169        .and_then(Value::as_str)
170        .map(str::trim)
171        .filter(|value| !value.is_empty())?;
172    let action = obj.get("action").and_then(Value::as_str).map(str::trim);
173    if let Some(action) = action
174        && !action.is_empty()
175        && !action_matches_any(Some(action), &["run", "exec", "execute", "shell"])
176    {
177        return None;
178    }
179
180    let mut mapped = serde_json::Map::new();
181    mapped.insert("action".to_string(), Value::String("run".to_string()));
182    mapped.insert("command".to_string(), Value::String(command.to_string()));
183
184    for key in [
185        "args",
186        "cwd",
187        "workdir",
188        "env",
189        "timeout_ms",
190        "yield_time_ms",
191        "login",
192        "shell",
193        "tty",
194        "sandbox_permissions",
195        "justification",
196        "prefix_rule",
197    ] {
198        if let Some(value) = obj.get(key) {
199            mapped.insert(key.to_string(), value.clone());
200        }
201    }
202
203    Some(Value::Object(mapped))
204}
205
206fn file_operation_intent(args: &Value) -> ToolIntent {
207    if file_operation_action_is(args, "read") {
208        ToolIntent::read_only_unified_action()
209    } else {
210        ToolIntent::mutating()
211    }
212}
213
214fn command_session_intent(args: &Value) -> ToolIntent {
215    let has_exec_input = command_session_has_input(args);
216    let readonly_unified_action = if command_session_action_is(args, "run") {
217        is_readonly_command_session_command(args)
218    } else {
219        command_session_action_in(args, &["poll", "wait", "list", "inspect"])
220            || (command_session_action_is(args, "continue") && !has_exec_input)
221    };
222
223    if readonly_unified_action {
224        ToolIntent::read_only_unified_action()
225    } else {
226        ToolIntent::mutating()
227    }
228}
229
230fn exec_command_intent(args: &Value) -> ToolIntent {
231    if is_readonly_command_session_command(args) {
232        ToolIntent::read_only_unified_action()
233    } else {
234        ToolIntent::mutating()
235    }
236}
237
238fn write_stdin_intent(args: &Value) -> ToolIntent {
239    match crate::tools::command_args::write_stdin_dispatch(args) {
240        Ok(crate::tools::command_args::WriteStdinDispatch::Poll) => ToolIntent::read_only(),
241        Ok(
242            crate::tools::command_args::WriteStdinDispatch::Wait
243            | crate::tools::command_args::WriteStdinDispatch::Inspect,
244        ) => ToolIntent::read_only(),
245        Ok(
246            crate::tools::command_args::WriteStdinDispatch::Write
247            | crate::tools::command_args::WriteStdinDispatch::Terminate
248            | crate::tools::command_args::WriteStdinDispatch::Close,
249        )
250        | Err(_) => ToolIntent::mutating(),
251    }
252}
253
254fn memory_tool_intent(args: &Value) -> ToolIntent {
255    let command = args.get("command").and_then(Value::as_str).map(str::trim).unwrap_or_default();
256    if command.eq_ignore_ascii_case("view") {
257        ToolIntent::read_only()
258    } else {
259        ToolIntent::mutating()
260    }
261}
262
263fn builtin_tool_behavior_canonical(tool: &str) -> Option<ToolBehavior> {
264    match tool {
265        tools::CODE_SEARCH => Some(ToolBehavior::function(ToolMutationModel::ReadOnly, true, false)),
266        tools::UNIFIED_EXEC => {
267            Some(ToolBehavior::function(ToolMutationModel::ByArgs(command_session_intent), false, true))
268        }
269        tools::EXEC_COMMAND => {
270            Some(ToolBehavior::function(ToolMutationModel::ByArgs(exec_command_intent), false, true))
271        }
272        tools::WRITE_STDIN => Some(ToolBehavior::function(ToolMutationModel::ByArgs(write_stdin_intent), false, true)),
273        tools::UNIFIED_FILE => {
274            Some(ToolBehavior::function(ToolMutationModel::ByArgs(file_operation_intent), false, false))
275        }
276        tools::APPLY_PATCH => Some(ToolBehavior::apply_patch(ToolMutationModel::Mutating, false, true)),
277        tools::REQUEST_USER_INPUT
278        | tools::MEMORY
279        | tools::START_PLANNING
280        | tools::LIST_SKILLS
281        | tools::LOAD_SKILL_RESOURCE
282        | tools::TASK_TRACKER
283        | tools::RECORD_DECISION
284        | tools::GET_ERRORS
285        | tools::SEARCH_TOOLS
286        | tools::MCP_SEARCH_TOOLS
287        | tools::MCP_GET_TOOL_DETAILS
288        | tools::MCP_LIST_SERVERS
289        | tools::THINK => Some(ToolBehavior::function(
290            if tool == tools::MEMORY {
291                ToolMutationModel::ByArgs(memory_tool_intent)
292            } else {
293                ToolMutationModel::ReadOnly
294            },
295            false,
296            false,
297        )),
298        tools::LOAD_SKILL => Some(ToolBehavior::function(ToolMutationModel::Mutating, false, true)),
299        tools::READ_FILE | tools::GREP_FILE | tools::LIST_FILES => {
300            Some(ToolBehavior::function(ToolMutationModel::ReadOnly, true, false))
301        }
302        tools::WEB_FETCH | tools::FETCH_URL | tools::WEB_SEARCH => {
303            Some(ToolBehavior::function(ToolMutationModel::ReadOnly, false, false))
304        }
305        tools::WRITE_FILE | tools::EDIT_FILE | tools::DELETE_FILE | tools::CREATE_FILE => {
306            Some(ToolBehavior::function(ToolMutationModel::Mutating, false, true))
307        }
308        tools::MCP_CONNECT_SERVER | tools::MCP_DISCONNECT_SERVER => {
309            Some(ToolBehavior::function(ToolMutationModel::Mutating, false, false))
310        }
311        tools::RUN_PTY_CMD
312        | tools::SEND_PTY_INPUT
313        | tools::CREATE_PTY_SESSION
314        | tools::READ_PTY_SESSION
315        | tools::LIST_PTY_SESSIONS
316        | tools::CLOSE_PTY_SESSION
317        | tools::EXECUTE_CODE
318        | tools::SHELL => Some(ToolBehavior::function(ToolMutationModel::Mutating, false, true)),
319        _ => None,
320    }
321}
322
323fn command_session_has_input(args: &Value) -> bool {
324    interactive_input_text(args).is_some()
325}