1use indexmap::IndexMap;
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11use serde_ignored::Path as IgnoredPath;
12
13use crate::alias::ModelAlias;
14use crate::dependency::RawEntry;
15use crate::diagnostic::{PathSegment, SchemaDiagnostic, unknown_field};
16use crate::keys;
17use crate::model_policy::ModelPolicyRule;
18use crate::names::SourceName;
19use crate::network::{NetworkHost, NetworkPolicy};
20use crate::package::PackageMetadata as PackageInfo;
21use crate::permission_set::PermissionSet;
22use crate::tool_rule_map::ToolRuleMap;
23
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
26pub struct Config {
27 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub package: Option<PackageInfo>,
29 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub plugin: Option<toml::Value>,
31 #[serde(default)]
32 pub dependencies: IndexMap<SourceName, RawEntry>,
33 #[serde(
37 default,
38 skip_serializing_if = "IndexMap::is_empty",
39 rename = "local-dependencies"
40 )]
41 pub local_dependencies: IndexMap<SourceName, RawEntry>,
42 #[serde(default)]
43 pub settings: Settings,
44 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
45 pub models: IndexMap<String, ModelAlias>,
46 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
47 pub agents: IndexMap<String, AgentOverlay>,
48 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
49 pub skills: IndexMap<String, SkillOverlay>,
50 #[serde(skip)]
52 pub unknown_keys: Vec<SchemaDiagnostic>,
53 #[serde(skip)]
55 pub floor: Option<keys::Floor>,
56}
57
58fn overlay_value<'de, D: serde::Deserializer<'de>>(
61 deserializer: D,
62 key: &str,
63 valid: fn(&str) -> bool,
64 allowed: &str,
65) -> Result<Option<String>, D::Error> {
66 let value = Option::<String>::deserialize(deserializer)?;
67 match value {
68 Some(value) if !valid(&value) => Err(serde::de::Error::custom(format!(
69 "`{key}` has invalid value `{value}`; allowed: {allowed}"
70 ))),
71 value => Ok(value),
72 }
73}
74
75fn overlay_effort<'de, D: serde::Deserializer<'de>>(
78 deserializer: D,
79) -> Result<Option<crate::agent::EffortRequest>, D::Error> {
80 use crate::agent::EffortRequest;
81 let Some(value) = Option::<String>::deserialize(deserializer)? else {
82 return Ok(None);
83 };
84 if let Some(request) = EffortRequest::parse(&value) {
85 return Ok(Some(request));
86 }
87 Err(serde::de::Error::custom(format!(
88 "`effort` has invalid value `{value}`; allowed: {}",
89 EffortRequest::ALLOWED
90 )))
91}
92
93fn overlay_approval<'de, D: serde::Deserializer<'de>>(
94 deserializer: D,
95) -> Result<Option<String>, D::Error> {
96 use crate::agent::ApprovalMode;
97 overlay_value(
98 deserializer,
99 "approval",
100 |value| ApprovalMode::parse(value).is_some(),
101 ApprovalMode::ALLOWED,
102 )
103}
104
105fn overlay_sandbox<'de, D: serde::Deserializer<'de>>(
106 deserializer: D,
107) -> Result<Option<String>, D::Error> {
108 use crate::agent::SandboxMode;
109 overlay_value(
110 deserializer,
111 "sandbox",
112 |value| SandboxMode::parse(value).is_some(),
113 SandboxMode::ALLOWED,
114 )
115}
116
117#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
119pub struct AgentOverlay {
120 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub description: Option<String>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub model: Option<String>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub harness: Option<String>,
126 #[serde(
127 default,
128 deserialize_with = "overlay_effort",
129 skip_serializing_if = "Option::is_none"
130 )]
131 pub effort: Option<crate::agent::EffortRequest>,
132 #[serde(
133 default,
134 deserialize_with = "overlay_approval",
135 skip_serializing_if = "Option::is_none"
136 )]
137 pub approval: Option<String>,
138 #[serde(
139 default,
140 deserialize_with = "overlay_sandbox",
141 skip_serializing_if = "Option::is_none"
142 )]
143 pub sandbox: Option<String>,
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub network: Option<NetworkPolicy>,
146 #[serde(
147 default,
148 rename = "network-allow",
149 alias = "network_allow",
150 skip_serializing_if = "PermissionSet::is_noop"
151 )]
152 pub network_allow: PermissionSet<NetworkHost>,
153 #[serde(
154 default,
155 rename = "network-deny",
156 alias = "network_deny",
157 skip_serializing_if = "PermissionSet::is_noop"
158 )]
159 pub network_deny: PermissionSet<NetworkHost>,
160 #[serde(
161 default,
162 rename = "model-invocable",
163 alias = "model_invocable",
164 skip_serializing_if = "Option::is_none"
165 )]
166 pub model_invocable: Option<bool>,
167 #[serde(
168 default,
169 rename = "user-invocable",
170 alias = "user_invocable",
171 skip_serializing_if = "Option::is_none"
172 )]
173 pub user_invocable: Option<bool>,
174 #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
175 pub tools: ToolRuleMap,
176 #[serde(
177 default,
178 rename = "model-policies",
179 skip_serializing_if = "Option::is_none"
180 )]
181 pub model_policies: Option<Vec<ModelPolicyRule>>,
182}
183
184#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
186pub struct SkillOverlay {
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub description: Option<String>,
189 #[serde(
190 default,
191 rename = "model-invocable",
192 alias = "model_invocable",
193 skip_serializing_if = "Option::is_none"
194 )]
195 pub model_invocable: Option<bool>,
196 #[serde(
197 default,
198 rename = "user-invocable",
199 alias = "user_invocable",
200 skip_serializing_if = "Option::is_none"
201 )]
202 pub user_invocable: Option<bool>,
203}
204
205impl SkillOverlay {
206 pub fn is_empty(&self) -> bool {
207 self.description.is_none()
208 && self.model_invocable.is_none()
209 && self.user_invocable.is_none()
210 }
211}
212
213#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
215pub struct Settings {
216 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub managed_root: Option<String>,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub targets: Option<Vec<String>>,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub models_cache_ttl_hours: Option<u32>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
232 pub min_mars_version: Option<String>,
233 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub default_harness: Option<String>,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub default_model: Option<String>,
239 #[serde(
241 default,
242 alias = "default-network",
243 skip_serializing_if = "Option::is_none"
244 )]
245 pub default_network: Option<NetworkPolicy>,
246 #[serde(
247 default,
248 rename = "network-allow",
249 alias = "network_allow",
250 skip_serializing_if = "PermissionSet::is_noop"
251 )]
252 pub network_allow: PermissionSet<NetworkHost>,
253 #[serde(
254 default,
255 rename = "network-deny",
256 alias = "network_deny",
257 skip_serializing_if = "PermissionSet::is_noop"
258 )]
259 pub network_deny: PermissionSet<NetworkHost>,
260 #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
262 pub tools: ToolRuleMap,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub harness_order: Option<Vec<String>>,
270 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub provider_order: Option<Vec<String>>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub catalog_providers: Option<Vec<String>>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub agent_emission: Option<AgentEmission>,
291 #[serde(default, skip_serializing_if = "MeridianSettings::is_empty")]
292 pub meridian: MeridianSettings,
293 #[serde(
294 default,
295 rename = "model-policies",
296 skip_serializing_if = "Option::is_none"
297 )]
298 pub model_policies: Option<Vec<ModelPolicyRule>>,
299}
300
301#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
303pub struct AgentCopyConfig {
304 #[serde(default)]
305 pub harnesses: Vec<String>,
306 #[serde(default)]
307 pub include_fanout: bool,
308}
309
310#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
312pub struct FanoutConfig {
313 #[serde(default)]
314 pub agents: Vec<String>,
315}
316
317#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
319pub struct MeridianSettings {
320 #[serde(default, skip_serializing_if = "Option::is_none")]
321 pub agent_copy: Option<AgentCopyConfig>,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub fanout: Option<FanoutConfig>,
324}
325
326impl MeridianSettings {
327 pub fn is_empty(&self) -> bool {
328 self.agent_copy.is_none() && self.fanout.is_none()
329 }
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
333#[serde(rename_all = "lowercase")]
334pub enum AgentEmission {
335 Auto,
336 Always,
337 Never,
338}
339
340const DEFAULT_MODELS_CACHE_TTL_HOURS: u32 = 24;
341
342impl Settings {
343 pub fn models_cache_ttl_hours(&self) -> u32 {
344 self.models_cache_ttl_hours
345 .unwrap_or(DEFAULT_MODELS_CACHE_TTL_HOURS)
346 }
347
348 pub fn model_policies(&self) -> &[ModelPolicyRule] {
349 self.model_policies.as_deref().unwrap_or_default()
350 }
351
352 pub fn meridian_agent_copy(&self) -> Option<&AgentCopyConfig> {
354 self.meridian.agent_copy.as_ref()
355 }
356
357 pub fn network_keys(&self) -> Vec<(&'static str, bool)> {
360 [
361 (
362 "default-network",
363 self.default_network
364 .as_ref()
365 .map(|policy| *policy != crate::network::NetworkPolicy::Allow),
366 ),
367 (
368 "network-allow",
369 (!self.network_allow.entries().is_empty()).then_some(true),
370 ),
371 (
372 "network-deny",
373 (!self.network_deny.entries().is_empty()).then_some(true),
374 ),
375 ]
376 .into_iter()
377 .filter_map(|(key, restricts)| restricts.map(|restricts| (key, restricts)))
378 .collect()
379 }
380
381 pub fn meridian_fanout_agents(&self) -> &[String] {
383 self.meridian
384 .fanout
385 .as_ref()
386 .map(|f| f.agents.as_slice())
387 .unwrap_or(&[])
388 }
389}
390
391impl Config {
392 pub fn dependency_unknown_keys(&self) -> Vec<SchemaDiagnostic> {
394 [
395 ("dependencies", &self.dependencies),
396 ("local-dependencies", &self.local_dependencies),
397 ]
398 .into_iter()
399 .flat_map(|(table, dependencies)| {
400 dependencies.iter().flat_map(move |(name, entry)| {
401 entry.unknown.keys().map(move |key| {
402 let path = vec![
403 PathSegment::Key(table.to_owned()),
404 PathSegment::Key(name.to_string()),
405 PathSegment::Key(key.clone()),
406 ];
407 unknown_field(path, &format!("{table}.{name}"), key)
408 })
409 })
410 })
411 .collect()
412 }
413}
414
415pub struct Read<T> {
418 pub value: T,
419 pub unknown_keys: Vec<SchemaDiagnostic>,
420 pub floor: Option<keys::Floor>,
421}
422
423pub fn read<T: DeserializeOwned>(
425 content: &str,
426 document: keys::Document,
427) -> Result<Read<T>, toml::de::Error> {
428 let mut ignored = Vec::new();
429 let value = serde_ignored::deserialize(toml::Deserializer::new(content), |at| {
430 ignored.push(segments(&at));
431 })?;
432 let mut unknown_keys = unknown_notes(ignored, &[]);
433 let table = content.parse::<toml::Table>().ok();
434 unknown_keys.extend(table.iter().flat_map(crate::retired::config_notes));
435 let floor = table.and_then(|table| keys::floor(keys::used(&table, document)));
436 Ok(Read {
437 value,
438 unknown_keys,
439 floor,
440 })
441}
442
443fn unknown_notes(ignored: Vec<Vec<PathSegment>>, prefix: &[PathSegment]) -> Vec<SchemaDiagnostic> {
446 let mut notes = Vec::new();
447 for at in ignored {
448 let mut at: Vec<PathSegment> = prefix.iter().cloned().chain(at).collect();
449 let Some(PathSegment::Key(key)) = at.pop() else {
450 continue;
451 };
452 if matches!(at.first(), Some(PathSegment::Key(table)) if table == "package" || table == "plugin")
454 {
455 continue;
456 }
457 let table = table_name(&at);
458 let mut path = at;
459 path.push(PathSegment::Key(key.clone()));
460 notes.push(unknown_field(path, &table, &key));
461 }
462 notes
463}
464
465#[derive(Debug, Clone, PartialEq, Eq)]
467pub struct ConfigIssue {
468 pub path: Vec<PathSegment>,
469 pub message: String,
470}
471
472pub struct ConsumerRead {
474 pub config: Config,
478 pub issues: Vec<ConfigIssue>,
481 pub parse_error: Option<toml::de::Error>,
484}
485
486pub fn read_consumer(content: &str) -> ConsumerRead {
490 match read::<Config>(content, keys::Document::Consumer) {
491 Ok(read) => {
492 let mut config = read.value;
493 config.unknown_keys = read.unknown_keys;
494 config.unknown_keys.extend(config.dependency_unknown_keys());
495 config.floor = read.floor;
496 let issues = settings_refusals(
497 Some(&config.settings.tools),
498 config.settings.min_mars_version.as_deref(),
499 );
500 ConsumerRead {
501 config,
502 issues,
503 parse_error: None,
504 }
505 }
506 Err(error) => {
507 let (config, issues) = read_tables(content, &error);
508 ConsumerRead {
509 config,
510 issues,
511 parse_error: Some(error),
512 }
513 }
514 }
515}
516
517fn key_path(parts: &[&str]) -> Vec<PathSegment> {
518 parts
519 .iter()
520 .map(|part| PathSegment::Key((*part).to_owned()))
521 .collect()
522}
523
524fn read_tables(content: &str, whole: &toml::de::Error) -> (Config, Vec<ConfigIssue>) {
528 let mut config = Config::default();
529 let Ok(table) = content.parse::<toml::Table>() else {
530 let issue = ConfigIssue {
531 path: Vec::new(),
532 message: whole.to_string(),
533 };
534 return (config, vec![issue]);
535 };
536 let mut issues = Vec::new();
537 let mut unknown = Vec::new();
538 config.floor = keys::floor(keys::used(&table, keys::Document::Consumer));
539 config.plugin = table.get("plugin").cloned();
540 unknown.extend(crate::retired::config_notes(&table));
541 if let Some(value) = table.get("settings") {
542 match read_value::<Settings>(value, key_path(&["settings"]), &mut unknown) {
543 Ok(settings) => {
544 issues.extend(settings_refusals(
545 Some(&settings.tools),
546 settings.min_mars_version.as_deref(),
547 ));
548 config.settings = settings;
549 }
550 Err(issue) => issues.push(issue),
551 }
552 }
553 config.models = read_entries(&table, "models", &mut unknown, &mut issues);
554 config.agents = read_entries(&table, "agents", &mut unknown, &mut issues);
555 config.skills = read_entries(&table, "skills", &mut unknown, &mut issues);
556 config.dependencies = read_dependency_entries(&table, "dependencies", &mut unknown);
557 config.local_dependencies = read_dependency_entries(&table, "local-dependencies", &mut unknown);
558 config.unknown_keys = unknown;
559 config.unknown_keys.extend(config.dependency_unknown_keys());
560 (config, issues)
561}
562
563fn read_value<T: DeserializeOwned>(
564 value: &toml::Value,
565 at: Vec<PathSegment>,
566 unknown: &mut Vec<SchemaDiagnostic>,
567) -> Result<T, ConfigIssue> {
568 let mut ignored = Vec::new();
569 match serde_ignored::deserialize(value.clone(), |path| ignored.push(segments(&path))) {
570 Ok(read) => {
571 unknown.extend(unknown_notes(ignored, &at));
572 Ok(read)
573 }
574 Err(error) => Err(ConfigIssue {
575 path: at,
576 message: error.to_string().trim_end().to_owned(),
577 }),
578 }
579}
580
581fn read_entries<T: DeserializeOwned>(
583 table: &toml::Table,
584 key: &str,
585 unknown: &mut Vec<SchemaDiagnostic>,
586 issues: &mut Vec<ConfigIssue>,
587) -> IndexMap<String, T> {
588 let mut entries = IndexMap::new();
589 match table.get(key) {
590 None => {}
591 Some(toml::Value::Table(named)) => {
592 for (name, value) in named {
593 match read_value(value, key_path(&[key, name]), unknown) {
594 Ok(entry) => {
595 entries.insert(name.clone(), entry);
596 }
597 Err(issue) => issues.push(issue),
598 }
599 }
600 }
601 Some(_) => issues.push(ConfigIssue {
602 path: key_path(&[key]),
603 message: format!("`{key}` must be a table"),
604 }),
605 }
606 entries
607}
608
609fn read_dependency_entries(
610 table: &toml::Table,
611 key: &str,
612 unknown: &mut Vec<SchemaDiagnostic>,
613) -> IndexMap<SourceName, RawEntry> {
614 let mut entries = IndexMap::new();
615 let Some(toml::Value::Table(named)) = table.get(key) else {
616 return entries;
617 };
618 for (name, value) in named {
619 let Ok(source) = toml::Value::String(name.clone()).try_into::<SourceName>() else {
620 continue;
621 };
622 if let Ok(entry) = read_value(value, key_path(&[key, name]), unknown) {
623 entries.insert(source, entry);
624 }
625 }
626 entries
627}
628
629pub fn read_models(content: &str) -> Result<IndexMap<String, ModelAlias>, toml::de::Error> {
632 #[derive(Deserialize)]
633 struct Models {
634 #[serde(default)]
635 models: IndexMap<String, ModelAlias>,
636 }
637 toml::from_str::<Models>(content).map(|parsed| parsed.models)
638}
639
640pub fn settings_refusals(
645 tools: Option<&ToolRuleMap>,
646 min_mars_version: Option<&str>,
647) -> Vec<ConfigIssue> {
648 let tools = tools
649 .and_then(|tools| {
650 tools.wildcard_refusal(
651 "[settings.tools]",
652 "`approval` is the default for calls no rule matches",
653 )
654 })
655 .map(|message| ConfigIssue {
656 path: key_path(&["settings", "tools"]),
657 message,
658 });
659 let min = min_mars_version
660 .and_then(|raw| parse_min_mars_version(raw).err())
661 .map(|message| ConfigIssue {
662 path: key_path(&["settings", "min_mars_version"]),
663 message,
664 });
665 tools.into_iter().chain(min).collect()
666}
667
668pub fn parse_min_mars_version(raw: &str) -> Result<semver::VersionReq, String> {
672 crate::package::parse_requirement(raw).map_err(|error| {
673 format!("`min_mars_version = \"{raw}\"` is not a version requirement: {error}")
674 })
675}
676
677fn segments(at: &IgnoredPath<'_>) -> Vec<PathSegment> {
678 match at {
679 IgnoredPath::Root => Vec::new(),
680 IgnoredPath::Seq { parent, index } => {
681 let mut out = segments(parent);
682 out.push(PathSegment::Index(*index));
683 out
684 }
685 IgnoredPath::Map { parent, key } => {
686 let mut out = segments(parent);
687 out.push(PathSegment::Key(key.clone()));
688 out
689 }
690 IgnoredPath::Some { parent }
691 | IgnoredPath::NewtypeStruct { parent }
692 | IgnoredPath::NewtypeVariant { parent } => segments(parent),
693 }
694}
695
696fn table_name(at: &[PathSegment]) -> String {
698 let mut name = String::new();
699 for segment in at {
700 match segment {
701 PathSegment::Key(key) => {
702 if !name.is_empty() {
703 name.push('.');
704 }
705 name.push_str(key);
706 }
707 PathSegment::Index(index) => name.push_str(&format!("[{index}]")),
708 }
709 }
710 name
711}