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")]
222 pub managed_root: Option<String>,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub targets: Option<Vec<String>>,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub models_cache_ttl_hours: Option<u32>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub min_mars_version: Option<String>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub default_harness: Option<String>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub default_model: Option<String>,
243 #[serde(
245 default,
246 alias = "default-network",
247 skip_serializing_if = "Option::is_none"
248 )]
249 pub default_network: Option<NetworkPolicy>,
250 #[serde(
251 default,
252 rename = "network-allow",
253 alias = "network_allow",
254 skip_serializing_if = "PermissionSet::is_noop"
255 )]
256 pub network_allow: PermissionSet<NetworkHost>,
257 #[serde(
258 default,
259 rename = "network-deny",
260 alias = "network_deny",
261 skip_serializing_if = "PermissionSet::is_noop"
262 )]
263 pub network_deny: PermissionSet<NetworkHost>,
264 #[serde(default, skip_serializing_if = "ToolRuleMap::is_empty")]
266 pub tools: ToolRuleMap,
267 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub harness_order: Option<Vec<String>>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub provider_order: Option<Vec<String>>,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub catalog_providers: Option<Vec<String>>,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub agent_emission: Option<AgentEmission>,
295 #[serde(default, skip_serializing_if = "MeridianSettings::is_empty")]
296 pub meridian: MeridianSettings,
297 #[serde(
298 default,
299 rename = "model-policies",
300 skip_serializing_if = "Option::is_none"
301 )]
302 pub model_policies: Option<Vec<ModelPolicyRule>>,
303}
304
305#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
307pub struct AgentCopyConfig {
308 #[serde(default)]
309 pub harnesses: Vec<String>,
310 #[serde(default)]
311 pub include_fanout: bool,
312}
313
314#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
316pub struct FanoutConfig {
317 #[serde(default)]
318 pub agents: Vec<String>,
319}
320
321#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
323pub struct MeridianSettings {
324 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub agent_copy: Option<AgentCopyConfig>,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub fanout: Option<FanoutConfig>,
328}
329
330impl MeridianSettings {
331 pub fn is_empty(&self) -> bool {
332 self.agent_copy.is_none() && self.fanout.is_none()
333 }
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
337#[serde(rename_all = "lowercase")]
338pub enum AgentEmission {
339 Auto,
340 Always,
341 Never,
342}
343
344const DEFAULT_MODELS_CACHE_TTL_HOURS: u32 = 24;
345
346impl Settings {
347 pub fn models_cache_ttl_hours(&self) -> u32 {
348 self.models_cache_ttl_hours
349 .unwrap_or(DEFAULT_MODELS_CACHE_TTL_HOURS)
350 }
351
352 pub fn model_policies(&self) -> &[ModelPolicyRule] {
353 self.model_policies.as_deref().unwrap_or_default()
354 }
355
356 pub fn meridian_agent_copy(&self) -> Option<&AgentCopyConfig> {
358 self.meridian.agent_copy.as_ref()
359 }
360
361 pub fn network_keys(&self) -> Vec<(&'static str, bool)> {
364 [
365 (
366 "default-network",
367 self.default_network
368 .as_ref()
369 .map(|policy| *policy != crate::network::NetworkPolicy::Allow),
370 ),
371 (
372 "network-allow",
373 (!self.network_allow.entries().is_empty()).then_some(true),
374 ),
375 (
376 "network-deny",
377 (!self.network_deny.entries().is_empty()).then_some(true),
378 ),
379 ]
380 .into_iter()
381 .filter_map(|(key, restricts)| restricts.map(|restricts| (key, restricts)))
382 .collect()
383 }
384
385 pub fn meridian_fanout_agents(&self) -> &[String] {
387 self.meridian
388 .fanout
389 .as_ref()
390 .map(|f| f.agents.as_slice())
391 .unwrap_or(&[])
392 }
393}
394
395impl Config {
396 pub fn dependency_unknown_keys(&self) -> Vec<SchemaDiagnostic> {
398 [
399 ("dependencies", &self.dependencies),
400 ("local-dependencies", &self.local_dependencies),
401 ]
402 .into_iter()
403 .flat_map(|(table, dependencies)| {
404 dependencies.iter().flat_map(move |(name, entry)| {
405 entry.unknown.keys().map(move |key| {
406 let path = vec![
407 PathSegment::Key(table.to_owned()),
408 PathSegment::Key(name.to_string()),
409 PathSegment::Key(key.clone()),
410 ];
411 unknown_field(path, &format!("{table}.{name}"), key)
412 })
413 })
414 })
415 .collect()
416 }
417}
418
419pub struct Read<T> {
422 pub value: T,
423 pub unknown_keys: Vec<SchemaDiagnostic>,
424 pub floor: Option<keys::Floor>,
425}
426
427pub fn read<T: DeserializeOwned>(content: &str) -> Result<Read<T>, toml::de::Error> {
429 let mut ignored = Vec::new();
430 let value = serde_ignored::deserialize(toml::Deserializer::new(content), |at| {
431 ignored.push(segments(&at));
432 })?;
433 let unknown_keys = unknown_notes(ignored, &[]);
434 let floor = content
435 .parse::<toml::Table>()
436 .ok()
437 .and_then(|table| keys::floor(keys::used(&table, keys::Document::Consumer)));
438 Ok(Read {
439 value,
440 unknown_keys,
441 floor,
442 })
443}
444
445fn unknown_notes(ignored: Vec<Vec<PathSegment>>, prefix: &[PathSegment]) -> Vec<SchemaDiagnostic> {
448 let mut notes = Vec::new();
449 for at in ignored {
450 let mut at: Vec<PathSegment> = prefix.iter().cloned().chain(at).collect();
451 let Some(PathSegment::Key(key)) = at.pop() else {
452 continue;
453 };
454 if matches!(at.first(), Some(PathSegment::Key(table)) if table == "package" || table == "plugin")
456 {
457 continue;
458 }
459 let table = table_name(&at);
460 let mut path = at;
461 path.push(PathSegment::Key(key.clone()));
462 notes.push(unknown_field(path, &table, &key));
463 }
464 notes
465}
466
467#[derive(Debug, Clone, PartialEq, Eq)]
469pub struct ConfigIssue {
470 pub path: Vec<PathSegment>,
471 pub message: String,
472}
473
474pub struct ConsumerRead {
476 pub config: Config,
480 pub issues: Vec<ConfigIssue>,
483 pub parse_error: Option<toml::de::Error>,
486}
487
488pub fn read_consumer(content: &str) -> ConsumerRead {
492 match read::<Config>(content) {
493 Ok(read) => {
494 let mut config = read.value;
495 config.unknown_keys = read.unknown_keys;
496 config.unknown_keys.extend(config.dependency_unknown_keys());
497 config.floor = read.floor;
498 let issues = settings_refusals(
499 Some(&config.settings.tools),
500 config.settings.min_mars_version.as_deref(),
501 );
502 ConsumerRead {
503 config,
504 issues,
505 parse_error: None,
506 }
507 }
508 Err(error) => {
509 let (config, issues) = read_tables(content, &error);
510 ConsumerRead {
511 config,
512 issues,
513 parse_error: Some(error),
514 }
515 }
516 }
517}
518
519fn key_path(parts: &[&str]) -> Vec<PathSegment> {
520 parts
521 .iter()
522 .map(|part| PathSegment::Key((*part).to_owned()))
523 .collect()
524}
525
526fn read_tables(content: &str, whole: &toml::de::Error) -> (Config, Vec<ConfigIssue>) {
530 let mut config = Config::default();
531 let Ok(table) = content.parse::<toml::Table>() else {
532 let issue = ConfigIssue {
533 path: Vec::new(),
534 message: whole.to_string(),
535 };
536 return (config, vec![issue]);
537 };
538 let mut issues = Vec::new();
539 let mut unknown = Vec::new();
540 config.floor = keys::floor(keys::used(&table, keys::Document::Consumer));
541 config.plugin = table.get("plugin").cloned();
542 if let Some(value) = table.get("settings") {
543 match read_value::<Settings>(value, key_path(&["settings"]), &mut unknown) {
544 Ok(settings) => {
545 issues.extend(settings_refusals(
546 Some(&settings.tools),
547 settings.min_mars_version.as_deref(),
548 ));
549 config.settings = settings;
550 }
551 Err(issue) => issues.push(issue),
552 }
553 }
554 config.models = read_entries(&table, "models", &mut unknown, &mut issues);
555 config.agents = read_entries(&table, "agents", &mut unknown, &mut issues);
556 config.skills = read_entries(&table, "skills", &mut unknown, &mut issues);
557 config.dependencies = read_dependency_entries(&table, "dependencies", &mut unknown);
558 config.local_dependencies = read_dependency_entries(&table, "local-dependencies", &mut unknown);
559 config.unknown_keys = unknown;
560 config.unknown_keys.extend(config.dependency_unknown_keys());
561 (config, issues)
562}
563
564fn read_value<T: DeserializeOwned>(
565 value: &toml::Value,
566 at: Vec<PathSegment>,
567 unknown: &mut Vec<SchemaDiagnostic>,
568) -> Result<T, ConfigIssue> {
569 let mut ignored = Vec::new();
570 match serde_ignored::deserialize(value.clone(), |path| ignored.push(segments(&path))) {
571 Ok(read) => {
572 unknown.extend(unknown_notes(ignored, &at));
573 Ok(read)
574 }
575 Err(error) => Err(ConfigIssue {
576 path: at,
577 message: error.to_string().trim_end().to_owned(),
578 }),
579 }
580}
581
582fn read_entries<T: DeserializeOwned>(
584 table: &toml::Table,
585 key: &str,
586 unknown: &mut Vec<SchemaDiagnostic>,
587 issues: &mut Vec<ConfigIssue>,
588) -> IndexMap<String, T> {
589 let mut entries = IndexMap::new();
590 match table.get(key) {
591 None => {}
592 Some(toml::Value::Table(named)) => {
593 for (name, value) in named {
594 match read_value(value, key_path(&[key, name]), unknown) {
595 Ok(entry) => {
596 entries.insert(name.clone(), entry);
597 }
598 Err(issue) => issues.push(issue),
599 }
600 }
601 }
602 Some(_) => issues.push(ConfigIssue {
603 path: key_path(&[key]),
604 message: format!("`{key}` must be a table"),
605 }),
606 }
607 entries
608}
609
610fn read_dependency_entries(
611 table: &toml::Table,
612 key: &str,
613 unknown: &mut Vec<SchemaDiagnostic>,
614) -> IndexMap<SourceName, RawEntry> {
615 let mut entries = IndexMap::new();
616 let Some(toml::Value::Table(named)) = table.get(key) else {
617 return entries;
618 };
619 for (name, value) in named {
620 let Ok(source) = toml::Value::String(name.clone()).try_into::<SourceName>() else {
621 continue;
622 };
623 if let Ok(entry) = read_value(value, key_path(&[key, name]), unknown) {
624 entries.insert(source, entry);
625 }
626 }
627 entries
628}
629
630pub fn read_models(content: &str) -> Result<IndexMap<String, ModelAlias>, toml::de::Error> {
633 #[derive(Deserialize)]
634 struct Models {
635 #[serde(default)]
636 models: IndexMap<String, ModelAlias>,
637 }
638 toml::from_str::<Models>(content).map(|parsed| parsed.models)
639}
640
641pub fn settings_refusals(
646 tools: Option<&ToolRuleMap>,
647 min_mars_version: Option<&str>,
648) -> Vec<ConfigIssue> {
649 let tools = tools
650 .and_then(|tools| {
651 tools.wildcard_refusal(
652 "[settings.tools]",
653 "`approval` is the default for calls no rule matches",
654 )
655 })
656 .map(|message| ConfigIssue {
657 path: key_path(&["settings", "tools"]),
658 message,
659 });
660 let min = min_mars_version
661 .and_then(|raw| parse_min_mars_version(raw).err())
662 .map(|message| ConfigIssue {
663 path: key_path(&["settings", "min_mars_version"]),
664 message,
665 });
666 tools.into_iter().chain(min).collect()
667}
668
669pub fn parse_min_mars_version(raw: &str) -> Result<semver::VersionReq, String> {
673 crate::package::parse_requirement(raw).map_err(|error| {
674 format!("`min_mars_version = \"{raw}\"` is not a version requirement: {error}")
675 })
676}
677
678fn segments(at: &IgnoredPath<'_>) -> Vec<PathSegment> {
679 match at {
680 IgnoredPath::Root => Vec::new(),
681 IgnoredPath::Seq { parent, index } => {
682 let mut out = segments(parent);
683 out.push(PathSegment::Index(*index));
684 out
685 }
686 IgnoredPath::Map { parent, key } => {
687 let mut out = segments(parent);
688 out.push(PathSegment::Key(key.clone()));
689 out
690 }
691 IgnoredPath::Some { parent }
692 | IgnoredPath::NewtypeStruct { parent }
693 | IgnoredPath::NewtypeVariant { parent } => segments(parent),
694 }
695}
696
697fn table_name(at: &[PathSegment]) -> String {
699 let mut name = String::new();
700 for segment in at {
701 match segment {
702 PathSegment::Key(key) => {
703 if !name.is_empty() {
704 name.push('.');
705 }
706 name.push_str(key);
707 }
708 PathSegment::Index(index) => name.push_str(&format!("[{index}]")),
709 }
710 }
711 name
712}