1use std::collections::{BTreeMap, BTreeSet};
11
12use serde::Serialize;
13
14use crate::claude::discover::discover_claude;
15use crate::claude::manifest::{
16 MARKETPLACE_MANIFEST, Marketplace, MarketplaceEntry, PLUGIN_MANIFEST, PLUGIN_NAME_RULE,
17 PluginManifest, PluginSpec, is_plugin_name, resolve_spec,
18};
19use crate::diagnostic::{SchemaDiagnostic, Severity};
20use crate::dialect::{Dialect, DialectChoice};
21use crate::discover::{Discovery, discover};
22use crate::item::DefinitionKind;
23use crate::package::{ManifestClassification, classify_manifest};
24use crate::plugin_metadata::{SENTINEL_FILE, is_valid_sentinel};
25use crate::prepare::{Classification, PrepareContext};
26use crate::tree::TreeSource;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum Kind {
32 #[serde(rename = "schema-1")]
33 Schema1,
34 SchemaNewer,
35 Marketplace,
36 Plugin,
37 SkillTree,
38 Invalid,
39 Empty,
40}
41
42#[derive(Debug, Clone)]
44pub(crate) enum Layout {
45 None,
47 Convention,
49 Claude(PluginSpec),
51 Marketplace(Marketplace),
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56pub struct Mirror {
57 pub dialect: Dialect,
58 pub paths: Vec<String>,
59 pub weak: bool,
62}
63
64pub(crate) struct Dispatched {
65 pub manifest: Option<Vec<u8>>,
68 pub classification: Classification,
69 pub layout: Layout,
70 pub discovery: Discovery,
71 pub also_found: Vec<Mirror>,
72}
73
74impl Dispatched {
75 pub(crate) fn kind(&self) -> Kind {
78 match (&self.classification, &self.layout) {
79 (Classification::Schema1, _) => Kind::Schema1,
80 (Classification::SchemaNewer { .. }, _) => Kind::SchemaNewer,
81 (Classification::Invalid, _) => Kind::Invalid,
82 (Classification::Marketplace, _) => Kind::Marketplace,
83 (Classification::Empty, _) => Kind::Empty,
84 (Classification::Foreign(_), Layout::Claude(spec)) if !spec.is_bare_tree() => {
85 Kind::Plugin
86 }
87 (Classification::Foreign(_), _) => Kind::SkillTree,
88 }
89 }
90
91 pub(crate) fn dialect(&self) -> Option<&DialectChoice> {
93 match &self.classification {
94 Classification::Foreign(choice) => Some(choice),
95 _ => None,
96 }
97 }
98}
99
100#[derive(Clone, Copy)]
103pub(crate) struct AsPlugin<'a> {
104 pub entry: &'a MarketplaceEntry,
105 pub at_marketplace_root: bool,
106}
107
108const STANDARD_SKILL_KEYS: &[&str] = &[
112 "name",
113 "description",
114 "license",
115 "compatibility",
116 "metadata",
117 "allowed-tools",
118];
119
120pub(crate) fn dispatch(
121 source: &impl TreeSource,
122 context: PrepareContext,
123 declared: Option<Dialect>,
124 as_plugin: Option<AsPlugin<'_>>,
125 fallback_name: Option<&str>,
126) -> Dispatched {
127 let manifest = source.read("mars.toml");
128 let manifest_class = classify_manifest(manifest.as_deref());
129 let consumer_tree = consumer_content(context, &manifest_class);
130 let mut dispatched = classify(
131 source,
132 &manifest_class,
133 consumer_tree,
134 declared,
135 as_plugin,
136 fallback_name,
137 );
138 dispatched.manifest = manifest.filter(|_| !consumer_tree);
139 dispatched
140}
141
142fn consumer_content(context: PrepareContext, manifest: &ManifestClassification) -> bool {
145 matches!(
146 (context, manifest),
147 (
148 PrepareContext::AuthoredLocal,
149 ManifestClassification::NoManifest
150 ) | (
151 PrepareContext::AuthoredLocal | PrepareContext::Project,
152 ManifestClassification::ConsumerConfig
153 )
154 )
155}
156
157fn classify(
158 source: &impl TreeSource,
159 manifest: &ManifestClassification,
160 consumer_tree: bool,
161 declared: Option<Dialect>,
162 as_plugin: Option<AsPlugin<'_>>,
163 fallback_name: Option<&str>,
164) -> Dispatched {
165 let done = |classification, layout, discovery, also_found| Dispatched {
166 manifest: None,
167 classification,
168 layout,
169 discovery,
170 also_found,
171 };
172 if source
173 .read(SENTINEL_FILE)
174 .is_some_and(|bytes| is_valid_sentinel(&bytes))
175 {
176 return done(
177 Classification::Empty,
178 Layout::None,
179 Discovery::generated_root(),
180 Vec::new(),
181 );
182 }
183
184 match manifest {
185 _ if consumer_tree => {
186 return done(
187 Classification::Schema1,
188 Layout::Convention,
189 discover(source, fallback_name),
190 Vec::new(),
191 );
192 }
193 ManifestClassification::Schema1 => {
194 return done(
195 Classification::Schema1,
196 Layout::Convention,
197 discover(source, fallback_name),
198 Vec::new(),
199 );
200 }
201 ManifestClassification::SchemaNewer { schema } => {
202 return done(
203 Classification::SchemaNewer { schema: *schema },
204 Layout::None,
205 Discovery::empty(),
206 Vec::new(),
207 );
208 }
209 ManifestClassification::Invalid { .. }
210 | ManifestClassification::NoSchema
211 | ManifestClassification::ConsumerConfig => {
212 return done(
213 Classification::Invalid,
214 Layout::None,
215 Discovery::empty(),
216 Vec::new(),
217 );
218 }
219 ManifestClassification::NoManifest => {}
220 }
221
222 if declared == Some(Dialect::MarsNative) {
223 return done(
224 Classification::Schema1,
225 Layout::Convention,
226 discover(source, fallback_name),
227 Vec::new(),
228 );
229 }
230
231 let evidence = collect_evidence(source);
232 let decided = declared.map(DialectChoice::declared).or_else(|| {
235 evidence
236 .strongest()
237 .map(|(dialect, paths)| DialectChoice::predicted(dialect, paths))
238 });
239 let also_found = |chosen: Dialect| evidence.mirrors(chosen, source);
240
241 if decided
242 .as_ref()
243 .is_none_or(|choice| matches!(choice.dialect, Dialect::Claude | Dialect::AgentSkills))
244 {
245 let (layout, manifest_diagnostics) = claude_layout(source, as_plugin);
246 let mut discovery = match &layout {
247 Layout::Claude(spec) => discover_claude(source, spec, fallback_name),
248 _ => Discovery::empty(),
249 };
250 for (path, diagnostic) in manifest_diagnostics {
251 discovery
252 .diagnostics
253 .entry(path)
254 .or_default()
255 .push(diagnostic);
256 }
257 if matches!(layout, Layout::None) {
258 return done(Classification::Invalid, layout, discovery, Vec::new());
259 }
260 let choice = match decided {
261 Some(choice) => choice,
262 None if as_plugin.is_some() => DialectChoice::predicted(Dialect::Claude, Vec::new()),
264 None => predict_from_items(source, &discovery),
265 };
266 let mirrors = also_found(choice.dialect);
267 let has_items = !discovery.definitions.is_empty()
268 || !discovery.dropped.is_empty()
269 || matches!(layout, Layout::Marketplace(_));
270 let bare_tree = matches!(&layout, Layout::Claude(spec) if spec.is_bare_tree());
271 if !has_items && choice.evidence.paths.is_empty() && bare_tree {
272 return done(Classification::Empty, Layout::None, discovery, mirrors);
273 }
274 let classification = if matches!(layout, Layout::Marketplace(_)) {
275 Classification::Marketplace
276 } else {
277 Classification::Foreign(choice)
278 };
279 return done(classification, layout, discovery, mirrors);
280 }
281
282 let choice = decided.expect("a non-Claude dialect was decided");
283 let discovery = discover(source, fallback_name);
284 let mirrors = also_found(choice.dialect);
285 if discovery.definitions.is_empty() && choice.evidence.paths.is_empty() {
286 return done(Classification::Empty, Layout::None, discovery, mirrors);
287 }
288 done(
289 Classification::Foreign(choice),
290 Layout::Convention,
291 discovery,
292 mirrors,
293 )
294}
295
296fn claude_layout(
299 source: &impl TreeSource,
300 as_plugin: Option<AsPlugin<'_>>,
301) -> (Layout, Vec<(String, SchemaDiagnostic)>) {
302 let mut diagnostics = Vec::new();
303 let invalid = |diagnostic: SchemaDiagnostic, path: &str| {
304 (Layout::None, vec![(path.to_owned(), diagnostic)])
305 };
306 if let Some(plugin) = as_plugin
307 && !is_plugin_name(&plugin.entry.name)
308 {
309 return invalid(
310 SchemaDiagnostic::new(
311 "marketplace.plugin-name-invalid",
312 Severity::Error,
313 Vec::new(),
314 format!(
315 "plugin name `{}` is not usable ({PLUGIN_NAME_RULE})",
316 plugin.entry.name
317 ),
318 ),
319 MARKETPLACE_MANIFEST,
320 );
321 }
322 if as_plugin.is_none()
323 && let Some(bytes) = source.read(MARKETPLACE_MANIFEST)
324 {
325 return match Marketplace::parse(&bytes, &mut diagnostics) {
326 Ok(marketplace) => (Layout::Marketplace(marketplace), diagnostics),
327 Err(diagnostic) => invalid(diagnostic, MARKETPLACE_MANIFEST),
328 };
329 }
330 let manifest = match source.read(PLUGIN_MANIFEST) {
331 Some(bytes) => match PluginManifest::parse(&bytes, &mut diagnostics) {
332 Ok(manifest) => Some(manifest),
333 Err(diagnostic) => return invalid(diagnostic, PLUGIN_MANIFEST),
334 },
335 None => None,
336 };
337 if manifest.is_none() && as_plugin.is_none() {
338 return (Layout::Claude(PluginSpec::walk()), diagnostics);
339 }
340 match resolve_spec(
341 manifest.as_ref(),
342 as_plugin.map(|plugin| plugin.entry),
343 as_plugin.is_some_and(|plugin| plugin.at_marketplace_root),
344 ) {
345 Ok(spec) => (Layout::Claude(spec), diagnostics),
346 Err(message) => invalid(
347 SchemaDiagnostic::new(
348 "plugin.conflicting-manifests",
349 Severity::Error,
350 Vec::new(),
351 message,
352 ),
353 PLUGIN_MANIFEST,
354 ),
355 }
356}
357
358fn predict_from_items(source: &impl TreeSource, discovery: &Discovery) -> DialectChoice {
363 let (mut claude_agents, mut claude_skills) = (Vec::new(), Vec::new());
364 let mut opencode_paths = Vec::new();
365 let mut standard_only = true;
366 let mut skills = 0;
367 for definition in &discovery.definitions {
368 if definition.kind == DefinitionKind::Agent {
369 standard_only = false;
370 } else {
371 skills += 1;
372 }
373 let Some(frontmatter) = source
374 .read(&definition.source_path)
375 .and_then(|bytes| String::from_utf8(bytes).ok())
376 .and_then(|text| crate::frontmatter::Frontmatter::parse(&text).ok())
377 else {
378 continue;
379 };
380 let keys = frontmatter.keys();
381 if keys
382 .iter()
383 .any(|key| crate::claude::translate::EVIDENCE_KEYS.contains(&key.as_str()))
384 {
385 match definition.kind {
386 DefinitionKind::Agent => claude_agents.push(definition.source_path.clone()),
387 DefinitionKind::Skill => claude_skills.push(definition.source_path.clone()),
388 }
389 }
390 if definition.kind == DefinitionKind::Agent && crate::lift::is_opencode_agent(&frontmatter)
391 {
392 opencode_paths.push(definition.source_path.clone());
393 }
394 if definition.kind == DefinitionKind::Skill
395 && keys
396 .iter()
397 .any(|key| !STANDARD_SKILL_KEYS.contains(&key.as_str()))
398 {
399 standard_only = false;
400 }
401 }
402 if !claude_agents.is_empty() {
405 claude_agents.extend(claude_skills);
406 claude_agents.truncate(5);
407 DialectChoice::predicted(Dialect::Claude, claude_agents)
408 } else if !opencode_paths.is_empty() {
409 opencode_paths.truncate(5);
410 DialectChoice::predicted(Dialect::OpenCode, opencode_paths)
411 } else if !claude_skills.is_empty() {
412 claude_skills.truncate(5);
413 DialectChoice::predicted(Dialect::Claude, claude_skills)
414 } else if skills > 0 && standard_only {
415 DialectChoice::predicted(Dialect::AgentSkills, Vec::new())
416 } else {
417 DialectChoice::predicted(Dialect::Claude, Vec::new())
418 }
419}
420
421#[derive(Default)]
423struct Evidence(BTreeMap<Dialect, Vec<String>>);
424
425const STRENGTH: &[Dialect] = &[
427 Dialect::Claude,
428 Dialect::Cursor,
429 Dialect::Codex,
430 Dialect::OpenCode,
431];
432
433fn collect_evidence(source: &impl TreeSource) -> Evidence {
434 let mut evidence = Evidence::default();
435 let mut add = |dialect, path: String| evidence.0.entry(dialect).or_default().push(path);
436 for path in [PLUGIN_MANIFEST, MARKETPLACE_MANIFEST] {
437 if source.is_file(path) {
438 add(Dialect::Claude, path.to_owned());
439 }
440 }
441 for (container, dialect) in [
442 (".claude", Dialect::Claude),
443 (".cursor", Dialect::Cursor),
444 (".codex", Dialect::Codex),
445 (".opencode", Dialect::OpenCode),
446 ] {
447 for kind in ["skills", "agents"] {
448 let path = format!("{container}/{kind}");
449 if source.is_dir(&path) && !source.children(&path).is_empty() {
450 add(dialect, path);
451 break;
452 }
453 }
454 }
455 if source.is_dir(".cursor-plugin") {
456 add(Dialect::Cursor, ".cursor-plugin".to_owned());
457 }
458 for rules in [".cursor/rules", "rules"] {
459 if let Some(rule) = source
460 .children(rules)
461 .into_iter()
462 .find(|path| path.ends_with(".mdc"))
463 {
464 add(Dialect::Cursor, rule);
465 }
466 }
467 if source.is_dir(".codex-plugin") {
468 add(Dialect::Codex, ".codex-plugin".to_owned());
469 }
470 evidence
471}
472
473impl Evidence {
474 fn strongest(&self) -> Option<(Dialect, Vec<String>)> {
475 STRENGTH
476 .iter()
477 .find_map(|dialect| Some((*dialect, self.0.get(dialect)?.clone())))
478 }
479
480 fn mirrors(&self, chosen: Dialect, source: &impl TreeSource) -> Vec<Mirror> {
482 let mut mirrors = STRENGTH
483 .iter()
484 .filter(|dialect| **dialect != chosen)
485 .filter_map(|dialect| {
486 Some(Mirror {
487 dialect: *dialect,
488 paths: self.0.get(dialect)?.clone(),
489 weak: false,
490 })
491 })
492 .collect::<Vec<_>>();
493 if chosen != Dialect::Codex {
494 let sidecars = openai_sidecars(source);
495 if !sidecars.is_empty() {
496 mirrors.push(Mirror {
497 dialect: Dialect::Codex,
498 paths: sidecars,
499 weak: true,
500 });
501 }
502 }
503 mirrors
504 }
505}
506
507fn openai_sidecars(source: &impl TreeSource) -> Vec<String> {
509 let mut found = BTreeSet::new();
510 let mut check = |dir: &str| {
511 let path = format!("{dir}/agents/openai.yaml");
512 if source.is_dir(dir) && source.is_file(&format!("{dir}/SKILL.md")) && source.is_file(&path)
513 {
514 found.insert(path);
515 }
516 };
517 for group in source.children("skills") {
518 check(&group);
519 for child in source.children(&group) {
520 check(&child);
521 }
522 }
523 found.into_iter().take(5).collect()
524}