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
//! Approval requirement types for execution policy.

use serde::{Deserialize, Serialize};

/// Fine-grained rejection controls for approval prompts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct RejectConfig {
    /// Reject approval prompts related to sandbox escalation, including
    /// `with_additional_permissions`.
    pub sandbox_approval: bool,
    /// Reject prompts triggered by policy `prompt` rules.
    pub rules: bool,
    /// Reject built-in permission request prompts that are separate from
    /// sandbox approval.
    pub request_permissions: bool,
    /// Reject MCP elicitation prompts.
    pub mcp_elicitations: bool,
}

impl RejectConfig {
    pub const fn rejects_sandbox_approval(self) -> bool {
        self.sandbox_approval
    }

    pub const fn rejects_rules_approval(self) -> bool {
        self.rules
    }

    pub const fn rejects_request_permissions(self) -> bool {
        self.request_permissions
    }

    pub const fn rejects_mcp_elicitations(self) -> bool {
        self.mcp_elicitations
    }
}

/// Policy for when to ask for approval before executing commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AskForApproval {
    /// Never ask for approval (autonomous mode).
    Never,

    /// Ask only when explicitly requested by policy.
    OnRequest,

    /// Ask unless the command is in the trusted list.
    #[default]
    UnlessTrusted,

    /// Ask only on failure (retry with approval).
    OnFailure,

    /// Fine-grained rejection controls for approval prompts.
    Reject(RejectConfig),
}

impl AskForApproval {
    /// Check if this policy requires asking for unknown commands.
    pub fn requires_approval_for_unknown(&self) -> bool {
        matches!(
            self,
            Self::UnlessTrusted | Self::OnRequest | Self::Reject(_)
        )
    }

    /// Check whether rule-triggered approval prompts are rejected.
    pub const fn rejects_rule_prompt(self) -> bool {
        match self {
            Self::Never => true,
            Self::Reject(reject_config) => reject_config.rejects_rules_approval(),
            Self::OnFailure | Self::OnRequest | Self::UnlessTrusted => false,
        }
    }

    /// Check whether sandbox-related approval prompts are rejected.
    pub const fn rejects_sandbox_prompt(self) -> bool {
        match self {
            Self::Never => true,
            Self::Reject(reject_config) => reject_config.rejects_sandbox_approval(),
            Self::OnFailure | Self::OnRequest | Self::UnlessTrusted => false,
        }
    }

    /// Check whether built-in permission request prompts are rejected.
    pub const fn rejects_request_permission_prompt(self) -> bool {
        match self {
            Self::Never => true,
            Self::Reject(reject_config) => reject_config.rejects_request_permissions(),
            Self::OnFailure | Self::OnRequest | Self::UnlessTrusted => false,
        }
    }

    /// Check whether MCP elicitation prompts are rejected.
    pub const fn rejects_mcp_elicitation(self) -> bool {
        match self {
            Self::Never => true,
            Self::Reject(reject_config) => reject_config.rejects_mcp_elicitations(),
            Self::OnFailure | Self::OnRequest | Self::UnlessTrusted => false,
        }
    }
}

/// Compute the default approval requirement for a tool invocation.
///
/// `requires_sandbox_approval_prompt` should be `true` when the selected
/// sandbox mode still requires an approval prompt, and `false` when the tool is
/// already running unsandboxed or under an external sandbox that should not
/// trigger an additional sandbox approval prompt.
#[must_use]
pub fn default_exec_approval_requirement(
    policy: AskForApproval,
    requires_sandbox_approval_prompt: bool,
) -> ExecApprovalRequirement {
    let needs_approval = match policy {
        AskForApproval::Never | AskForApproval::OnFailure => false,
        AskForApproval::OnRequest | AskForApproval::Reject(_) => requires_sandbox_approval_prompt,
        AskForApproval::UnlessTrusted => true,
    };

    if needs_approval && policy.rejects_sandbox_prompt() {
        ExecApprovalRequirement::forbidden("approval policy rejected sandbox approval prompt")
    } else if needs_approval {
        ExecApprovalRequirement::NeedsApproval {
            reason: None,
            proposed_execpolicy_amendment: None,
        }
    } else {
        ExecApprovalRequirement::skip()
    }
}

/// A proposed amendment to the execution policy.
///
/// When a command requires approval but isn't explicitly forbidden,
/// this amendment can be proposed to allow similar commands in the future.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecPolicyAmendment {
    /// The command pattern to add to the policy.
    pub pattern: Vec<String>,
}

impl ExecPolicyAmendment {
    /// Create a new policy amendment.
    pub fn new(pattern: Vec<String>) -> Self {
        Self { pattern }
    }

    /// Create from a single command prefix.
    pub fn from_prefix(prefix: impl Into<String>) -> Self {
        Self {
            pattern: vec![prefix.into()],
        }
    }

    /// Check if a command matches this amendment pattern.
    pub fn matches(&self, command: &[String]) -> bool {
        if command.len() < self.pattern.len() {
            return false;
        }
        self.pattern
            .iter()
            .zip(command.iter())
            .all(|(pattern, cmd)| pattern == cmd)
    }

    /// Convert the amendment to a policy rule string.
    pub fn to_rule_string(&self) -> String {
        let pattern_json = serde_json::to_string(&self.pattern).unwrap_or_default();
        format!("prefix_rule(pattern={}, decision=\"allow\")", pattern_json)
    }

    /// Get the command pattern for Codex compatibility.
    pub fn command_pattern(&self) -> &[String] {
        &self.pattern
    }
}

/// Requirement for approval before executing a command.
///
/// This enum represents the outcome of evaluating a command against the
/// execution policy, indicating whether the command can proceed, needs
/// approval, or is forbidden.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecApprovalRequirement {
    /// Command can be executed without approval.
    Skip {
        /// Whether to bypass the sandbox for this command.
        bypass_sandbox: bool,
        /// Proposed policy amendment if the user wants to trust this command.
        proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
    },

    /// Command requires user approval before execution.
    NeedsApproval {
        /// Reason for requiring approval.
        reason: Option<String>,
        /// Proposed policy amendment to skip future approvals.
        proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
    },

    /// Command is forbidden by policy and cannot be executed.
    Forbidden {
        /// Reason for forbidding the command.
        reason: String,
    },
}

impl ExecApprovalRequirement {
    /// Create a skip requirement.
    pub fn skip() -> Self {
        Self::Skip {
            bypass_sandbox: false,
            proposed_execpolicy_amendment: None,
        }
    }

    /// Create a skip requirement with sandbox bypass.
    pub fn skip_with_bypass() -> Self {
        Self::Skip {
            bypass_sandbox: true,
            proposed_execpolicy_amendment: None,
        }
    }

    /// Create an approval requirement.
    pub fn needs_approval(reason: impl Into<String>) -> Self {
        Self::NeedsApproval {
            reason: Some(reason.into()),
            proposed_execpolicy_amendment: None,
        }
    }

    /// Create a needs approval requirement with an amendment.
    pub fn needs_approval_with_amendment(
        reason: Option<String>,
        amendment: ExecPolicyAmendment,
    ) -> Self {
        Self::NeedsApproval {
            reason,
            proposed_execpolicy_amendment: Some(amendment),
        }
    }

    /// Create a forbidden requirement.
    pub fn forbidden(reason: impl Into<String>) -> Self {
        Self::Forbidden {
            reason: reason.into(),
        }
    }

    /// Check if approval is needed.
    pub fn requires_approval(&self) -> bool {
        matches!(self, Self::NeedsApproval { .. })
    }

    /// Check if the command is forbidden.
    pub fn is_forbidden(&self) -> bool {
        matches!(self, Self::Forbidden { .. })
    }

    /// Check if the command can proceed (skip or approved).
    pub fn can_proceed(&self) -> bool {
        matches!(self, Self::Skip { .. })
    }

    /// Get the proposed amendment, if any.
    pub fn get_amendment(&self) -> Option<&ExecPolicyAmendment> {
        match self {
            Self::Skip {
                proposed_execpolicy_amendment,
                ..
            } => proposed_execpolicy_amendment.as_ref(),
            Self::NeedsApproval {
                proposed_execpolicy_amendment,
                ..
            } => proposed_execpolicy_amendment.as_ref(),
            Self::Forbidden { .. } => None,
        }
    }

    /// Get the proposed exec policy amendment if any (Codex-compatible name).
    pub fn proposed_execpolicy_amendment(&self) -> Option<&ExecPolicyAmendment> {
        self.get_amendment()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_skip_requirement() {
        let req = ExecApprovalRequirement::skip();
        assert!(req.can_proceed());
        assert!(!req.requires_approval());
        assert!(!req.is_forbidden());
    }

    #[test]
    fn test_needs_approval_requirement() {
        let req = ExecApprovalRequirement::needs_approval("dangerous command");
        assert!(!req.can_proceed());
        assert!(req.requires_approval());
        assert!(!req.is_forbidden());
    }

    #[test]
    fn test_forbidden_requirement() {
        let req = ExecApprovalRequirement::forbidden("policy violation");
        assert!(!req.can_proceed());
        assert!(!req.requires_approval());
        assert!(req.is_forbidden());
    }

    #[test]
    fn test_amendment() {
        let amendment = ExecPolicyAmendment::new(vec!["cargo".to_string(), "build".to_string()]);
        let rule = amendment.to_rule_string();
        assert!(rule.contains("cargo"));
        assert!(rule.contains("build"));
        assert!(rule.contains("allow"));
    }

    #[test]
    fn test_reject_config_helpers() {
        let config = RejectConfig {
            sandbox_approval: true,
            rules: false,
            request_permissions: false,
            mcp_elicitations: true,
        };
        assert!(config.rejects_sandbox_approval());
        assert!(!config.rejects_rules_approval());
        assert!(!config.rejects_request_permissions());
        assert!(config.rejects_mcp_elicitations());
    }

    #[test]
    fn test_ask_for_approval_rejection_helpers() {
        assert!(AskForApproval::Never.rejects_rule_prompt());
        assert!(AskForApproval::Never.rejects_sandbox_prompt());
        assert!(AskForApproval::Never.rejects_request_permission_prompt());
        assert!(AskForApproval::Never.rejects_mcp_elicitation());

        assert!(!AskForApproval::OnRequest.rejects_rule_prompt());
        assert!(!AskForApproval::OnRequest.rejects_sandbox_prompt());
        assert!(!AskForApproval::OnRequest.rejects_request_permission_prompt());
        assert!(!AskForApproval::OnRequest.rejects_mcp_elicitation());

        let sandbox_reject_policy = AskForApproval::Reject(RejectConfig {
            sandbox_approval: true,
            rules: false,
            request_permissions: false,
            mcp_elicitations: true,
        });
        assert!(!sandbox_reject_policy.rejects_rule_prompt());
        assert!(sandbox_reject_policy.rejects_sandbox_prompt());
        assert!(!sandbox_reject_policy.rejects_request_permission_prompt());
        assert!(sandbox_reject_policy.rejects_mcp_elicitation());

        let request_permissions_reject_policy = AskForApproval::Reject(RejectConfig {
            sandbox_approval: false,
            rules: false,
            request_permissions: true,
            mcp_elicitations: false,
        });
        assert!(!request_permissions_reject_policy.rejects_rule_prompt());
        assert!(!request_permissions_reject_policy.rejects_sandbox_prompt());
        assert!(request_permissions_reject_policy.rejects_request_permission_prompt());
        assert!(!request_permissions_reject_policy.rejects_mcp_elicitation());
    }

    #[test]
    fn test_reject_policy_serde_roundtrip() {
        let value = json!({
            "reject": {
                "sandbox_approval": true,
                "rules": false,
                "mcp_elicitations": true
            }
        });
        let policy: AskForApproval = serde_json::from_value(value).expect("deserialize policy");
        assert_eq!(
            policy,
            AskForApproval::Reject(RejectConfig {
                sandbox_approval: true,
                rules: false,
                request_permissions: false,
                mcp_elicitations: true,
            })
        );

        let serialized = serde_json::to_value(policy).expect("serialize policy");
        assert_eq!(
            serialized,
            json!({
                "reject": {
                    "sandbox_approval": true,
                    "rules": false,
                    "request_permissions": false,
                    "mcp_elicitations": true
                }
            })
        );
    }

    #[test]
    fn test_reject_policy_defaults_missing_request_permissions_to_false() {
        let policy: AskForApproval = serde_json::from_value(json!({
            "reject": {
                "sandbox_approval": true,
                "rules": false,
                "mcp_elicitations": true
            }
        }))
        .expect("deserialize legacy reject policy");

        assert_eq!(
            policy,
            AskForApproval::Reject(RejectConfig {
                sandbox_approval: true,
                rules: false,
                request_permissions: false,
                mcp_elicitations: true,
            })
        );
    }

    #[test]
    fn default_exec_approval_requirement_skips_for_never() {
        let requirement = default_exec_approval_requirement(AskForApproval::Never, true);

        assert_eq!(requirement, ExecApprovalRequirement::skip());
    }

    #[test]
    fn default_exec_approval_requirement_skips_for_on_failure() {
        let requirement = default_exec_approval_requirement(AskForApproval::OnFailure, true);

        assert_eq!(requirement, ExecApprovalRequirement::skip());
    }

    #[test]
    fn default_exec_approval_requirement_requires_approval_for_on_request() {
        let requirement = default_exec_approval_requirement(AskForApproval::OnRequest, true);

        assert_eq!(
            requirement,
            ExecApprovalRequirement::NeedsApproval {
                reason: None,
                proposed_execpolicy_amendment: None,
            }
        );
    }

    #[test]
    fn default_exec_approval_requirement_skips_on_request_without_prompt() {
        let requirement = default_exec_approval_requirement(AskForApproval::OnRequest, false);

        assert_eq!(requirement, ExecApprovalRequirement::skip());
    }

    #[test]
    fn default_exec_approval_requirement_requires_approval_for_unless_trusted() {
        let requirement = default_exec_approval_requirement(AskForApproval::UnlessTrusted, false);

        assert_eq!(
            requirement,
            ExecApprovalRequirement::NeedsApproval {
                reason: None,
                proposed_execpolicy_amendment: None,
            }
        );
    }

    #[test]
    fn default_exec_approval_requirement_rejects_sandbox_prompt_when_configured() {
        let policy = AskForApproval::Reject(RejectConfig {
            sandbox_approval: true,
            rules: false,
            request_permissions: false,
            mcp_elicitations: false,
        });

        let requirement = default_exec_approval_requirement(policy, true);

        assert_eq!(
            requirement,
            ExecApprovalRequirement::Forbidden {
                reason: "approval policy rejected sandbox approval prompt".to_string(),
            }
        );
    }

    #[test]
    fn default_exec_approval_requirement_ignores_request_permission_rejection() {
        let policy = AskForApproval::Reject(RejectConfig {
            sandbox_approval: false,
            rules: false,
            request_permissions: true,
            mcp_elicitations: false,
        });

        let requirement = default_exec_approval_requirement(policy, false);

        assert_eq!(requirement, ExecApprovalRequirement::skip());
    }

    #[test]
    fn default_exec_approval_requirement_keeps_prompt_when_rejection_disabled() {
        let policy = AskForApproval::Reject(RejectConfig {
            sandbox_approval: false,
            rules: true,
            request_permissions: false,
            mcp_elicitations: true,
        });

        let requirement = default_exec_approval_requirement(policy, true);

        assert_eq!(
            requirement,
            ExecApprovalRequirement::NeedsApproval {
                reason: None,
                proposed_execpolicy_amendment: None,
            }
        );
    }
}