vtcode-core 0.104.1

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use rustc_hash::FxHashSet;
use std::path::Path;

use anyhow::{Result, anyhow};
use serde_json::{Value, json};

use crate::config::constants::tools;
use crate::config::mcp::McpAllowListConfig;
use crate::tool_policy::{ToolExecutionDecision, ToolPolicy, ToolPolicyManager};
use crate::tools::names::canonical_tool_name;
use crate::tools::tool_intent::{unified_file_action_is, unified_search_action_is};

use super::ToolPermissionDecision;
use super::risk_scorer::{RiskLevel, ToolRiskContext, ToolRiskScorer, ToolSource, WorkspaceTrust};

#[derive(Clone, Default)]
pub(super) struct ToolPolicyGateway {
    tool_policy: Option<ToolPolicyManager>,
    preapproved_tools: FxHashSet<String>,
    full_auto_allowlist: Option<FxHashSet<String>>,
    enforce_safe_mode_prompts: bool,
}

impl ToolPolicyGateway {
    pub async fn new(workspace_root: &Path) -> Self {
        let tool_policy = match ToolPolicyManager::new_with_workspace(workspace_root).await {
            Ok(manager) => Some(manager),
            Err(err) => {
                tracing::warn!(%err, "Failed to initialize tool policy manager");
                None
            }
        };

        Self {
            tool_policy,
            preapproved_tools: FxHashSet::default(),
            full_auto_allowlist: None,
            enforce_safe_mode_prompts: false,
        }
    }

    pub fn with_policy_manager(manager: ToolPolicyManager) -> Self {
        Self {
            tool_policy: Some(manager),
            preapproved_tools: FxHashSet::default(),
            full_auto_allowlist: None,
            enforce_safe_mode_prompts: false,
        }
    }

    pub fn set_enforce_safe_mode_prompts(&mut self, enabled: bool) {
        self.enforce_safe_mode_prompts = enabled;
    }

    fn requires_safe_mode_prompt(&self, safe_mode_prompt: bool) -> bool {
        self.enforce_safe_mode_prompts && safe_mode_prompt
    }

    pub fn has_policy_manager(&self) -> bool {
        self.tool_policy.is_some()
    }

    pub async fn sync_available_tools(&mut self, mut available: Vec<String>, mcp_keys: &[String]) {
        available.extend(mcp_keys.iter().cloned());
        available.sort();
        available.dedup();

        if let Some(ref mut policy) = self.tool_policy
            && let Err(err) = policy.update_available_tools(available).await
        {
            tracing::warn!(%err, "Failed to update tool policies");
        }
    }

    pub fn apply_policy_constraints(&self, name: &str, args: &Value) -> Result<Value> {
        let mut args = args.clone();
        let canonical = canonical_tool_name(name);
        let normalized = canonical.as_ref();
        let unified_file_read =
            normalized == tools::UNIFIED_FILE && unified_file_action_is(&args, "read");
        let unified_search_list =
            normalized == tools::UNIFIED_SEARCH && unified_search_action_is(&args, "list");
        let unified_search_grep =
            normalized == tools::UNIFIED_SEARCH && unified_search_action_is(&args, "grep");

        if let Some(constraints) = self
            .tool_policy
            .as_ref()
            .and_then(|tp| tp.get_constraints(normalized))
            .cloned()
        {
            let obj = args
                .as_object_mut()
                .ok_or_else(|| anyhow!("Error: tool arguments must be an object"))?;

            if let Some(fmt) = constraints.default_response_format {
                obj.entry("response_format").or_insert(json!(fmt));
            }

            if let Some(allowed) = constraints.allowed_modes
                && let Some(mode) = obj.get("mode").and_then(|v| v.as_str())
                && !allowed.iter().any(|m| m == mode)
            {
                return Err(anyhow!(
                    "Mode '{}' not allowed by policy for '{}'. Allowed: {}",
                    mode,
                    normalized,
                    allowed.join(", ")
                ));
            }

            match normalized {
                n if n == tools::UNIFIED_SEARCH && unified_search_list => {
                    if let Some(cap) = constraints.max_items_per_call {
                        let requested = obj
                            .get("max_items")
                            .and_then(|v| v.as_u64())
                            .unwrap_or(cap as u64) as usize;
                        if requested > cap {
                            obj.insert("max_items".to_string(), json!(cap));
                            obj.insert(
                                "_policy_note".to_string(),
                                json!(format!("Capped max_items to {} by policy", cap)),
                            );
                        }
                    }
                }
                n if n == tools::UNIFIED_SEARCH && unified_search_grep => {
                    if let Some(cap) = constraints.max_results_per_call {
                        let requested = obj
                            .get("max_results")
                            .and_then(|v| v.as_u64())
                            .unwrap_or(cap as u64) as usize;
                        if requested > cap {
                            obj.insert("max_results".to_string(), json!(cap));
                            obj.insert(
                                "_policy_note".to_string(),
                                json!(format!("Capped max_results to {} by policy", cap)),
                            );
                        }
                    }
                }
                n if n == tools::READ_FILE || unified_file_read => {
                    if let Some(cap) = constraints.max_bytes_per_read {
                        let requested = obj
                            .get("max_bytes")
                            .and_then(|v| v.as_u64())
                            .unwrap_or(cap as u64) as usize;
                        if requested > cap {
                            obj.insert("max_bytes".to_string(), json!(cap));
                            obj.insert(
                                "_policy_note".to_string(),
                                json!(format!("Capped max_bytes to {} by policy", cap)),
                            );
                        }
                    }
                }

                _ => {}
            }
        }

        Ok(args)
    }

    pub fn policy_manager_mut(&mut self) -> Result<&mut ToolPolicyManager> {
        self.tool_policy
            .as_mut()
            .ok_or_else(|| anyhow!("Tool policy manager not available"))
    }

    pub fn set_policy_manager(&mut self, manager: ToolPolicyManager) {
        self.tool_policy = Some(manager);
    }

    pub async fn set_tool_policy(&mut self, tool_name: &str, policy: ToolPolicy) -> Result<()> {
        let canonical = canonical_tool_name(tool_name);
        if let Some(ref mut manager) = self.tool_policy {
            manager.set_policy(canonical.as_ref(), policy).await
        } else {
            Err(anyhow::anyhow!("Tool policy manager not initialized"))
        }
    }

    pub async fn add_approval_cache_key(&mut self, approval_key: &str) -> Result<()> {
        if let Some(ref mut manager) = self.tool_policy {
            manager.add_approval_cache_key(approval_key).await
        } else {
            Err(anyhow::anyhow!("Tool policy manager not initialized"))
        }
    }

    pub async fn add_approval_cache_prefix(&mut self, prefix_entry: &str) -> Result<()> {
        if let Some(ref mut manager) = self.tool_policy {
            manager.add_approval_cache_prefix(prefix_entry).await
        } else {
            Err(anyhow::anyhow!("Tool policy manager not initialized"))
        }
    }

    pub fn has_approval_cache_key(&self, approval_key: &str) -> bool {
        self.tool_policy
            .as_ref()
            .is_some_and(|manager| manager.has_approval_cache_key(approval_key))
    }

    pub fn matching_shell_approval_prefix(
        &self,
        command_words: &[String],
        scope_signature: &str,
    ) -> Option<String> {
        self.tool_policy.as_ref().and_then(|manager| {
            manager.matching_shell_approval_prefix(command_words, scope_signature)
        })
    }

    pub fn get_tool_policy(&self, tool_name: &str) -> ToolPolicy {
        let canonical = canonical_tool_name(tool_name);
        self.tool_policy
            .as_ref()
            .map(|tp| tp.get_policy(canonical.as_ref()))
            .unwrap_or(ToolPolicy::Allow)
    }

    pub async fn reset_tool_policies(&mut self) -> Result<()> {
        if let Some(tp) = self.tool_policy.as_mut() {
            tp.reset_all_to_prompt().await
        } else {
            Err(anyhow!("Tool policy manager not available"))
        }
    }

    pub async fn allow_all_tools(&mut self) -> Result<()> {
        if let Some(tp) = self.tool_policy.as_mut() {
            tp.allow_all_tools().await
        } else {
            Err(anyhow!("Tool policy manager not available"))
        }
    }

    pub async fn deny_all_tools(&mut self) -> Result<()> {
        if let Some(tp) = self.tool_policy.as_mut() {
            tp.deny_all_tools().await
        } else {
            Err(anyhow!("Tool policy manager not available"))
        }
    }

    pub fn print_policy_status(&self) {
        if let Some(tp) = self.tool_policy.as_ref() {
            tp.print_status();
        } else {
            tracing::warn!("Tool policy manager not available");
        }
    }

    pub fn enable_full_auto_mode(&mut self, allowed_tools: &[String], available_tools: &[String]) {
        let mut normalized: FxHashSet<String> = FxHashSet::default();
        if allowed_tools
            .iter()
            .any(|tool| tool.trim() == tools::WILDCARD_ALL)
        {
            for tool in available_tools {
                let canonical = canonical_tool_name(tool);
                normalized.insert(canonical.into_owned());
            }
        } else {
            for tool in allowed_tools {
                let trimmed = tool.trim();
                if !trimmed.is_empty() {
                    let canonical = canonical_tool_name(trimmed);
                    normalized.insert(canonical.into_owned());
                }
            }
        }

        self.full_auto_allowlist = Some(normalized);
    }

    pub fn disable_full_auto_mode(&mut self) {
        self.full_auto_allowlist = None;
    }

    pub fn current_full_auto_allowlist(&self) -> Option<Vec<String>> {
        self.full_auto_allowlist.as_ref().map(|set| {
            let mut items: Vec<String> = set.iter().cloned().collect();
            items.sort();
            items
        })
    }

    pub fn is_allowed_in_full_auto(&self, name: &str) -> bool {
        let canonical = canonical_tool_name(name);
        self.full_auto_allowlist
            .as_ref()
            .map(|allowlist| allowlist.contains(&*canonical))
            .unwrap_or(true)
    }

    pub fn has_full_auto_allowlist(&self) -> bool {
        self.full_auto_allowlist.is_some()
    }

    pub async fn evaluate_tool_policy(
        &mut self,
        name: &str,
        safe_mode_prompt: bool,
        default_permission: ToolPolicy,
    ) -> Result<ToolPermissionDecision> {
        let canonical = canonical_tool_name(name);
        let normalized = canonical.as_ref();

        // In safe mode (tools_policy), high-risk tools always require a prompt
        // regardless of persisted policy
        if self.requires_safe_mode_prompt(safe_mode_prompt) {
            tracing::debug!(
                "Tool '{}' requires prompt in safe mode (tools_policy)",
                normalized
            );
            return Ok(ToolPermissionDecision::Prompt);
        }

        if let Some(allowlist) = self.full_auto_allowlist.as_ref() {
            if !allowlist.contains(normalized) {
                return Ok(ToolPermissionDecision::Deny);
            }

            if let Some(policy_manager) = self.tool_policy.as_mut() {
                match policy_manager.get_policy(normalized) {
                    ToolPolicy::Deny => return Ok(ToolPermissionDecision::Deny),
                    ToolPolicy::Allow => {
                        self.preapproved_tools.insert(normalized.to_string());
                        return Ok(ToolPermissionDecision::Allow);
                    }
                    ToolPolicy::Prompt => {
                        // Always prompt for explicit "prompt" policy, even in full-auto mode
                        // This ensures human-in-the-loop approval for sensitive operations
                        return Ok(ToolPermissionDecision::Prompt);
                    }
                }
            }

            self.preapproved_tools.insert(normalized.to_string());
            return Ok(ToolPermissionDecision::Allow);
        }

        if let Some(policy_manager) = self.tool_policy.as_mut() {
            match policy_manager.get_policy(normalized) {
                ToolPolicy::Allow => {
                    self.preapproved_tools.insert(normalized.to_string());
                    Ok(ToolPermissionDecision::Allow)
                }
                ToolPolicy::Deny => Ok(ToolPermissionDecision::Deny),
                ToolPolicy::Prompt => {
                    // Check if low-risk by using risk scorer
                    if Self::should_auto_approve_by_risk(normalized)
                        || ToolPolicyManager::is_auto_allow_tool(normalized)
                    {
                        policy_manager
                            .set_policy(normalized, ToolPolicy::Allow)
                            .await?;
                        self.preapproved_tools.insert(normalized.to_string());
                        Ok(ToolPermissionDecision::Allow)
                    } else {
                        Ok(ToolPermissionDecision::Prompt)
                    }
                }
            }
        } else {
            Ok(match default_permission {
                ToolPolicy::Allow => {
                    self.preapproved_tools.insert(normalized.to_string());
                    ToolPermissionDecision::Allow
                }
                ToolPolicy::Deny => ToolPermissionDecision::Deny,
                ToolPolicy::Prompt => ToolPermissionDecision::Prompt,
            })
        }
    }

    /// Determine if a tool should be auto-approved based on risk level
    /// Low-risk read-only tools are auto-approved to reduce approval friction
    fn should_auto_approve_by_risk(tool_name: &str) -> bool {
        let ctx = ToolRiskContext::new(
            tool_name.to_string(),
            ToolSource::Internal,
            WorkspaceTrust::Trusted,
        );
        let risk = ToolRiskScorer::calculate_risk(&ctx);
        // Auto-approve only low-risk tools
        matches!(risk, RiskLevel::Low)
    }

    pub fn take_preapproved(&mut self, name: &str) -> bool {
        let canonical = canonical_tool_name(name);
        let was_preapproved = self.preapproved_tools.remove(&*canonical);
        tracing::trace!(
            "take_preapproved: tool='{}', canonical='{}', was_preapproved={}, remaining={:?}",
            name,
            canonical,
            was_preapproved,
            self.preapproved_tools
        );
        was_preapproved
    }

    pub fn preapprove(&mut self, name: &str) {
        let canonical = canonical_tool_name(name);
        let canonical_owned = canonical.into_owned();
        self.preapproved_tools.insert(canonical_owned.clone());
        tracing::trace!(
            "preapprove: tool='{}', canonical='{}', preapproved_tools={:?}",
            name,
            canonical_owned,
            self.preapproved_tools
        );
    }

    pub async fn should_execute_tool(&mut self, name: &str) -> Result<ToolExecutionDecision> {
        let canonical = canonical_tool_name(name);
        if let Some(policy_manager) = self.tool_policy.as_mut() {
            policy_manager.should_execute_tool(canonical.as_ref()).await
        } else {
            Ok(ToolExecutionDecision::Allowed)
        }
    }

    pub async fn update_mcp_tools(
        &mut self,
        mcp_tool_index: &hashbrown::HashMap<String, Vec<String>>,
    ) -> Result<Option<McpAllowListConfig>> {
        if let Some(policy_manager) = self.tool_policy.as_mut() {
            policy_manager.update_mcp_tools(mcp_tool_index).await?;
            return Ok(Some(policy_manager.mcp_allowlist().clone()));
        }
        Ok(None)
    }

    pub async fn persist_mcp_tool_policy(
        &mut self,
        provider: &str,
        tool_name: &str,
        policy: ToolPolicy,
    ) -> Result<()> {
        if let Some(manager) = self.tool_policy.as_mut() {
            manager
                .set_mcp_tool_policy(provider, tool_name, policy)
                .await?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tool_policy::{ToolConstraints, ToolPolicyConfig};
    use indexmap::IndexMap;
    use serde_json::json;

    async fn gateway_with_constraints(
        tool_name: &str,
        constraints: ToolConstraints,
    ) -> ToolPolicyGateway {
        let temp = tempfile::tempdir().expect("temp workspace");
        let config_path = temp.path().join("tool-policy.json");
        let config = ToolPolicyConfig {
            constraints: IndexMap::from([(tool_name.to_string(), constraints)]),
            ..ToolPolicyConfig::default()
        };
        std::fs::write(
            &config_path,
            serde_json::to_vec_pretty(&config).expect("policy config json"),
        )
        .expect("policy config file");
        let manager = ToolPolicyManager::new_with_config_path(config_path)
            .await
            .expect("policy manager");
        ToolPolicyGateway::with_policy_manager(manager)
    }

    #[tokio::test]
    async fn apply_policy_constraints_caps_inferred_unified_search_list_calls() {
        let gateway = gateway_with_constraints(
            tools::UNIFIED_SEARCH,
            ToolConstraints {
                max_items_per_call: Some(10),
                ..ToolConstraints::default()
            },
        )
        .await;

        let constrained = gateway
            .apply_policy_constraints(
                tools::UNIFIED_SEARCH,
                &json!({
                    "path": ".",
                    "pattern": "*.rs",
                    "max_items": 25
                }),
            )
            .expect("constrained args");

        assert_eq!(constrained["max_items"], json!(10));
        assert_eq!(
            constrained["_policy_note"],
            json!("Capped max_items to 10 by policy")
        );
    }

    #[tokio::test]
    async fn apply_policy_constraints_caps_inferred_unified_search_grep_calls() {
        let gateway = gateway_with_constraints(
            tools::UNIFIED_SEARCH,
            ToolConstraints {
                max_results_per_call: Some(15),
                ..ToolConstraints::default()
            },
        )
        .await;

        let constrained = gateway
            .apply_policy_constraints(
                tools::UNIFIED_SEARCH,
                &json!({
                    "path": ".",
                    "pattern": "ToolRegistry",
                    "max_results": 50
                }),
            )
            .expect("constrained args");

        assert_eq!(constrained["max_results"], json!(15));
        assert_eq!(
            constrained["_policy_note"],
            json!("Capped max_results to 15 by policy")
        );
    }
}