mars-schema 0.27.3

Pure schema reader and editor for Mars agent packages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Claude plugin and marketplace manifests, and Claude's rule for combining them.
//!
//! Rules: <https://code.claude.com/docs/en/plugins/manifest-reference> (a manifest list
//! **adds** to the default skills folder and **replaces** the default Agents and commands
//! folders) and <https://code.claude.com/docs/en/plugins/marketplace-reference#strict-mode>.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, key_path};

pub(crate) const PLUGIN_MANIFEST: &str = ".claude-plugin/plugin.json";
pub const MARKETPLACE_MANIFEST: &str = ".claude-plugin/marketplace.json";

/// The component lists a manifest or marketplace entry can carry. `None` means the key is
/// absent, which is different from an empty list (an empty Agents list replaces the default).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComponentLists {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skills: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agents: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commands: Option<Vec<String>>,
    /// The manifest declares `hooks` (not converted yet) or `mcpServers` (read from the plugin's
    /// own files by `claude::mcp`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub hooks: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub mcp: bool,
}

impl ComponentLists {
    fn has_components(&self) -> bool {
        self.skills.is_some() || self.agents.is_some() || self.commands.is_some() || self.hooks
    }

    fn from_object(
        object: &serde_json::Map<String, Value>,
        file: &str,
        diagnostics: &mut Vec<(String, SchemaDiagnostic)>,
    ) -> Self {
        let mut list = |key: &str| {
            object
                .get(key)
                .map(|value| declared_paths(value, key, file, diagnostics))
        };
        Self {
            skills: list("skills"),
            agents: list("agents"),
            commands: list("commands"),
            hooks: object.contains_key("hooks"),
            mcp: object.contains_key("mcpServers"),
        }
    }
}

/// A list value is a path, an array of paths, or (as Mars read it before) `{path}` objects.
/// An entry that is not a `./` path is reported and left out; `.` names the plugin root.
fn declared_paths(
    value: &Value,
    key: &str,
    file: &str,
    diagnostics: &mut Vec<(String, SchemaDiagnostic)>,
) -> Vec<String> {
    let entries: Vec<&Value> = match value {
        Value::Array(values) => values.iter().collect(),
        other => vec![other],
    };
    let mut paths = Vec::new();
    for entry in entries {
        let raw = entry
            .as_str()
            .or_else(|| entry.get("path").and_then(Value::as_str));
        match raw {
            Some(raw) if raw == "." || raw.starts_with("./") => paths.push(raw.to_owned()),
            _ => diagnostics.push((
                file.to_owned(),
                SchemaDiagnostic::new(
                    "source-manifest.path-invalid",
                    Severity::Warning,
                    key_path(key),
                    format!("`{key}` entry {entry} is not a `./` path and was left out"),
                ),
            )),
        }
    }
    paths
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PluginManifest {
    pub name: Option<String>,
    pub version: Option<String>,
    pub description: Option<String>,
    pub lists: ComponentLists,
}

fn parse_object(
    bytes: &[u8],
    file: &str,
) -> Result<serde_json::Map<String, Value>, SchemaDiagnostic> {
    let fail = |message: String| {
        SchemaDiagnostic::new(
            "source-manifest.invalid-json",
            Severity::Error,
            Vec::new(),
            message,
        )
    };
    match serde_json::from_slice::<Value>(bytes) {
        Ok(Value::Object(object)) => Ok(object),
        Ok(_) => Err(fail(format!("`{file}` must be a JSON object"))),
        Err(error) => Err(fail(format!("failed to parse `{file}`: {error}"))),
    }
}

fn text(object: &serde_json::Map<String, Value>, key: &str) -> Option<String> {
    object.get(key).and_then(Value::as_str).map(str::to_owned)
}

impl PluginManifest {
    pub fn parse(
        bytes: &[u8],
        diagnostics: &mut Vec<(String, SchemaDiagnostic)>,
    ) -> Result<Self, SchemaDiagnostic> {
        let object = parse_object(bytes, PLUGIN_MANIFEST)?;
        let name = text(&object, "name");
        if let Some(name) = name.as_deref().filter(|name| !is_plugin_name(name)) {
            diagnostics.push((
                PLUGIN_MANIFEST.to_owned(),
                SchemaDiagnostic::new(
                    "plugin.name-invalid",
                    Severity::Warning,
                    vec![PathSegment::Key("name".into())],
                    format!(
                        "plugin name `{name}` is not usable ({PLUGIN_NAME_RULE}); the marketplace entry's or the repository's name is used"
                    ),
                ),
            ));
        }
        Ok(Self {
            name: name.filter(|name| is_plugin_name(name)),
            version: text(&object, "version"),
            description: text(&object, "description"),
            lists: ComponentLists::from_object(&object, PLUGIN_MANIFEST, diagnostics),
        })
    }
}

/// Where a marketplace plugin's files come from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum PluginSource {
    /// A directory of the marketplace's own checkout; `path` is root-relative (`""` is the root).
    Local { path: String },
    /// A Git repository the caller fetches. `path` roots the plugin inside it.
    Remote {
        repository: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
        checkout: Checkout,
    },
    /// `npm`, `archive`, `command`, or a shape this version does not know.
    Unsupported { reason: String },
}

/// What to check out: a full commit, else a branch or tag, else the default branch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Checkout {
    Sha { sha: String },
    Ref { name: String },
    DefaultBranch,
}

/// One marketplace `plugins[]` entry, as `inspect` reports it and `normalize` takes it back.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MarketplaceEntry {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    pub source: PluginSource,
    /// `strict` as written; Claude treats an absent value as `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strict: Option<bool>,
    #[serde(default)]
    pub lists: ComponentLists,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Marketplace {
    pub name: Option<String>,
    pub plugins: Vec<MarketplaceEntry>,
}

impl Marketplace {
    pub fn parse(
        bytes: &[u8],
        diagnostics: &mut Vec<(String, SchemaDiagnostic)>,
    ) -> Result<Self, SchemaDiagnostic> {
        let object = parse_object(bytes, MARKETPLACE_MANIFEST)?;
        let plugin_root = object
            .get("metadata")
            .and_then(|metadata| metadata.get("pluginRoot"))
            .and_then(Value::as_str);
        let mut plugins = Vec::new();
        for (index, entry) in object
            .get("plugins")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .enumerate()
        {
            let Some(entry) = entry.as_object() else {
                continue;
            };
            let Some(name) = text(entry, "name") else {
                diagnostics.push((
                    MARKETPLACE_MANIFEST.to_owned(),
                    SchemaDiagnostic::new(
                        "marketplace.plugin-unnamed",
                        Severity::Warning,
                        vec![
                            PathSegment::Key("plugins".into()),
                            PathSegment::Index(index),
                        ],
                        "a plugin entry without a `name` was left out",
                    ),
                ));
                continue;
            };
            if !is_plugin_name(&name) {
                diagnostics.push((
                    MARKETPLACE_MANIFEST.to_owned(),
                    SchemaDiagnostic::new(
                        "marketplace.plugin-name-invalid",
                        Severity::Warning,
                        vec![
                            PathSegment::Key("plugins".into()),
                            PathSegment::Index(index),
                            PathSegment::Key("name".into()),
                        ],
                        format!(
                            "plugin name `{name}` is not usable ({PLUGIN_NAME_RULE}); the entry was left out"
                        ),
                    ),
                ));
                continue;
            }
            plugins.push(MarketplaceEntry {
                source: parse_source(entry.get("source"), plugin_root),
                description: text(entry, "description"),
                version: text(entry, "version"),
                strict: entry.get("strict").and_then(Value::as_bool),
                lists: ComponentLists::from_object(entry, MARKETPLACE_MANIFEST, diagnostics),
                name,
            });
        }
        Ok(Self {
            name: text(&object, "name"),
            plugins,
        })
    }
}

/// What a plugin name may be: it becomes a package id and the tail of a dependency name, so it is
/// one path component that no tool reads as an option or a hidden entry.
pub const PLUGIN_NAME_RULE: &str =
    "letters, digits, `-`, `_` and `.`, starting with a letter or digit";

/// Whether `name` is a usable plugin name. The marketplace reader leaves out an entry that fails
/// it, and a caller that takes a plugin name from a user checks the same rule.
pub fn is_plugin_name(name: &str) -> bool {
    name.bytes()
        .next()
        .is_some_and(|byte| byte.is_ascii_alphanumeric())
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
}

fn unsupported(reason: impl Into<String>) -> PluginSource {
    PluginSource::Unsupported {
        reason: reason.into(),
    }
}

/// Normalize a marketplace-relative path: `.` and `./` are the root, `..` and absolute
/// paths are refused.
fn local_path(raw: &str) -> Option<String> {
    let trimmed = raw.strip_prefix("./").unwrap_or(raw).trim_end_matches('/');
    let trimmed = if trimmed == "." { "" } else { trimmed };
    if trimmed
        .split('/')
        .any(|part| matches!(part, ".." | "") && !trimmed.is_empty())
        || trimmed.starts_with('/')
        || trimmed.contains('\\')
    {
        None
    } else {
        Some(trimmed.to_owned())
    }
}

fn parse_source(source: Option<&Value>, plugin_root: Option<&str>) -> PluginSource {
    let Some(source) = source else {
        return unsupported("the entry has no `source`");
    };
    if let Some(raw) = source.as_str() {
        let relative = if raw == "." || raw.starts_with("./") {
            raw.to_owned()
        } else if let Some(root) = plugin_root {
            // A bare name resolves under `metadata.pluginRoot`.
            format!("{}/{raw}", root.trim_end_matches('/'))
        } else {
            return unsupported(format!("`{raw}` is not a `./` path"));
        };
        return match local_path(&relative) {
            Some(path) => PluginSource::Local { path },
            None => unsupported(format!("`{raw}` leaves the marketplace")),
        };
    }
    let Some(object) = source.as_object() else {
        return unsupported("`source` must be a path or an object");
    };
    let field = |key: &str| object.get(key).and_then(Value::as_str);
    // What the entry pins: a full commit, else a ref, else the default branch. A `sha` that is
    // not a full commit is refused, never read as an unpinned checkout.
    let checkout = || -> Result<Checkout, String> {
        match object.get("sha").filter(|sha| !sha.is_null()) {
            Some(sha) => match sha.as_str().filter(|sha| is_full_sha(sha)) {
                Some(sha) => Ok(Checkout::Sha {
                    sha: sha.to_owned(),
                }),
                None => Err("`sha` is not a full 40-character commit".to_owned()),
            },
            None => match field("ref") {
                Some(name) => match git_argument_refusal("ref", name) {
                    Some(reason) => Err(reason),
                    None => Ok(Checkout::Ref {
                        name: name.to_owned(),
                    }),
                },
                None => Ok(Checkout::DefaultBranch),
            },
        }
    };
    // The repository and ref are third-party text that reaches `git`'s argument list.
    let remote = |repository: &str, path: Option<String>| {
        let repository = repository_url(repository);
        if let Some(reason) = repository_refusal(&repository) {
            return unsupported(reason);
        }
        match checkout() {
            Ok(checkout) => PluginSource::Remote {
                repository,
                path,
                checkout,
            },
            Err(reason) => unsupported(reason),
        }
    };
    let kind = field("source").unwrap_or_default();
    match kind {
        "github" => match field("repo") {
            Some(repo) => remote(repo, None),
            None => unsupported("a `github` source needs `repo`"),
        },
        "url" => match field("url") {
            Some(url) => remote(url, None),
            None => unsupported("a `url` source needs `url`"),
        },
        "git-subdir" => match (field("url"), field("path").and_then(local_path)) {
            (Some(url), Some(path)) => remote(url, Some(path).filter(|path| !path.is_empty())),
            _ => unsupported("a `git-subdir` source needs `url` and an in-repository `path`"),
        },
        "" => unsupported("`source` has no `source` type"),
        other => unsupported(format!("`{other}` sources cannot be imported")),
    }
}

/// Why `value` (a repository or a ref) must not reach `git` as an argument: it would be read as
/// an option (`--upload-pack=<cmd>` runs a command), or holds whitespace or control characters.
fn git_argument_refusal(what: &str, value: &str) -> Option<String> {
    if value.is_empty() {
        Some(format!("the {what} is empty"))
    } else if value.starts_with('-') {
        Some(format!(
            "{what} `{value}` starts with `-`, which git reads as an option"
        ))
    } else if value
        .chars()
        .any(|character| character.is_whitespace() || character.is_control())
    {
        Some(format!(
            "{what} `{value}` holds whitespace or a control character"
        ))
    } else {
        None
    }
}

/// Only a network repository may be named: `https://`, `ssh://` or `user@host:path`. A local
/// repository (`file://`, an absolute path) would read the machine that runs the fetch, and
/// another scheme (`ext::<cmd>`, `git://`, `http://`) is a transport helper or unencrypted.
fn repository_refusal(repository: &str) -> Option<String> {
    if let Some(reason) = git_argument_refusal("repository", repository) {
        return Some(reason);
    }
    if repository.starts_with("file://") || repository.starts_with('/') {
        return Some(format!(
            "repository `{repository}` is a local repository; a marketplace entry names only network repositories"
        ));
    }
    let scp_like = repository
        .split_once(':')
        .is_some_and(|(user_host, path)| user_host.contains('@') && !path.is_empty());
    (!(repository.starts_with("https://") || repository.starts_with("ssh://") || scp_like)).then(
        || {
            format!(
                "repository `{repository}` is not an `https://` or `ssh://` URL or a `user@host:path` address"
            )
        },
    )
}

fn is_full_sha(value: &str) -> bool {
    value.len() == 40
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

/// `owner/repo` shorthand means GitHub; anything else is a URL as written, minus `.git`.
fn repository_url(value: &str) -> String {
    let value = value.strip_suffix(".git").unwrap_or(value);
    let shorthand = !value.contains("://")
        && !value.starts_with("git@")
        && value.matches('/').count() == 1
        && !value.starts_with('/');
    if shorthand {
        format!("https://github.com/{value}")
    } else {
        value.to_owned()
    }
}

/// What one plugin contains once Claude's rules have combined `plugin.json` with a
/// marketplace entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginSpec {
    pub name: Option<String>,
    pub version: Option<String>,
    pub description: Option<String>,
    pub skills: SkillSources,
    /// `None` reads the default `agents/` folder.
    pub agents: Option<Vec<String>>,
    /// `None` reads the default `commands/` folder; commands are only reported.
    pub commands: Option<Vec<String>>,
    pub hooks: bool,
    pub mcp: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillSources {
    /// No manifest: every `SKILL.md` directory within five levels of the root.
    Walk,
    /// A manifest: the default `skills/<name>/SKILL.md` (unless `default` is off) plus `listed`.
    Declared { default: bool, listed: Vec<String> },
}

impl PluginSpec {
    /// The spec of a tree with no manifest, where every `SKILL.md` directory is a skill.
    pub(crate) fn is_bare_tree(&self) -> bool {
        self.skills == SkillSources::Walk
    }

    pub fn walk() -> Self {
        Self {
            name: None,
            version: None,
            description: None,
            skills: SkillSources::Walk,
            agents: None,
            commands: None,
            hooks: false,
            mcp: false,
        }
    }
}

/// The marketplace entry and `strict` rules; `entry_at_root` is whether the entry's source is
/// the marketplace root itself.
pub(crate) fn resolve_spec(
    manifest: Option<&PluginManifest>,
    entry: Option<&MarketplaceEntry>,
    entry_at_root: bool,
) -> Result<PluginSpec, String> {
    let name = manifest
        .and_then(|manifest| manifest.name.clone())
        .or_else(|| entry.map(|entry| entry.name.clone()));
    let version = manifest
        .and_then(|manifest| manifest.version.clone())
        .or_else(|| entry.and_then(|entry| entry.version.clone()));
    let description = manifest
        .and_then(|manifest| manifest.description.clone())
        .or_else(|| entry.and_then(|entry| entry.description.clone()));
    let empty = ComponentLists::default();
    let entry_lists = entry.map_or(&empty, |entry| &entry.lists);

    let (lists, default_skills) = match manifest {
        None => (
            entry_lists.clone(),
            // Only the marketplace-root entry with a `skills` list narrows the default scan.
            !(entry_at_root && entry_lists.skills.is_some()),
        ),
        Some(manifest) => {
            if entry.is_some_and(|entry| entry.strict == Some(false))
                && entry_lists.has_components()
            {
                return Err("conflicting manifests: both plugin.json and the marketplace entry (with `strict: false`) specify components".to_owned());
            }
            // A non-strict entry with no components adds nothing, so appending is uniform.
            let append = |own: &Option<Vec<String>>, entry: &Option<Vec<String>>| {
                (own.is_some() || entry.is_some()).then(|| {
                    own.iter()
                        .flatten()
                        .chain(entry.iter().flatten())
                        .cloned()
                        .collect()
                })
            };
            (
                ComponentLists {
                    skills: append(&manifest.lists.skills, &entry_lists.skills),
                    agents: append(&manifest.lists.agents, &entry_lists.agents),
                    commands: append(&manifest.lists.commands, &entry_lists.commands),
                    hooks: manifest.lists.hooks || entry_lists.hooks,
                    mcp: manifest.lists.mcp,
                },
                true,
            )
        }
    };
    Ok(PluginSpec {
        name,
        version,
        description,
        skills: SkillSources::Declared {
            default: default_skills,
            listed: lists.skills.unwrap_or_default(),
        },
        agents: lists.agents,
        commands: lists.commands,
        hooks: lists.hooks,
        mcp: lists.mcp,
    })
}