yosh-plugin-manager 0.2.7

Plugin manager for yosh shell
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
pub mod config;
pub mod github;
pub mod install;
pub mod lockfile;
pub mod metadata_extract;
pub mod precompile;
pub mod resolve;
pub mod runner;
pub mod scenario;
pub mod sync;
pub mod test_host;
pub mod update;
pub mod verify;

/// wasmtime bindgen for the `plugin-world` WIT contract.
///
/// Path is `wit/` inside this crate. The canonical source lives in
/// `yosh-plugin-api/wit/`; `build.rs` verifies the bundled copy matches
/// when built inside the workspace. The copy is required because
/// `cargo install yosh-plugin-manager` extracts each crate standalone,
/// so a sibling-relative path (`../yosh-plugin-api/wit`) is unresolvable
/// from `~/.cargo/registry/src/.../yosh-plugin-manager-<ver>/`.
///
/// This is independent from the host's bindgen invocation in
/// `src/plugin/mod.rs` — the two crates produce separate generated
/// types, so we cannot share. The host needs `HostContext` as the store
/// type and full host imports; the manager needs `MetadataCtx` and
/// deny-only imports.
pub mod generated {
    wasmtime::component::bindgen!({
        path: "wit",
        world: "plugin-world",
        async: false,
    });
}

use clap::{Parser, Subcommand};

const VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    " (",
    env!("YOSH_GIT_HASH"),
    " ",
    env!("YOSH_BUILD_DATE"),
    ")"
);

#[derive(Parser)]
#[command(name = "yosh-plugin", about = "Manage yosh shell plugins")]
#[command(version = VERSION)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
pub enum RunAction {
    /// Call `plugin/exec` with the given command and argv.
    Exec { command: String, args: Vec<String> },
    /// Call one hook.
    Hook {
        #[command(subcommand)]
        which: HookKind,
    },
}

#[derive(Subcommand)]
pub enum HookKind {
    PreExec {
        command_line: String,
    },
    PostExec {
        command_line: String,
        exit_code: i32,
    },
    OnCd {
        old: String,
        new: String,
    },
    PrePrompt,
}

#[derive(Copy, Clone, clap::ValueEnum, Debug)]
pub enum OutputFormat {
    Human,
    Json,
}

fn parse_kv(s: &str) -> Result<(String, String), String> {
    let (k, v) = s
        .split_once('=')
        .ok_or_else(|| format!("expected KEY=VALUE, got `{}`", s))?;
    Ok((k.to_string(), v.to_string()))
}

#[derive(Subcommand)]
enum Commands {
    /// Install plugins from plugins.toml
    Sync {
        /// Remove plugins not in plugins.toml
        #[arg(long)]
        prune: bool,
    },
    /// Update installed plugins to latest version
    Update {
        /// Only update the named plugin
        name: Option<String>,
    },
    /// List installed plugins
    List,
    /// Verify plugin integrity (SHA-256)
    Verify,
    /// Add a plugin from a GitHub URL or local path to plugins.toml
    Install {
        /// GitHub URL (https://github.com/owner/repo[@version]) or local file path
        source: String,
        /// Overwrite existing plugin with the same name
        #[arg(long)]
        force: bool,
    },
    /// Run a single exec / hook against a plugin wasm with an in-memory host.
    Run {
        /// Path to the wasm component.
        wasm: std::path::PathBuf,
        #[command(subcommand)]
        action: RunAction,
        /// Capabilities to grant (comma-separated, e.g. `io,variables:read`).
        /// Defaults to the plugin's declared `required_capabilities`.
        #[arg(long, value_delimiter = ',')]
        cap: Vec<String>,
        /// Seed a shell variable: `--var KEY=VALUE` (repeatable).
        #[arg(long = "var", value_parser = parse_kv)]
        vars: Vec<(String, String)>,
        /// Seed an exported variable.
        #[arg(long = "export", value_parser = parse_kv)]
        exports: Vec<(String, String)>,
        /// Virtual cwd.
        #[arg(long, default_value = ".")]
        cwd: std::path::PathBuf,
        /// Allowlist pattern for `commands:exec` (repeatable).
        #[arg(long = "allow-exec")]
        allow_exec: Vec<String>,
        /// If set, files:* operate on the real FS scoped here.
        #[arg(long = "sandbox-root")]
        sandbox_root: Option<std::path::PathBuf>,
        /// Watchdog deadline in milliseconds.
        #[arg(long, default_value_t = 5000)]
        timeout: u64,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Human)]
        format: OutputFormat,
    },
    /// Run declarative scenarios (TOML) from a directory.
    Test {
        /// Directory or single file. Default: `tests/`.
        #[arg(default_value = "tests")]
        path: std::path::PathBuf,
        /// Regex filter over the scenario file path.
        #[arg(long)]
        filter: Option<String>,
        #[arg(long, value_enum, default_value_t = OutputFormat::Human)]
        format: OutputFormat,
    },
}

pub fn run() -> i32 {
    let cli = Cli::parse();
    match cli.command {
        Commands::Sync { prune } => cmd_sync(prune),
        Commands::Update { name } => cmd_update(name.as_deref()),
        Commands::List => cmd_list(),
        Commands::Verify => cmd_verify(),
        Commands::Install { source, force } => cmd_install(&source, force),
        Commands::Run {
            wasm,
            action,
            cap,
            vars,
            exports,
            cwd,
            allow_exec,
            sandbox_root,
            timeout,
            format,
        } => cmd_run(
            wasm,
            action,
            cap,
            vars,
            exports,
            cwd,
            allow_exec,
            sandbox_root,
            timeout,
            format,
        ),
        Commands::Test {
            path,
            filter,
            format,
        } => cmd_test(path, filter, format),
    }
}

fn cmd_test(path: std::path::PathBuf, filter: Option<String>, format: OutputFormat) -> i32 {
    let reports = crate::scenario::run_dir(&path, filter.as_deref());
    let all_passed = reports.iter().all(|r| r.passed());
    match format {
        OutputFormat::Human => print!("{}", crate::scenario::format_summary_human(&reports)),
        OutputFormat::Json => print!("{}", crate::scenario::format_summary_json(&reports)),
    }
    if all_passed { 0 } else { 1 }
}

#[allow(clippy::too_many_arguments)]
fn cmd_run(
    wasm: std::path::PathBuf,
    action: RunAction,
    cap: Vec<String>,
    vars: Vec<(String, String)>,
    exports: Vec<(String, String)>,
    cwd: std::path::PathBuf,
    allow_exec: Vec<String>,
    sandbox_root: Option<std::path::PathBuf>,
    timeout: u64,
    format: OutputFormat,
) -> i32 {
    use crate::runner::{
        HookCall, format_human, format_json, invoke_exec, invoke_hook, load_plugin,
    };
    use crate::test_host::TestState;
    use yosh_plugin_api::pattern::CommandPattern;
    use yosh_plugin_api::{capabilities_to_bitflags, parse_capability};

    // Build TestState.
    let mut state = TestState::default();
    let parsed_caps: Vec<_> = cap.iter().filter_map(|s| parse_capability(s)).collect();
    state.caps = if cap.is_empty() {
        // Fall back to plugin-declared capabilities. We need them from
        // the cached metadata, which requires reading plugins.lock OR
        // running metadata_extract. For local-run UX, run metadata_extract
        // inline on the same wasm bytes.
        let bytes = match std::fs::read(&wasm) {
            Ok(b) => b,
            Err(e) => {
                eprintln!("yosh-plugin: read {}: {}", wasm.display(), e);
                return 99;
            }
        };
        let engine = match crate::precompile::make_engine() {
            Ok(e) => e,
            Err(e) => {
                eprintln!("yosh-plugin: engine: {}", e);
                return 99;
            }
        };
        match crate::metadata_extract::extract(&engine, &bytes) {
            Ok(m) => {
                let caps: Vec<_> = m
                    .required_capabilities
                    .iter()
                    .filter_map(|s| parse_capability(s))
                    .collect();
                capabilities_to_bitflags(&caps)
            }
            Err(e) => {
                eprintln!("yosh-plugin: metadata: {}", e);
                return 99;
            }
        }
    } else {
        capabilities_to_bitflags(&parsed_caps)
    };

    for (k, v) in vars {
        state.vars.insert(k, v);
    }
    for (k, v) in exports {
        state.vars.insert(k.clone(), v);
        state.exported.insert(k);
    }
    state.cwd = cwd;
    state.allow_exec = allow_exec
        .iter()
        .filter_map(|p| match CommandPattern::parse(p) {
            Ok(pat) => Some(pat),
            Err(e) => {
                eprintln!(
                    "yosh-plugin: ignoring invalid --allow-exec pattern {:?}: {}",
                    p, e
                );
                None
            }
        })
        .collect();
    state.sandbox_root = sandbox_root.map(|p| std::fs::canonicalize(&p).unwrap_or(p));

    let loaded = match load_plugin(&wasm, state, std::time::Duration::from_millis(timeout)) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("yosh-plugin: {}", e);
            return 99;
        }
    };

    let outcome = match action {
        RunAction::Exec { command, args } => invoke_exec(loaded, &command, &args),
        RunAction::Hook { which } => {
            let call = match which {
                HookKind::PreExec { command_line } => HookCall::PreExec { command_line },
                HookKind::PostExec {
                    command_line,
                    exit_code,
                } => HookCall::PostExec {
                    command_line,
                    exit_code,
                },
                HookKind::OnCd { old, new } => HookCall::OnCd { old, new },
                HookKind::PrePrompt => HookCall::PrePrompt,
            };
            invoke_hook(loaded, call)
        }
    };

    match format {
        OutputFormat::Human => print!("{}", format_human(&outcome)),
        OutputFormat::Json => println!("{}", format_json(&outcome)),
    }

    match outcome.error_kind {
        Some(_) => 99,
        None => outcome.exit_code.unwrap_or(0),
    }
}

fn cmd_install(source: &str, force: bool) -> i32 {
    let config_path = sync::config_path();
    match install::install(source, force, &config_path, None) {
        Ok(msg) => {
            eprintln!("{}", msg);
            if source.starts_with("https://github.com/") {
                eprintln!("Run 'yosh plugin sync' to download.");
            }
            0
        }
        Err(e) => {
            eprintln!("yosh-plugin: {}", e);
            1
        }
    }
}

fn cmd_sync(prune: bool) -> i32 {
    let result = match sync::sync(prune) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("yosh-plugin: {}", e);
            return 2;
        }
    };

    for name in &result.succeeded {
        eprintln!("  \u{2713} {}", name);
    }
    for (name, err) in &result.failed {
        eprintln!("  \u{2717} {}: {}", name, err);
    }

    if result.failed.is_empty() {
        eprintln!(
            "yosh-plugin: sync complete ({} plugins)",
            result.succeeded.len()
        );
        0
    } else {
        eprintln!(
            "yosh-plugin: sync partial ({} succeeded, {} failed)",
            result.succeeded.len(),
            result.failed.len()
        );
        1
    }
}

fn cmd_update(name_filter: Option<&str>) -> i32 {
    let config_path = sync::config_path();
    let client = github::GitHubClient::new();
    let outcome = match update::update(&config_path, name_filter, &client) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("yosh-plugin: {}", e);
            return 2;
        }
    };

    for result in &outcome.results {
        match &result.status {
            update::UpdateStatus::Updated { from, to } => {
                eprintln!("  {} {} \u{2192} {}", result.name, from, to);
            }
            update::UpdateStatus::AlreadyLatest { current } => {
                eprintln!("  {} {} (already latest)", result.name, current);
            }
            update::UpdateStatus::Failed(e) => {
                eprintln!("  \u{2717} {}: {}", result.name, e);
            }
            update::UpdateStatus::Skipped(_) => {
                // Silent: matches HEAD's behavior of not surfacing
                // name_filter mismatches or local-source skips.
            }
        }
    }

    if outcome.any_updated {
        return cmd_sync(false);
    }

    0
}

fn cmd_list() -> i32 {
    let lock_path = sync::lock_path();
    let lockfile = match lockfile::load_lockfile(&lock_path) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("yosh-plugin: {}", e);
            return 2;
        }
    };

    if lockfile.plugin.is_empty() {
        eprintln!("no plugins installed (run 'yosh-plugin sync' first)");
        return 0;
    }

    for entry in &lockfile.plugin {
        let version = entry.version.as_deref().unwrap_or("-");
        let verified =
            match verify::verify_checksum(&config::expand_tilde_path(&entry.path), &entry.sha256) {
                Ok(true) => "\u{2713} verified",
                Ok(false) => "\u{2717} checksum mismatch",
                Err(_) => "\u{2717} file missing",
            };
        // "cached" reflects whether a precompiled cwasm is present AND
        // matches the manager's pinned wasmtime version. A mismatched
        // version means the host will fall back to in-memory precompile
        // at startup — not a hard failure, but worth surfacing here so
        // the user can re-sync.
        let cached = match (&entry.cwasm_path, &entry.wasmtime_version) {
            (Some(p), Some(wv))
                if std::path::Path::new(&config::expand_tilde_path(p)).exists()
                    && wv == precompile::WASMTIME_VERSION =>
            {
                "\u{2713} cached"
            }
            _ => "\u{2717} stale",
        };
        let caps = entry
            .required_capabilities
            .as_ref()
            .map(|v| {
                if v.is_empty() {
                    "[- (no capabilities)]".to_string()
                } else {
                    format!("[{}]", v.join(", "))
                }
            })
            .unwrap_or_else(|| "[?]".into());
        println!(
            "{:<16} {:<8} {:<48} {} {} {}",
            entry.name, version, entry.source, verified, cached, caps
        );
    }

    0
}

fn cmd_verify() -> i32 {
    let lock_path = sync::lock_path();
    let lockfile = match lockfile::load_lockfile(&lock_path) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("yosh-plugin: {}", e);
            return 2;
        }
    };

    let mut all_ok = true;
    for entry in &lockfile.plugin {
        let path = config::expand_tilde_path(&entry.path);
        match verify::verify_checksum(&path, &entry.sha256) {
            Ok(true) => {
                eprintln!("  \u{2713} {}", entry.name);
            }
            Ok(false) => {
                eprintln!("  \u{2717} {}: checksum mismatch", entry.name);
                all_ok = false;
            }
            Err(e) => {
                eprintln!("  \u{2717} {}: {}", entry.name, e);
                all_ok = false;
            }
        }
    }

    if all_ok { 0 } else { 1 }
}