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. Needs a verified computer-use model. 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. Only OpenAI providers
39    /// whose route supports Decisions are reviewed; anything else
40    /// proceeds on the human turn approval alone. Uses OpenAI API billing.
41    #[serde(default)]
42    pub decisions_review: bool,
43}
44
45impl Default for ComputerUseConfig {
46    fn default() -> Self {
47        Self {
48            enabled: false,
49            browser_build: None,
50            image: default_image(),
51            turn_timeout_secs: default_turn_timeout_secs(),
52            max_actions_per_turn: default_max_actions_per_turn(),
53            decisions_review: false,
54        }
55    }
56}
57
58impl ComputerUseConfig {
59    /// Validate shapes and bounds without touching the filesystem.
60    pub fn validate(&self) -> Result<()> {
61        // Image pinning mirrors the container launcher
62        // (`vtcode_computer_use::browser::container`), which re-validates at
63        // launch and stays authoritative; this fails fast on config errors.
64        if self.image.is_empty()
65            || self.image.len() > 512
66            || self.image.chars().any(|c| c.is_control() || c.is_whitespace())
67        {
68            bail!("computer_use.image must be a non-empty image reference without whitespace");
69        }
70        if !has_image_pin(&self.image) || self.image.ends_with(":latest") {
71            bail!("computer_use.image must be pinned with a tag or digest other than latest");
72        }
73        // Enabled without a target is a legitimate intermediate state (the
74        // Settings switch persists first; turns fail closed until a target
75        // is set), so only the shape of a present value is validated here.
76        if let Some(build) = self.browser_build.as_ref()
77            && (!build.is_absolute() || build.as_os_str().is_empty())
78        {
79            bail!("computer_use.browser_build must be an absolute directory");
80        }
81        if self.turn_timeout_secs == 0 || self.turn_timeout_secs > 3600 {
82            bail!("computer_use.turn_timeout_secs must be between 1 and 3600");
83        }
84        if self.max_actions_per_turn == 0 || self.max_actions_per_turn > 1000 {
85            bail!("computer_use.max_actions_per_turn must be between 1 and 1000");
86        }
87        Ok(())
88    }
89}
90
91fn default_image() -> String {
92    DEFAULT_IMAGE.to_string()
93}
94
95/// Whether the reference carries a tag or digest. A registry port colon
96/// (`registry:5000/foo`) is not a tag: only a colon after the last slash
97/// counts. Mirrors the launcher check in
98/// `vtcode_computer_use::browser::container`.
99fn has_image_pin(image: &str) -> bool {
100    if image.contains('@') {
101        return true;
102    }
103    match image.rsplit_once('/') {
104        Some((_, last)) => last.contains(':'),
105        None => image.contains(':'),
106    }
107}
108
109const fn default_turn_timeout_secs() -> u64 {
110    DEFAULT_TURN_TIMEOUT_SECS
111}
112
113const fn default_max_actions_per_turn() -> usize {
114    DEFAULT_MAX_ACTIONS_PER_TURN
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn defaults_keep_computer_use_disabled() {
123        let config = ComputerUseConfig::default();
124        assert!(!config.enabled);
125        assert_eq!(config.browser_build, None);
126        assert_eq!(config.image, "vtcode-computer-use-browser:1.65.1");
127        assert_eq!(config.turn_timeout_secs, 300);
128        assert_eq!(config.max_actions_per_turn, 50);
129        assert!(!config.decisions_review);
130        config.validate().expect("defaults should validate");
131    }
132
133    #[test]
134    fn parses_decisions_review_flag() {
135        let config: ComputerUseConfig = toml::from_str("decisions_review = true\n").expect("computer use config");
136        assert!(config.decisions_review);
137        let serialized = toml::to_string(&config).expect("serialize computer use");
138        assert!(serialized.contains("decisions_review = true"));
139        let roundtrip: ComputerUseConfig = toml::from_str(&serialized).expect("roundtrip computer use");
140        assert!(roundtrip.decisions_review);
141    }
142
143    #[test]
144    fn enabled_without_a_target_persists_and_relative_targets_reject() {
145        // The Settings switch persists first; turns fail closed until a
146        // target is set, so validation must not refuse the switch.
147        let config = ComputerUseConfig { enabled: true, ..Default::default() };
148        config.validate().expect("enabled without a target should validate");
149        for enabled in [false, true] {
150            let config = ComputerUseConfig {
151                enabled,
152                browser_build: Some(PathBuf::from("relative/build")),
153                ..Default::default()
154            };
155            assert!(config.validate().is_err(), "enabled={enabled} accepted a relative build");
156            let config = ComputerUseConfig {
157                enabled,
158                browser_build: Some(PathBuf::from("/absolute/build")),
159                ..Default::default()
160            };
161            config.validate().expect("absolute build should validate");
162        }
163    }
164
165    #[test]
166    fn image_must_be_pinned() {
167        for image in [
168            "",
169            "runner",
170            "runner:latest",
171            "run ner:1.0",
172            "registry.invalid/runner:1.64\n1",
173            "registry.invalid:5000/runner",
174        ] {
175            let config = ComputerUseConfig { image: image.to_string(), ..Default::default() };
176            assert!(config.validate().is_err(), "accepted {image:?}");
177        }
178        for image in [
179            "registry.invalid/runner:1.64.1",
180            "registry.invalid/runner@sha256:abc",
181            "registry.invalid:5000/runner:1.64.1",
182        ] {
183            let config = ComputerUseConfig { image: image.to_string(), ..Default::default() };
184            assert!(config.validate().is_ok(), "rejected {image:?}");
185        }
186    }
187
188    #[test]
189    fn budgets_have_sane_bounds() {
190        for (timeout, actions, valid) in [
191            (0, 50, false),
192            (1, 50, true),
193            (3600, 50, true),
194            (3601, 50, false),
195            (300, 0, false),
196            (300, 1, true),
197            (300, 1000, true),
198            (300, 1001, false),
199        ] {
200            let config = ComputerUseConfig {
201                turn_timeout_secs: timeout,
202                max_actions_per_turn: actions,
203                ..Default::default()
204            };
205            assert_eq!(config.validate().is_ok(), valid, "timeout={timeout} actions={actions}");
206        }
207    }
208}