1mod cache;
2mod inspect;
3mod migrate;
4mod persistence;
5mod repository;
6
7use cache::{
8 RepositoryProviderSecurityViolation, canonicalize_workspace_root, push_unique_layer_source,
9 should_skip_optional_global_error,
10};
11#[cfg(not(test))]
12use cache::{cache_get, cache_insert, cache_remove, with_cache_mut};
13use migrate::migrate_custom_api_keys_if_needed;
14
15use std::collections::HashMap;
16use std::fmt;
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::sync::{Arc, Mutex};
20
21use anyhow::{Context, Result, bail};
22
23use crate::api_keys::{api_key_env_var, credential_metadata_key, store_credential_with_mode};
24use crate::defaults::{self};
25use crate::hooks::{HooksConfig, LifecycleHooksConfig, WorkspaceHookCommand, WorkspaceLifecycleHooks};
26use crate::loader::config::VTCodeConfig;
27use crate::loader::layers::{
28 ConfigLayerEntry, ConfigLayerMetadata, ConfigLayerSource, ConfigLayerStack, LayerDisabledReason,
29};
30use crate::loader::session_override;
31use vtcode_commons::VtCodePaths;
32use vtcode_commons::canonicalize;
33
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub struct ConfigPhaseTiming {
37 pub path_resolution_us: u64,
39 pub layer_loading_us: u64,
41 pub merge_and_parse_us: u64,
43 pub validation_us: u64,
45}
46
47#[derive(Clone)]
49pub struct ConfigManager {
50 pub(crate) config: VTCodeConfig,
51 pub(super) config_path: Option<PathBuf>,
52 pub(super) canonical_user_config_path: Option<PathBuf>,
53 pub(super) tracked_user_config_paths: Vec<PathBuf>,
54 write_global_config_to_canonical: bool,
55 pub(super) explicit_config_is_trusted: bool,
60 pub(super) workspace_root: Option<PathBuf>,
61 pub(super) config_file_name: String,
62 pub(crate) layer_stack: ConfigLayerStack,
63 pub(super) phase_timing: Option<ConfigPhaseTiming>,
64}
65
66impl ConfigManager {
67 pub fn load() -> Result<Self> {
69 if let Some(override_path) = session_override::explicit_config_path() {
70 return Self::load_for_session(std::env::current_dir()?, &override_path).with_context(|| {
71 format!("Failed to load configuration from explicit path {}", override_path.display())
72 });
73 }
74
75 Self::load_from_workspace_with_repository_repair(std::env::current_dir()?)
76 }
77
78 pub fn load_for_session(workspace: impl AsRef<Path>, explicit_path: impl AsRef<Path>) -> Result<Self> {
88 let workspace = workspace.as_ref();
89 let explicit_path = explicit_path.as_ref();
90 #[cfg(not(test))]
91 let canonical_workspace = canonicalize_workspace_root(workspace);
92
93 #[cfg(not(test))]
94 if let Some(cached) = cache_get(&canonical_workspace) {
95 return Ok(cached.as_ref().clone());
96 }
97
98 let mut manager = Self::load_from_file_impl(explicit_path, false).with_context(|| {
99 format!(
100 "Failed to load explicit session config file {} (from --config / VTCODE_CONFIG_PATH)",
101 explicit_path.display()
102 )
103 })?;
104 manager.workspace_root = Some(canonicalize_workspace_root(workspace));
107
108 #[cfg(not(test))]
109 cache_insert(canonical_workspace, Arc::new(manager.clone()));
110
111 Ok(manager)
112 }
113
114 pub fn load_global() -> Result<Self> {
120 let defaults_provider = defaults::current_config_defaults();
121 let config_file_name = defaults_provider.config_file_name().to_string();
122 let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
123 let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
124 if let Some(path) = &canonical_user_config_path
125 && !tracked_user_config_paths.iter().any(|existing| existing == path)
126 {
127 tracked_user_config_paths.push(path.clone());
128 }
129
130 let mut layer_sources = Vec::new();
131 for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
132 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
133 }
134 for home_config_path in &tracked_user_config_paths {
135 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
136 }
137
138 let mut layer_stack = ConfigLayerStack::default();
139 for source in layer_sources {
140 if let Some(layer) = Self::load_optional_layer(source) {
141 layer_stack.push(layer);
142 }
143 }
144
145 if let Some((layer, error)) = layer_stack.first_layer_error() {
146 bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
147 }
148
149 let (config, config_path) = if layer_stack.layers().is_empty() {
150 let config = VTCodeConfig::default();
151 config.validate().context("Default configuration failed validation")?;
152 (config, None)
153 } else {
154 let (effective_toml, origins) = layer_stack.effective_config_with_origins();
155 let mut config: VTCodeConfig = effective_toml
156 .try_into()
157 .context("Failed to deserialize effective global configuration")?;
158 Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
159 Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
160 config.validate().context("Global configuration failed validation")?;
161 config.workspace_lifecycle_hooks =
162 Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
163 let config_path = layer_stack
164 .layers()
165 .iter()
166 .rev()
167 .find(|layer| layer.is_enabled())
168 .and_then(|layer| match &layer.source {
169 ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => Some(file.clone()),
170 _ => None,
171 });
172 (config, config_path)
173 };
174
175 Ok(Self {
176 config,
177 config_path,
178 canonical_user_config_path,
179 tracked_user_config_paths,
180 write_global_config_to_canonical: false,
181 explicit_config_is_trusted: false,
182 workspace_root: None,
183 config_file_name,
184 layer_stack,
185 phase_timing: None,
186 })
187 }
188
189 pub fn invalidate_workspace_cache(workspace: impl AsRef<Path>) {
195 let workspace = workspace.as_ref();
196 #[cfg(not(test))]
197 {
198 let canonical_workspace = canonicalize_workspace_root(workspace);
199 cache_remove(&canonical_workspace);
200 }
201 #[cfg(test)]
202 let _ = workspace;
203 }
204
205 pub fn invalidate_all_workspace_cache() {
212 #[cfg(not(test))]
213 with_cache_mut(|map| map.clear());
214 }
215
216 pub fn load_from_workspace(workspace: impl AsRef<Path>) -> Result<Self> {
223 if let Some(override_path) = session_override::explicit_config_path() {
224 return Self::load_for_session(workspace, override_path);
225 }
226
227 let workspace = workspace.as_ref();
228 #[cfg(not(test))]
229 let canonical_workspace = canonicalize_workspace_root(workspace);
230
231 #[cfg(not(test))]
232 if let Some(cached) = cache_get(&canonical_workspace) {
233 return Ok(cached.as_ref().clone());
234 }
235
236 let manager = Self::load_from_workspace_impl(workspace)?;
237
238 #[cfg(not(test))]
239 cache_insert(canonical_workspace, Arc::new(manager.clone()));
240
241 Ok(manager)
242 }
243
244 pub fn load_from_workspace_with_repository_repair(workspace: impl AsRef<Path>) -> Result<Self> {
255 let workspace = workspace.as_ref();
256 let mut error = match Self::load_from_workspace(workspace) {
257 Ok(manager) => return Ok(manager),
258 Err(error) => error,
259 };
260
261 let repository_paths = Self::repository_config_paths(workspace);
265 for _ in 0..=repository_paths.len() {
266 let Some(violation) = error.downcast_ref::<RepositoryProviderSecurityViolation>() else {
267 return Err(error);
268 };
269
270 let source = violation.source.clone();
271 let Some(path) = repository_paths
272 .iter()
273 .find(|candidate| Self::repository_source_matches_path(&source, candidate))
274 else {
275 return Err(error);
276 };
277
278 if !Self::repair_repository_config_file(path)? {
279 return Err(error);
280 }
281
282 tracing::warn!(
283 path = %path.display(),
284 "Removed prohibited provider settings left by an older repository configuration write"
285 );
286
287 Self::invalidate_workspace_cache(workspace);
288 match Self::load_from_workspace(workspace) {
289 Ok(manager) => return Ok(manager),
290 Err(next_error) => error = next_error,
291 }
292 }
293
294 Err(error).context("Failed to load workspace configuration after repairing prohibited provider settings")
295 }
296
297 fn load_from_workspace_impl(workspace: impl AsRef<Path>) -> Result<Self> {
298 let t0 = std::time::Instant::now();
299 let workspace = workspace.as_ref();
300 let defaults_provider = defaults::current_config_defaults();
301 let workspace_paths = defaults_provider.workspace_paths_for(workspace);
302 let workspace_root = canonicalize_workspace_root(workspace_paths.workspace_root());
303 let config_dir = workspace_paths.config_dir();
304 let config_file_name = defaults_provider.config_file_name().to_string();
305 let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
306 let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
307 if let Some(path) = &canonical_user_config_path
308 && !tracked_user_config_paths.iter().any(|existing| existing == path)
309 {
310 tracked_user_config_paths.push(path.clone());
311 }
312 let path_res_duration = t0.elapsed();
313
314 let t1 = std::time::Instant::now();
315
316 let mut layer_sources: Vec<ConfigLayerSource> = Vec::with_capacity(8);
319
320 for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
323 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
324 }
325
326 for home_config_path in &tracked_user_config_paths {
328 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
329 }
330
331 if let Some(project_config_path) = Self::project_config_path(&config_dir, &workspace_root, &config_file_name) {
333 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Project { file: project_config_path });
334 }
335
336 let fallback_path = config_dir.join(&config_file_name);
338 let workspace_config_path = workspace_root.join(&config_file_name);
339 if fallback_path != workspace_config_path {
340 push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Workspace { file: fallback_path });
341 }
342
343 push_unique_layer_source(
345 &mut layer_sources,
346 ConfigLayerSource::Workspace { file: workspace_config_path.clone() },
347 );
348
349 let raw_layers: Vec<Option<ConfigLayerEntry>> = std::thread::scope(|s| {
354 let handles = layer_sources
355 .into_iter()
356 .map(|source| s.spawn(move || Self::load_optional_layer(source)))
357 .collect::<Vec<_>>();
358 let joined = handles.into_iter().map(|h| h.join()).collect::<Vec<_>>();
360 joined
361 .into_iter()
362 .map(|r| r.map_err(|_payload| anyhow::anyhow!("config layer loader thread panicked")))
363 .collect::<Result<Vec<_>>>()
364 })?;
365
366 let mut layer_stack = ConfigLayerStack::default();
367 for layer in raw_layers.into_iter().flatten() {
368 layer_stack.push(layer);
369 }
370
371 let layer_load_duration = t1.elapsed();
372
373 if layer_stack.layers().is_empty() {
375 let t_val = std::time::Instant::now();
376 let config = VTCodeConfig::default();
377 config.validate().context("Default configuration failed validation")?;
378 let val_duration = t_val.elapsed();
379
380 let phase_timing = ConfigPhaseTiming {
381 path_resolution_us: path_res_duration.as_micros() as u64,
382 layer_loading_us: layer_load_duration.as_micros() as u64,
383 merge_and_parse_us: 0,
384 validation_us: val_duration.as_micros() as u64,
385 };
386 tracing::debug!(target: "vtcode_config", ?phase_timing, "Default configuration loaded");
387
388 return Ok(Self {
389 config,
390 config_path: None,
391 canonical_user_config_path,
392 tracked_user_config_paths,
393 write_global_config_to_canonical: false,
394 explicit_config_is_trusted: false,
395 workspace_root: Some(workspace_root),
396 config_file_name,
397 layer_stack,
398 phase_timing: Some(phase_timing),
399 });
400 }
401
402 let use_root_config = layer_stack
406 .layers()
407 .iter()
408 .find(|l| {
409 matches!(
410 &l.source,
411 ConfigLayerSource::Workspace { file }
412 if *file == workspace_config_path
413 )
414 })
415 .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
416 .unwrap_or(false);
417 if use_root_config {
418 layer_stack.retain(|layer| {
419 matches!(
420 &layer.source,
421 ConfigLayerSource::Workspace { file }
422 if *file == workspace_config_path
423 ) || matches!(&layer.source, ConfigLayerSource::Runtime)
424 });
425 if layer_stack.layers().is_empty() {
426 bail!(
427 "workspace.use_root_config is true but no workspace root config was found at {}",
428 workspace_config_path.display()
429 );
430 }
431 }
432
433 if let Some((layer, error)) = layer_stack.first_layer_error() {
434 bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
435 }
436
437 let t2 = std::time::Instant::now();
438 let (effective_toml, origins) = layer_stack.effective_config_with_origins();
439 let mut config: VTCodeConfig = effective_toml
440 .try_into()
441 .context("Failed to deserialize effective configuration")?;
442 let merge_duration = t2.elapsed();
443
444 let t3 = std::time::Instant::now();
445 Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
446 Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
447
448 config.validate().context("Configuration failed validation")?;
449 config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
450
451 migrate_custom_api_keys_if_needed(&mut config)?;
453 let val_duration = t3.elapsed();
454
455 let phase_timing = ConfigPhaseTiming {
456 path_resolution_us: path_res_duration.as_micros() as u64,
457 layer_loading_us: layer_load_duration.as_micros() as u64,
458 merge_and_parse_us: merge_duration.as_micros() as u64,
459 validation_us: val_duration.as_micros() as u64,
460 };
461 tracing::debug!(target: "vtcode_config", ?phase_timing, "Workspace configuration loaded");
462
463 let config_path = layer_stack
464 .layers()
465 .iter()
466 .rev()
467 .find(|layer| layer.is_enabled())
468 .and_then(|l| match &l.source {
469 ConfigLayerSource::User { file } => Some(file.clone()),
470 ConfigLayerSource::Project { file } => Some(file.clone()),
471 ConfigLayerSource::Workspace { file } => Some(file.clone()),
472 ConfigLayerSource::System { file } => Some(file.clone()),
473 ConfigLayerSource::Runtime => None,
474 });
475
476 Ok(Self {
477 config,
478 config_path,
479 canonical_user_config_path,
480 tracked_user_config_paths,
481 write_global_config_to_canonical: false,
482 explicit_config_is_trusted: false,
483 workspace_root: Some(workspace_root),
484 config_file_name,
485 layer_stack,
486 phase_timing: Some(phase_timing),
487 })
488 }
489
490 fn load_toml_from_file(path: &Path) -> Result<toml::Value> {
491 let content =
492 fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
493 Self::parse_layer_value(&content, path)
494 }
495
496 fn parse_layer_value(content: &str, path: &Path) -> Result<toml::Value> {
501 let mut value: toml::Value =
502 toml::from_str(content).with_context(|| format!("Failed to parse config file: {}", path.display()))?;
503 crate::loader::merge::normalize_legacy_top_level_provider_aliases(&mut value);
504 Self::warn_removed_config_keys(&value, path);
505 Ok(value)
506 }
507
508 fn warn_removed_config_keys(value: &toml::Value, path: &Path) {
513 for key_path in removed_config_key_paths_present(value) {
514 let joined = key_path.join(".");
515 tracing::warn!(
516 config = %path.display(),
517 "Configuration key `{joined}` was removed and is ignored; it will be pruned on the next config save."
518 );
519 }
520 }
521
522 fn load_optional_layer(source: ConfigLayerSource) -> Option<ConfigLayerEntry> {
523 let file = match &source {
524 ConfigLayerSource::System { file }
525 | ConfigLayerSource::User { file }
526 | ConfigLayerSource::Project { file }
527 | ConfigLayerSource::Workspace { file } => file,
528 ConfigLayerSource::Runtime => {
529 return Some(ConfigLayerEntry::new(source, toml::Value::Table(toml::Table::new())));
530 }
531 };
532
533 let content = match fs::read_to_string(file) {
535 Ok(content) => content,
536 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
537 Err(err) if should_skip_optional_global_error(&source, &err) => {
538 tracing::debug!(path = %file.display(), "skipping inaccessible optional configuration layer");
539 return None;
540 }
541 Err(err) => {
542 let resolved_file = canonicalize_workspace_root(file);
543 let resolved_source = source.with_file(resolved_file);
544 return Some(Self::disabled_layer_from_error(resolved_source, err.into()));
545 }
546 };
547
548 let resolved_file = canonicalize_workspace_root(file);
549 let parsed = Self::parse_layer_value(&content, &resolved_file);
550 let resolved_source = source.with_file(resolved_file);
551
552 match parsed {
553 Ok(toml) => Some(ConfigLayerEntry::new(resolved_source, toml)),
554 Err(error) => Some(Self::disabled_layer_from_error(resolved_source, error)),
555 }
556 }
557
558 fn disabled_layer_from_error(source: ConfigLayerSource, error: anyhow::Error) -> ConfigLayerEntry {
559 let reason = if error.is::<toml::de::Error>() {
560 LayerDisabledReason::ParseError
561 } else {
562 LayerDisabledReason::LoadError
563 };
564 ConfigLayerEntry::disabled(source, reason, format!("{error:#}"))
565 }
566
567 fn workspace_root_wants_root_config_only(config: &toml::Value) -> bool {
572 config
573 .get("workspace")
574 .and_then(|v| v.get("use_root_config"))
575 .and_then(|v| v.as_bool())
576 .unwrap_or(false)
577 }
578
579 pub fn load_from_file(path: impl AsRef<Path>) -> Result<Self> {
581 Self::load_from_file_impl(path, false)
582 }
583
584 fn load_from_file_impl(path: impl AsRef<Path>, write_global_config_to_canonical: bool) -> Result<Self> {
585 let path = path.as_ref();
586 let defaults_provider = defaults::current_config_defaults();
587 let config_file_name = defaults_provider.config_file_name().to_string();
594 let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
595 let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
596 if let Some(path) = &canonical_user_config_path
597 && !tracked_user_config_paths.iter().any(|existing| existing == path)
598 {
599 tracked_user_config_paths.push(path.clone());
600 }
601
602 let mut layer_stack = ConfigLayerStack::default();
603 let mut global_sources = Vec::new();
604
605 for system_config in defaults_provider.system_config_paths(&config_file_name)? {
606 push_unique_layer_source(&mut global_sources, ConfigLayerSource::System { file: system_config });
607 }
608 for home_config_path in &tracked_user_config_paths {
609 push_unique_layer_source(&mut global_sources, ConfigLayerSource::User { file: home_config_path.clone() });
610 }
611 for source in global_sources {
612 if let Some(layer) = Self::load_optional_layer(source) {
613 layer_stack.push(layer);
614 }
615 }
616
617 let file = path.to_path_buf();
619 match Self::load_toml_from_file(path) {
620 Ok(toml) => layer_stack.push(ConfigLayerEntry::new(ConfigLayerSource::Workspace { file }, toml)),
621 Err(error) => {
622 layer_stack.push(Self::disabled_layer_from_error(ConfigLayerSource::Workspace { file }, error))
623 }
624 }
625
626 let use_root_config = layer_stack
629 .layers()
630 .iter()
631 .find(|l| {
632 matches!(
633 &l.source,
634 ConfigLayerSource::Workspace { file }
635 if *file == path
636 )
637 })
638 .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
639 .unwrap_or(false);
640 if use_root_config {
641 layer_stack.retain(|layer| {
642 matches!(
643 &layer.source,
644 ConfigLayerSource::Workspace { file }
645 if *file == path
646 ) || matches!(&layer.source, ConfigLayerSource::Runtime)
647 });
648 }
649
650 if let Some((layer, error)) = layer_stack.first_layer_error() {
651 bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
652 }
653
654 let (effective_toml, origins) = layer_stack.effective_config_with_origins();
655 let mut config: VTCodeConfig = effective_toml
656 .try_into()
657 .with_context(|| format!("Failed to parse effective config with file: {}", path.display()))?;
658 Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
659 Self::validate_provider_security_fields(&layer_stack, &origins, &config, true)?;
663
664 config
665 .validate()
666 .with_context(|| format!("Failed to validate effective config with file: {}", path.display()))?;
667 config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
668
669 Ok(Self {
670 config,
671 config_path: Some(canonicalize_workspace_root(path)),
672 canonical_user_config_path,
673 tracked_user_config_paths,
674 write_global_config_to_canonical,
675 explicit_config_is_trusted: true,
676 workspace_root: path.parent().map(canonicalize_workspace_root),
677 config_file_name,
678 layer_stack,
679 phase_timing: None,
680 })
681 }
682
683 pub fn current_project_name(workspace_root: &Path) -> Option<String> {
685 Self::identify_current_project(workspace_root)
686 }
687
688 fn validate_restricted_agent_fields(
689 layer_stack: &ConfigLayerStack,
690 origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
691 ) -> Result<()> {
692 if let Some(origin) = origins.get("agent.persistent_memory.directory_override")
693 && let Some(layer) = layer_stack.layers().iter().find(|layer| layer.metadata == *origin)
694 {
695 match layer.source {
696 ConfigLayerSource::System { .. }
697 | ConfigLayerSource::User { .. }
698 | ConfigLayerSource::Project { .. } => {}
699 ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Runtime => {
700 bail!(
701 "agent.persistent_memory.directory_override may only be set in system, user, or project-profile configuration layers"
702 );
703 }
704 }
705 }
706
707 Ok(())
708 }
709
710 fn validate_provider_security_fields(
719 layer_stack: &ConfigLayerStack,
720 origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
721 config: &VTCodeConfig,
722 explicit_config_is_trusted: bool,
723 ) -> Result<()> {
724 if explicit_config_is_trusted {
725 return Ok(());
726 }
727
728 if !config.custom_providers.is_empty()
729 && let Some(origin) = origins.get("custom_providers")
730 && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
731 && Self::is_repository_controlled_source(&layer.source)
732 {
733 return Err(RepositoryProviderSecurityViolation {
734 source: layer.source.clone(),
735 message: format!(
736 "repository-controlled configuration cannot define `custom_providers` (including `auth.command`); move custom provider settings to system, user, or an explicitly selected config file (source: {})",
737 layer.source.label()
738 ),
739 }
740 .into());
741 }
742
743 for (path, origin) in origins {
744 if path == "auth.copilot.command"
745 && config
746 .auth
747 .copilot
748 .command
749 .as_deref()
750 .is_some_and(|command| !command.trim().is_empty())
751 && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
752 && Self::is_repository_controlled_source(&layer.source)
753 {
754 bail!(
755 "repository-controlled configuration cannot set `auth.copilot.command`; configure it in system, user, or an explicitly selected config file (source: {})",
756 layer.source.label()
757 );
758 }
759 if !Self::is_provider_endpoint_or_credential_path(path) {
760 continue;
761 }
762
763 let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
764 continue;
765 };
766 if Self::is_repository_controlled_source(&layer.source) {
767 return Err(RepositoryProviderSecurityViolation {
768 source: layer.source.clone(),
769 message: format!(
770 "repository-controlled configuration cannot set `{path}`; provider endpoints and credential environment variables must be configured in system, user, or an explicitly selected config file (source: {})",
771 layer.source.label()
772 ),
773 }
774 .into());
775 }
776 }
777
778 Ok(())
779 }
780
781 fn enabled_layer_for_origin<'a>(
782 layer_stack: &'a ConfigLayerStack,
783 origin: &ConfigLayerMetadata,
784 ) -> Option<&'a ConfigLayerEntry> {
785 layer_stack
786 .layers()
787 .iter()
788 .find(|layer| layer.is_enabled() && layer.metadata == *origin)
789 }
790
791 fn is_repository_controlled_source(source: &ConfigLayerSource) -> bool {
792 matches!(source, ConfigLayerSource::Project { .. } | ConfigLayerSource::Workspace { .. })
793 }
794
795 fn is_provider_endpoint_or_credential_path(path: &str) -> bool {
796 let mut segments = path.split('.');
797 matches!(segments.next(), Some("provider_overrides"))
798 && segments.next().is_some()
799 && matches!(segments.next(), Some("base_url" | "api_key_env"))
800 && segments.next().is_none()
801 }
802
803 pub(crate) fn collect_workspace_lifecycle_hooks(
809 layer_stack: &ConfigLayerStack,
810 hooks: &HooksConfig,
811 ) -> WorkspaceLifecycleHooks {
812 let (_, origins) = layer_stack.effective_config_with_origins();
813 let mut commands = Vec::new();
814
815 for event in crate::hooks::LIFECYCLE_HOOK_EVENTS {
816 let origin_key = format!("hooks.lifecycle.{event}");
817 let Some(origin) = origins.get(&origin_key) else {
818 continue;
819 };
820 let workspace_controlled = layer_stack.layers().iter().any(|layer| {
821 layer.is_enabled()
822 && layer.metadata == *origin
823 && matches!(layer.source, ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Project { .. })
824 });
825 if !workspace_controlled {
826 continue;
827 }
828
829 let tag = match *event {
831 "task_completion" | "task_completed" => "stop",
832 other => other,
833 };
834 for group in hooks.lifecycle.groups_for_event(event) {
835 for command in &group.hooks {
836 commands.push(WorkspaceHookCommand {
837 event: tag.to_string(),
838 matcher: group.matcher.clone(),
839 command: command.command.clone(),
840 timeout_seconds: command.timeout_seconds,
841 });
842 }
843 }
844 }
845
846 WorkspaceLifecycleHooks { commands }
847 }
848}
849
850const REMOVED_CONFIG_KEY_PATHS: &[&[&str]] = &[
853 &["agent", "harness", "max_tool_calls_per_turn"],
854 &["tools", "max_tool_loops"],
855 &["automation", "full_auto", "auto_grant_tool_limits"],
856];
857
858pub(super) fn removed_config_key_paths_present(value: &toml::Value) -> Vec<&'static [&'static str]> {
859 REMOVED_CONFIG_KEY_PATHS
860 .iter()
861 .copied()
862 .filter(|key_path| key_path.iter().try_fold(value, |cursor, key| cursor.get(*key)).is_some())
863 .collect()
864}
865
866#[cfg(test)]
867mod sparse_config_tests;
868#[cfg(test)]
869mod workspace_lifecycle_hooks_tests;