返回 CodeWhale
marketplace.rs
根目录 / crates / tui / src / commands / groups / plugins / marketplace.rs
1 //! `/plugin marketplace` — the #5311 user journey over the catalog parsers.
2 //!
3 //! `add` reads a LOCAL catalog document (no network here, ever), parses it
4 //! with the strict per-format parsers, and persists the parsed result next to
5 //! the plugin registry state. `list`/`show` render candidates with their
6 //! honest install plans and per-entry diagnostics. `install` routes a
7 //! candidate through the EXISTING reviewed installer — the same code path as
8 //! `/plugin install`, so installed bundles still enter disabled and untrusted.
9 //!
10 //! Catalog-declared tiers and provenance are display-only: nothing in this
11 //! module grants trust, enables anything, or auto-installs (Codex
12 //! `INSTALLED_BY_DEFAULT` is visibly ignored).
13 //!
14 //! FEAT-020: the marketplace store/parse/install machinery runs host-side in
15 //! the TUI adapter; the handler consumes portable marketplace values and
16 //! renders them.
17
18 use super::render::ReviewTextContext;
19 use std::fmt::Write as _;
20 use std::path::{Path, PathBuf};
21
22 use codewhale_command_contract::facets::{
23 CommandPluginContext, CommandPresentationContext, PluginMarketplaceCatalog,
24 PluginMarketplaceInstallPlan,
25 };
26
27 use crate::commands::CommandResult;
28
29 const USAGE: &str = "Usage: /plugin marketplace add|list|show|remove|install\n\
30 \x20 add <name> <path> read a local catalog file (kimi/claude/codex/dsh/codewhale)\n\
31 \x20 list show catalogs and their candidates\n\
32 \x20 show <name> one catalog in detail\n\
33 \x20 remove <name> forget a catalog (installed plugins unaffected)\n\
34 \x20 install <catalog> <candidate> install via the reviewed installer";
35
36 pub(super) fn dispatch(
37 presentation: &mut dyn CommandPresentationContext,
38 plugin: &mut dyn CommandPluginContext,
39 words: &[&str],
40 ) -> CommandResult {
41 match words {
42 [] | ["list"] => list(presentation, plugin),
43 ["add", name, path] => add(presentation, plugin, name, path),
44 ["show", name] => show(presentation, plugin, name),
45 ["remove", name] => remove(presentation, plugin, name),
46 ["install", catalog, candidate] => install(presentation, plugin, catalog, candidate),
47 _ => CommandResult::error(USAGE),
48 }
49 }
50
51 fn add(
52 _presentation: &mut dyn CommandPresentationContext,
53 plugin: &mut dyn CommandPluginContext,
54 name: &str,
55 raw_path: &str,
56 ) -> CommandResult {
57 let path = PathBuf::from(raw_path.trim());
58 let path = if path.is_absolute() {
59 path
60 } else {
61 PathBuf::from(".").join(path)
62 };
63 match plugin.marketplace_add(name, &path) {
64 Ok(receipt) => {
65 let summary = render_catalog_summary(name, &receipt.catalog);
66 CommandResult::message(format!(
67 "Added marketplace `{}` ({} candidate(s), {} warning(s)).\n{summary}\n\
68 Tiers and provenance are display-only. Nothing was installed, trusted, or enabled.",
69 escape_review_text(name, ReviewTextContext::InlineCode),
70 receipt.candidate_count,
71 receipt.warning_count,
72 ))
73 }
74 Err(error) => CommandResult::error(error),
75 }
76 }
77
78 fn list(
79 presentation: &mut dyn CommandPresentationContext,
80 plugin: &dyn CommandPluginContext,
81 ) -> CommandResult {
82 let state = match plugin.marketplace_state() {
83 Ok(state) => state,
84 Err(error) => {
85 return CommandResult::error(format!(
86 "Marketplace state is fail-closed and will not be rewritten: {error}"
87 ));
88 }
89 };
90 if state.official.is_none() && state.stored.is_empty() {
91 return CommandResult::message(format!(
92 "No marketplace catalogs are registered.\n{USAGE}\n\
93 Reads a LOCAL catalog file; nothing is fetched over the network."
94 ));
95 }
96 let mut output = String::from("Marketplace catalogs:\n");
97 if let Some(official) = &state.official {
98 output.push('\n');
99 output.push_str(&render_catalog_summary("official", official));
100 output.push_str(" built into this Codewhale release; nothing is downloaded\n");
101 output.push_str(&render_candidates(presentation, official, false));
102 }
103 for catalog in &state.stored {
104 output.push('\n');
105 output.push_str(&render_catalog_summary(&catalog.id, catalog));
106 output.push_str(&render_candidates(presentation, catalog, false));
107 }
108 output.push_str(
109 "\nTiers and provenance are display-only. Install with /plugin marketplace install <catalog> <candidate>; \
110 installs go through the reviewed installer and start disabled and untrusted.",
111 );
112 CommandResult::message(output)
113 }
114
115 fn show(
116 presentation: &mut dyn CommandPresentationContext,
117 plugin: &dyn CommandPluginContext,
118 name: &str,
119 ) -> CommandResult {
120 let state = match plugin.marketplace_state() {
121 Ok(state) => state,
122 Err(error) => {
123 return CommandResult::error(format!(
124 "Marketplace state is fail-closed and will not be rewritten: {error}"
125 ));
126 }
127 };
128 let catalog = if name == "official" {
129 state.official.as_ref()
130 } else {
131 state.stored.iter().find(|catalog| catalog.id == name)
132 };
133 let Some(catalog) = catalog else {
134 return CommandResult::error(format!(
135 "No marketplace named `{}`. Use /plugin marketplace list.",
136 escape_review_text(name, ReviewTextContext::InlineCode)
137 ));
138 };
139 let mut output = render_catalog_summary(name, catalog);
140 output.push_str("\n added from: ");
141 let _ = writeln!(
142 output,
143 "{}",
144 escape_review_path(
145 Path::new(catalog.source_path.as_deref().unwrap_or(name)),
146 ReviewTextContext::Prose
147 )
148 );
149 output.push_str(&render_candidates(presentation, catalog, true));
150 CommandResult::message(output)
151 }
152
153 fn remove(
154 _presentation: &mut dyn CommandPresentationContext,
155 plugin: &mut dyn CommandPluginContext,
156 name: &str,
157 ) -> CommandResult {
158 match plugin.marketplace_remove(name) {
159 Ok(true) => CommandResult::message(format!(
160 "Removed marketplace `{}`. Installed plugins and their trust state are unaffected.",
161 escape_review_text(name, ReviewTextContext::InlineCode)
162 )),
163 Ok(false) => CommandResult::error(format!(
164 "No marketplace named `{}`. Use /plugin marketplace list.",
165 escape_review_text(name, ReviewTextContext::InlineCode)
166 )),
167 Err(error) => CommandResult::error(error),
168 }
169 }
170
171 fn install(
172 presentation: &mut dyn CommandPresentationContext,
173 plugin: &mut dyn CommandPluginContext,
174 catalog_name: &str,
175 candidate_name: &str,
176 ) -> CommandResult {
177 match plugin.marketplace_install(catalog_name, candidate_name) {
178 Ok(receipt) => {
179 use codewhale_command_contract::facets::PluginMutationOutcome;
180 match receipt.outcome {
181 PluginMutationOutcome::Installed => {
182 // Marketplace installs route through the same reviewed
183 // installer as `/plugin install`: the result is disabled
184 // and untrusted and drops into the trust review.
185 let name = receipt.name;
186 let mut output = format!(
187 "Installed plugin '{name}' from marketplace `{}`.\n\
188 It is disabled and untrusted. Review its requested authority below, then trust and enable it.\n",
189 escape_review_text(catalog_name, ReviewTextContext::InlineCode)
190 );
191 if let Some(review) = super::review_bundle(presentation, plugin, &name).message
192 {
193 output.push('\n');
194 output.push_str(&review);
195 }
196 CommandResult::with_message_and_action(
197 output,
198 crate::tui::app::AppAction::PluginRegistryChanged,
199 )
200 }
201 PluginMutationOutcome::NeedsApproval(host) => {
202 CommandResult::error(needs_approval_message(&host))
203 }
204 PluginMutationOutcome::NetworkDenied(host) => {
205 CommandResult::error(network_denied_message(&host))
206 }
207 PluginMutationOutcome::NoChange => CommandResult::message(format!(
208 "`{}` is built into Codewhale, so there is nothing to install. \
209 Review it with /plugin show {}.",
210 escape_review_text(candidate_name, ReviewTextContext::InlineCode),
211 escape_review_text(&receipt.name, ReviewTextContext::Prose)
212 )),
213 _ => CommandResult::message(format!(
214 "Installed `{}` from marketplace `{}`.",
215 escape_review_text(candidate_name, ReviewTextContext::InlineCode),
216 escape_review_text(catalog_name, ReviewTextContext::InlineCode)
217 )),
218 }
219 }
220 Err(error) => CommandResult::error(error),
221 }
222 }
223
224 fn needs_approval_message(host: &str) -> String {
225 format!(
226 "Network policy requires approval for {host}.\n\
227 Add it to your allow list with `/network allow {host}` (or set [network].default = \"allow\" in ~/.codewhale/config.toml), then retry."
228 )
229 }
230
231 fn network_denied_message(host: &str) -> String {
232 format!(
233 "Network policy denied access to {host}.\n\
234 Remove the deny entry from ~/.codewhale/config.toml under [network] or contact your administrator."
235 )
236 }
237
238 fn render_catalog_summary(name: &str, catalog: &PluginMarketplaceCatalog) -> String {
239 let mut out = String::new();
240 let display = catalog
241 .display_name
242 .as_deref()
243 .filter(|d| !d.trim().is_empty());
244 let _ = writeln!(
245 out,
246 "`{}` — {} format, {} candidate(s), tier={} (display only)",
247 escape_review_text(name, ReviewTextContext::InlineCode),
248 catalog.format,
249 catalog.total_candidates,
250 catalog.tier
251 );
252 if let Some(display) = display {
253 let _ = writeln!(
254 out,
255 " display name: {}",
256 escape_review_text(display, ReviewTextContext::Prose)
257 );
258 }
259 if let Some(description) = catalog
260 .description
261 .as_deref()
262 .filter(|d| !d.trim().is_empty())
263 {
264 let _ = writeln!(
265 out,
266 " {}",
267 escape_review_text(description, ReviewTextContext::Prose)
268 );
269 }
270 if !catalog.diagnostics.is_empty() {
271 let _ = writeln!(
272 out,
273 " catalog diagnostics: {}",
274 render_diagnostics_inline(&catalog.diagnostics)
275 );
276 }
277 out
278 }
279
280 fn render_candidates(
281 presentation: &mut dyn CommandPresentationContext,
282 catalog: &PluginMarketplaceCatalog,
283 detailed: bool,
284 ) -> String {
285 let mut out = String::new();
286 for candidate in &catalog.candidates {
287 let status = if candidate.has_errors {
288 "unusable"
289 } else if matches!(
290 candidate.install_plan,
291 PluginMarketplaceInstallPlan::AlreadyPresent { .. }
292 ) {
293 "name already present"
294 } else {
295 "candidate"
296 };
297 let _ = write!(
298 out,
299 " • {} [{}] — {}",
300 escape_review_text(&candidate.name, ReviewTextContext::Prose),
301 status,
302 candidate
303 .display_name
304 .as_deref()
305 .map(|value| escape_review_text(value, ReviewTextContext::Prose))
306 .as_deref()
307 .unwrap_or("no display name")
308 );
309 if let Some(version) = &candidate.version {
310 let _ = write!(
311 out,
312 " · v{}",
313 escape_review_text(version, ReviewTextContext::Prose)
314 );
315 }
316 let _ = write!(out, " · tier={}", candidate.tier);
317 let _ = writeln!(out);
318 let compatibility = candidate
319 .compatibility
320 .clone()
321 .unwrap_or_else(|| "decided at install review".to_string());
322 let _ = writeln!(out, " compatibility: {compatibility}");
323 match &candidate.install_plan {
324 PluginMarketplaceInstallPlan::Supported {
325 spec: _,
326 source_kind,
327 } => {
328 let source_kind = localized_plan_text(presentation, source_kind);
329 let _ = writeln!(
330 out,
331 " installable via {source_kind}: /plugin marketplace install {} {}",
332 escape_review_text(&catalog.id, ReviewTextContext::Prose),
333 escape_review_text(&candidate.name, ReviewTextContext::Prose)
334 );
335 }
336 PluginMarketplaceInstallPlan::AlreadyPresent { selector, reason } => {
337 let _ = writeln!(
338 out,
339 " {}",
340 escape_review_text(reason, ReviewTextContext::Prose)
341 );
342 let _ = writeln!(
343 out,
344 " manage: /plugin show {}",
345 escape_review_text(selector, ReviewTextContext::Prose)
346 );
347 }
348 PluginMarketplaceInstallPlan::Unsupported { reason } => {
349 let reason = localized_plan_text(presentation, reason);
350 let _ = writeln!(
351 out,
352 " not installable: {}",
353 escape_review_text(&reason, ReviewTextContext::Prose)
354 );
355 }
356 }
357 if detailed {
358 if let Some(description) = candidate
359 .description
360 .as_deref()
361 .filter(|d| !d.trim().is_empty())
362 {
363 let _ = writeln!(
364 out,
365 " {}",
366 escape_review_text(description, ReviewTextContext::Prose)
367 );
368 }
369 if let Some(homepage) = &candidate.homepage {
370 let _ = writeln!(
371 out,
372 " homepage: {}",
373 escape_review_text(homepage, ReviewTextContext::Prose)
374 );
375 }
376 if let Some(repository) = &candidate.repository {
377 let _ = writeln!(
378 out,
379 " repository: {}",
380 escape_review_text(repository, ReviewTextContext::Prose)
381 );
382 }
383 if let Some(author) = &candidate.author {
384 let _ = writeln!(
385 out,
386 " author: {}",
387 escape_review_text(author, ReviewTextContext::Prose)
388 );
389 }
390 if let Some(license) = &candidate.license {
391 let _ = writeln!(
392 out,
393 " license: {}",
394 escape_review_text(license, ReviewTextContext::Prose)
395 );
396 }
397 if !candidate.keywords.is_empty() {
398 let _ = writeln!(
399 out,
400 " keywords: {}",
401 escape_review_text(&candidate.keywords.join(", "), ReviewTextContext::Prose)
402 );
403 }
404 if let Some(when) = &candidate.when {
405 let _ = writeln!(out, " when: {when}");
406 }
407 }
408 if !candidate.diagnostics.is_empty() {
409 let _ = writeln!(
410 out,
411 " diagnostics: {}",
412 render_diagnostics_inline(&candidate.diagnostics)
413 );
414 }
415 }
416 out
417 }
418
419 /// Resolve a marketplace plan code through the presentation facet, falling
420 /// back to the raw code when unknown (mirrors the legacy localized plan text).
421 fn localized_plan_text(presentation: &mut dyn CommandPresentationContext, value: &str) -> String {
422 presentation
423 .translate(value, &[])
424 .unwrap_or_else(|_| value.to_string())
425 }
426
427 fn render_diagnostics_inline(
428 diagnostics: &[codewhale_command_contract::facets::PluginDiagnostic],
429 ) -> String {
430 diagnostics
431 .iter()
432 .map(|d| {
433 format!(
434 "{} {}: {}",
435 match d.level {
436 codewhale_command_contract::facets::PluginDiagnosticLevel::Error => "error",
437 codewhale_command_contract::facets::PluginDiagnosticLevel::Warning => {
438 "warning"
439 }
440 },
441 d.code,
442 escape_review_text(&d.message, ReviewTextContext::Prose)
443 )
444 })
445 .collect::<Vec<_>>()
446 .join("; ")
447 }
448
449 pub(super) fn escape_review_text(value: &str, context: ReviewTextContext) -> String {
450 super::escape_review_text(value, context)
451 }
452
453 pub(super) fn escape_review_path(path: &Path, context: ReviewTextContext) -> String {
454 super::escape_review_path(path, context)
455 }
456
456 lines RUST