Skip to main content

vtcode_commons/
tool_types.rs

1#![expect(
2    clippy::cast_possible_truncation,
3    reason = "Quality scores are normalized to the documented 0..=100 display range before narrowing."
4)]
5
6//! Shared runtime types for the VT Code tool system.
7//!
8//! This module provides types shared between the LLM and tools subsystems,
9//! breaking the circular dependency that would otherwise exist between them.
10//!
11//! # Overview
12//!
13//! The key types here are:
14//! - [`CompactStr`] - stack-allocated string for short tool names
15//! - [`EnhancedToolResult`] - tool result with quality metadata
16//! - [`ResultMetadata`] - quality/confidence scoring for tool results
17//! - [`tool_names`] - tool name constants used across subsystems
18
19// ---------------------------------------------------------------------------
20// CompactStr type alias
21// ---------------------------------------------------------------------------
22
23/// Compact inline string -- stack-allocated for strings up to 24 bytes.
24/// Drop-in replacement for `String` with zero heap allocation for short strings.
25pub type CompactStr = compact_str::CompactString;
26
27// ---------------------------------------------------------------------------
28// Tool name constants (canonical names used across subsystems)
29// ---------------------------------------------------------------------------
30
31/// Canonical tool name constants — the single source of truth for tool
32/// identities across commons, config, core, and the CLI.
33///
34/// Names are grouped by purpose into submodules so policy/catalog layers can
35/// consume a whole group as a slice; every name is also re-exported flat so
36/// existing `tool_names::NAME` paths keep working. `vtcode-config` re-exports
37/// this module as `constants::tools`. A raw `"read_file"` at a call site can
38/// drift silently — reference the constant instead.
39pub mod tool_names {
40    /// Tools the model may call directly.
41    pub mod model_facing {
42        pub const EXEC_COMMAND: &str = "exec_command";
43        pub const WRITE_STDIN: &str = "write_stdin";
44        pub const APPLY_PATCH: &str = "apply_patch";
45        pub const RECORD_DECISION: &str = "record_decision";
46        pub const CODE_SEARCH: &str = "code_search";
47        pub const COMPUTER_USE: &str = "computer_use";
48    }
49
50    /// Internal dispatchers retained behind the public tools.
51    pub mod dispatchers {
52        pub const UNIFIED_SEARCH: &str = "search_dispatch_internal";
53        pub const UNIFIED_EXEC: &str = "command_session_internal";
54        pub const UNIFIED_FILE: &str = "file_operation_internal";
55    }
56
57    /// Standalone tool ids: discovery, MCP, web, and legacy search helpers.
58    pub mod ids {
59        pub const THINK: &str = "think";
60        pub const SEARCH_TOOLS: &str = "search_tools";
61        pub const MCP: &str = "mcp";
62        pub const MCP_SEARCH_TOOLS: &str = "mcp_search_tools";
63        pub const MCP_GET_TOOL_DETAILS: &str = "mcp_get_tool_details";
64        pub const MCP_LIST_SERVERS: &str = "mcp_list_servers";
65        pub const MCP_CONNECT_SERVER: &str = "mcp_connect_server";
66        pub const MCP_DISCONNECT_SERVER: &str = "mcp_disconnect_server";
67        pub const WEB_SEARCH: &str = "web_search";
68        pub const WEB_FETCH: &str = "web_fetch";
69        pub const FETCH_URL: &str = "fetch_url";
70        pub const LIST: &str = "list";
71        pub const GREP: &str = "grep";
72        pub const FETCH: &str = "fetch";
73        pub const EXEC_PTY_CMD: &str = "exec_pty_cmd";
74        pub const SHELL: &str = "shell";
75        pub const GREP_FILE: &str = "grep_file";
76        pub const LIST_FILES: &str = "list_files";
77    }
78
79    /// Internal execution helpers (PTY session management).
80    pub mod execution {
81        pub const RUN_PTY_CMD: &str = "run_pty_cmd";
82        pub const CREATE_PTY_SESSION: &str = "create_pty_session";
83        pub const LIST_PTY_SESSIONS: &str = "list_pty_sessions";
84        pub const CLOSE_PTY_SESSION: &str = "close_pty_session";
85        pub const SEND_PTY_INPUT: &str = "send_pty_input";
86        pub const READ_PTY_SESSION: &str = "read_pty_session";
87        pub const RESIZE_PTY_SESSION: &str = "resize_pty_session";
88        pub const EXECUTE_CODE: &str = "execute_code";
89    }
90
91    /// Internal file-operation helpers.
92    pub mod files {
93        pub const READ_FILE: &str = "read_file";
94        pub const WRITE_FILE: &str = "write_file";
95        pub const EDIT_FILE: &str = "edit_file";
96        pub const DELETE_FILE: &str = "delete_file";
97        pub const CREATE_FILE: &str = "create_file";
98        pub const SEARCH_REPLACE: &str = "search_replace";
99        pub const FILE_OP: &str = "file_op";
100        pub const MOVE_FILE: &str = "move_file";
101        pub const COPY_FILE: &str = "copy_file";
102    }
103
104    /// Skill progressive disclosure.
105    pub mod skills {
106        pub const LIST_SKILLS: &str = "list_skills";
107        pub const LOAD_SKILL: &str = "load_skill";
108        pub const LOAD_SKILL_RESOURCE: &str = "load_skill_resource";
109    }
110
111    /// Goal-loop control.
112    pub mod goal {
113        pub const GET_GOAL: &str = "get_goal";
114        pub const UPDATE_GOAL: &str = "update_goal";
115    }
116
117    /// Diagnostics.
118    pub mod diagnostics {
119        pub const GET_ERRORS: &str = "get_errors";
120    }
121
122    /// Human-in-the-loop and durable scheduling control.
123    pub mod control {
124        pub const REQUEST_USER_INPUT: &str = "request_user_input";
125        pub const MEMORY: &str = "memory";
126        pub const ASK_QUESTIONS: &str = "ask_questions";
127        pub const ASK_USER_QUESTION: &str = "ask_user_question";
128        pub const MATRIX: &str = "matrix";
129        pub const AGENT: &str = "agent";
130        pub const CRON: &str = "cron";
131        pub const CRON_CREATE: &str = "cron_create";
132        pub const CRON_LIST: &str = "cron_list";
133        pub const CRON_DELETE: &str = "cron_delete";
134    }
135
136    /// Planning workflow coordination.
137    pub mod planning {
138        pub const START_PLANNING: &str = "start_planning";
139        pub const TASK_TRACKER: &str = "task_tracker";
140    }
141
142    /// Subagent collaboration and peer sessions.
143    pub mod subagents {
144        pub const SPAWN_AGENT: &str = "spawn_agent";
145        pub const SPAWN_BACKGROUND_SUBPROCESS: &str = "spawn_background_subprocess";
146        pub const SEND_INPUT: &str = "send_input";
147        pub const WAIT_AGENT: &str = "wait_agent";
148        pub const RESUME_AGENT: &str = "resume_agent";
149        pub const CLOSE_AGENT: &str = "close_agent";
150        pub const ASK_SESSION: &str = "ask_session";
151        pub const ANSWER_SESSION: &str = "answer_session";
152        pub const LIST_SESSIONS: &str = "list_sessions";
153    }
154
155    /// Wire aliases emitted by transcript layers, not canonical tool names.
156    /// Dotted spellings are intentionally excluded from canonical-name shape
157    /// validation, but producers still reference them by constant.
158    pub mod aliases {
159        pub const BASH: &str = "bash";
160        pub const EXEC: &str = "exec";
161        pub const CONTAINER_EXEC: &str = "container.exec";
162        pub const REPO_BROWSER_LIST_FILES: &str = "repo_browser.list_files";
163        pub const REPO_BROWSER_READ_FILE: &str = "repo_browser.read_file";
164        pub const REPO_BROWSER_WRITE_FILE: &str = "repo_browser.write_file";
165    }
166
167    /// Wildcard (not a real tool name — exempt from the canonical-name shape).
168    pub const WILDCARD_ALL: &str = "*";
169
170    // Flat re-exports: every existing `tool_names::NAME` path keeps working.
171    pub use aliases::{
172        BASH as BASH_ALIAS, CONTAINER_EXEC as CONTAINER_EXEC_ALIAS, EXEC as EXEC_ALIAS, REPO_BROWSER_LIST_FILES,
173        REPO_BROWSER_READ_FILE, REPO_BROWSER_WRITE_FILE,
174    };
175    pub use control::{
176        AGENT, ASK_QUESTIONS, ASK_USER_QUESTION, CRON, CRON_CREATE, CRON_DELETE, CRON_LIST, MATRIX, MEMORY,
177        REQUEST_USER_INPUT,
178    };
179    pub use diagnostics::GET_ERRORS;
180    pub use dispatchers::{UNIFIED_EXEC, UNIFIED_FILE, UNIFIED_SEARCH};
181    pub use execution::{
182        CLOSE_PTY_SESSION, CREATE_PTY_SESSION, EXECUTE_CODE, LIST_PTY_SESSIONS, READ_PTY_SESSION, RESIZE_PTY_SESSION,
183        RUN_PTY_CMD, SEND_PTY_INPUT,
184    };
185    pub use files::{
186        COPY_FILE, CREATE_FILE, DELETE_FILE, EDIT_FILE, FILE_OP, MOVE_FILE, READ_FILE, SEARCH_REPLACE, WRITE_FILE,
187    };
188    pub use goal::{GET_GOAL, UPDATE_GOAL};
189    pub use ids::{
190        EXEC_PTY_CMD, FETCH, FETCH_URL, GREP, GREP_FILE, LIST, LIST_FILES, MCP, MCP_CONNECT_SERVER,
191        MCP_DISCONNECT_SERVER, MCP_GET_TOOL_DETAILS, MCP_LIST_SERVERS, MCP_SEARCH_TOOLS, SEARCH_TOOLS, SHELL, THINK,
192        WEB_FETCH, WEB_SEARCH,
193    };
194    pub use model_facing::{APPLY_PATCH, CODE_SEARCH, COMPUTER_USE, EXEC_COMMAND, RECORD_DECISION, WRITE_STDIN};
195    pub use planning::{START_PLANNING, TASK_TRACKER};
196    pub use skills::{LIST_SKILLS, LOAD_SKILL, LOAD_SKILL_RESOURCE};
197    pub use subagents::{
198        ANSWER_SESSION, ASK_SESSION, CLOSE_AGENT, LIST_SESSIONS, RESUME_AGENT, SEND_INPUT, SPAWN_AGENT,
199        SPAWN_BACKGROUND_SUBPROCESS, WAIT_AGENT,
200    };
201
202    /// Composable group slices for policy/catalog layers that operate on a
203    /// whole category rather than one name at a time.
204    pub mod groups {
205        use super::{
206            aliases, control, diagnostics, dispatchers, execution, files, goal, ids, model_facing, planning, skills,
207            subagents,
208        };
209        pub const MODEL_FACING: &[&str] = &[
210            model_facing::EXEC_COMMAND,
211            model_facing::WRITE_STDIN,
212            model_facing::APPLY_PATCH,
213            model_facing::RECORD_DECISION,
214            model_facing::CODE_SEARCH,
215            model_facing::COMPUTER_USE,
216        ];
217        pub const DISPATCHERS: &[&str] = &[
218            dispatchers::UNIFIED_SEARCH,
219            dispatchers::UNIFIED_EXEC,
220            dispatchers::UNIFIED_FILE,
221        ];
222        pub const EXECUTION: &[&str] = &[
223            execution::RUN_PTY_CMD,
224            execution::CREATE_PTY_SESSION,
225            execution::LIST_PTY_SESSIONS,
226            execution::CLOSE_PTY_SESSION,
227            execution::SEND_PTY_INPUT,
228            execution::READ_PTY_SESSION,
229            execution::RESIZE_PTY_SESSION,
230            execution::EXECUTE_CODE,
231        ];
232        pub const FILES: &[&str] = &[
233            files::READ_FILE,
234            files::WRITE_FILE,
235            files::EDIT_FILE,
236            files::DELETE_FILE,
237            files::CREATE_FILE,
238            files::SEARCH_REPLACE,
239            files::FILE_OP,
240            files::MOVE_FILE,
241            files::COPY_FILE,
242        ];
243        pub const CONTROL: &[&str] = &[
244            control::REQUEST_USER_INPUT,
245            control::MEMORY,
246            control::ASK_QUESTIONS,
247            control::ASK_USER_QUESTION,
248            control::MATRIX,
249            control::AGENT,
250            control::CRON,
251            control::CRON_CREATE,
252            control::CRON_LIST,
253            control::CRON_DELETE,
254        ];
255        pub const PLANNING: &[&str] = &[planning::START_PLANNING, planning::TASK_TRACKER];
256        pub const SUBAGENTS: &[&str] = &[
257            subagents::SPAWN_AGENT,
258            subagents::SPAWN_BACKGROUND_SUBPROCESS,
259            subagents::SEND_INPUT,
260            subagents::WAIT_AGENT,
261            subagents::RESUME_AGENT,
262            subagents::CLOSE_AGENT,
263            subagents::ASK_SESSION,
264            subagents::ANSWER_SESSION,
265            subagents::LIST_SESSIONS,
266        ];
267        pub const SKILLS: &[&str] = &[skills::LIST_SKILLS, skills::LOAD_SKILL, skills::LOAD_SKILL_RESOURCE];
268        pub const GOAL: &[&str] = &[goal::GET_GOAL, goal::UPDATE_GOAL];
269        pub const DIAGNOSTICS: &[&str] = &[diagnostics::GET_ERRORS];
270        pub const IDS: &[&str] = &[
271            ids::THINK,
272            ids::SEARCH_TOOLS,
273            ids::MCP,
274            ids::MCP_SEARCH_TOOLS,
275            ids::MCP_GET_TOOL_DETAILS,
276            ids::MCP_LIST_SERVERS,
277            ids::MCP_CONNECT_SERVER,
278            ids::MCP_DISCONNECT_SERVER,
279            ids::WEB_SEARCH,
280            ids::WEB_FETCH,
281            ids::FETCH_URL,
282            ids::LIST,
283            ids::GREP,
284            ids::FETCH,
285            ids::EXEC_PTY_CMD,
286            ids::SHELL,
287            ids::GREP_FILE,
288            ids::LIST_FILES,
289        ];
290        /// Wire aliases (dotted spellings included) — not canonical tool names.
291        pub const ALIASES: &[&str] = &[
292            aliases::BASH,
293            aliases::EXEC,
294            aliases::CONTAINER_EXEC,
295            aliases::REPO_BROWSER_LIST_FILES,
296            aliases::REPO_BROWSER_READ_FILE,
297            aliases::REPO_BROWSER_WRITE_FILE,
298        ];
299    }
300}
301
302/// Use direct tool name without alias resolution.
303/// Alias resolution is now handled by the tool registry inventory
304/// which maintains a mapping of aliases to canonical tool names.
305pub const fn canonical_tool_name(name: &str) -> &str {
306    name
307}
308
309// ---------------------------------------------------------------------------
310// Operational constants shared across subsystems
311// ---------------------------------------------------------------------------
312
313/// Standard error patterns used for error detection across tools
314pub const ERROR_DETECTION_PATTERNS: &[&str] = &[
315    "error",
316    "failed",
317    "exception",
318    "permission denied",
319    "not found",
320    "no such file",
321    "cannot",
322    "could not",
323    "panic",
324    "crash",
325    "unhandled",
326    "fatal",
327    "timeout",
328    "connection refused",
329    "access denied",
330    "stack trace",
331    "traceback",
332    "abort",
333    "terminate",
334];
335
336/// Network-related error patterns for more specific error detection
337pub const NETWORK_ERROR_PATTERNS: &[&str] = &["connection", "timeout", "network", "http", "ssl", "tls", "dns", "proxy"];
338
339/// Default capacity hints for common collections
340pub const DEFAULT_VEC_CAPACITY: usize = 32;
341pub const DEFAULT_HASHMAP_CAPACITY: usize = 16;
342pub const DEFAULT_STRING_CAPACITY: usize = 256;
343
344/// Context optimization constants following AGENTS.md guidelines
345pub const MAX_SEARCH_RESULTS: usize = 5;
346pub const MAX_LIST_ITEMS_SUMMARY: usize = 5;
347pub const OVERFLOW_INDICATOR_PREFIX: &str = "[+]";
348pub const OVERFLOW_INDICATOR_SUFFIX: &str = "more items]";
349
350/// Common tool operation limits
351pub const MAX_FILE_SIZE_FOR_PROCESSING: usize = 100 * 1024 * 1024; // 100MB
352pub const MAX_CONTEXT_LINES: usize = 20;
353pub const MAX_OUTPUT_TOKENS: usize = 4000;
354
355/// Reusable empty JSON object schema `{"type": "object"}` for tool parameter definitions.
356/// Used by tools that accept no parameters or only optional parameters.
357pub fn empty_object_schema() -> Value {
358    serde_json::json!({"type": "object"})
359}
360
361// ---------------------------------------------------------------------------
362// Tool result metadata types
363// ---------------------------------------------------------------------------
364
365use hashbrown::HashMap;
366use serde::{Deserialize, Serialize};
367use serde_json::Value;
368use std::fmt;
369use std::time::SystemTime;
370
371/// Result completeness level
372#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
373pub enum ResultCompleteness {
374    /// Full result with no truncation
375    Complete,
376    /// Partial result (more data exists but not shown)
377    Partial,
378    /// Result truncated due to size limits
379    Truncated,
380    /// Empty result (no matches)
381    Empty,
382}
383
384impl ResultCompleteness {
385    /// Deprecated: prefer using the `Display` impl; `ToString` is derived from Display.
386    fn to_static_str(self) -> &'static str {
387        match self {
388            Self::Complete => "complete",
389            Self::Partial => "partial",
390            Self::Truncated => "truncated",
391            Self::Empty => "empty",
392        }
393    }
394}
395
396impl fmt::Display for ResultCompleteness {
397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398        f.write_str(self.to_static_str())
399    }
400}
401
402/// Quality metadata for tool results
403#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct ResultMetadata {
405    /// Confidence that result is correct (0.0-1.0)
406    #[serde(default = "default_confidence")]
407    pub confidence: f32,
408
409    /// Relevance to current task (0.0-1.0)
410    #[serde(default = "default_relevance")]
411    pub relevance: f32,
412
413    /// Result completeness level
414    pub completeness: ResultCompleteness,
415
416    /// Count of matches/results
417    #[serde(default)]
418    pub result_count: usize,
419
420    /// Likelihood of false positives (0.0-1.0)
421    #[serde(default)]
422    pub false_positive_likelihood: f32,
423
424    /// Detected content types (code, docs, config, binary, etc.)
425    #[serde(default)]
426    pub content_types: Vec<String>,
427
428    /// Tool-specific metrics (lines matched, execution time, etc.)
429    #[serde(default)]
430    pub tool_metrics: HashMap<String, Value>,
431}
432
433fn default_confidence() -> f32 {
434    0.5
435}
436
437fn default_relevance() -> f32 {
438    0.5
439}
440
441impl Default for ResultMetadata {
442    fn default() -> Self {
443        Self {
444            confidence: 0.5,
445            relevance: 0.5,
446            completeness: ResultCompleteness::Complete,
447            result_count: 0,
448            false_positive_likelihood: 0.1,
449            content_types: vec![],
450            tool_metrics: HashMap::new(),
451        }
452    }
453}
454
455impl ResultMetadata {
456    /// Overall quality score (0.0-1.0)
457    #[inline]
458    pub fn quality_score(&self) -> f32 {
459        let weighted = (self.confidence * 0.4) + (self.relevance * 0.4) + (self.false_positive_likelihood * -0.2);
460        weighted.clamp(0.0, 1.0)
461    }
462
463    /// Create metadata for a successful tool execution
464    #[inline]
465    pub fn success(confidence: f32, relevance: f32) -> Self {
466        Self {
467            confidence: confidence.clamp(0.0, 1.0),
468            relevance: relevance.clamp(0.0, 1.0),
469            completeness: ResultCompleteness::Complete,
470            result_count: 1,
471            false_positive_likelihood: 0.05,
472            ..Default::default()
473        }
474    }
475
476    /// Create metadata for empty results
477    #[inline]
478    pub fn empty() -> Self {
479        Self {
480            completeness: ResultCompleteness::Empty,
481            result_count: 0,
482            confidence: 1.0, // High confidence in "no results"
483            ..Default::default()
484        }
485    }
486
487    /// Create metadata for error/inconclusive results
488    pub fn error() -> Self {
489        Self {
490            confidence: 0.2,
491            completeness: ResultCompleteness::Empty,
492            ..Default::default()
493        }
494    }
495
496    /// Merge with another metadata (for combining results)
497    pub fn merge(&mut self, other: &ResultMetadata) {
498        self.result_count += other.result_count;
499        self.confidence = (self.confidence + other.confidence) / 2.0;
500        self.relevance = (self.relevance + other.relevance) / 2.0;
501
502        // Merge content types
503        for ct in &other.content_types {
504            if !self.content_types.contains(ct) {
505                self.content_types.push(ct.clone());
506            }
507        }
508
509        // Merge tool metrics - use extend to avoid double clone
510        self.tool_metrics
511            .extend(other.tool_metrics.iter().map(|(k, v)| (k.clone(), v.clone())));
512    }
513}
514
515/// Enhanced tool result with metadata
516#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct EnhancedToolResult {
518    /// The actual tool result
519    value: Value,
520
521    /// Quality metadata
522    pub metadata: ResultMetadata,
523
524    /// When result was produced
525    timestamp: u64,
526
527    /// Tool name that produced this
528    tool_name: CompactStr,
529
530    /// Whether this was from cache
531    #[serde(default)]
532    from_cache: bool,
533}
534
535impl EnhancedToolResult {
536    pub fn new(value: Value, metadata: ResultMetadata, tool_name: impl Into<CompactStr>) -> Self {
537        Self {
538            value,
539            metadata,
540            timestamp: SystemTime::now()
541                .duration_since(SystemTime::UNIX_EPOCH)
542                .unwrap_or_default()
543                .as_secs(),
544            tool_name: tool_name.into(),
545            from_cache: false,
546        }
547    }
548
549    pub fn from_cache(value: Value, metadata: ResultMetadata, tool_name: impl Into<CompactStr>) -> Self {
550        Self {
551            value,
552            metadata,
553            timestamp: SystemTime::now()
554                .duration_since(SystemTime::UNIX_EPOCH)
555                .unwrap_or_default()
556                .as_secs(),
557            tool_name: tool_name.into(),
558            from_cache: true,
559        }
560    }
561
562    /// Whether this result is useful enough to include
563    #[inline]
564    pub fn is_useful(&self) -> bool {
565        self.metadata.quality_score() > 0.3
566    }
567
568    /// Whether this result is high quality
569    #[inline]
570    pub fn is_high_quality(&self) -> bool {
571        self.metadata.quality_score() > 0.7
572    }
573
574    /// Convert to a message-friendly format
575    #[allow(
576        clippy::cast_sign_loss,
577        reason = "Intentional compatibility, platform, or test-only suppression."
578    )] // quality_score is always 0.0-1.0
579    pub fn to_summary(&self) -> String {
580        let quality = ((self.metadata.quality_score() * 100.0).round().max(0.0) as u32).min(100);
581        match self.metadata.completeness {
582            ResultCompleteness::Complete => {
583                format!("{} found {} results (confidence: {}%)", self.tool_name, self.metadata.result_count, quality)
584            }
585            ResultCompleteness::Partial => {
586                format!(
587                    "{} found {} results (truncated, confidence: {}%)",
588                    self.tool_name, self.metadata.result_count, quality
589                )
590            }
591            ResultCompleteness::Empty => {
592                format!("{} found no results", self.tool_name)
593            }
594            ResultCompleteness::Truncated => {
595                format!("{} found results (truncated due to size, confidence: {}%)", self.tool_name, quality)
596            }
597        }
598    }
599}
600
601/// Trait for scoring tool results
602pub trait ResultScorer {
603    /// Score a tool result and return metadata
604    fn score(&self, result: &Value) -> ResultMetadata;
605
606    /// Tool name this scorer handles
607    fn tool_name(&self) -> &str;
608}
609
610#[cfg(test)]
611mod tool_names_tests;