Skip to main content

vtcode_core/tool_policy/
model.rs

1use anyhow::Result;
2use indexmap::{IndexMap, IndexSet};
3use serde::{Deserialize, Serialize};
4
5use super::{McpPolicyStore, ToolPolicy};
6
7/// Decision result for tool execution
8#[derive(Debug, Clone, PartialEq)]
9#[must_use = "tool execution decisions must be enforced"]
10pub enum ToolExecutionDecision {
11    /// The tool is allowed to execute.
12    Allowed,
13    /// The tool execution is denied.
14    Denied,
15    /// The tool execution is denied with a feedback message.
16    DeniedWithFeedback(String),
17}
18
19impl ToolExecutionDecision {
20    #[must_use]
21    pub fn is_allowed(&self) -> bool {
22        matches!(self, Self::Allowed)
23    }
24}
25
26/// Tool policy configuration stored in the canonical user config directory.
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct ToolPolicyConfig {
29    /// Configuration version for future compatibility
30    pub version: u32,
31    /// Available tools at time of last update
32    pub available_tools: Vec<String>,
33    /// Policy for each tool
34    pub policies: IndexMap<String, ToolPolicy>,
35    /// Optional per-tool constraints to scope permissions and enforce safety
36    #[serde(default)]
37    pub constraints: IndexMap<String, ToolConstraints>,
38    /// MCP-specific policy configuration
39    #[serde(default)]
40    pub mcp: McpPolicyStore,
41    /// Explicit remembered approvals for future prompts in this workspace
42    #[serde(default)]
43    pub approval_cache: ApprovalCacheConfig,
44}
45
46impl Default for ToolPolicyConfig {
47    fn default() -> Self {
48        Self {
49            version: 1,
50            available_tools: Vec::new(),
51            policies: IndexMap::new(),
52            constraints: IndexMap::new(),
53            mcp: McpPolicyStore::default(),
54            approval_cache: ApprovalCacheConfig::default(),
55        }
56    }
57}
58
59/// Persisted approval cache stored alongside tool policies
60#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
61pub struct ApprovalCacheConfig {
62    /// Stable approval keys that should bypass future prompts
63    #[serde(default)]
64    pub allowed: IndexSet<String>,
65    /// Shell command prefixes that should bypass future prompts in the same scope
66    #[serde(default)]
67    pub prefixes: IndexSet<String>,
68    /// Regex patterns matched against approval keys for advanced manual policy tuning
69    #[serde(default)]
70    pub regexes: IndexSet<String>,
71}
72
73/// Maximum remembered approval entries per cache collection. Unbounded growth
74/// turned `tool-policy.json` into a multi-hundred-kilobyte file after a few
75/// long sessions (see session-vtcode-20260925T234343Z: 294 KB). Oldest
76/// insertions are dropped first so recent approvals survive.
77pub const APPROVAL_CACHE_MAX_ENTRIES: usize = 256;
78
79impl ApprovalCacheConfig {
80    /// Drop the oldest entries so each collection stays within
81    /// [`APPROVAL_CACHE_MAX_ENTRIES`]. Returns `true` when anything was trimmed.
82    pub fn trim_to_budget(&mut self) -> bool {
83        let mut trimmed = false;
84        for collection in [&mut self.allowed, &mut self.prefixes, &mut self.regexes] {
85            while collection.len() > APPROVAL_CACHE_MAX_ENTRIES {
86                let _ = collection.shift_remove_index(0);
87                trimmed = true;
88            }
89        }
90        trimmed
91    }
92}
93
94/// Handler for tool permission prompts
95///
96/// This trait allows different UI modes (CLI, TUI) to provide their own
97/// implementation for prompting users about tool execution.
98pub trait PermissionPromptHandler: Send + Sync {
99    /// Prompt the user for tool execution permission
100    fn prompt_tool_permission(&mut self, tool_name: &str) -> Result<ToolExecutionDecision>;
101}
102
103/// Scoped, optional constraints for a tool to align with safe defaults
104#[derive(Debug, Clone, Default, Serialize, Deserialize)]
105pub struct ToolConstraints {
106    /// Whitelisted modes for tools that support modes (e.g., 'terminal')
107    #[serde(default)]
108    pub allowed_modes: Option<Vec<String>>,
109    /// Cap on results for list/search-like tools
110    #[serde(default)]
111    pub max_results_per_call: Option<usize>,
112    /// Cap on items scanned for file listing
113    #[serde(default)]
114    pub max_items_per_call: Option<usize>,
115    /// Default response format if unspecified by caller
116    #[serde(default)]
117    pub default_response_format: Option<String>,
118    /// Cap maximum bytes when reading files
119    #[serde(default)]
120    pub max_bytes_per_read: Option<usize>,
121    /// Cap maximum bytes when fetching over the network
122    #[serde(default)]
123    pub max_response_bytes: Option<usize>,
124    /// Allowed URL schemes for network tools
125    #[serde(default)]
126    pub allowed_url_schemes: Option<Vec<String>>,
127    /// Denied URL hosts or suffixes for network tools
128    #[serde(default)]
129    pub denied_url_hosts: Option<Vec<String>>,
130}