vtcode-core 0.175.2

Core library for VT Code - a Rust-based terminal coding agent
Documentation
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
use super::AgentRunner;
use crate::config::constants::tools;
use crate::core::agent::harness_kernel::PreparedToolCall;
use crate::core::agent::session::AgentSessionState;
use crate::permissions::{
    ResolvedPermissionDecision, build_advertised_permission_requests, build_permission_request,
    evaluate_effective_permissions, evaluate_permissions,
};
use crate::primary_agent::primary_agent_allows_tool;
use crate::tools::file_ops::restore_exact_text_content;
use crate::tools::registry::{ExecutionPolicySnapshot, ToolErrorType, ToolExecutionError};
use crate::tools::{command_args, tool_intent};
use anyhow::{Result, bail};
use serde_json::Value;
use tracing::{info, warn};
use vtcode_commons::ErrorCategory;

pub(super) struct PreparedToolExecution {
    pub result: std::result::Result<Value, ToolExecutionError>,
    pub attempts: u32,
    pub total_duration: std::time::Duration,
    pub last_error_category: Option<ErrorCategory>,
}

fn restore_exact_file_read_output(mut output: Value) -> Value {
    let Some(obj) = output.as_object_mut() else {
        return output;
    };

    let is_text_file_read = obj
        .get("content_kind")
        .and_then(Value::as_str)
        .is_some_and(|value| value == "text")
        && obj.get("path").and_then(Value::as_str).is_some();
    if !is_text_file_read {
        return output;
    }

    let Some(content) = obj.get("content").and_then(Value::as_str) else {
        return output;
    };
    let Some(size_bytes) = obj
        .get("metadata")
        .and_then(|metadata| metadata.get("data"))
        .and_then(|data| data.get("size_bytes"))
        .and_then(Value::as_u64)
    else {
        return output;
    };

    if let Some(exact_content) = restore_exact_text_content(content, size_bytes) {
        obj.insert("content".to_string(), Value::String(exact_content));
    }

    output
}

impl AgentRunner {
    pub(super) async fn resolve_executable_tool_name(&self, tool_name: &str) -> Option<String> {
        let canonical_name = self.tool_registry.resolve_public_tool_name(tool_name).ok()?;

        self.is_tool_exposed(&canonical_name).await.then_some(canonical_name)
    }

    pub(super) fn admit_tool_call(
        &self,
        tool_name: &str,
        args: Value,
        session_state: &mut AgentSessionState,
    ) -> Result<PreparedToolCall> {
        let normalized_args = self.normalize_tool_args(tool_name, args, session_state);
        self.ensure_tool_call_permissions(tool_name, &normalized_args)?;
        self.tool_registry.admit_public_tool_call(tool_name, &normalized_args)
    }

    fn ensure_tool_call_permissions(&self, tool_name: &str, args: &Value) -> Result<()> {
        let normalized_tool_name = self
            .tool_registry
            .resolve_public_tool_name(tool_name)
            .unwrap_or_else(|_| tool_name.to_string());

        if let Some(active_primary_agent) = self.active_primary_agent.as_ref()
            && !primary_agent_allows_tool(active_primary_agent, &normalized_tool_name)
        {
            bail!(
                "Tool '{}' is not permitted by active primary agent '{}'",
                normalized_tool_name,
                active_primary_agent.identity.name
            );
        }

        let current_dir = std::env::current_dir().unwrap_or_else(|_| self._workspace.clone());
        let permission_request =
            build_permission_request(&self._workspace, &current_dir, &normalized_tool_name, Some(args));
        let denied = if let Some(active_primary_agent) = self.active_primary_agent.as_ref() {
            evaluate_effective_permissions(
                &self.config().permissions,
                &active_primary_agent.permissions,
                &self._workspace,
                &current_dir,
                &permission_request,
            ) == ResolvedPermissionDecision::Deny
        } else {
            evaluate_permissions(&self.config().permissions, &self._workspace, &current_dir, &permission_request).deny
        };

        if denied {
            if let Some(active_primary_agent) = self.active_primary_agent.as_ref() {
                bail!(
                    "Tool '{}' is denied by active primary agent '{}'",
                    normalized_tool_name,
                    active_primary_agent.identity.name
                );
            }
            bail!("Tool '{}' is denied by effective permissions", normalized_tool_name);
        }

        Ok(())
    }

    /// Scheduler-issued calls share runner permissions and registry admission.
    pub(crate) async fn execute_scheduled_tool(&self, tool_name: &str, args: Value) -> Result<Value> {
        self.ensure_tool_call_permissions(tool_name, &args)?;
        self.tool_registry.execute_tool(tool_name, args).await
    }

    /// Check if a tool is allowed for this agent
    async fn is_tool_allowed(&self, tool_name: &str) -> bool {
        if self.local_tools_only
            && self.tool_registry.tool_network_access(tool_name) != crate::tools::registry::ToolNetworkAccess::Local
        {
            return false;
        }
        let policy = self.tool_registry.get_tool_policy(tool_name).await;
        matches!(policy, crate::tool_policy::ToolPolicy::Allow | crate::tool_policy::ToolPolicy::Prompt)
    }

    /// Check if a tool is exposed to the active runtime after feature gating.
    pub(super) async fn is_tool_exposed(&self, tool_name: &str) -> bool {
        if !self
            .features()
            .allows_tool_name(tool_name, self.tool_registry.is_planning_active(), false)
        {
            return false;
        }

        self.is_tool_permitted_for_advertisement(tool_name).await
    }

    /// Check policy and permission gates without applying runtime mode filtering.
    pub(super) async fn is_tool_permitted_for_advertisement(&self, tool_name: &str) -> bool {
        if let Some(active_primary_agent) = self.active_primary_agent.as_ref()
            && !primary_agent_allows_tool(active_primary_agent, tool_name)
        {
            return false;
        }

        let current_dir = std::env::current_dir().unwrap_or_else(|_| self._workspace.clone());
        if tool_name == tools::EXEC_COMMAND {
            let bash_probe_args = serde_json::json!({ "cmd": "true" });
            let bash_probe =
                build_permission_request(&self._workspace, &current_dir, tool_name, Some(&bash_probe_args));
            if evaluate_permissions(&self.config().permissions, &self._workspace, &current_dir, &bash_probe).deny {
                return false;
            }
            if let Some(active_primary_agent) = self.active_primary_agent.as_ref()
                && evaluate_effective_permissions(
                    &self.config().permissions,
                    &active_primary_agent.permissions,
                    &self._workspace,
                    &current_dir,
                    &bash_probe,
                ) == ResolvedPermissionDecision::Deny
            {
                return false;
            }
        }
        let advertised_requests = if tool_name == tools::EXEC_COMMAND {
            Vec::new()
        } else {
            build_advertised_permission_requests(&self._workspace, &current_dir, tool_name)
        };
        if advertised_requests.iter().any(|request| {
            evaluate_permissions(&self.config().permissions, &self._workspace, &current_dir, request).deny
        }) {
            return false;
        }

        if let Some(active_primary_agent) = self.active_primary_agent.as_ref() {
            let permission_denied = advertised_requests.iter().any(|permission_request| {
                evaluate_effective_permissions(
                    &self.config().permissions,
                    &active_primary_agent.permissions,
                    &self._workspace,
                    &current_dir,
                    permission_request,
                ) == ResolvedPermissionDecision::Deny
            });
            if permission_denied {
                return false;
            }
        }

        if self.tool_registry.is_denied_in_full_auto(tool_name).await {
            return false;
        }

        self.is_tool_allowed(tool_name).await
    }

    /// Validate if a tool name is safe, registered, and allowed by policy
    #[inline]
    pub(super) async fn is_valid_tool(&self, tool_name: &str) -> bool {
        self.resolve_executable_tool_name(tool_name).await.is_some()
    }

    /// Execute a prepared tool call and retain its one canonical terminal
    /// result together with retry and timing metadata.
    pub(super) async fn execute_prepared_tool_internal(&self, prepared: &PreparedToolCall) -> PreparedToolExecution {
        let execution_started_at = std::time::Instant::now();
        let resolved_tool_name = prepared.canonical_name.as_str();
        let args = &prepared.effective_args;
        let shell_command = if tool_intent::is_command_run_tool_call(resolved_tool_name, args)
            || (resolved_tool_name == tools::UNIFIED_EXEC && tool_intent::command_session_action(args).is_none())
        {
            command_args::command_text(args).ok().flatten()
        } else {
            None
        };

        // Enforce per-agent shell policies for shell-executed commands.
        if let Some(cmd_text) = shell_command {
            let cfg = self.config();

            let agent_prefix = format!("VTCODE_{}_COMMANDS_", self.agent_type.to_string().to_uppercase());

            let deny_regex_patterns = crate::utils::merge_env_patterns(
                &cfg.commands.deny_regex,
                &format!("{}{}", agent_prefix, "DENY_REGEX"),
            );
            let deny_glob_patterns =
                crate::utils::merge_env_patterns(&cfg.commands.deny_glob, &format!("{}{}", agent_prefix, "DENY_GLOB"));

            if let Err(error) = self
                .tool_registry
                .check_shell_policy(&cmd_text, &deny_regex_patterns, &deny_glob_patterns)
                .map_err(|err| {
                    ToolExecutionError::policy_violation(
                        resolved_tool_name.to_string(),
                        format!("tool denied by policy: {err}"),
                    )
                    .with_surface("agent_runner")
                })
            {
                return PreparedToolExecution {
                    attempts: 1,
                    total_duration: execution_started_at.elapsed(),
                    last_error_category: Some(error.category),
                    result: Err(error),
                };
            }

            info!(target = "policy", agent = ?self.agent_type, tool = resolved_tool_name, cmd = %cmd_text, "shell_policy_checked");
        }

        let mut policy = ExecutionPolicySnapshot::default()
            .with_prevalidated(prepared.already_preflighted)
            .with_max_retries(self.config().agent.harness.max_tool_retries as usize);
        policy.retry_jitter = 0.15;

        // Enforce the harness tool wall-clock budget per call. This is the
        // single chokepoint for both parallel and sequential batch paths. On
        // elapsed, surface a `Timeout` error so the call flows through the
        // existing retry/fallback handling — no new state type is introduced.
        // `0` disables the bound and preserves the previous unbounded behaviour.
        let wall_clock_secs = self.config().agent.harness.max_tool_wall_clock_secs;
        let outcome = if wall_clock_secs > 0 {
            let budget = std::time::Duration::from_secs(wall_clock_secs);
            match tokio::time::timeout(
                budget,
                self.tool_registry.execute_prepared_public_tool_request(prepared, policy),
            )
            .await
            {
                Ok(outcome) => outcome,
                Err(_elapsed) => {
                    warn!(
                        agent = ?self.agent_type,
                        tool = resolved_tool_name,
                        budget_secs = wall_clock_secs,
                        "tool execution exceeded the harness wall-clock budget; aborting"
                    );
                    let error = ToolExecutionError::new(
                        resolved_tool_name.to_string(),
                        ToolErrorType::Timeout,
                        format!("tool execution exceeded the harness wall-clock budget of {wall_clock_secs}s"),
                    )
                    .with_surface("agent_runner");
                    return PreparedToolExecution {
                        attempts: 1,
                        total_duration: execution_started_at.elapsed(),
                        last_error_category: Some(error.category),
                        result: Err(error),
                    };
                }
            }
        } else {
            self.tool_registry.execute_prepared_public_tool_request(prepared, policy).await
        };
        let result = match (outcome.output, outcome.error) {
            (Some(output), None) => Ok(restore_exact_file_read_output(output)),
            (_, Some(error)) => Err(error.with_surface("agent_runner")),
            _ => Err(ToolExecutionError::policy_violation(
                resolved_tool_name.to_string(),
                "tool execution failed without output or error",
            )
            .with_surface("agent_runner")),
        };
        PreparedToolExecution {
            result,
            attempts: outcome.attempts,
            total_duration: outcome.total_duration,
            last_error_category: outcome.last_error_category,
        }
    }

    /// Internal tool execution, skipping validation.
    /// Use when `is_valid_tool` has already been called by the caller.
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "Internal validation-bypassing path is exercised only by tests and trusted callers."
        )
    )]
    pub(super) async fn execute_tool_internal(
        &self,
        tool_name: &str,
        args: &Value,
    ) -> std::result::Result<Value, Box<ToolExecutionError>> {
        let prepared = self.tool_registry.admit_public_tool_call(tool_name, args).map_err(|error| {
            ToolExecutionError::from_anyhow(tool_name, &error, 0, false, false, Some("agent_runner"))
                .with_tool_call_context(tool_name, args)
        })?;
        self.execute_prepared_tool_internal(&prepared).await.result.map_err(Box::new)
    }
}

#[cfg(test)]
mod tests {
    use crate::retry::{RetryPolicy, RetryPolicyCoreExt};
    use std::time::Duration;
    use vtcode_commons::ErrorCategory;

    /// Verify that the canonical retry policy correctly identifies transient
    /// errors as retryable via the `ErrorCategory` classifier.
    #[test]
    fn policy_retries_transient_errors() {
        let policy = RetryPolicy::new(3, Duration::from_millis(200), Duration::from_secs(2), 2.0);

        let network_err = anyhow::anyhow!("network connection dropped");
        let decision = policy.decision_for_anyhow(&network_err, 0, Some("test_tool"));
        assert!(decision.retryable, "network errors should be retryable");
        assert_eq!(decision.category, ErrorCategory::Network);

        let timeout_err = anyhow::anyhow!("operation timed out");
        let decision = policy.decision_for_anyhow(&timeout_err, 0, Some("test_tool"));
        assert!(decision.retryable, "timeout errors should be retryable");
        assert_eq!(decision.category, ErrorCategory::Timeout);

        let rate_limit_err = anyhow::anyhow!("429 Too Many Requests");
        let decision = policy.decision_for_anyhow(&rate_limit_err, 0, Some("test_tool"));
        assert!(decision.retryable, "rate limit errors should be retryable");
    }

    /// Verify that non-retryable errors fail fast without retry.
    #[test]
    fn policy_does_not_retry_permanent_errors() {
        let policy = RetryPolicy::new(3, Duration::from_millis(200), Duration::from_secs(2), 2.0);

        let policy_err = anyhow::anyhow!("tool denied by policy");
        let decision = policy.decision_for_anyhow(&policy_err, 0, Some("test_tool"));
        assert!(!decision.retryable, "policy violations should not be retryable");

        let auth_err = anyhow::anyhow!("invalid api key");
        let decision = policy.decision_for_anyhow(&auth_err, 0, Some("test_tool"));
        assert!(!decision.retryable, "authentication errors should not be retryable");

        let param_err = anyhow::anyhow!("invalid arguments: missing required field");
        let decision = policy.decision_for_anyhow(&param_err, 0, Some("test_tool"));
        assert!(!decision.retryable, "invalid parameter errors should not be retryable");
    }

    /// Verify that retryable decisions include backoff delays.
    #[test]
    fn policy_provides_backoff_delays() {
        let policy = RetryPolicy::new(3, Duration::from_millis(200), Duration::from_secs(2), 2.0);

        let err = anyhow::anyhow!("network connection dropped");

        let d0 = policy.decision_for_anyhow(&err, 0, Some("test_tool"));
        let d1 = policy.decision_for_anyhow(&err, 1, Some("test_tool"));

        assert!(d0.delay.is_some(), "first retry should have a delay");
        assert!(d1.delay.is_some(), "second retry should have a delay");
        assert!(d1.delay.unwrap_or_default() >= d0.delay.unwrap_or_default(), "backoff should increase");
    }
}