返回 CodeWhale
mod.rs
根目录 / crates / tui / src / commands / groups / plugins / mod.rs
1 //! Codewhale bundle lifecycle and legacy executable plugin-tool inventory.
2 //!
3 //! `/plugin` owns declarative bundles (`plugin.toml`). Script tools under
4 //! `[tools].plugin_dir` remain supported, but are labeled as legacy executable
5 //! tools and never share bundle trust state.
6 //!
7 //! # Module map
8 //!
9 //! This file is the command surface: registration, the `/plugin` verb
10 //! dispatch, and the bundle lifecycle verbs (list/show/trust/validate/
11 //! install/update/uninstall/enable/disable/revoke). Two seams live next
12 //! door:
13 //!
14 //! * [`render`] — every string the user reads: bundle detail, the
15 //! capability review body, diagnostics, and the escaping that keeps
16 //! manifest-controlled text from forging review output.
17 //! * [`legacy`] — the separate `[tools].plugin_dir` executable inventory,
18 //! which shares no trust state with declarative bundles.
19 //!
20 //! FEAT-020 converts this group to the portable command contract: every
21 //! production handler consumes workspace, presentation, and plugin facets —
22 //! never concrete `App`, `PluginRegistry`, or `Config`. Production registration
23 //! uses `ContextualCommand::from_contract`; a test-only shell builds the same
24 //! capability bundle for focused parity tests. `CommandResult` and `AppAction`
25 //! remain temporary TUI-owned references until FEAT-037.
26
27 use std::fmt::Write as _;
28 use std::path::{Path, PathBuf};
29
30 use codewhale_command_contract::facets::{
31 CommandPluginContext, CommandPresentationContext, CommandSessionLifecycleContext, PluginDetail,
32 PluginDiagnosticLevel, PluginMutationOutcome, PluginMutationReceipt,
33 };
34 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
35 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
36
37 use crate::commands::CommandResult;
38 use crate::commands::groups::session::transition_blocked_message;
39 use crate::commands::traits::{CommandGroup, ContextualCommand};
40 #[cfg(test)]
41 use crate::tui::app::App;
42 use crate::tui::app::AppAction;
43
44 pub(crate) mod dsh_import;
45 pub(crate) mod headless;
46 mod kimi_import;
47 pub(crate) mod legacy;
48 pub(crate) mod marketplace;
49 #[cfg(test)]
50 mod marketplace_tests;
51 pub(crate) mod render;
52
53 #[cfg(test)]
54 mod tests;
55
56 use legacy::legacy_tools;
57 use render::ReviewTextContext;
58
59 pub struct PluginsCommands;
60
61 impl CommandGroup for PluginsCommands {
62 fn commands(&self) -> &'static [Box<dyn crate::commands::traits::Command>] {
63 cached_command_list!(vec![Box::new(
64 ContextualCommand::from_contract::<PluginsCmd>().expect("plugin registration"),
65 )])
66 }
67 }
68
69 pub(in crate::commands) const PLUGINS_INFO: CommandInfo = CommandInfo {
70 name: "plugin",
71 aliases: &["plugins", "extensions"],
72 usage: "/plugin [list|status|show|create|suggest|validate|export|install|import|update|uninstall|trust|enable|restage|disable|revoke|reload|doctor|tools|marketplace|dismissals]",
73 description_key: "cmd_plugin_description",
74 };
75
76 pub(in crate::commands) struct PluginsCmd;
77
78 impl RegisterCommand<CommandResult> for PluginsCmd {
79 fn info() -> &'static CommandInfo {
80 &PLUGINS_INFO
81 }
82
83 fn handler() -> CommandHandler<CommandResult> {
84 CommandHandler::Contextual {
85 capabilities: CommandCapabilities::WORKSPACE
86 .union(CommandCapabilities::PRESENTATION)
87 .union(CommandCapabilities::PLUGIN)
88 .union(CommandCapabilities::SESSION_LIFECYCLE),
89 handler: plugins_contextual,
90 }
91 }
92 }
93
94 fn plugins_contextual(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
95 let mut parts = contexts.into_parts();
96 let Some(workspace) = parts.workspace.as_deref() else {
97 return CommandResult::error("Command capability unavailable: workspace");
98 };
99 let Some(presentation) = parts.presentation.as_deref_mut() else {
100 return CommandResult::error("Command capability unavailable: presentation");
101 };
102 let Some(plugin) = parts.plugin.as_deref_mut() else {
103 return CommandResult::error("Command capability unavailable: plugin");
104 };
105 let Some(lifecycle) = parts.lifecycle.as_deref_mut() else {
106 return CommandResult::error("Command capability unavailable: session_lifecycle");
107 };
108 plugins(
109 &workspace.workspace(),
110 presentation,
111 plugin,
112 lifecycle,
113 arg,
114 None,
115 )
116 }
117
118 #[cfg(test)]
119 fn plugins_with_kimi_home(app: &mut App, arg: Option<&str>, home: &Path) -> CommandResult {
120 plugins_with_kimi_home_override(app, arg, Some(home))
121 }
122
123 #[cfg(test)]
124 fn plugins_with_kimi_home_override(
125 app: &mut App,
126 arg: Option<&str>,
127 kimi_home: Option<&Path>,
128 ) -> CommandResult {
129 let mut bundle = app.command_contexts();
130 let capabilities = CommandCapabilities::WORKSPACE
131 .union(CommandCapabilities::PRESENTATION)
132 .union(CommandCapabilities::PLUGIN)
133 .union(CommandCapabilities::SESSION_LIFECYCLE);
134 let mut contexts = bundle.contexts(capabilities).into_parts();
135 let Some(workspace) = contexts.workspace.as_deref() else {
136 return CommandResult::error("Command capability unavailable: workspace");
137 };
138 let Some(presentation) = contexts.presentation.as_deref_mut() else {
139 return CommandResult::error("Command capability unavailable: presentation");
140 };
141 let Some(plugin) = contexts.plugin.as_deref_mut() else {
142 return CommandResult::error("Command capability unavailable: plugin");
143 };
144 let Some(lifecycle) = contexts.lifecycle.as_deref_mut() else {
145 return CommandResult::error("Command capability unavailable: session_lifecycle");
146 };
147 plugins(
148 &workspace.workspace(),
149 presentation,
150 plugin,
151 lifecycle,
152 arg,
153 kimi_home,
154 )
155 }
156
157 /// Portable `/plugin` dispatch (FEAT-020 Phase 4).
158 ///
159 /// The handler consumes only portable facets; all concrete host access lives
160 /// in the TUI adapter. `kimi_home` is a test-only home override for the Kimi
161 /// managed-import scan.
162 pub(super) fn plugins(
163 workspace: &Path,
164 presentation: &mut dyn CommandPresentationContext,
165 plugin: &mut dyn CommandPluginContext,
166 lifecycle: &mut dyn CommandSessionLifecycleContext,
167 arg: Option<&str>,
168 kimi_home: Option<&Path>,
169 ) -> CommandResult {
170 let words = arg
171 .unwrap_or_default()
172 .split_whitespace()
173 .collect::<Vec<_>>();
174 match words.as_slice() {
175 [] => CommandResult::action(AppAction::OpenExtensions {
176 tab: crate::tui::views::extensions::ExtensionsTab::Plugins,
177 }),
178 ["list"] | ["status"] => list_bundles_and_legacy_tools(presentation, plugin),
179 ["status", selector] => show_bundle(presentation, plugin, selector),
180 ["restage"] => CommandResult::error("Usage: /plugin restage <name>"),
181 ["restage", selector] => mutate_bundle(presentation, plugin, selector, Mutation::Restage),
182 ["help"] => CommandResult::message(format!(
183 "{}\n\n/plugin create [idea]\n/plugin import kimi [list]\n/plugin import kimi approve <name> <content-hash>\n{}\n{}",
184 translate(presentation, "cmd_plugin_bundle_usage"),
185 dsh_import::USAGE,
186 DOCTOR_USAGE
187 )),
188 ["marketplace", rest @ ..] => marketplace::dispatch(presentation, plugin, rest),
189 ["import", "kimi", rest @ ..] => {
190 kimi_import::dispatch(presentation, plugin, rest, kimi_home)
191 }
192 ["import", "dsh", rest @ ..] => dsh_import::dispatch(presentation, plugin, rest),
193 ["import", ..] => CommandResult::error(format!(
194 "{}\n{}",
195 kimi_import::usage(presentation),
196 dsh_import::USAGE
197 )),
198 ["show", selector] => show_bundle(presentation, plugin, selector),
199 ["suggest"] | ["recommend"] => CommandResult::error("Usage: /plugin suggest <task>"),
200 ["suggest", task @ ..] | ["recommend", task @ ..] => {
201 suggest_bundles(presentation, plugin, &task.join(" "))
202 }
203 ["validate"] => validate_bundles(presentation, plugin, None),
204 ["validate", selector] => validate_bundles(presentation, plugin, Some(selector)),
205 ["export"] => CommandResult::error("Usage: /plugin export <name> <target-dir>"),
206 ["export", selector, target @ ..] => {
207 export_bundle(workspace, presentation, plugin, selector, &target.join(" "))
208 }
209 ["install"] => CommandResult::error(translate(presentation, "cmd_plugin_bundle_usage")),
210 ["install", rest @ ..] => install_bundle(presentation, plugin, &rest.join(" ")),
211 ["update"] | ["uninstall"] => {
212 CommandResult::error(translate(presentation, "cmd_plugin_bundle_usage"))
213 }
214 ["update", selector] => update_bundle(presentation, plugin, selector),
215 ["uninstall", selector] => uninstall_bundle(presentation, plugin, selector),
216 ["trust", selector] => review_bundle(presentation, plugin, selector),
217 ["trust", selector, token] => {
218 mutate_bundle(presentation, plugin, selector, Mutation::Trust(token))
219 }
220 ["enable", selector] => mutate_bundle(presentation, plugin, selector, Mutation::Enable),
221 ["disable", selector] => mutate_bundle(presentation, plugin, selector, Mutation::Disable),
222 ["revoke", selector] => mutate_bundle(presentation, plugin, selector, Mutation::Revoke),
223 ["reload"] => reload(workspace, presentation, plugin),
224 ["doctor"] => doctor(presentation, plugin, false),
225 ["doctor", "--fix"] => doctor(presentation, plugin, true),
226 ["doctor", ..] => CommandResult::error(DOCTOR_USAGE),
227 ["dismissals"] => list_dismissals(plugin),
228 ["dismissals", "reset"] => reset_dismissals(plugin, None),
229 ["dismissals", "reset", name] => reset_dismissals(plugin, Some(name)),
230 ["dismissals", ..] => CommandResult::error("Usage: /plugin dismissals [reset [<name>]]"),
231 ["tools"] => legacy_tools(presentation, plugin, None),
232 ["tools", name] => legacy_tools(presentation, plugin, Some(name)),
233 ["create", ..] => create_plugin(lifecycle, create_draft_from_arg(arg.unwrap_or_default())),
234 [selector] => {
235 if plugin.detail(selector).is_ok() {
236 show_bundle(presentation, plugin, selector)
237 } else {
238 // Preserve `/plugin <script-tool>` compatibility while making
239 // its distinct execution model explicit in the output.
240 legacy_tools(presentation, plugin, Some(selector))
241 }
242 }
243 _ => CommandResult::error(translate(presentation, "cmd_plugin_bundle_usage")),
244 }
245 }
246
247 fn create_draft_from_arg(raw: &str) -> Option<String> {
248 let trimmed = raw.trim_start();
249 let rest = trimmed.strip_prefix("create")?;
250 let delimiter = rest.chars().next()?;
251 if !delimiter.is_whitespace() {
252 return None;
253 }
254 let idea = &rest[delimiter.len_utf8()..];
255 (!idea.trim().is_empty()).then(|| idea.to_string())
256 }
257
258 fn create_plugin(
259 lifecycle: &mut dyn CommandSessionLifecycleContext,
260 draft: Option<String>,
261 ) -> CommandResult {
262 if lifecycle.transition_blocked() {
263 return CommandResult::error(transition_blocked_message(
264 "start a new session",
265 &lifecycle.transition_blockers(),
266 ));
267 }
268 match lifecycle.fresh_session(false, Some("creator")) {
269 Ok(receipt) => CommandResult::action(AppAction::NewSession {
270 sync: receipt.sync,
271 force: false,
272 draft,
273 }),
274 Err(error) => CommandResult::error(error),
275 }
276 }
277
278 /// `/plugin dismissals`: which plugins suggestions skip, and for how long
279 /// (plugin policy rule 9: dismissal is reversible).
280 fn list_dismissals(plugin: &dyn CommandPluginContext) -> CommandResult {
281 let dismissals = match plugin.suggestion_dismissals() {
282 Ok(dismissals) => dismissals,
283 Err(error) => return CommandResult::error(error),
284 };
285 if dismissals.persisted.is_empty() && dismissals.session.is_empty() {
286 return CommandResult::message("No plugins are hidden from suggestions.".to_string());
287 }
288 let mut output = String::from("Plugins hidden from suggestions:\n");
289 if !dismissals.persisted.is_empty() {
290 output.push_str(" Don't suggest again (kept across sessions):\n");
291 for name in &dismissals.persisted {
292 let _ = writeln!(
293 output,
294 " {}",
295 escape_review_text(name, ReviewTextContext::Prose)
296 );
297 }
298 }
299 if !dismissals.session.is_empty() {
300 output.push_str(" This session only:\n");
301 for name in &dismissals.session {
302 let _ = writeln!(
303 output,
304 " {}",
305 escape_review_text(name, ReviewTextContext::Prose)
306 );
307 }
308 }
309 output.push_str(
310 "\nReset with /plugin dismissals reset [<name>]. Manual /plugin commands work either way.",
311 );
312 CommandResult::message(output)
313 }
314
315 /// `/plugin dismissals reset [<name>]`: let suggestions offer a plugin again.
316 fn reset_dismissals(plugin: &mut dyn CommandPluginContext, name: Option<&str>) -> CommandResult {
317 match plugin.reset_suggestion_dismissals(name) {
318 Ok(cleared) if cleared.is_empty() => CommandResult::message(match name {
319 Some(name) => format!(
320 "`{}` was not hidden from suggestions.",
321 escape_review_text(name, ReviewTextContext::InlineCode)
322 ),
323 None => "No plugins were hidden from suggestions.".to_string(),
324 }),
325 Ok(cleared) => CommandResult::message(format!(
326 "Suggestions may offer {} again.",
327 cleared
328 .iter()
329 .map(|name| escape_review_text(name, ReviewTextContext::Prose))
330 .collect::<Vec<_>>()
331 .join(", ")
332 )),
333 Err(error) => CommandResult::error(error),
334 }
335 }
336
337 /// Translate one stable plugin key through the presentation facet.
338 fn translate(presentation: &mut dyn CommandPresentationContext, key: &str) -> String {
339 presentation.translate(key, &[]).unwrap_or_default()
340 }
341
342 fn reload(
343 workspace: &Path,
344 presentation: &mut dyn CommandPresentationContext,
345 plugin: &mut dyn CommandPluginContext,
346 ) -> CommandResult {
347 match plugin.reload() {
348 Ok(count) => {
349 let message = presentation
350 .translate(
351 "cmd_plugin_bundle_reloaded",
352 &[
353 ("count", &count.to_string()),
354 (
355 "workspace",
356 &escape_review_path(workspace, ReviewTextContext::Prose),
357 ),
358 ],
359 )
360 .unwrap_or_default();
361 CommandResult::with_message_and_action(message, AppAction::PluginRegistryChanged)
362 }
363 Err(error) => action_error(presentation, &format!("Plugin reload failed: {error}")),
364 }
365 }
366
367 const DOCTOR_USAGE: &str =
368 "Usage: /plugin doctor [--fix] (report superseded plugin state; --fix applies it)";
369
370 /// `/plugin doctor [--fix]`: report, or retire, plugin state that no longer
371 /// points at anything: records and snapshots of superseded built-in builds,
372 /// inert records for vanished workspaces, orphaned runtime snapshots. The
373 /// report is read-only; `--fix` backs `state.json` up, then rewrites it
374 /// atomically. The same safe subset also runs automatically at startup.
375 fn doctor(
376 presentation: &mut dyn CommandPresentationContext,
377 plugin: &mut dyn CommandPluginContext,
378 fix: bool,
379 ) -> CommandResult {
380 use codewhale_plugins::registry::gc;
381
382 let Some(state_path) = plugin.state_path() else {
383 return CommandResult::error("Plugin registry has no persistence store; nothing to check");
384 };
385 let live = match plugin.summaries() {
386 Ok(summaries) => summaries.into_iter().map(|summary| summary.id).collect(),
387 Err(error) => return CommandResult::error(error),
388 };
389 let options = gc::GcOptions::default();
390 // Path identity is resolved off this thread. Reloading the session
391 // registry stays here: that is session state, not the directory walk.
392 let report = gc::run(
393 state_path,
394 live,
395 options,
396 fix.then_some(gc::GcTier::Explicit),
397 );
398 if !fix {
399 return match report {
400 Ok(report) => CommandResult::message(render::render_gc_report(&report, false)),
401 Err(error) => {
402 CommandResult::error(format!("Plugin doctor could not read state: {error}"))
403 }
404 };
405 }
406 match report {
407 Ok(report) => {
408 let message = render::render_gc_report(&report, true);
409 // Rediscover so the session stops listing what was just retired.
410 match plugin.reload() {
411 Ok(_) => CommandResult::with_message_and_action(
412 message,
413 AppAction::PluginRegistryChanged,
414 ),
415 Err(error) => action_error(
416 presentation,
417 &format!("{message}\nPlugin reload failed: {error}"),
418 ),
419 }
420 }
421 Err(error) => CommandResult::error(format!("Plugin doctor changed nothing: {error}")),
422 }
423 }
424
425 /// Rank installed bundles and locally-added marketplace candidates for a task
426 /// without changing trust, enablement, disk state, or network state.
427 fn suggest_bundles(
428 _presentation: &mut dyn CommandPresentationContext,
429 plugin: &dyn CommandPluginContext,
430 task: &str,
431 ) -> CommandResult {
432 let task = task.trim();
433 if task.chars().count() < 3 {
434 return CommandResult::error("Usage: /plugin suggest <task of at least 3 characters>");
435 }
436 let suggestions = plugin.suggest(task).unwrap_or_default();
437 if suggestions.is_empty() {
438 return CommandResult::message(format!(
439 "No installed or catalog plugin matched `{}`.\n\nInstall a reviewed bundle with /plugin install <source>, or add a catalog with /plugin marketplace add. Nothing was installed, trusted, or enabled.",
440 escape_review_text(task, ReviewTextContext::InlineCode)
441 ));
442 }
443 let mut output = format!(
444 "Suggested plugins for `{}`:\n",
445 escape_review_text(task, ReviewTextContext::InlineCode)
446 );
447 output.push_str("─────────────────────────────\n");
448 for suggestion in suggestions {
449 let why = suggestion
450 .why
451 .iter()
452 .map(|term| escape_review_text(term, ReviewTextContext::Prose))
453 .collect::<Vec<_>>()
454 .join(", ");
455 let _ = writeln!(
456 output,
457 " {} — {} · {}",
458 escape_review_text(&suggestion.name, ReviewTextContext::Prose),
459 suggestion.state_label,
460 escape_review_text(&suggestion.description, ReviewTextContext::Prose)
461 );
462 let _ = writeln!(output, " Why: {why}");
463 let _ = writeln!(output, " {}", suggestion.next_step);
464 }
465 output.push_str("\nNothing was installed, trusted, or enabled.");
466 CommandResult::message(output)
467 }
468
469 fn list_bundles_and_legacy_tools(
470 presentation: &mut dyn CommandPresentationContext,
471 plugin: &mut dyn CommandPluginContext,
472 ) -> CommandResult {
473 let summaries = plugin.summaries().unwrap_or_default();
474 let mut output = if summaries.is_empty() {
475 translate(presentation, "cmd_plugin_bundle_none_found")
476 } else {
477 let mut output = presentation
478 .translate(
479 "cmd_plugin_bundle_list_header",
480 &[("count", &summaries.len().to_string())],
481 )
482 .unwrap_or_default();
483 output.push('\n');
484 for summary in &summaries {
485 let review = summary
486 .review_display
487 .as_deref()
488 .unwrap_or(&summary.trust_status);
489 let _ = writeln!(
490 output,
491 "• {} — {}\n {} · {} · compatibility={} · {}\n {}",
492 escape_review_text(&summary.name, ReviewTextContext::Prose),
493 summary.state_label,
494 summary.scope,
495 review,
496 summary.compatibility,
497 summary.inventory,
498 escape_review_text(&summary.id, ReviewTextContext::Prose)
499 );
500 if let Some(approver) = summary.approver.as_deref() {
501 if let Some(date) = summary.reviewed_date.as_deref() {
502 let safe_date = escape_review_text(date, ReviewTextContext::Plain);
503 let approved_date = presentation
504 .translate("cmd_plugin_audit_approved_date", &[("date", &safe_date)])
505 .unwrap_or_else(|_| format!("approved {safe_date}"));
506 let _ = writeln!(output, " {approver} ({approved_date})");
507 } else {
508 let _ = writeln!(output, " {approver}");
509 }
510 }
511 if let Some(enabled_by) = summary.enabled_by.as_deref() {
512 let _ = writeln!(output, " {enabled_by}");
513 }
514 if summary.outside_reach || summary.reach_folder.is_some() {
515 let folder = escape_review_text(
516 summary.reach_folder.as_deref().unwrap_or("unknown"),
517 ReviewTextContext::Prose,
518 );
519 let key = if summary.outside_reach {
520 "cmd_plugin_audit_reach_only_in"
521 } else {
522 "cmd_plugin_audit_reach_here"
523 };
524 let reach = presentation
525 .translate(key, &[("folder", &folder)])
526 .unwrap_or(folder);
527 let _ = writeln!(output, " {reach}");
528 }
529 if let Some(note) = summary.process_note.as_deref() {
530 let _ = writeln!(output, " {note}");
531 }
532 }
533 output
534 };
535 append_diagnostics(
536 presentation,
537 &mut output,
538 &plugin.registry_diagnostics(),
539 ReviewTextContext::Prose,
540 );
541 // Diagnostics and the stderr tail carry plugin-controlled text.
542 for line in codewhale_engine::extension_host::status_report().lines() {
543 output.push('\n');
544 output.push_str(&escape_review_text(line, ReviewTextContext::Prose));
545 }
546
547 if let Ok(Some(scan)) = plugin.legacy_scan() {
548 output.push('\n');
549 output.push_str(
550 &presentation
551 .translate(
552 "cmd_plugin_legacy_list_header",
553 &[
554 ("count", &scan.tools.len().to_string()),
555 ("dir", &scan.dir.display().to_string()),
556 ],
557 )
558 .unwrap_or_default(),
559 );
560 output.push('\n');
561 for tool in &scan.tools {
562 let _ = writeln!(
563 output,
564 "• {} — {}\n {}",
565 escape_review_text(&tool.name, ReviewTextContext::Prose),
566 escape_review_text(&tool.description, ReviewTextContext::Prose),
567 escape_review_path(&tool.path, ReviewTextContext::Prose)
568 );
569 }
570 append_diagnostics(
571 presentation,
572 &mut output,
573 &scan.diagnostics,
574 ReviewTextContext::Prose,
575 );
576 }
577
578 if let Some(nudge) = plugin.reload_nudge() {
579 output.push('\n');
580 output.push_str(&nudge);
581 }
582
583 CommandResult::message(output)
584 }
585
586 fn show_bundle(
587 presentation: &mut dyn CommandPresentationContext,
588 plugin: &dyn CommandPluginContext,
589 selector: &str,
590 ) -> CommandResult {
591 let detail = match plugin.detail(selector) {
592 Ok(detail) => detail,
593 Err(_) => {
594 return CommandResult::error(
595 presentation
596 .translate("cmd_plugin_bundle_not_found", &[("name", selector)])
597 .unwrap_or_default(),
598 );
599 }
600 };
601 let mut output =
602 render::render_bundle_detail(presentation, &detail, true, ReviewTextContext::Prose);
603 if let Some(report) = codewhale_engine::extension_host::owner_report(&detail.id) {
604 append_host_owner_report(presentation, &mut output, &report);
605 }
606 // What the user configured for the plugin is data its code will read, so
607 // it is part of what `/plugin show` puts in front of them (keys only: a
608 // value can be anything, including something they would rather not echo).
609 if let Some(summary) = codewhale_engine::extension_host::plugin_config_summary(&detail.name) {
610 append_plugin_config_summary(&mut output, &detail.name, &summary);
611 }
612 CommandResult::message(output)
613 }
614
615 /// The `[plugins."<name>".config]` line of `/plugin show`: the configured
616 /// keys, never the values, or why the config is refused. Every part is escaped.
617 fn append_plugin_config_summary(
618 output: &mut String,
619 plugin_name: &str,
620 summary: &Result<Vec<String>, String>,
621 ) {
622 let name = escape_review_text(plugin_name, ReviewTextContext::Prose);
623 match summary {
624 Ok(keys) => {
625 let keys = keys
626 .iter()
627 .map(|key| escape_review_text(key, ReviewTextContext::Prose))
628 .collect::<Vec<_>>()
629 .join(", ");
630 let _ = write!(
631 output,
632 "\n config from [plugins.\"{name}\".config] in your config.toml (values not shown): {keys}"
633 );
634 }
635 Err(reason) => {
636 let _ = write!(
637 output,
638 "\n config from [plugins.\"{name}\".config] is refused: {}",
639 escape_review_text(reason, ReviewTextContext::Prose)
640 );
641 }
642 }
643 }
644
645 fn append_host_owner_report(
646 presentation: &dyn CommandPresentationContext,
647 output: &mut String,
648 report: &codewhale_engine::extension_host::OwnerReport,
649 ) {
650 use codewhale_engine::extension_host::registry::OwnerState;
651
652 let (state_key, reason) = match &report.state {
653 Some(OwnerState::Activating) => ("cmd_plugin_owner_activating", None),
654 Some(OwnerState::Active) => ("cmd_plugin_owner_active", None),
655 Some(OwnerState::Failed(reason)) => ("cmd_plugin_owner_failed", Some(reason)),
656 Some(OwnerState::Faulted(reason)) => ("cmd_plugin_owner_faulted", Some(reason)),
657 Some(OwnerState::Revoked) => ("cmd_plugin_owner_revoked", None),
658 None => ("cmd_plugin_owner_inactive", None),
659 };
660 let reason = reason.map(|value| escape_review_text(value, ReviewTextContext::Prose));
661 let replacements = reason
662 .as_deref()
663 .map(|value| vec![("reason", value)])
664 .unwrap_or_default();
665 let state = presentation
666 .translate(state_key, &replacements)
667 .unwrap_or_default();
668 let tools = report
669 .tools
670 .iter()
671 .map(|name| escape_review_text(name, ReviewTextContext::Prose))
672 .collect::<Vec<_>>();
673 let tool_names = if tools.is_empty() {
674 "—".to_string()
675 } else {
676 tools.join(", ")
677 };
678 output.push('\n');
679 output.push_str(
680 &presentation
681 .translate(
682 "cmd_plugin_owner_report",
683 &[
684 ("state", &state),
685 ("count", &tools.len().to_string()),
686 ("tools", &tool_names),
687 ],
688 )
689 .unwrap_or_default(),
690 );
691 for line in &report.diagnostics {
692 let _ = write!(
693 output,
694 "\n · {}",
695 escape_review_text(line, ReviewTextContext::Prose)
696 );
697 }
698 }
699
700 /// `/plugin export <name> <target-dir>` — publish a loaded bundle as a
701 /// spec-valid Agent Plugins v1.0.0 directory.
702 fn export_bundle(
703 workspace: &Path,
704 presentation: &mut dyn CommandPresentationContext,
705 plugin: &dyn CommandPluginContext,
706 selector: &str,
707 target: &str,
708 ) -> CommandResult {
709 if plugin.detail(selector).is_err() {
710 return CommandResult::error(
711 presentation
712 .translate("cmd_plugin_bundle_not_found", &[("name", selector)])
713 .unwrap_or_default(),
714 );
715 }
716 let target = target.trim();
717 if target.is_empty() {
718 return CommandResult::error("Usage: /plugin export <name> <target-dir>");
719 }
720 let target = PathBuf::from(target);
721 let target = if target.is_absolute() {
722 target
723 } else {
724 workspace.join(target)
725 };
726 match plugin.export(selector, &target) {
727 Ok(receipt) => {
728 let mut output = format!(
729 "Exported `{}` as an Agent Plugins v1.0.0 bundle:\n {}\n",
730 escape_review_text(&receipt.exported_name, ReviewTextContext::InlineCode),
731 escape_review_path(&receipt.target, ReviewTextContext::Prose),
732 );
733 if let Some(display_name) = &receipt.display_name {
734 let _ = writeln!(
735 output,
736 " Published under a slugified name; `{}` is preserved as the display name.",
737 escape_review_text(display_name, ReviewTextContext::InlineCode)
738 );
739 }
740 let _ = writeln!(
741 output,
742 " plugin.json{} · {} file(s) copied{}",
743 if receipt.wrote_mcp_json {
744 " + mcp.json"
745 } else {
746 ""
747 },
748 receipt.files_copied,
749 if receipt.skills_normalized {
750 " · skills moved to the standard skills/ layout"
751 } else {
752 ""
753 }
754 );
755 output.push_str("The installed bundle was not modified.");
756 CommandResult::message(output)
757 }
758 Err(error) => CommandResult::error(format!(
759 "Export of `{}` failed: {}",
760 escape_review_text(selector, ReviewTextContext::InlineCode),
761 escape_review_text(&error, ReviewTextContext::Prose)
762 )),
763 }
764 }
765
766 fn review_bundle(
767 presentation: &mut dyn CommandPresentationContext,
768 plugin: &dyn CommandPluginContext,
769 selector: &str,
770 ) -> CommandResult {
771 let detail = match plugin.detail(selector) {
772 Ok(detail) => detail,
773 Err(_) => {
774 return CommandResult::error(
775 presentation
776 .translate("cmd_plugin_bundle_not_found", &[("name", selector)])
777 .unwrap_or_default(),
778 );
779 }
780 };
781 let mut output =
782 render::render_bundle_detail(presentation, &detail, true, ReviewTextContext::Prose);
783 let content =
784 render::render_bundle_detail(presentation, &detail, true, ReviewTextContext::Plain);
785 let command = format!("/plugin trust {} {}", detail.name, review_token(&detail));
786 let _ = writeln!(output, "\n{command}");
787 CommandResult::with_message_and_action(
788 output,
789 AppAction::OpenCommandReview {
790 title: escape_review_text(&detail.name, ReviewTextContext::Plain),
791 content,
792 command,
793 },
794 )
795 }
796
797 pub(crate) fn review_token(detail: &PluginDetail) -> String {
798 // This is an explicit user confirmation, not cosmetic display text. Bind
799 // the command to both complete SHA-256 receipts so a same-inventory bundle
800 // cannot collide through the former 48-bit content prefix.
801 format!("{}.{}", detail.content_hash, detail.capability_hash)
802 }
803
804 fn validate_bundles(
805 presentation: &mut dyn CommandPresentationContext,
806 plugin: &dyn CommandPluginContext,
807 selector: Option<&str>,
808 ) -> CommandResult {
809 if plugin.is_empty() && selector.is_none() {
810 return CommandResult::error(translate(presentation, "cmd_plugin_bundle_none_found"));
811 }
812
813 let mut output = String::new();
814 if let Some(selector) = selector {
815 match plugin.detail(selector) {
816 Ok(detail) => {
817 let invalid = detail
818 .diagnostics
819 .iter()
820 .any(|diagnostic| diagnostic.level == PluginDiagnosticLevel::Error);
821 let _ = writeln!(
822 output,
823 "{} — {} — {}",
824 detail.name,
825 if invalid { "invalid" } else { "valid" },
826 detail.inventory_summary
827 );
828 append_diagnostics(
829 presentation,
830 &mut output,
831 &detail.diagnostics,
832 ReviewTextContext::Prose,
833 );
834 }
835 Err(_) => {
836 return CommandResult::error(
837 presentation
838 .translate("cmd_plugin_bundle_not_found", &[("name", selector)])
839 .unwrap_or_default(),
840 );
841 }
842 }
843 } else {
844 for summary in plugin.summaries().unwrap_or_default() {
845 let _ = writeln!(
846 output,
847 "{} — {} — {}",
848 summary.name, summary.state_label, summary.inventory
849 );
850 }
851 append_diagnostics(
852 presentation,
853 &mut output,
854 &plugin.registry_diagnostics(),
855 ReviewTextContext::Prose,
856 );
857 }
858 if output.is_empty() {
859 output.push_str(if plugin.validation_is_clean() {
860 "valid"
861 } else {
862 "invalid"
863 });
864 }
865 CommandResult::message(output)
866 }
867
868 // ─── /plugin install | update | uninstall (#5182) ──────────────────────────
869
870 fn install_bundle(
871 presentation: &mut dyn CommandPresentationContext,
872 plugin: &mut dyn CommandPluginContext,
873 spec: &str,
874 ) -> CommandResult {
875 match plugin.install(spec, None) {
876 Ok(receipt) => render_install_receipt(presentation, plugin, receipt, None),
877 Err(error) => action_error(presentation, &format!("Plugin install failed: {error}")),
878 }
879 }
880
881 fn install_bundle_with_expected_hash(
882 presentation: &mut dyn CommandPresentationContext,
883 plugin: &mut dyn CommandPluginContext,
884 path: &Path,
885 expected_content_hash: &str,
886 ) -> CommandResult {
887 match plugin.install(
888 path.to_str().unwrap_or_default(),
889 Some(expected_content_hash),
890 ) {
891 Ok(receipt) => {
892 render_install_receipt(presentation, plugin, receipt, Some(expected_content_hash))
893 }
894 Err(error) => action_error(presentation, &format!("Plugin install failed: {error}")),
895 }
896 }
897
898 fn render_install_receipt(
899 presentation: &mut dyn CommandPresentationContext,
900 plugin: &mut dyn CommandPluginContext,
901 receipt: PluginMutationReceipt,
902 expected_content_hash: Option<&str>,
903 ) -> CommandResult {
904 match receipt.outcome {
905 PluginMutationOutcome::Installed => {
906 let name = receipt.name.clone();
907 let installed_path = receipt.path.clone();
908 let path = installed_path
909 .as_deref()
910 .map(|path| path.display().to_string())
911 .unwrap_or_default();
912 if let Some(expected) = expected_content_hash
913 && receipt.content_hash.as_deref() != Some(expected)
914 {
915 return rollback_hash_mismatch(
916 presentation,
917 plugin,
918 &name,
919 installed_path.as_deref(),
920 expected,
921 receipt.content_hash.as_deref(),
922 );
923 }
924 let mut output = format!(
925 "Installed plugin '{name}' to {path}.\n\
926 It is disabled and untrusted. Review its requested authority below, then trust and enable it.\n"
927 );
928 if let Some(review) = review_bundle(presentation, plugin, &name).message {
929 output.push('\n');
930 output.push_str(&review);
931 }
932 CommandResult::with_message_and_action(output, AppAction::PluginRegistryChanged)
933 }
934 PluginMutationOutcome::NeedsApproval(host) => {
935 CommandResult::error(needs_approval_message(&host))
936 }
937 PluginMutationOutcome::NetworkDenied(host) => {
938 CommandResult::error(network_denied_message(&host))
939 }
940 other => CommandResult::error(format!("Unexpected install outcome: {other:?}")),
941 }
942 }
943
944 fn rollback_hash_mismatch(
945 presentation: &mut dyn CommandPresentationContext,
946 plugin: &mut dyn CommandPluginContext,
947 name: &str,
948 installed_path: Option<&Path>,
949 expected: &str,
950 actual: Option<&str>,
951 ) -> CommandResult {
952 let missing_destination = translate(presentation, "plugin_kimi_rollback_destination_missing");
953 // File-level rollback removal crosses the boundary through the plugin
954 // facet (D1); the host adapter owns the `codewhale_plugins::install::uninstall`
955 // call.
956 let rollback = installed_path
957 .and_then(Path::parent)
958 .ok_or_else(|| anyhow::anyhow!(missing_destination))
959 .and_then(|plugins_dir| {
960 plugin
961 .uninstall_path(name, plugins_dir)
962 .map_err(anyhow::Error::msg)
963 });
964 let actual = actual
965 .map(|value| escape_review_text(value, ReviewTextContext::Prose))
966 .unwrap_or_else(|| translate(presentation, "plugin_kimi_hash_unavailable"));
967 let name = escape_review_text(name, ReviewTextContext::InlineCode);
968 let expected = escape_review_text(expected, ReviewTextContext::Prose);
969 match rollback {
970 Ok(()) => CommandResult::error(
971 presentation
972 .translate(
973 "plugin_kimi_mismatch_removed",
974 &[
975 ("name", &name),
976 ("expected", &expected),
977 ("actual", &actual),
978 ],
979 )
980 .unwrap_or_default(),
981 ),
982 Err(error) => {
983 let error_text = escape_review_text(&format!("{error:#}"), ReviewTextContext::Prose);
984 let path_text = installed_path
985 .map(|value| escape_review_path(value, ReviewTextContext::Prose))
986 .unwrap_or_else(|| translate(presentation, "plugin_kimi_user_plugin_directory"));
987 CommandResult {
988 message: Some(
989 presentation
990 .translate(
991 "plugin_kimi_mismatch_rollback_failed",
992 &[
993 ("name", &name),
994 ("expected", &expected),
995 ("actual", &actual),
996 ("error", &error_text),
997 ("path", &path_text),
998 ],
999 )
1000 .unwrap_or_default(),
1001 ),
1002 action: Some(AppAction::PluginRegistryChanged),
1003 is_error: true,
1004 }
1005 }
1006 }
1007 }
1008
1009 fn update_bundle(
1010 presentation: &mut dyn CommandPresentationContext,
1011 plugin: &mut dyn CommandPluginContext,
1012 selector: &str,
1013 ) -> CommandResult {
1014 match plugin.update(selector) {
1015 Ok(receipt) => match receipt.outcome {
1016 PluginMutationOutcome::Updated => {
1017 let name = receipt.name.clone();
1018 let mut output = format!(
1019 "Updated plugin '{name}'. Review its current capabilities and trust it \
1020 if needed before enabling.\n"
1021 );
1022 if let Some(review) = review_bundle(presentation, plugin, &name).message {
1023 output.push('\n');
1024 output.push_str(&review);
1025 }
1026 CommandResult::with_message_and_action(output, AppAction::PluginRegistryChanged)
1027 }
1028 PluginMutationOutcome::NoChange => {
1029 CommandResult::message(format!("Plugin '{}' is already up to date.", receipt.name))
1030 }
1031 PluginMutationOutcome::NeedsApproval(host) => {
1032 CommandResult::error(needs_approval_message(&host))
1033 }
1034 PluginMutationOutcome::NetworkDenied(host) => {
1035 CommandResult::error(network_denied_message(&host))
1036 }
1037 other => CommandResult::error(format!("Unexpected update outcome: {other:?}")),
1038 },
1039 Err(error) => action_error(presentation, &format!("Plugin update failed: {error}")),
1040 }
1041 }
1042
1043 fn uninstall_bundle(
1044 presentation: &mut dyn CommandPresentationContext,
1045 plugin: &mut dyn CommandPluginContext,
1046 selector: &str,
1047 ) -> CommandResult {
1048 match plugin.uninstall(selector) {
1049 Ok(receipt) => CommandResult::with_message_and_action(
1050 format!("Uninstalled plugin '{}'.", receipt.name),
1051 AppAction::PluginRegistryChanged,
1052 ),
1053 Err(error) => action_error(presentation, &format!("Plugin uninstall failed: {error}")),
1054 }
1055 }
1056
1057 /// Read the active network policy for plugin downloads (host-side, D11).
1058 pub(crate) fn plugin_network_policy() -> codewhale_net::network_policy::NetworkPolicy {
1059 codewhale_plugins::providers::load_config(None, None)
1060 .unwrap_or_default()
1061 .network
1062 .map(codewhale_net::network_policy::NetworkPolicy::from)
1063 .unwrap_or_default()
1064 }
1065
1066 fn needs_approval_message(host: &str) -> String {
1067 format!(
1068 "Network policy requires approval for {host}.\n\
1069 Add it to your allow list with `/network allow {host}` (or set [network].default = \"allow\" in ~/.codewhale/config.toml), then retry."
1070 )
1071 }
1072
1073 fn network_denied_message(host: &str) -> String {
1074 format!(
1075 "Network policy denied access to {host}.\n\
1076 Remove the deny entry from ~/.codewhale/config.toml under [network] or contact your administrator."
1077 )
1078 }
1079
1080 #[derive(Clone, Copy)]
1081 enum Mutation<'a> {
1082 Trust(&'a str),
1083 Enable,
1084 Restage,
1085 Disable,
1086 Revoke,
1087 }
1088
1089 fn mutate_bundle(
1090 presentation: &mut dyn CommandPresentationContext,
1091 plugin: &mut dyn CommandPluginContext,
1092 selector: &str,
1093 mutation: Mutation<'_>,
1094 ) -> CommandResult {
1095 if matches!(mutation, Mutation::Enable) {
1096 let needs_review = plugin
1097 .detail(selector)
1098 .map(|detail| !detail.trusted)
1099 .unwrap_or(false);
1100 if needs_review {
1101 // Enabling is the natural entry point. Open the exact capability
1102 // review instead of leaving the user at an opaque denial.
1103 return review_bundle(presentation, plugin, selector);
1104 }
1105 }
1106
1107 let result = match mutation {
1108 Mutation::Trust(token) => plugin.trust(selector, token).map(|()| "trusted"),
1109 Mutation::Enable => plugin.enable(selector).map(|()| "enabled"),
1110 Mutation::Restage => plugin.restage(selector).map(|()| "restaged"),
1111 Mutation::Disable => plugin.disable(selector).map(|()| "disabled"),
1112 Mutation::Revoke => plugin.revoke_trust(selector).map(|()| "trust-revoked"),
1113 };
1114 match result {
1115 Ok(action) => {
1116 let mut message = presentation
1117 .translate(
1118 "cmd_plugin_bundle_mutation_success",
1119 &[("name", selector), ("action", action)],
1120 )
1121 .unwrap_or_default();
1122 if matches!(mutation, Mutation::Enable)
1123 && let Ok(detail) = plugin.detail(selector)
1124 {
1125 let inactive = detail.unsupported_labels;
1126 if !inactive.is_empty() {
1127 message.push(' ');
1128 message.push_str(&format!(
1129 "Compatibility: {}. Supported declarative components are active; inactive: {}.",
1130 detail.compatibility,
1131 inactive.join(", ")
1132 ));
1133 }
1134 }
1135 CommandResult::with_message_and_action(message, AppAction::PluginRegistryChanged)
1136 }
1137 Err(error) => action_error(presentation, &error),
1138 }
1139 }
1140
1141 fn action_error(presentation: &mut dyn CommandPresentationContext, error: &str) -> CommandResult {
1142 CommandResult::error(
1143 presentation
1144 .translate("cmd_plugin_action_failed", &[("error", error)])
1145 .unwrap_or_default(),
1146 )
1147 }
1148
1149 pub(super) fn append_diagnostics(
1150 presentation: &mut dyn CommandPresentationContext,
1151 output: &mut String,
1152 diagnostics: &[codewhale_command_contract::facets::PluginDiagnostic],
1153 context: ReviewTextContext,
1154 ) {
1155 if diagnostics.is_empty() {
1156 return;
1157 }
1158 if !output.ends_with('\n') {
1159 output.push('\n');
1160 }
1161 output.push_str(
1162 &presentation
1163 .translate(
1164 "cmd_plugin_bundle_diagnostics_header",
1165 &[("count", &diagnostics.len().to_string())],
1166 )
1167 .unwrap_or_default(),
1168 );
1169 output.push('\n');
1170 for diagnostic in diagnostics {
1171 let level = match diagnostic.level {
1172 PluginDiagnosticLevel::Warning => "warning",
1173 PluginDiagnosticLevel::Error => "error",
1174 };
1175 let path = diagnostic
1176 .path
1177 .as_deref()
1178 .map(|path| format!(" ({})", escape_review_path(path, context)))
1179 .unwrap_or_default();
1180 let _ = writeln!(
1181 output,
1182 "• {level} [{}]: {}{path}",
1183 diagnostic.code,
1184 escape_review_text(&diagnostic.message, context)
1185 );
1186 }
1187 }
1188
1189 pub(super) fn escape_review_path(path: &Path, context: ReviewTextContext) -> String {
1190 render::escape_review_path(path, context)
1191 }
1192
1193 pub(super) fn escape_review_text(value: &str, context: ReviewTextContext) -> String {
1194 render::escape_review_text(value, context)
1195 }
1196
1196 lines RUST