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, ModelsItem};
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")]
125 pub model: Option<String>,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub models: Option<Vec<ModelsItem>>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub harness: Option<String>,
132 #[serde(
133 default,
134 deserialize_with = "overlay_effort",
135 skip_serializing_if = "Option::is_none"
136 )]
137 pub effort: Option<crate::agent::EffortRequest>,
138 #[serde(
139 default,
140 deserialize_with = "overlay_approval",
141 skip_serializing_if = "Option::is_none"
142 )]
143 pub approval: Option<String>,
144 #[serde(
145 default,
146 deserialize_with = "overlay_sandbox",
147 skip_serializing_if = "Option::is_none"
148 )]
149 pub sandbox: Option<String>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub network: Option<NetworkPolicy>,
152 #[serde(
153 default,
154 rename = "network-allow",
155 alias = "network_allow",
156 skip_serializing_if = "PermissionSet::is_noop"
157 )]
158 pub network_allow: PermissionSet<NetworkHost>,
159 #[serde(
160 default,
161 rename = "network-deny",
162 alias = "network_deny",
163 skip_serializing_if = "PermissionSet::is_noop"
164 )]
165 pub network_deny: PermissionSet<NetworkHost>,
166 #[serde(
167 default,
168 rename = "model-invocable",
169 alias = "model_invocable",
170 skip_serializing_if = "Option::is_none"
171 )]
172 pub model_invocable: Option<bool>,
173 #[serde(
174 default,
175 rename = "user-invocable",
176 alias = "user_invocable",
177 skip_serializing_if = "Option::is_none"
178 )]
179 pub user_invocable: Option<bool>,
180 #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
181 pub tools: ToolRuleMap,
182 #[serde(
183 default,
184 rename = "model-policies",
185 skip_serializing_if = "Option::is_none"
186 )]
187 pub model_policies: Option<Vec<ModelPolicyRule>>,
188}
189
190#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
192pub struct SkillOverlay {
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub description: Option<String>,
195 #[serde(
196 default,
197 rename = "model-invocable",
198 alias = "model_invocable",
199 skip_serializing_if = "Option::is_none"
200 )]
201 pub model_invocable: Option<bool>,
202 #[serde(
203 default,
204 rename = "user-invocable",
205 alias = "user_invocable",
206 skip_serializing_if = "Option::is_none"
207 )]
208 pub user_invocable: Option<bool>,
209}
210
211impl SkillOverlay {
212 pub fn is_empty(&self) -> bool {
213 self.description.is_none()
214 && self.model_invocable.is_none()
215 && self.user_invocable.is_none()
216 }
217}
218
219#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
221pub struct Settings {
222 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub managed_root: Option<String>,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub targets: Option<Vec<String>>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub models_cache_ttl_hours: Option<u32>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub min_mars_version: Option<String>,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub default_harness: Option<String>,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub default_model: Option<String>,
245 #[serde(
247 default,
248 alias = "default-network",
249 skip_serializing_if = "Option::is_none"
250 )]
251 pub default_network: Option<NetworkPolicy>,
252 #[serde(
253 default,
254 rename = "network-allow",
255 alias = "network_allow",
256 skip_serializing_if = "PermissionSet::is_noop"
257 )]
258 pub network_allow: PermissionSet<NetworkHost>,
259 #[serde(
260 default,
261 rename = "network-deny",
262 alias = "network_deny",
263 skip_serializing_if = "PermissionSet::is_noop"
264 )]
265 pub network_deny: PermissionSet<NetworkHost>,
266 #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
268 pub tools: ToolRuleMap,
269 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub harness_order: Option<Vec<String>>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub provider_order: Option<Vec<String>>,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub catalog_providers: Option<Vec<String>>,
290 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub agent_emission: Option<AgentEmission>,
297 #[serde(default, skip_serializing_if = "MeridianSettings::is_empty")]
298 pub meridian: MeridianSettings,
299 #[serde(
300 default,
301 rename = "model-policies",
302 skip_serializing_if = "Option::is_none"
303 )]
304 pub model_policies: Option<Vec<ModelPolicyRule>>,
305}
306
307#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
309pub struct AgentCopyConfig {
310 #[serde(default)]
311 pub harnesses: Vec<String>,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub include_fanout: Option<bool>,
315}
316
317#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
319pub struct FanoutConfig {
320 #[serde(default)]
321 pub agents: Vec<String>,
322}
323
324#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
326pub struct MeridianSettings {
327 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub agent_copy: Option<AgentCopyConfig>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub fanout: Option<FanoutConfig>,
331}
332
333impl MeridianSettings {
334 pub fn is_empty(&self) -> bool {
335 self.agent_copy.is_none() && self.fanout.is_none()
336 }
337}
338
339#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
340#[serde(rename_all = "lowercase")]
341pub enum AgentEmission {
342 Auto,
343 Always,
344 Never,
345}
346
347const DEFAULT_MODELS_CACHE_TTL_HOURS: u32 = 24;
348
349impl Settings {
350 pub fn models_cache_ttl_hours(&self) -> u32 {
351 self.models_cache_ttl_hours
352 .unwrap_or(DEFAULT_MODELS_CACHE_TTL_HOURS)
353 }
354
355 pub fn model_policies(&self) -> &[ModelPolicyRule] {
356 self.model_policies.as_deref().unwrap_or_default()
357 }
358
359 pub fn meridian_agent_copy(&self) -> Option<&AgentCopyConfig> {
361 self.meridian.agent_copy.as_ref()
362 }
363
364 pub fn network_keys(&self) -> Vec<(&'static str, bool)> {
367 [
368 (
369 "default-network",
370 self.default_network
371 .as_ref()
372 .map(|policy| *policy != crate::network::NetworkPolicy::Allow),
373 ),
374 (
375 "network-allow",
376 (!self.network_allow.entries().is_empty()).then_some(true),
377 ),
378 (
379 "network-deny",
380 (!self.network_deny.entries().is_empty()).then_some(true),
381 ),
382 ]
383 .into_iter()
384 .filter_map(|(key, restricts)| restricts.map(|restricts| (key, restricts)))
385 .collect()
386 }
387
388 pub fn meridian_fanout_agents(&self) -> &[String] {
390 self.meridian
391 .fanout
392 .as_ref()
393 .map(|f| f.agents.as_slice())
394 .unwrap_or(&[])
395 }
396}
397
398impl Config {
399 pub fn dependency_unknown_keys(&self) -> Vec<SchemaDiagnostic> {
401 [
402 ("dependencies", &self.dependencies),
403 ("local-dependencies", &self.local_dependencies),
404 ]
405 .into_iter()
406 .flat_map(|(table, dependencies)| {
407 dependencies.iter().flat_map(move |(name, entry)| {
408 entry.unknown.keys().map(move |key| {
409 let path = vec![
410 PathSegment::Key(table.to_owned()),
411 PathSegment::Key(name.to_string()),
412 PathSegment::Key(key.clone()),
413 ];
414 unknown_field(path, &format!("{table}.{name}"), key)
415 })
416 })
417 })
418 .collect()
419 }
420}
421
422pub struct Read<T> {
425 pub value: T,
426 pub unknown_keys: Vec<SchemaDiagnostic>,
427 pub floor: Option<keys::Floor>,
428}
429
430pub fn read<T: DeserializeOwned>(
432 content: &str,
433 document: keys::Document,
434) -> Result<Read<T>, toml::de::Error> {
435 let mut ignored = Vec::new();
436 let value = serde_ignored::deserialize(toml::Deserializer::new(content), |at| {
437 ignored.push(segments(&at));
438 })?;
439 let mut unknown_keys = unknown_notes(ignored, &[]);
440 let table = content.parse::<toml::Table>().ok();
441 unknown_keys.extend(table.iter().flat_map(crate::retired::config_notes));
442 let floor = table.and_then(|table| keys::floor(keys::used(&table, document)));
443 Ok(Read {
444 value,
445 unknown_keys,
446 floor,
447 })
448}
449
450fn unknown_notes(ignored: Vec<Vec<PathSegment>>, prefix: &[PathSegment]) -> Vec<SchemaDiagnostic> {
453 let mut notes = Vec::new();
454 for at in ignored {
455 let mut at: Vec<PathSegment> = prefix.iter().cloned().chain(at).collect();
456 let Some(PathSegment::Key(key)) = at.pop() else {
457 continue;
458 };
459 if matches!(at.first(), Some(PathSegment::Key(table)) if table == "package" || table == "plugin")
461 {
462 continue;
463 }
464 let table = table_name(&at);
465 let mut path = at;
466 path.push(PathSegment::Key(key.clone()));
467 notes.push(unknown_field(path, &table, &key));
468 }
469 notes
470}
471
472#[derive(Debug, Clone, PartialEq, Eq)]
474pub struct ConfigIssue {
475 pub path: Vec<PathSegment>,
476 pub message: String,
477}
478
479pub struct ConsumerRead {
481 pub config: Config,
485 pub issues: Vec<ConfigIssue>,
488 pub parse_error: Option<toml::de::Error>,
491}
492
493pub fn read_consumer(content: &str) -> ConsumerRead {
497 match read::<Config>(content, keys::Document::Consumer) {
498 Ok(read) => {
499 let mut config = read.value;
500 config.unknown_keys = read.unknown_keys;
501 config.unknown_keys.extend(config.dependency_unknown_keys());
502 config.floor = read.floor;
503 let mut issues = settings_refusals(
504 Some(&config.settings.tools),
505 config.settings.min_mars_version.as_deref(),
506 );
507 issues.extend(agent_overlay_refusals(&config.agents));
508 ConsumerRead {
509 config,
510 issues,
511 parse_error: None,
512 }
513 }
514 Err(error) => {
515 let (config, issues) = read_tables(content, &error);
516 ConsumerRead {
517 config,
518 issues,
519 parse_error: Some(error),
520 }
521 }
522 }
523}
524
525fn key_path(parts: &[&str]) -> Vec<PathSegment> {
526 parts
527 .iter()
528 .map(|part| PathSegment::Key((*part).to_owned()))
529 .collect()
530}
531
532fn read_tables(content: &str, whole: &toml::de::Error) -> (Config, Vec<ConfigIssue>) {
536 let mut config = Config::default();
537 let Ok(table) = content.parse::<toml::Table>() else {
538 let issue = ConfigIssue {
539 path: Vec::new(),
540 message: whole.to_string(),
541 };
542 return (config, vec![issue]);
543 };
544 let mut issues = Vec::new();
545 let mut unknown = Vec::new();
546 config.floor = keys::floor(keys::used(&table, keys::Document::Consumer));
547 config.plugin = table.get("plugin").cloned();
548 unknown.extend(crate::retired::config_notes(&table));
549 if let Some(value) = table.get("settings") {
550 match read_value::<Settings>(value, key_path(&["settings"]), &mut unknown) {
551 Ok(settings) => {
552 issues.extend(settings_refusals(
553 Some(&settings.tools),
554 settings.min_mars_version.as_deref(),
555 ));
556 config.settings = settings;
557 }
558 Err(issue) => issues.push(issue),
559 }
560 }
561 config.models = read_entries(&table, "models", &mut unknown, &mut issues);
562 config.agents = read_entries(&table, "agents", &mut unknown, &mut issues);
563 issues.extend(agent_overlay_refusals(&config.agents));
564 config.skills = read_entries(&table, "skills", &mut unknown, &mut issues);
565 config.dependencies = read_dependency_entries(&table, "dependencies", &mut unknown);
566 config.local_dependencies = read_dependency_entries(&table, "local-dependencies", &mut unknown);
567 config.unknown_keys = unknown;
568 config.unknown_keys.extend(config.dependency_unknown_keys());
569 (config, issues)
570}
571
572fn read_value<T: DeserializeOwned>(
573 value: &toml::Value,
574 at: Vec<PathSegment>,
575 unknown: &mut Vec<SchemaDiagnostic>,
576) -> Result<T, ConfigIssue> {
577 let mut ignored = Vec::new();
578 match serde_ignored::deserialize(value.clone(), |path| ignored.push(segments(&path))) {
579 Ok(read) => {
580 unknown.extend(unknown_notes(ignored, &at));
581 Ok(read)
582 }
583 Err(error) => Err(ConfigIssue {
584 path: at,
585 message: error.to_string().trim_end().to_owned(),
586 }),
587 }
588}
589
590fn read_entries<T: DeserializeOwned>(
592 table: &toml::Table,
593 key: &str,
594 unknown: &mut Vec<SchemaDiagnostic>,
595 issues: &mut Vec<ConfigIssue>,
596) -> IndexMap<String, T> {
597 let mut entries = IndexMap::new();
598 match table.get(key) {
599 None => {}
600 Some(toml::Value::Table(named)) => {
601 for (name, value) in named {
602 match read_value(value, key_path(&[key, name]), unknown) {
603 Ok(entry) => {
604 entries.insert(name.clone(), entry);
605 }
606 Err(issue) => issues.push(issue),
607 }
608 }
609 }
610 Some(_) => issues.push(ConfigIssue {
611 path: key_path(&[key]),
612 message: format!("`{key}` must be a table"),
613 }),
614 }
615 entries
616}
617
618fn read_dependency_entries(
619 table: &toml::Table,
620 key: &str,
621 unknown: &mut Vec<SchemaDiagnostic>,
622) -> IndexMap<SourceName, RawEntry> {
623 let mut entries = IndexMap::new();
624 let Some(toml::Value::Table(named)) = table.get(key) else {
625 return entries;
626 };
627 for (name, value) in named {
628 let Ok(source) = toml::Value::String(name.clone()).try_into::<SourceName>() else {
629 continue;
630 };
631 if let Ok(entry) = read_value(value, key_path(&[key, name]), unknown) {
632 entries.insert(source, entry);
633 }
634 }
635 entries
636}
637
638pub fn read_models(content: &str) -> Result<IndexMap<String, ModelAlias>, toml::de::Error> {
641 #[derive(Deserialize)]
642 struct Models {
643 #[serde(default)]
644 models: IndexMap<String, ModelAlias>,
645 }
646 toml::from_str::<Models>(content).map(|parsed| parsed.models)
647}
648
649pub fn agent_overlay_refusals(agents: &IndexMap<String, AgentOverlay>) -> Vec<ConfigIssue> {
652 agents
653 .iter()
654 .flat_map(|(name, overlay)| {
655 let problems = overlay.models.as_ref().map_or_else(Vec::new, |items| {
656 crate::model_policy::list_problems(items.iter().map(ModelsItem::entry))
657 });
658 problems.into_iter().map(move |problem| ConfigIssue {
659 path: key_path(&["agents", name, "models"]),
660 message: format!("[agents.{name}] {}", problem.message),
661 })
662 })
663 .collect()
664}
665
666pub fn settings_refusals(
671 tools: Option<&ToolRuleMap>,
672 min_mars_version: Option<&str>,
673) -> Vec<ConfigIssue> {
674 let tools = tools
675 .and_then(|tools| {
676 tools.wildcard_refusal(
677 "[settings.tools]",
678 "`approval` is the default for calls no rule matches",
679 )
680 })
681 .map(|message| ConfigIssue {
682 path: key_path(&["settings", "tools"]),
683 message,
684 });
685 let min = min_mars_version
686 .and_then(|raw| parse_min_mars_version(raw).err())
687 .map(|message| ConfigIssue {
688 path: key_path(&["settings", "min_mars_version"]),
689 message,
690 });
691 tools.into_iter().chain(min).collect()
692}
693
694pub fn parse_min_mars_version(raw: &str) -> Result<semver::VersionReq, String> {
698 crate::package::parse_requirement(raw).map_err(|error| {
699 format!("`min_mars_version = \"{raw}\"` is not a version requirement: {error}")
700 })
701}
702
703fn segments(at: &IgnoredPath<'_>) -> Vec<PathSegment> {
704 match at {
705 IgnoredPath::Root => Vec::new(),
706 IgnoredPath::Seq { parent, index } => {
707 let mut out = segments(parent);
708 out.push(PathSegment::Index(*index));
709 out
710 }
711 IgnoredPath::Map { parent, key } => {
712 let mut out = segments(parent);
713 out.push(PathSegment::Key(key.clone()));
714 out
715 }
716 IgnoredPath::Some { parent }
717 | IgnoredPath::NewtypeStruct { parent }
718 | IgnoredPath::NewtypeVariant { parent } => segments(parent),
719 }
720}
721
722fn table_name(at: &[PathSegment]) -> String {
724 let mut name = String::new();
725 for segment in at {
726 match segment {
727 PathSegment::Key(key) => {
728 if !name.is_empty() {
729 name.push('.');
730 }
731 name.push_str(key);
732 }
733 PathSegment::Index(index) => name.push_str(&format!("[{index}]")),
734 }
735 }
736 name
737}