Skip to main content

vtcode_config/
computer_use.rs

1use std::path::PathBuf;
2
3use anyhow::{Result, bail};
4use serde::{Deserialize, Serialize};
5
6const DEFAULT_IMAGE: &str = "vtcode-computer-use-browser:1.65.1";
7const DEFAULT_TURN_TIMEOUT_SECS: u64 = 300;
8const DEFAULT_MAX_ACTIONS_PER_TURN: usize = 50;
9
10/// Configuration for the opt-in computer-use runtime.
11///
12/// Approval stays per turn and per target regardless of these settings: the
13/// run loop requests human review through the permission flow before any
14/// control sequence, and automation policies cannot bypass it.
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
17pub struct ComputerUseConfig {
18    /// Opt-in marker. Works with any model on OpenAI or Anthropic native computer-use routes. The feature stays inert unless this is true.
19    #[serde(default)]
20    pub enabled: bool,
21    /// Approved static build served to the browser target. Required before
22    /// turns can run, but not before the switch can persist: Settings
23    /// enables first and guides to the target second, and turns fail
24    /// closed until a target is set. Must be absolute when present.
25    /// Existence is verified at launch, not here.
26    #[serde(default)]
27    pub browser_build: Option<PathBuf>,
28    /// Pinned browser container image (tag or digest, never `latest`).
29    #[serde(default = "default_image")]
30    pub image: String,
31    /// Wall-clock budget for one approved turn, in seconds.
32    #[serde(default = "default_turn_timeout_secs")]
33    pub turn_timeout_secs: u64,
34    /// Maximum actions executed in one approved turn.
35    #[serde(default = "default_max_actions_per_turn")]
36    pub max_actions_per_turn: usize,
37    /// Ask OpenAI Decisions to review each proposed batch for prompt
38    /// injection and task drift before execution. A suspect batch or a review
39    /// that cannot conclude (timeout, request failure, inconclusive answer)
40    /// halts the turn; only OpenAI providers whose route supports Decisions
41    /// are reviewed, and anything else proceeds on human approval alone.
42    /// Uses OpenAI API billing.
43    #[serde(default)]
44    pub decisions_review: bool,
45}
46
47impl Default for ComputerUseConfig {
48    fn default() -> Self {
49        Self {
50            enabled: false,
51            browser_build: None,
52            image: default_image(),
53            turn_timeout_secs: default_turn_timeout_secs(),
54            max_actions_per_turn: default_max_actions_per_turn(),
55            decisions_review: false,
56        }
57    }
58}
59
60impl ComputerUseConfig {
61    /// Validate shapes and bounds without touching the filesystem.
62    pub fn validate(&self) -> Result<()> {
63        // Image pinning mirrors the container launcher
64        // (`vtcode_computer_use::browser::container`), which re-validates at
65        // launch and stays authoritative; this fails fast on config errors.
66        if self.image.is_empty()
67            || self.image.len() > 512
68            || self.image.chars().any(|c| c.is_control() || c.is_whitespace())
69        {
70            bail!("computer_use.image must be a non-empty image reference without whitespace");
71        }
72        if !has_image_pin(&self.image) || self.image.ends_with(":latest") {
73            bail!("computer_use.image must be pinned with a tag or digest other than latest");
74        }
75        // Enabled without a target is a legitimate intermediate state (the
76        // Settings switch persists first; turns fail closed until a target
77        // is set), so only the shape of a present value is validated here.
78        if let Some(build) = self.browser_build.as_ref()
79            && (!build.is_absolute() || build.as_os_str().is_empty())
80        {
81            bail!("computer_use.browser_build must be an absolute directory");
82        }
83        if self.turn_timeout_secs == 0 || self.turn_timeout_secs > 3600 {
84            bail!("computer_use.turn_timeout_secs must be between 1 and 3600");
85        }
86        if self.max_actions_per_turn == 0 || self.max_actions_per_turn > 1000 {
87            bail!("computer_use.max_actions_per_turn must be between 1 and 1000");
88        }
89        Ok(())
90    }
91}
92
93fn default_image() -> String {
94    DEFAULT_IMAGE.to_string()
95}
96
97/// Whether the reference carries a tag or digest. A registry port colon
98/// (`registry:5000/foo`) is not a tag: only a colon after the last slash
99/// counts. Mirrors the launcher check in
100/// `vtcode_computer_use::browser::container`.
101fn has_image_pin(image: &str) -> bool {
102    if image.contains('@') {
103        return true;
104    }
105    match image.rsplit_once('/') {
106        Some((_, last)) => last.contains(':'),
107        None => image.contains(':'),
108    }
109}
110
111const fn default_turn_timeout_secs() -> u64 {
112    DEFAULT_TURN_TIMEOUT_SECS
113}
114
115const fn default_max_actions_per_turn() -> usize {
116    DEFAULT_MAX_ACTIONS_PER_TURN
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn defaults_keep_computer_use_disabled() {
125        let config = ComputerUseConfig::default();
126        assert!(!config.enabled);
127        assert_eq!(config.browser_build, None);
128        assert_eq!(config.image, "vtcode-computer-use-browser:1.65.1");
129        assert_eq!(config.turn_timeout_secs, 300);
130        assert_eq!(config.max_actions_per_turn, 50);
131        assert!(!config.decisions_review);
132        config.validate().expect("defaults should validate");
133    }
134
135    #[test]
136    fn parses_decisions_review_flag() {
137        let config: ComputerUseConfig = toml::from_str("decisions_review = true\n").expect("computer use config");
138        assert!(config.decisions_review);
139        let serialized = toml::to_string(&config).expect("serialize computer use");
140        assert!(serialized.contains("decisions_review = true"));
141        let roundtrip: ComputerUseConfig = toml::from_str(&serialized).expect("roundtrip computer use");
142        assert!(roundtrip.decisions_review);
143    }
144
145    #[test]
146    fn enabled_without_a_target_persists_and_relative_targets_reject() {
147        // The Settings switch persists first; turns fail closed until a
148        // target is set, so validation must not refuse the switch.
149        let config = ComputerUseConfig { enabled: true, ..Default::default() };
150        config.validate().expect("enabled without a target should validate");
151        for enabled in [false, true] {
152            let config = ComputerUseConfig {
153                enabled,
154                browser_build: Some(PathBuf::from("relative/build")),
155                ..Default::default()
156            };
157            assert!(config.validate().is_err(), "enabled={enabled} accepted a relative build");
158            let config = ComputerUseConfig {
159                enabled,
160                browser_build: Some(PathBuf::from("/absolute/build")),
161                ..Default::default()
162            };
163            config.validate().expect("absolute build should validate");
164        }
165    }
166
167    #[test]
168    fn image_must_be_pinned() {
169        for image in [
170            "",
171            "runner",
172            "runner:latest",
173            "run ner:1.0",
174            "registry.invalid/runner:1.64\n1",
175            "registry.invalid:5000/runner",
176        ] {
177            let config = ComputerUseConfig { image: image.to_string(), ..Default::default() };
178            assert!(config.validate().is_err(), "accepted {image:?}");
179        }
180        for image in [
181            "registry.invalid/runner:1.64.1",
182            "registry.invalid/runner@sha256:abc",
183            "registry.invalid:5000/runner:1.64.1",
184        ] {
185            let config = ComputerUseConfig { image: image.to_string(), ..Default::default() };
186            assert!(config.validate().is_ok(), "rejected {image:?}");
187        }
188    }
189
190    #[test]
191    fn budgets_have_sane_bounds() {
192        for (timeout, actions, valid) in [
193            (0, 50, false),
194            (1, 50, true),
195            (3600, 50, true),
196            (3601, 50, false),
197            (300, 0, false),
198            (300, 1, true),
199            (300, 1000, true),
200            (300, 1001, false),
201        ] {
202            let config = ComputerUseConfig {
203                turn_timeout_secs: timeout,
204                max_actions_per_turn: actions,
205                ..Default::default()
206            };
207            assert_eq!(config.validate().is_ok(), valid, "timeout={timeout} actions={actions}");
208        }
209    }
210}