返回 CodeWhale
mod.rs
1 //! Catalog parsers, one per real published schema.
2 //!
3 //! Each parser consumes only fields its format documents. Unknown fields
4 //! produce visible warnings, never silent acceptance and never invented
5 //! fallbacks: a field the format does not define is not parsed as some
6 //! plausible equivalent. There is no network access at this layer.
7
8 pub mod claude;
9 pub mod codewhale;
10 pub mod codex;
11 pub mod dsh;
12 pub mod kimi;
13
14 use serde_json::Value;
15
16 use crate::manifest::{PluginCompatibility, PluginInventory};
17
18 use super::types::{
19 MarketplaceCatalog, MarketplaceCatalogId, MarketplaceDiagnostic, MarketplaceFormat,
20 MarketplaceInstallPlan, MarketplaceSourceSpec,
21 };
22
23 /// Catalog-side compatibility. Unlike an installed bundle's reviewed
24 /// inventory, catalog declarations do not state MCP transport, so any
25 /// declared `mcp_servers` count is treated as a supported-capable
26 /// declaration; the install-time review decides the real activation
27 /// policy binding.
28 pub(super) fn declared_catalog_compatibility(declared: &PluginInventory) -> PluginCompatibility {
29 let supported = declared.skills > 0 || declared.mcp_servers > 0;
30 let unsupported = declared.commands > 0
31 || declared.agents > 0
32 || declared.hooks > 0
33 || declared.lsp > 0
34 || declared.native > 0
35 || !declared.filesystem_roots.is_empty()
36 || !declared.network_hosts.is_empty()
37 || declared.lifecycle_mutation;
38 match (supported, unsupported) {
39 (true, false) => PluginCompatibility::Full,
40 (true, true) => PluginCompatibility::Partial,
41 (false, true) => PluginCompatibility::Unsupported,
42 (false, false) => PluginCompatibility::Full,
43 }
44 }
45
46 /// Input to catalog parsing. `base` is where the document was read from
47 /// (path or URL) — kept for install-time resolution of relative sources;
48 /// the parser itself never touches it.
49 pub struct MarketplaceDocument {
50 pub catalog_id: MarketplaceCatalogId,
51 pub format: MarketplaceFormat,
52 pub root: Value,
53 pub base: Option<String>,
54 }
55
56 /// Parse one catalog document. `MarketplaceFormat::Auto` detects the
57 /// format from documented structural markers only, and reports ambiguity
58 /// as an error diagnostic rather than guessing.
59 pub fn parse_catalog(document: MarketplaceDocument) -> MarketplaceCatalog {
60 let format = match document.format {
61 MarketplaceFormat::Auto => match detect_format(&document.root) {
62 Ok(format) => format,
63 Err(diagnostic) => {
64 let name = document.catalog_id.as_str().to_string();
65 return MarketplaceCatalog {
66 id: document.catalog_id,
67 format: MarketplaceFormat::Auto,
68 name,
69 display_name: None,
70 description: None,
71 version: None,
72 base: document.base,
73 provenance: super::types::CatalogProvenance::default(),
74 candidates: Vec::new(),
75 diagnostics: vec![diagnostic],
76 };
77 }
78 },
79 explicit => explicit,
80 };
81
82 let mut catalog = match format {
83 MarketplaceFormat::Kimi => kimi::parse_kimi_catalog(document),
84 MarketplaceFormat::Claude => claude::parse_claude_catalog(document),
85 MarketplaceFormat::Codex => codex::parse_codex_catalog(document),
86 MarketplaceFormat::Codewhale => codewhale::parse_codewhale_catalog(document),
87 MarketplaceFormat::Dsh => dsh::parse_dsh_catalog(document),
88 MarketplaceFormat::Auto => unreachable!("resolved above"),
89 };
90 flag_duplicate_names(&mut catalog);
91 catalog
92 }
93
94 /// A candidate's name is its identity: `/plugin show`, install, and registry
95 /// lookups all resolve by it, and a lookup returns the first match. Entries
96 /// sharing a name (after each format's normalization) are ambiguous, so every
97 /// one of them carries an error and none installs from the catalog.
98 fn flag_duplicate_names(catalog: &mut super::types::MarketplaceCatalog) {
99 let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
100 for candidate in &catalog.candidates {
101 *counts.entry(candidate.name.clone()).or_default() += 1;
102 }
103 for candidate in &mut catalog.candidates {
104 let count = counts.get(&candidate.name).copied().unwrap_or(0);
105 if count > 1 {
106 candidate.diagnostics.push(MarketplaceDiagnostic::error(
107 "DUPLICATE_NAME",
108 format!(
109 "{count} catalog entries are named `{}`; the entry's identity is ambiguous",
110 candidate.name
111 ),
112 Some(candidate.name.clone()),
113 None,
114 ));
115 }
116 }
117 }
118
119 /// Detection uses only markers each format's own documentation defines:
120 ///
121 /// - **Kimi**: `plugins[]` whose entries carry `id` + `source` (Kimi uses
122 /// `id`; the Claude-family formats use `name`).
123 /// - **Claude**: top-level `owner` object, a `plugins[]` entry with a
124 /// `source` object using the Claude discriminators (`github`, `url`,
125 /// `git-subdir`, `npm`, `archive`, `command`), or `metadata.pluginRoot`.
126 /// - **Codex**: a `plugins[]` entry with a `policy` object, a `source`
127 /// object with the `local` discriminator, or a top-level `interface`
128 /// object.
129 /// - **Codewhale**: `plugins[]` entries with `name` + a string `source`
130 /// that is a Codewhale install spec (`github:`, `path:`, URL).
131 /// - **DSH**: a top-level numeric `format` (the DSH plugin market index
132 /// format; version `1` is the only one defined, and any other value is
133 /// reported by the parser rather than guessed).
134 ///
135 /// Documents matching no documented marker are ambiguous, not guessed.
136 fn detect_format(root: &Value) -> Result<MarketplaceFormat, MarketplaceDiagnostic> {
137 let Some(obj) = root.as_object() else {
138 return Err(MarketplaceDiagnostic::error(
139 "NOT_AN_OBJECT",
140 "marketplace catalog must be a JSON object",
141 None,
142 None,
143 ));
144 };
145 let Some(entries) = obj.get("plugins").and_then(Value::as_array) else {
146 return Err(MarketplaceDiagnostic::error(
147 "UNKNOWN_FORMAT",
148 "catalog has no documented marker: expected Kimi `plugins` with `id` entries, \
149 Claude `owner`/`plugins`, Codex `policy`/`interface`, DSH `format: 1` with \
150 `versions` entries, or Codewhale `plugins` with install-spec sources",
151 None,
152 None,
153 ));
154 };
155
156 // DSH market index: the format declares a numeric `format`, and 1 is the
157 // only version of it. Any numeric `format` routes here so the parser can
158 // report the version it cannot read instead of calling the document
159 // ambiguous. No other supported format declares a numeric `format`.
160 if obj.get("format").is_some_and(Value::is_number) {
161 return Ok(MarketplaceFormat::Dsh);
162 }
163
164 // Claude: `owner` and `metadata.pluginRoot` are documented top-level
165 // fields no other format defines.
166 if obj.contains_key("owner")
167 || obj
168 .get("metadata")
169 .and_then(|m| m.get("pluginRoot"))
170 .is_some()
171 {
172 return Ok(MarketplaceFormat::Claude);
173 }
174
175 let entry_markers: Vec<MapMarker> = entries
176 .iter()
177 .map(|entry| {
178 let entry_obj = entry.as_object();
179 MapMarker {
180 has_id: entry_obj.is_some_and(|o| o.contains_key("id")),
181 has_name: entry_obj.is_some_and(|o| o.contains_key("name")),
182 source_kind: entry_obj.and_then(|o| o.get("source")).map(source_marker),
183 has_policy: entry_obj.is_some_and(|o| o.contains_key("policy")),
184 }
185 })
186 .collect();
187
188 // Codex: `policy` blocks or `local` sources are Codex-only markers.
189 if entry_markers
190 .iter()
191 .any(|m| m.has_policy || m.source_kind == Some(SourceMarker::Local))
192 || obj.contains_key("interface")
193 {
194 return Ok(MarketplaceFormat::Codex);
195 }
196
197 // Claude source discriminators other than `local`.
198 if entry_markers.iter().any(|m| {
199 matches!(
200 m.source_kind,
201 Some(SourceMarker::Github)
202 | Some(SourceMarker::Url)
203 | Some(SourceMarker::GitSubdir)
204 | Some(SourceMarker::Npm)
205 | Some(SourceMarker::Archive)
206 | Some(SourceMarker::Command)
207 )
208 }) {
209 return Ok(MarketplaceFormat::Claude);
210 }
211
212 // Kimi: `id`-keyed entries with string sources.
213 if entry_markers.iter().any(|m| {
214 m.has_id
215 && matches!(
216 m.source_kind,
217 Some(SourceMarker::String | SourceMarker::UrlString)
218 )
219 }) {
220 return Ok(MarketplaceFormat::Kimi);
221 }
222
223 // Codewhale: `name` entries with install-spec string sources.
224 if entry_markers.iter().any(|m| {
225 m.has_name
226 && matches!(
227 m.source_kind,
228 Some(SourceMarker::InstallSpec | SourceMarker::UrlString)
229 )
230 }) {
231 return Ok(MarketplaceFormat::Codewhale);
232 }
233
234 Err(MarketplaceDiagnostic::error(
235 "AMBIGUOUS_FORMAT",
236 "catalog markers match no documented format uniquely; pass the format explicitly",
237 None,
238 None,
239 ))
240 }
241
242 struct MapMarker {
243 has_id: bool,
244 has_name: bool,
245 source_kind: Option<SourceMarker>,
246 has_policy: bool,
247 }
248
249 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
250 enum SourceMarker {
251 String,
252 UrlString,
253 InstallSpec,
254 Github,
255 Url,
256 GitSubdir,
257 Npm,
258 Archive,
259 Command,
260 Local,
261 OtherObject,
262 }
263
264 fn source_marker(source: &Value) -> SourceMarker {
265 match source {
266 Value::String(s) => {
267 if s.starts_with("github:") || s.starts_with("path:") {
268 SourceMarker::InstallSpec
269 } else if s.starts_with("https://") || s.starts_with("http://") {
270 SourceMarker::UrlString
271 } else {
272 SourceMarker::String
273 }
274 }
275 Value::Object(o) => match o.get("source").and_then(Value::as_str) {
276 Some("github") => SourceMarker::Github,
277 Some("url") => SourceMarker::Url,
278 Some("git-subdir") => SourceMarker::GitSubdir,
279 Some("npm") => SourceMarker::Npm,
280 Some("archive") => SourceMarker::Archive,
281 Some("command") => SourceMarker::Command,
282 Some("local") => SourceMarker::Local,
283 _ => SourceMarker::OtherObject,
284 },
285 _ => SourceMarker::OtherObject,
286 }
287 }
288
289 /// Shared helper: read a documented string field; a wrong-typed value is
290 /// a per-entry warning and treated as absent, not a guess.
291 pub(super) fn str_field<'a>(
292 entry: &'a serde_json::Map<String, Value>,
293 field: &str,
294 ) -> (Option<&'a str>, Option<MarketplaceDiagnostic>) {
295 match entry.get(field) {
296 None | Some(Value::Null) => (None, None),
297 Some(Value::String(s)) => (Some(s.as_str()), None),
298 Some(other) => (
299 None,
300 Some(MarketplaceDiagnostic::warning(
301 "FIELD_TYPE",
302 format!("field `{field}` must be a string, got {}", type_name(other)),
303 None,
304 None,
305 )),
306 ),
307 }
308 }
309
310 /// Shared helper: read a documented string-array field.
311 pub(super) fn str_array_field(
312 entry: &serde_json::Map<String, Value>,
313 field: &str,
314 ) -> (Vec<String>, Option<MarketplaceDiagnostic>) {
315 match entry.get(field) {
316 None | Some(Value::Null) => (Vec::new(), None),
317 Some(Value::Array(items)) => {
318 let mut out = Vec::new();
319 let mut skipped = false;
320 for item in items {
321 match item {
322 Value::String(s) => out.push(s.clone()),
323 _ => skipped = true,
324 }
325 }
326 let diag = skipped.then(|| {
327 MarketplaceDiagnostic::warning(
328 "FIELD_TYPE",
329 format!(
330 "field `{field}` must be an array of strings; non-string items skipped"
331 ),
332 None,
333 None,
334 )
335 });
336 (out, diag)
337 }
338 Some(other) => (
339 Vec::new(),
340 Some(MarketplaceDiagnostic::warning(
341 "FIELD_TYPE",
342 format!(
343 "field `{field}` must be an array of strings, got {}",
344 type_name(other)
345 ),
346 None,
347 None,
348 )),
349 ),
350 }
351 }
352
353 /// Shared helper: warn on fields this format does not document. Unknown
354 /// fields are preserved in diagnostics so catalog authors see them; they
355 /// are never silently reinterpreted.
356 pub(super) fn unknown_fields_warning(
357 entry: &serde_json::Map<String, Value>,
358 known: &[&str],
359 ) -> Option<MarketplaceDiagnostic> {
360 let unknown: Vec<&String> = entry
361 .keys()
362 .filter(|k| !known.contains(&k.as_str()))
363 .collect();
364 if unknown.is_empty() {
365 return None;
366 }
367 Some(MarketplaceDiagnostic::warning(
368 "UNKNOWN_FIELD",
369 format!(
370 "undeclared field(s) ignored: {}",
371 unknown
372 .iter()
373 .map(|s| s.as_str())
374 .collect::<Vec<_>>()
375 .join(", ")
376 ),
377 None,
378 None,
379 ))
380 }
381
382 fn type_name(value: &Value) -> &'static str {
383 match value {
384 Value::Null => "null",
385 Value::Bool(_) => "a boolean",
386 Value::Number(_) => "a number",
387 Value::String(_) => "a string",
388 Value::Array(_) => "an array",
389 Value::Object(_) => "an object",
390 }
391 }
392
393 fn github_url_parts(url: &str) -> Option<(String, String)> {
394 let rest = url
395 .strip_prefix("https://github.com/")
396 .or_else(|| url.strip_prefix("http://github.com/"))?;
397 let mut parts = rest.trim_end_matches('/').split('/');
398 match (parts.next(), parts.next(), parts.next()) {
399 (Some(owner), Some(repo), None) if !owner.is_empty() && !repo.is_empty() => {
400 Some((owner.to_string(), repo.trim_end_matches(".git").to_string()))
401 }
402 _ => None,
403 }
404 }
405
406 type GitSourcePlan = (
407 MarketplaceSourceSpec,
408 MarketplaceInstallPlan,
409 Vec<MarketplaceDiagnostic>,
410 );
411
412 fn git_url_source(value: &Value) -> GitSourcePlan {
413 let url = value["url"].as_str().unwrap_or_default();
414 if value["source"] == "url"
415 && let Some((owner, repo)) = github_url_parts(url)
416 {
417 return github_source(value, &owner, &repo);
418 }
419 let reason = if value["source"] == "git-subdir" {
420 "Git subdirectory installs are unavailable. Install a reviewed local copy of the requested subdirectory."
421 } else {
422 "Git URL sources must point to a GitHub repository."
423 };
424 (
425 MarketplaceSourceSpec::GitUrl {
426 url: url.to_string(),
427 },
428 MarketplaceInstallPlan::Unsupported {
429 reason: reason.to_string(),
430 raw: value.to_string(),
431 },
432 Vec::new(),
433 )
434 }
435
436 fn github_source(value: &Value, owner: &str, repo: &str) -> GitSourcePlan {
437 let git_ref = value.get("ref").and_then(Value::as_str);
438 let sha = value.get("sha").and_then(Value::as_str);
439 let source = MarketplaceSourceSpec::GitHub {
440 owner: owner.to_string(),
441 repo: repo.to_string(),
442 git_ref: git_ref.map(str::to_string),
443 sha: sha.map(str::to_string),
444 };
445 if value.get("path").is_some() {
446 return (
447 source,
448 MarketplaceInstallPlan::Unsupported {
449 reason: "Git subdirectory installs are unavailable. Install a reviewed local copy of the requested subdirectory.".to_string(),
450 raw: value.to_string(),
451 },
452 Vec::new(),
453 );
454 }
455 let mut spec = format!("git:github.com/{owner}/{repo}");
456 if let Some(revision) = sha.or(git_ref) {
457 spec.push('@');
458 spec.push_str(revision);
459 }
460 let valid_sha = value.get("sha").is_none()
461 || sha.is_some_and(|pin| pin.len() == 40 && pin.bytes().all(|b| b.is_ascii_hexdigit()));
462 let valid_ref =
463 value.get("ref").is_none() || git_ref.is_some_and(|revision| !revision.is_empty());
464 let plan = if !repo.contains('@')
465 && spec.trim() == spec
466 && valid_sha
467 && valid_ref
468 && crate::install::PluginInstallSource::parse(&spec).is_ok()
469 {
470 MarketplaceInstallPlan::Supported {
471 spec: if git_ref.is_some() || sha.is_some() {
472 spec
473 } else {
474 format!("github:{owner}/{repo}")
475 },
476 source_kind: "GitHub repository".to_string(),
477 }
478 } else {
479 MarketplaceInstallPlan::Unsupported { reason: "The GitHub repository or requested revision cannot be installed exactly as declared.".to_string(), raw: value.to_string() }
480 };
481 (source, plan, Vec::new())
482 }
483
483 lines RUST