codewhale-tui 0.9.5

Terminal UI for open-source and open-weight coding models
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! Codewhale bundle lifecycle and legacy executable plugin-tool inventory.
//!
//! `/plugin` owns declarative bundles (`plugin.toml`). Script tools under
//! `[tools].plugin_dir` remain supported, but are labeled as legacy executable
//! tools and never share bundle trust state.
//!
//! # Module map
//!
//! This file is the command surface: registration, the `/plugin` verb
//! dispatch, and the bundle lifecycle verbs (list/show/trust/validate/
//! install/update/uninstall/enable/disable/revoke). Two seams live next
//! door:
//!
//! * [`render`] — every string the user reads: bundle detail, the
//!   capability review body, diagnostics, and the escaping that keeps
//!   manifest-controlled text from forging review output.
//! * [`legacy`] — the separate `[tools].plugin_dir` executable inventory,
//!   which shares no trust state with declarative bundles.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::path::PathBuf;

use crate::commands::CommandResult;
use crate::commands::traits::{
    Command, CommandGroup, CommandInfo, FunctionCommand, RegisterCommand,
};
use crate::localization::{MessageId, tr};
use crate::plugins::types::{LoadedPlugin, PluginDiagnosticLevel};
use crate::tui::app::{App, AppAction};

mod legacy;
mod render;

#[cfg(test)]
mod tests;

use legacy::{legacy_tools, scan_legacy_tools};
use render::{
    append_diagnostics, escape_review_path, escape_review_text, render_bundle_detail, review_token,
};

pub struct PluginsCommands;

impl CommandGroup for PluginsCommands {
    fn commands(&self) -> &'static [Box<dyn Command>] {
        cached_command_list!(vec![Box::new(FunctionCommand::new(
            PluginsCmd::info(),
            PluginsCmd::execute,
        ))])
    }
}

pub(in crate::commands) const PLUGINS_INFO: CommandInfo = CommandInfo {
    name: "plugin",
    aliases: &["plugins"],
    usage: "/plugin [list|show|suggest|validate|export|install|update|uninstall|trust|enable|disable|revoke|reload|tools]",
    description_id: MessageId::CmdPluginDescription,
};

pub(in crate::commands) struct PluginsCmd;

impl RegisterCommand for PluginsCmd {
    fn info() -> &'static CommandInfo {
        &PLUGINS_INFO
    }

    fn execute(app: &mut App, arg: Option<&str>) -> CommandResult {
        plugins(app, arg)
    }
}

fn plugins(app: &mut App, arg: Option<&str>) -> CommandResult {
    let words = arg
        .unwrap_or_default()
        .split_whitespace()
        .collect::<Vec<_>>();
    match words.as_slice() {
        [] | ["list"] => list_bundles_and_legacy_tools(app),
        ["help"] => CommandResult::message(tr(app.ui_locale, MessageId::CmdPluginBundleUsage)),
        ["show", selector] => show_bundle(app, selector),
        ["suggest"] | ["recommend"] => CommandResult::error("Usage: /plugin suggest <task>"),
        ["suggest", task @ ..] | ["recommend", task @ ..] => suggest_bundles(app, &task.join(" ")),
        ["validate"] => validate_bundles(app, None),
        ["validate", selector] => validate_bundles(app, Some(selector)),
        ["export"] => CommandResult::error("Usage: /plugin export <name> <target-dir>"),
        ["export", selector, target @ ..] => export_bundle(app, selector, &target.join(" ")),
        ["install"] => CommandResult::error(tr(app.ui_locale, MessageId::CmdPluginBundleUsage)),
        ["install", rest @ ..] => install_bundle(app, &rest.join(" ")),
        ["update"] | ["uninstall"] => {
            CommandResult::error(tr(app.ui_locale, MessageId::CmdPluginBundleUsage))
        }
        ["update", selector] => update_bundle(app, selector),
        ["uninstall", selector] => uninstall_bundle(app, selector),
        ["trust", selector] => review_bundle(app, selector),
        ["trust", selector, token] => mutate_bundle(app, selector, Mutation::Trust(token)),
        ["enable", selector] => mutate_bundle(app, selector, Mutation::Enable),
        ["disable", selector] => mutate_bundle(app, selector, Mutation::Disable),
        ["revoke", selector] => mutate_bundle(app, selector, Mutation::Revoke),
        ["reload"] => {
            app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&app.workspace);
            app.refresh_skill_cache();
            let count = app.plugin_registry.len();
            CommandResult::with_message_and_action(
                tr(app.ui_locale, MessageId::CmdPluginBundleReloaded)
                    .replace("{count}", &count.to_string())
                    .replace("{workspace}", &app.workspace.display().to_string()),
                AppAction::PluginRegistryChanged,
            )
        }
        ["tools"] => legacy_tools(app, None),
        ["tools", name] => legacy_tools(app, Some(name)),
        [selector] => {
            if app.plugin_registry.get(selector).is_some() {
                show_bundle(app, selector)
            } else {
                // Preserve `/plugin <script-tool>` compatibility while making
                // its distinct execution model explicit in the output.
                legacy_tools(app, Some(selector))
            }
        }
        _ => CommandResult::error(tr(app.ui_locale, MessageId::CmdPluginBundleUsage)),
    }
}

/// Rank already installed bundle metadata for a task without changing trust,
/// enablement, disk state, or network state. A full remote plugin marketplace
/// needs separately curated publisher/provenance policy; the existing plugin
/// registry is intentionally local-only for this release.
fn suggest_bundles(app: &App, task: &str) -> CommandResult {
    let task = task.trim();
    if task.chars().count() < 3 {
        return CommandResult::error("Usage: /plugin suggest <task of at least 3 characters>");
    }

    let mut skills = BTreeMap::new();
    for plugin in app.plugin_registry.list() {
        let mut description_parts = plugin
            .manifest
            .plugin
            .description
            .iter()
            .cloned()
            .collect::<Vec<_>>();
        let mut keywords = Vec::new();
        for skill in &plugin.skill_snapshots {
            description_parts.push(skill.name.clone());
            description_parts.push(skill.description.clone());
            keywords.push(skill.name.clone());
            keywords.extend(skill.aliases.iter().cloned());
        }
        skills.insert(
            plugin.name().to_string(),
            crate::skills::RegistryEntry {
                source: plugin.id.as_str().to_string(),
                description: (!description_parts.is_empty()).then(|| description_parts.join(" ")),
                keywords,
                domains: plugin.inventory.network_hosts.clone(),
            },
        );
    }

    let index = crate::skills::RegistryDocument { skills };
    let recommendations = crate::skills::recommend::recommend_remote_skills(task, &index, 3);
    if recommendations.is_empty() {
        return CommandResult::message(format!(
            "No installed plugin bundles matched `{}`.\n\nInstall a reviewed bundle with /plugin install <source>. Nothing was installed, trusted, or enabled.",
            escape_review_text(task)
        ));
    }

    let mut output = format!(
        "Suggested installed plugins for `{}`:\n",
        escape_review_text(task)
    );
    output.push_str("─────────────────────────────\n");
    for recommendation in recommendations {
        let Some(plugin) = app.plugin_registry.get(&recommendation.entry.source) else {
            continue;
        };
        let description = plugin
            .manifest
            .plugin
            .description
            .as_deref()
            .filter(|description| !description.trim().is_empty())
            .unwrap_or("No description provided.");
        let why = recommendation
            .matched_terms
            .iter()
            .map(|term| escape_review_text(term))
            .collect::<Vec<_>>()
            .join(", ");
        let next_step = if plugin.active() {
            format!("Already active: /plugin show {}", plugin.name())
        } else if !plugin.trusted() {
            format!("Review before enabling: /plugin trust {}", plugin.name())
        } else if !plugin.enabled {
            format!(
                "Enable if that review still applies: /plugin enable {}",
                plugin.name()
            )
        } else {
            format!("Inspect its inactive state: /plugin show {}", plugin.name())
        };
        let _ = writeln!(
            output,
            "  {}{} · {}",
            escape_review_text(plugin.name()),
            plugin.state_label(),
            escape_review_text(description)
        );
        let _ = writeln!(output, "    Why: {why}");
        let _ = writeln!(output, "    {next_step}");
    }
    output.push_str("\nNothing was installed, trusted, or enabled.");
    CommandResult::message(output)
}

fn list_bundles_and_legacy_tools(app: &App) -> CommandResult {
    let mut output = {
        let registry = app.plugin_registry.as_ref();
        let plugins = registry.list();
        let mut output = if plugins.is_empty() {
            tr(app.ui_locale, MessageId::CmdPluginBundleNoneFound).into_owned()
        } else {
            let mut output = tr(app.ui_locale, MessageId::CmdPluginBundleListHeader)
                .replace("{count}", &plugins.len().to_string());
            output.push('\n');
            for plugin in plugins {
                let _ = writeln!(
                    output,
                    "{}{}\n  {} · {} · {}\n  {}",
                    escape_review_text(plugin.name()),
                    plugin.state_label(),
                    plugin.scope,
                    plugin.trust_status.as_str(),
                    plugin.inventory.summary(),
                    escape_review_text(plugin.id.as_str())
                );
            }
            output
        };
        append_diagnostics(app, &mut output, registry.diagnostics());
        output
    };

    if let Some((dir, tools)) = scan_legacy_tools(app) {
        output.push('\n');
        output.push_str(
            &tr(app.ui_locale, MessageId::CmdPluginLegacyListHeader)
                .replace("{count}", &tools.len().to_string())
                .replace("{dir}", &dir.display().to_string()),
        );
        output.push('\n');
        for (path, metadata) in tools {
            let _ = writeln!(
                output,
                "{}{}\n  {}",
                escape_review_text(&metadata.name),
                escape_review_text(&metadata.description),
                escape_review_path(&path)
            );
        }
    }

    CommandResult::message(output)
}

fn show_bundle(app: &App, selector: &str) -> CommandResult {
    let Some(plugin) = app.plugin_registry.get(selector).cloned() else {
        return CommandResult::error(
            tr(app.ui_locale, MessageId::CmdPluginBundleNotFound).replace("{name}", selector),
        );
    };
    CommandResult::message(render_bundle_detail(app, &plugin, true))
}

/// `/plugin export <name> <target-dir>` — publish a loaded bundle as a
/// spec-valid Agent Plugins v1.0.0 directory (`plugin.json`, `mcp.json` when
/// servers exist, and the `skills/` tree). The installed bundle is never
/// modified; a relative target resolves against the workspace.
fn export_bundle(app: &App, selector: &str, target: &str) -> CommandResult {
    let Some(plugin) = app.plugin_registry.get(selector).cloned() else {
        return CommandResult::error(
            tr(app.ui_locale, MessageId::CmdPluginBundleNotFound).replace("{name}", selector),
        );
    };
    let target = target.trim();
    if target.is_empty() {
        return CommandResult::error("Usage: /plugin export <name> <target-dir>");
    }
    let target = PathBuf::from(target);
    let target = if target.is_absolute() {
        target
    } else {
        app.workspace.join(target)
    };
    let existing_names: BTreeSet<String> = app
        .plugin_registry
        .list()
        .iter()
        .map(|other| other.name().to_string())
        .filter(|name| name != plugin.name())
        .collect();
    match crate::plugins::export::export_plugin_bundle(&plugin, &target, &existing_names) {
        Ok(receipt) => {
            let mut output = format!(
                "Exported `{}` as an Agent Plugins v1.0.0 bundle:\n  {}\n",
                escape_review_text(&receipt.exported_name),
                escape_review_path(&receipt.target),
            );
            if let Some(display_name) = &receipt.display_name {
                let _ = writeln!(
                    output,
                    "  Published under a slugified name; `{}` is preserved as the display name.",
                    escape_review_text(display_name)
                );
            }
            let _ = writeln!(
                output,
                "  plugin.json{} · {} file(s) copied{}",
                if receipt.wrote_mcp_json {
                    " + mcp.json"
                } else {
                    ""
                },
                receipt.files_copied,
                if receipt.skills_normalized {
                    " · skills moved to the standard skills/ layout"
                } else {
                    ""
                }
            );
            output.push_str("The installed bundle was not modified.");
            CommandResult::message(output)
        }
        Err(error) => CommandResult::error(format!(
            "Export of `{}` failed: {}",
            escape_review_text(plugin.name()),
            escape_review_text(&error)
        )),
    }
}

fn review_bundle(app: &App, selector: &str) -> CommandResult {
    let Some(plugin) = app.plugin_registry.get(selector).cloned() else {
        return CommandResult::error(
            tr(app.ui_locale, MessageId::CmdPluginBundleNotFound).replace("{name}", selector),
        );
    };
    let mut output = render_bundle_detail(app, &plugin, true);
    let _ = writeln!(
        output,
        "\n/plugin trust {} {}",
        plugin.name(),
        review_token(&plugin)
    );
    CommandResult::message(output)
}

fn validate_bundles(app: &App, selector: Option<&str>) -> CommandResult {
    let (plugins, diagnostics, clean) = {
        let registry = app.plugin_registry.as_ref();
        let plugins: Vec<LoadedPlugin> = match selector {
            Some(selector) => registry.get(selector).cloned().into_iter().collect(),
            None => registry.list().into_iter().cloned().collect(),
        };
        (
            plugins,
            registry.diagnostics().to_vec(),
            registry.validation_is_clean(),
        )
    };
    if app.plugin_registry.is_empty() && selector.is_none() {
        return CommandResult::error(tr(app.ui_locale, MessageId::CmdPluginBundleNoneFound));
    };
    if selector.is_some() && plugins.is_empty() {
        return CommandResult::error(
            tr(app.ui_locale, MessageId::CmdPluginBundleNotFound)
                .replace("{name}", selector.unwrap_or_default()),
        );
    }

    let mut output = String::new();
    for plugin in &plugins {
        let _ = writeln!(
            output,
            "{}{}{}",
            plugin.name(),
            if plugin
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.level == PluginDiagnosticLevel::Error)
            {
                "invalid"
            } else {
                "valid"
            },
            plugin.inventory.summary()
        );
        append_diagnostics(app, &mut output, &plugin.diagnostics);
    }
    append_diagnostics(app, &mut output, &diagnostics);
    if output.is_empty() {
        output.push_str(if clean { "valid" } else { "invalid" });
    }
    CommandResult::message(output)
}

// ─── /plugin install | update | uninstall (#5182) ──────────────────────────
//
// The fetch/place on-ramp. All writes go through `plugins::mutation`; after a
// successful install or update the command rediscovers and drops the user
// into the existing trust review (`review_bundle`) — installed or replaced
// bits are always disabled and untrusted until the hash-bound trust flow runs.

fn install_bundle(app: &mut App, spec: &str) -> CommandResult {
    use crate::plugins::mutation::{
        PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
    };

    let source = match crate::plugins::install::PluginInstallSource::parse(spec) {
        Ok(source) => source,
        Err(error) => {
            return CommandResult::error(format!(
                "Invalid plugin install source `{spec}`: {error:#}\n\
                 Expected a local path, github:owner/repo, or an HTTPS tarball URL."
            ));
        }
    };
    let network = plugin_network_policy();
    let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
    let outcome = run_async(async move {
        let ctx = PluginMutationContext {
            network: &network,
            max_size: crate::plugins::install::DEFAULT_MAX_SIZE_BYTES,
        };
        crate::plugins::mutation::execute(PluginMutationRequest::Install { source }, &ctx, registry)
            .await
    });

    match outcome {
        Ok(receipt) => match receipt.outcome {
            PluginMutationOutcome::Installed => {
                let name = receipt.name.clone();
                let path = receipt
                    .path
                    .as_deref()
                    .map(|path| path.display().to_string())
                    .unwrap_or_default();
                app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&app.workspace);
                app.refresh_skill_cache();
                let mut output = format!(
                    "Installed plugin '{name}' to {path}.\n\
                     It is disabled and untrusted. Review its requested authority below, then trust and enable it.\n"
                );
                if let Some(review) = review_bundle(app, &name).message {
                    output.push('\n');
                    output.push_str(&review);
                }
                CommandResult::with_message_and_action(output, AppAction::PluginRegistryChanged)
            }
            PluginMutationOutcome::NeedsApproval(host) => {
                CommandResult::error(needs_approval_message(&host))
            }
            PluginMutationOutcome::NetworkDenied(host) => {
                CommandResult::error(network_denied_message(&host))
            }
            other => CommandResult::error(format!("Unexpected install outcome: {other:?}")),
        },
        Err(error) => action_error(app, &format!("Plugin install failed: {error:#}")),
    }
}

fn update_bundle(app: &mut App, selector: &str) -> CommandResult {
    use crate::plugins::mutation::{
        PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
    };

    let network = plugin_network_policy();
    let selector_owned = selector.to_string();
    let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
    let outcome = run_async(async move {
        let ctx = PluginMutationContext {
            network: &network,
            max_size: crate::plugins::install::DEFAULT_MAX_SIZE_BYTES,
        };
        crate::plugins::mutation::execute(
            PluginMutationRequest::Update {
                selector: selector_owned,
            },
            &ctx,
            registry,
        )
        .await
    });

    match outcome {
        Ok(receipt) => match receipt.outcome {
            PluginMutationOutcome::Updated => {
                let name = receipt.name.clone();
                app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&app.workspace);
                app.refresh_skill_cache();
                let mut output = format!(
                    "Updated plugin '{name}'. Its content changed, so the previous trust receipt no \
                     longer matches — review and trust it again before enabling.\n"
                );
                if let Some(review) = review_bundle(app, &name).message {
                    output.push('\n');
                    output.push_str(&review);
                }
                CommandResult::with_message_and_action(output, AppAction::PluginRegistryChanged)
            }
            PluginMutationOutcome::NoChange => {
                CommandResult::message(format!("Plugin '{}' is already up to date.", receipt.name))
            }
            PluginMutationOutcome::NeedsApproval(host) => {
                CommandResult::error(needs_approval_message(&host))
            }
            PluginMutationOutcome::NetworkDenied(host) => {
                CommandResult::error(network_denied_message(&host))
            }
            other => CommandResult::error(format!("Unexpected update outcome: {other:?}")),
        },
        Err(error) => action_error(app, &format!("Plugin update failed: {error:#}")),
    }
}

fn uninstall_bundle(app: &mut App, selector: &str) -> CommandResult {
    use crate::plugins::mutation::{
        PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
    };

    let network = plugin_network_policy();
    let selector_owned = selector.to_string();
    let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
    let outcome = run_async(async move {
        let ctx = PluginMutationContext {
            network: &network,
            max_size: crate::plugins::install::DEFAULT_MAX_SIZE_BYTES,
        };
        crate::plugins::mutation::execute(
            PluginMutationRequest::Uninstall {
                selector: selector_owned,
            },
            &ctx,
            registry,
        )
        .await
    });

    match outcome {
        Ok(receipt) => {
            debug_assert!(matches!(
                receipt.outcome,
                PluginMutationOutcome::Uninstalled
            ));
            app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&app.workspace);
            app.refresh_skill_cache();
            app.active_skill = None;
            app.active_skill_provenance = None;
            CommandResult::with_message_and_action(
                format!("Uninstalled plugin '{}'.", receipt.name),
                AppAction::PluginRegistryChanged,
            )
        }
        Err(error) => action_error(app, &format!("Plugin uninstall failed: {error:#}")),
    }
}

/// Read the active network policy for plugin downloads. Mirrors the skill
/// installer's on-demand `Config::load` (`App` carries no `Config` field);
/// a parse failure falls back to the prompt-default policy so the download
/// stays gated rather than crashing.
fn plugin_network_policy() -> crate::network_policy::NetworkPolicy {
    crate::config::Config::load(None, None)
        .unwrap_or_default()
        .network
        .map(|policy| policy.into_runtime())
        .unwrap_or_default()
}

fn run_async<F, T>(future: F) -> T
where
    F: std::future::Future<Output = T>,
{
    // Same bridge as the skill commands: the TUI thread is part of the
    // multi-threaded runtime, so `block_in_place` + `block_on` brings the
    // sync slash-command handler back into the async ecosystem.
    tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(future))
}

fn needs_approval_message(host: &str) -> String {
    format!(
        "Network policy requires approval for {host}.\n\
         Add it to your allow list with `/network allow {host}` (or set [network].default = \"allow\" in ~/.codewhale/config.toml), then retry."
    )
}

fn network_denied_message(host: &str) -> String {
    format!(
        "Network policy denied access to {host}.\n\
         Remove the deny entry from ~/.codewhale/config.toml under [network] or contact your administrator."
    )
}

#[derive(Clone, Copy)]
enum Mutation<'a> {
    Trust(&'a str),
    Enable,
    Disable,
    Revoke,
}

fn mutate_bundle(app: &mut App, selector: &str, mutation: Mutation<'_>) -> CommandResult {
    if matches!(mutation, Mutation::Enable) {
        let needs_review = app
            .plugin_registry
            .get(selector)
            .is_some_and(|plugin| !plugin.trusted());
        if needs_review {
            // Enabling is the natural entry point. Open the exact capability
            // review instead of leaving the user at an opaque denial.
            return review_bundle(app, selector);
        }
    }
    if let Mutation::Trust(token) = mutation {
        let Some(expected) = app.plugin_registry.get(selector).map(review_token) else {
            return CommandResult::error(
                tr(app.ui_locale, MessageId::CmdPluginBundleNotFound).replace("{name}", selector),
            );
        };
        if token != expected {
            return action_error(
                app,
                "Review token does not match this bundle content and capability set; run `/plugin trust <name>` again",
            );
        }
    }

    let result = match mutation {
        Mutation::Trust(_) => std::sync::Arc::make_mut(&mut app.plugin_registry)
            .trust(selector)
            .map(|()| "trusted"),
        Mutation::Enable => std::sync::Arc::make_mut(&mut app.plugin_registry)
            .enable(selector)
            .map(|()| "enabled"),
        Mutation::Disable => std::sync::Arc::make_mut(&mut app.plugin_registry)
            .disable(selector)
            .map(|()| "disabled"),
        Mutation::Revoke => std::sync::Arc::make_mut(&mut app.plugin_registry)
            .revoke_trust(selector)
            .map(|()| "trust-revoked"),
    };
    match result {
        Ok(action) => {
            app.refresh_skill_cache();
            if matches!(mutation, Mutation::Disable | Mutation::Revoke) {
                app.active_skill = None;
                app.active_skill_provenance = None;
            }
            CommandResult::with_message_and_action(
                tr(app.ui_locale, MessageId::CmdPluginBundleMutationSuccess)
                    .replace("{name}", selector)
                    .replace("{action}", action),
                AppAction::PluginRegistryChanged,
            )
        }
        Err(error) => action_error(app, &error),
    }
}

fn action_error(app: &App, error: &str) -> CommandResult {
    CommandResult::error(
        tr(app.ui_locale, MessageId::CmdPluginActionFailed).replace("{error}", error),
    )
}