vtcode-config 0.185.2

Config loader components shared across VT Code and downstream adopters
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Sparse configuration saves and comment-preserving TOML persistence.

use std::fs;
use std::path::Path;

use anyhow::{Context, Result, bail};
use vtcode_commons::VtCodePaths;

use super::super::toml_patch::render_toml_edit;
use super::{ConfigLayerSource, ConfigManager, VTCodeConfig};

fn ensure_private_parent_dir(path: &Path) -> Result<()> {
    let Some(parent) = path.parent() else {
        return Ok(());
    };
    let _ = VtCodePaths::ensure_user_dir(parent)
        .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    Ok(())
}

impl ConfigManager {
    /// Persist configuration to a specific path, preserving comments.
    pub fn save_config_to_path(path: impl AsRef<Path>, config: &VTCodeConfig) -> Result<()> {
        Self::save_config_to_path_internal(path, config, false)
    }

    /// Persist configuration to a repository-controlled path.
    ///
    /// Repository and project files may contain ordinary settings, but they
    /// must never receive trusted provider definitions or provider endpoint and
    /// credential overrides from the merged configuration. Existing protected
    /// keys are removed as well so this method can repair files written by an
    /// older version that flattened the effective configuration.
    pub fn save_repository_config_to_path(path: impl AsRef<Path>, config: &VTCodeConfig) -> Result<()> {
        Self::save_config_to_path_internal(path, config, true)
    }

    /// Render a targeted edit, pruning deprecated configuration keys.
    ///
    /// # Errors
    ///
    /// Returns an error if the original document or requested update cannot be rendered.
    pub fn merge_config_edit(original: &str, updated: &toml::Value) -> Result<String> {
        render_toml_edit(original, updated, Self::remove_deprecated_config_keys)
    }

    /// Render a targeted edit while applying the repository provider trust policy.
    ///
    /// # Errors
    ///
    /// Returns an error if the original document or requested update cannot be rendered.
    pub fn merge_repository_config_edit(original: &str, updated: &toml::Value) -> Result<String> {
        render_toml_edit(original, updated, |doc| {
            let removed_deprecated = Self::remove_deprecated_config_keys(doc);
            Self::remove_protected_repository_keys(doc) || removed_deprecated
        })
    }

    fn remove_protected_repository_keys(doc: &mut toml_edit::DocumentMut) -> bool {
        let provider_changed = Self::remove_repository_provider_settings(doc);
        let auth_changed =
            Self::remove_path_and_prune_empty_parents(doc.as_table_mut(), &["auth", "copilot", "command"]);
        provider_changed || auth_changed
    }

    fn save_config_to_path_internal(
        path: impl AsRef<Path>,
        config: &VTCodeConfig,
        repository_controlled: bool,
    ) -> Result<()> {
        let path = path.as_ref();
        ensure_private_parent_dir(path)?;
        let config_to_persist = if repository_controlled {
            Self::repository_safe_config(config)
        } else {
            config.clone()
        };
        let sparse_value =
            Self::sparse_config_value(&config_to_persist).context("Failed to prepare sparse configuration")?;
        let sparse_content =
            toml::to_string_pretty(&sparse_value).context("Failed to serialize sparse configuration")?;

        // If file exists, preserve comments by using toml_edit. Read and
        // publish through the shared no-follow/atomic file policy so a
        // user-controlled symlink cannot redirect configuration writes.
        let existing_content = match fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                bail!("Refusing to read symlinked config file: {}", path.display())
            }
            Ok(metadata) if !metadata.is_file() => {
                bail!("Config path is not a regular file: {}", path.display())
            }
            Ok(_) => Some(
                String::from_utf8(VtCodePaths::read_file_no_follow(path)?)
                    .with_context(|| format!("Failed to read existing config: {}", path.display()))?,
            ),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => {
                return Err(error).with_context(|| format!("Failed to inspect config: {}", path.display()));
            }
        };

        if let Some(original_content) = existing_content {
            let mut doc = original_content
                .parse::<toml_edit::DocumentMut>()
                .with_context(|| format!("Failed to parse existing config: {}", path.display()))?;
            Self::remove_deprecated_config_keys(&mut doc);
            if repository_controlled {
                Self::remove_protected_repository_keys(&mut doc);
            }

            let new_doc: toml_edit::DocumentMut = sparse_content
                .parse()
                .context("Failed to parse sparse serialized configuration")?;
            let default_value =
                toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
            let default_doc: toml_edit::DocumentMut = toml::to_string_pretty(&default_value)
                .context("Failed to serialize default configuration")?
                .parse()
                .context("Failed to parse default serialized configuration")?;

            // Update values while preserving structure and comments
            Self::merge_sparse_toml_documents(&mut doc, &new_doc, &default_doc);
            // The sparse merge cannot express the deletion of optional fields
            // whose default serializes to absent (they appear in neither the
            // sparse update nor the defaults), so resets issued through save
            // paths (e.g. service_tier back to Project default) would leave
            // stale file values behind forever. Reconcile those explicitly.
            Self::prune_cleared_optional_fields(&mut doc, &config_to_persist);

            VtCodePaths::write_private_file_atomic(path, doc.to_string().as_bytes())
                .with_context(|| format!("Failed to write config file: {}", path.display()))?;
        } else {
            VtCodePaths::write_private_file_atomic(path, sparse_content.as_bytes())
                .with_context(|| format!("Failed to write config file: {}", path.display()))?;
        }

        Ok(())
    }

    fn repository_safe_config(config: &VTCodeConfig) -> VTCodeConfig {
        let mut safe_config = config.clone();
        safe_config.custom_providers.clear();
        safe_config.auth.copilot.command = None;
        for provider_override in safe_config.provider_overrides.values_mut() {
            provider_override.base_url = None;
            provider_override.api_key_env = None;
        }
        safe_config
    }

    /// Remove file values for optional fields the effective config reset to
    /// their absent default (e.g. `provider.openai.service_tier` back to
    /// Project default). The sparse merge cannot express these deletions
    /// (absent from both the sparse update and the defaults), so each entry
    /// pairs a dotted path with a typed cleared-check. Only listed paths are
    /// touched; foreign keys are never removed. Extend the list when a new
    /// resettable optional reaches a save path.
    fn prune_cleared_optional_fields(doc: &mut toml_edit::DocumentMut, config: &VTCodeConfig) {
        // Each entry: (dotted path, is_cleared).
        let cleared: &[(&[&str], bool)] = &[
            (&["provider", "openai", "service_tier"], config.provider.openai.service_tier.is_none()),
            (&["provider", "anthropic", "speed"], config.provider.anthropic.speed.is_none()),
        ];
        for (path, is_cleared) in cleared {
            if *is_cleared {
                Self::remove_path_and_prune_empty_parents(doc.as_table_mut(), path);
            }
        }
    }

    /// Remove `path` from `table`, then drop ancestor tables left empty.
    /// Returns true when anything was removed.
    fn remove_path_and_prune_empty_parents(table: &mut dyn toml_edit::TableLike, path: &[&str]) -> bool {
        let Some((first, rest)) = path.split_first() else {
            return false;
        };
        if rest.is_empty() {
            return table.remove(first).is_some();
        }
        let Some(child) = table.get_mut(first).and_then(toml_edit::Item::as_table_like_mut) else {
            return false;
        };
        let changed = Self::remove_path_and_prune_empty_parents(child, rest);
        if child.is_empty() {
            table.remove(first);
            return true;
        }
        changed
    }

    fn remove_deprecated_config_keys(doc: &mut toml_edit::DocumentMut) -> bool {
        let table = doc.as_table_mut();
        let mut changed = table.remove("project_doc_max_bytes").is_some();
        changed |= table.remove("project_doc_fallback_filenames").is_some();
        changed |= Self::remove_table_keys(table, "agent", &["autonomous_mode", "default_editing_mode"]);
        changed |=
            Self::remove_table_keys(table, "permissions", &["allowed_tools", "disallowed_tools", "auto_permission"]);
        // Keep this in sync with the loader warning that retired keys are pruned on save.
        for &key_path in super::REMOVED_CONFIG_KEY_PATHS {
            changed |= Self::remove_path_and_prune_empty_parents(table, key_path);
        }
        changed
    }

    fn remove_table_keys(table: &mut toml_edit::Table, section: &str, keys: &[&str]) -> bool {
        let Some(section) = table.get_mut(section).and_then(toml_edit::Item::as_table_mut) else {
            return false;
        };
        let mut changed = false;
        for key in keys {
            changed |= section.remove(key).is_some();
        }
        changed
    }

    pub fn sparse_config_value(config: &VTCodeConfig) -> Result<toml::Value> {
        let mut value = toml::Value::try_from(config).context("Failed to serialize configuration")?;
        let default_value =
            toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
        Self::prune_default_values(&mut value, &default_value);
        Ok(value)
    }

    fn prune_default_values(value: &mut toml::Value, default_value: &toml::Value) -> bool {
        match (value, default_value) {
            (toml::Value::Table(table), toml::Value::Table(default_table)) => {
                table.retain(|key, child| {
                    default_table
                        .get(key)
                        .is_none_or(|default_child| !Self::prune_default_values(child, default_child))
                });
                table.is_empty()
            }
            (value, default_value) => value == default_value,
        }
    }

    /// Merge TOML documents, preserving comments and structure from original
    fn merge_sparse_toml_documents(
        original: &mut toml_edit::DocumentMut,
        new: &toml_edit::DocumentMut,
        default_doc: &toml_edit::DocumentMut,
    ) {
        Self::merge_sparse_tables(original.as_table_mut(), new.as_table(), default_doc.as_table());
    }

    fn merge_sparse_tables(original: &mut toml_edit::Table, new: &toml_edit::Table, default_table: &toml_edit::Table) {
        let mut remove_keys = Vec::with_capacity(default_table.len());

        for (key, default_value) in default_table.iter() {
            if let Some(new_value) = new.get(key) {
                if let Some(original_value) = original.get_mut(key) {
                    Self::merge_sparse_items(original_value, new_value, default_value);
                } else {
                    original[key] = new_value.clone();
                }
            } else {
                let Some(original_value) = original.get_mut(key) else {
                    continue;
                };
                if Self::remove_known_default_item(original_value, default_value) {
                    remove_keys.push(key.to_string());
                }
            }
        }

        for key in remove_keys {
            original.remove(&key);
        }

        for (key, new_value) in new.iter() {
            if default_table.contains_key(key) {
                continue;
            }
            if let Some(original_value) = original.get_mut(key) {
                *original_value = new_value.clone();
            } else {
                original[key] = new_value.clone();
            }
        }
    }

    fn merge_sparse_items(original: &mut toml_edit::Item, new: &toml_edit::Item, default_value: &toml_edit::Item) {
        match (original, new, default_value) {
            (
                toml_edit::Item::Table(orig_table),
                toml_edit::Item::Table(new_table),
                toml_edit::Item::Table(default_table),
            ) => Self::merge_sparse_tables(orig_table, new_table, default_table),
            (orig, new, _) => {
                *orig = new.clone();
            }
        }
    }

    fn remove_known_default_item(original: &mut toml_edit::Item, default_value: &toml_edit::Item) -> bool {
        match (original, default_value) {
            (toml_edit::Item::Table(orig_table), toml_edit::Item::Table(default_table)) => {
                let mut remove_keys = Vec::new();
                for (key, default_child) in default_table.iter() {
                    let Some(orig_child) = orig_table.get_mut(key) else {
                        continue;
                    };
                    if Self::remove_known_default_item(orig_child, default_child) {
                        remove_keys.push(key.to_string());
                    }
                }
                for key in remove_keys {
                    orig_table.remove(&key);
                }
                orig_table.is_empty()
            }
            _ => true,
        }
    }

    /// Persist configuration to the manager's associated path or workspace
    pub fn save_config(&mut self, config: &VTCodeConfig) -> Result<()> {
        let (target, repository_controlled) = if let Some(path) = &self.config_path {
            if self.write_global_config_to_canonical || self.is_global_config_path(path) {
                (self.preferred_user_config_path().unwrap_or_else(|| path.clone()), false)
            } else {
                (path.clone(), !self.explicit_config_is_trusted)
            }
        } else if let Some(workspace_root) = &self.workspace_root {
            (workspace_root.join(&self.config_file_name), !self.explicit_config_is_trusted)
        } else {
            let cwd = std::env::current_dir().context("Failed to resolve current directory")?;
            (cwd.join(&self.config_file_name), !self.explicit_config_is_trusted)
        };

        if repository_controlled {
            Self::save_repository_config_to_path(target, config)?;
        } else {
            Self::save_config_to_path(target, config)?;
        }

        #[cfg(not(test))]
        if let Some(workspace) = &self.workspace_root {
            Self::invalidate_workspace_cache(workspace);
        }

        self.sync_from_config(config)
    }

    fn is_global_config_path(&self, path: &Path) -> bool {
        self.layer_stack.layers().iter().any(|layer| {
            layer.is_enabled()
                && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
                && match &layer.source {
                    ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => file == path,
                    _ => false,
                }
        })
    }

    /// Sync internal config from a saved config
    /// Call this after save_config to keep internal state in sync
    fn sync_from_config(&mut self, config: &VTCodeConfig) -> Result<()> {
        self.config = config.clone();
        Ok(())
    }
}

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

    #[test]
    fn repository_edit_writes_cleanup_when_setting_did_not_change() {
        let original = concat!(
            "[ui]\nshow_timeline_pane = false\n",
            "[ui.fullscreen]\ncopy_on_select = true\n",
            "\n[auth.copilot]\ncommand = 'helper'\n",
        );
        let updated = toml::from_str(original).expect("parse update");

        let rendered = ConfigManager::merge_repository_config_edit(original, &updated).expect("patch repository");
        let saved: toml::Value = toml::from_str(&rendered).expect("parse output");
        assert_eq!(saved["ui"]["fullscreen"]["copy_on_select"].as_bool(), Some(true));
        assert!(saved["ui"].get("show_timeline_pane").is_none());
        assert!(saved.get("auth").is_none());
    }

    #[test]
    fn repository_edit_preserves_explicit_defaults_and_strips_trusted_fields() {
        let original = "# notes\n[ui.fullscreen]\ncopy_on_select  =  true # pinned\n";
        let updated: toml::Value = toml::from_str(concat!(
            "[ui.fullscreen]\ncopy_on_select = true\n",
            "[auth.copilot]\ncommand = 'helper'\n",
            "[provider_overrides.openai]\nbase_url = 'https://example.com'\napi_key_env = 'SENSITIVE'\n",
        ))
        .expect("parse update");

        let rendered = ConfigManager::merge_repository_config_edit(original, &updated).expect("patch repository");
        assert_eq!(rendered, original);
    }

    #[test]
    fn save_prunes_removed_budget_keys_from_existing_config() {
        let temp = tempfile::tempdir().expect("tempdir");
        let path = temp.path().join("vtcode.toml");
        fs::write(
            &path,
            "[agent.harness]\nmax_tool_calls_per_turn = 32\n\n[tools]\nmax_tool_loops = 20\nmax_repeated_tool_calls = 4\n\n[automation.full_auto]\nauto_grant_tool_limits = false\nenabled = true\n",
        )
        .expect("seed stale config");

        // The save merges a sparse serialization of this config, so surviving
        // keys must be non-default to appear in it.
        let mut config = VTCodeConfig::default();
        config.tools.max_repeated_tool_calls = 4;
        config.automation.full_auto.enabled = true;
        ConfigManager::save_config_to_path(&path, &config).expect("save");

        let rewritten = fs::read_to_string(&path).expect("rewritten config");
        assert!(!rewritten.contains("max_tool_calls_per_turn"));
        assert!(!rewritten.contains("max_tool_loops"));
        assert!(!rewritten.contains("auto_grant_tool_limits"));
        // Surviving non-default keys stay.
        assert!(rewritten.contains("max_repeated_tool_calls"));
        assert!(rewritten.contains("enabled = true"));
    }
}