fledge 1.1.1

Dev lifecycle CLI. One tool for the dev loop, any language.
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
use anyhow::{bail, Context, Result};
use console::style;
use std::fs;
use std::process::Command;

use crate::trust::{determine_trust_tier, parse_source_ref, TrustTier};

use super::{
    apply_git_auth, extract_name_from_source, link_commands, load_registry, normalize_source,
    plugin_bin_dir, plugins_dir, run_build, run_hook, save_registry, validate_plugin_name,
    PluginCapabilities, PluginEntry, PluginManifest, PLUGINS_INSTALL_SCHEMA,
};

pub(super) fn check_tier_capabilities(
    tier: TrustTier,
    caps: &PluginCapabilities,
) -> std::result::Result<(), Vec<&'static str>> {
    if tier != TrustTier::Unverified {
        return Ok(());
    }
    let mut blocked = Vec::new();
    if caps.exec {
        blocked.push("exec");
    }
    if caps.network {
        blocked.push("network");
    }
    if blocked.is_empty() {
        Ok(())
    } else {
        Err(blocked)
    }
}

/// Top-level dispatcher for `fledge plugins install`. Splits the
/// single-source path from the `--defaults` bulk-install path so each
/// caller stays simple. Reports a per-plugin pass/fail count when
/// installing the bundle so a single bad repo doesn't abort the rest.
pub(crate) fn install_action(
    source: Option<&str>,
    force: bool,
    defaults: bool,
    json: bool,
) -> Result<()> {
    if defaults {
        if source.is_some() {
            bail!("--defaults installs the curated set; do not pass a source ref alongside it.");
        }
        return install_defaults(force, json);
    }
    let source = source.ok_or_else(|| {
        anyhow::anyhow!(
            "Either pass a source ref (owner/repo[@ref]) or use --defaults to install the curated set."
        )
    })?;
    let report = install_plugin(source, force, json)?;
    if json {
        let result = serde_json::json!({
            "schema_version": PLUGINS_INSTALL_SCHEMA,
            "action": "install",
            "scope": "single",
            "installed": [report],
            "failed": [],
            "summary": { "total": 1, "installed": 1, "failed": 0 },
        });
        println!("{}", serde_json::to_string_pretty(&result)?);
    }
    Ok(())
}

/// Install every entry in `DEFAULT_PLUGINS`. Failures are collected and
/// reported at the end — one broken default doesn't block the rest, so
/// users on slow networks or with one transient 403 still get the
/// remaining plugins installed.
pub(crate) fn install_defaults(force: bool, json: bool) -> Result<()> {
    use super::DEFAULT_PLUGINS;

    if !json {
        println!(
            "{} Installing {} default plugins...",
            style("*").cyan().bold(),
            DEFAULT_PLUGINS.len()
        );
    }

    let mut installed: Vec<serde_json::Value> = Vec::new();
    let mut installed_sources: Vec<&str> = Vec::new();
    let mut failed: Vec<(&str, String)> = Vec::new();

    for source in DEFAULT_PLUGINS {
        if !json {
            println!();
            println!("  {} {}", style("").dim(), style(source).cyan());
        }
        match install_plugin(source, force, json) {
            Ok(report) => {
                installed.push(report);
                installed_sources.push(source);
            }
            Err(e) => failed.push((source, e.to_string())),
        }
    }

    if !json {
        println!();
        println!(
            "{} {} of {} default plugins installed.",
            if failed.is_empty() {
                style("").green().bold()
            } else {
                style("⚠️").yellow().bold()
            },
            installed_sources.len(),
            DEFAULT_PLUGINS.len()
        );

        if !failed.is_empty() {
            println!();
            println!("Failures:");
            for (source, err) in &failed {
                println!("  {} {}{}", style("").red(), style(source).cyan(), err);
            }
        }
    }

    if json {
        let failed_json: Vec<serde_json::Value> = failed
            .iter()
            .map(|(source, err)| serde_json::json!({ "source": source, "error": err }))
            .collect();
        let result = serde_json::json!({
            "schema_version": PLUGINS_INSTALL_SCHEMA,
            "action": "install",
            "scope": "defaults",
            "installed": installed,
            "failed": failed_json,
            "summary": {
                "total": DEFAULT_PLUGINS.len(),
                "installed": installed_sources.len(),
                "failed": failed.len(),
            },
        });
        println!("{}", serde_json::to_string_pretty(&result)?);
    }

    if !failed.is_empty() {
        bail!("{} default plugin(s) failed to install.", failed.len());
    }

    Ok(())
}

/// Install a single plugin. Returns a JSON-serializable report describing
/// what was installed; the caller is responsible for printing the JSON
/// envelope (so single-install and bulk-install share one shape).
pub(crate) fn install_plugin(source: &str, force: bool, json: bool) -> Result<serde_json::Value> {
    let force = force || crate::utils::is_non_interactive();
    let (_, git_ref) = parse_source_ref(source);
    let url = normalize_source(source);
    let repo_name = extract_name_from_source(source);
    validate_plugin_name(&repo_name)?;

    let tier = determine_trust_tier(source);
    if !json {
        println!(
            "\n{} Installing plugin from: {} [{}]",
            style("!").yellow().bold(),
            style(&url).cyan(),
            tier.styled_label()
        );
        if tier == TrustTier::Official {
            println!(
                "  {} This is an official CorvidLabs plugin.",
                style("").green()
            );
        } else {
            println!(
                "  {} Plugins can execute arbitrary code on your system.",
                style("*").yellow()
            );
            println!(
                "  {} Only install plugins from sources you trust.\n",
                style("*").yellow()
            );
        }
    }

    if !force {
        if !crate::utils::is_interactive() {
            bail!(
                "Plugin installation requires confirmation in non-interactive mode.\n  \
                 Use --yes or --force to skip prompts."
            );
        }
        let confirm = dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
            .with_prompt(format!("Install plugin '{repo_name}' from {url}?"))
            .default(true)
            .interact()?;
        if !confirm {
            bail!("Plugin installation cancelled.");
        }
    }

    let plugins = plugins_dir();
    let bin_dir = plugin_bin_dir();
    fs::create_dir_all(&plugins)?;
    fs::create_dir_all(&bin_dir)?;

    let plugin_dir = plugins.join(&repo_name);

    let mut registry = load_registry()?;
    let existing = registry.plugins.iter().position(|p| p.name == repo_name);

    if plugin_dir.exists() {
        if !force {
            bail!(
                "Plugin '{}' is already installed.\n  Use {} to reinstall.",
                repo_name,
                style("--force").cyan()
            );
        }
        fs::remove_dir_all(&plugin_dir).context("removing existing plugin")?;
    }

    let sp = if json {
        None
    } else {
        let clone_msg = match git_ref {
            Some(r) => format!("Cloning {}@{}:", &url, r),
            None => format!("Cloning {}:", &url),
        };
        Some(crate::spinner::Spinner::start(&clone_msg))
    };

    let mut clone_args = vec!["clone"];
    if git_ref.is_none() {
        clone_args.push("--depth");
        clone_args.push("1");
    }
    clone_args.push(&url);

    let mut cmd = Command::new("git");
    cmd.args(&clone_args)
        .arg(&plugin_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped());
    apply_git_auth(&mut cmd);

    let status = cmd.status().context("running git clone")?;

    if let Some(s) = sp {
        s.finish();
    }

    if !status.success() {
        bail!(
            "Failed to clone '{}'. Check the repository URL and your network connection.",
            source
        );
    }

    if let Some(ref_str) = git_ref {
        let status = Command::new("git")
            .args(["checkout", ref_str])
            .current_dir(&plugin_dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::piped())
            .status()
            .with_context(|| format!("checking out ref '{ref_str}'"))?;
        if !status.success() {
            fs::remove_dir_all(&plugin_dir).ok();
            bail!(
                "Git ref '{}' not found in '{}'. Check available tags with:\n  {}",
                ref_str,
                source,
                style(format!("git ls-remote --tags {url}")).cyan()
            );
        }
    }

    let manifest_path = plugin_dir.join("plugin.toml");
    if !manifest_path.exists() {
        fs::remove_dir_all(&plugin_dir).ok();
        bail!(
            "Repository '{}' has no plugin.toml manifest.\n  See {} for the plugin format.",
            source,
            style("https://github.com/CorvidLabs/fledge#plugins").cyan()
        );
    }

    let manifest_content = fs::read_to_string(&manifest_path).context("reading plugin.toml")?;
    let manifest: PluginManifest =
        toml::from_str(&manifest_content).context("parsing plugin.toml")?;

    let caps = &manifest.capabilities;
    let has_protocol_caps = caps.exec || caps.store || caps.metadata;
    let has_wasm_caps = caps.filesystem.as_deref().is_some_and(|f| f != "none") || caps.network;
    let has_caps = has_protocol_caps || has_wasm_caps;
    let needs_cap_prompt =
        has_caps && (manifest.plugin.protocol.is_some() || manifest.plugin.is_wasm());
    let has_hooks = manifest.hooks.has_any();

    if let Err(blocked) = check_tier_capabilities(tier, caps) {
        if let Err(e) = fs::remove_dir_all(&plugin_dir) {
            eprintln!(
                "Warning: failed to clean up partial install at {}: {e}",
                plugin_dir.display()
            );
        }
        bail!(
            "Unverified plugin '{}' requests dangerous capabilities: {}\n  \
             Only official and team-tier plugins may use exec or network.\n  \
             If you trust this source, fork it under an account you control or an org in your team allowlist.",
            repo_name,
            blocked.join(", ")
        );
    }

    if needs_cap_prompt || has_hooks {
        if !json {
            if needs_cap_prompt {
                println!("\n  {} Requested capabilities:", style("*").cyan().bold());
                if caps.exec {
                    println!("    {} exec — run shell commands", style("").yellow());
                }
                if caps.store {
                    println!(
                        "    {} store — persist data between runs",
                        style("").yellow()
                    );
                }
                if caps.metadata {
                    println!(
                        "    {} metadata — read project metadata and environment",
                        style("").yellow()
                    );
                }
                if let Some(ref fs_cap) = caps.filesystem {
                    match fs_cap.as_str() {
                        "project" => {
                            println!(
                                "    {} filesystem (project) — read-only access to project directory",
                                style("").yellow()
                            );
                        }
                        "plugin" => {
                            println!(
                                "    {} filesystem (plugin) — read-only project access + read-write plugin data",
                                style("").yellow()
                            );
                        }
                        "none" => {}
                        other => {
                            println!(
                                "    {} filesystem ({}) — access host files",
                                style("").yellow(),
                                other
                            );
                        }
                    }
                }
                if caps.network {
                    println!(
                        "    {} network — make outbound network requests (unrestricted)",
                        style("").yellow()
                    );
                }
                if caps.exec && caps.network {
                    println!(
                        "\n    {} This plugin can both execute commands and access the network.",
                        style("").yellow().bold()
                    );
                    println!(
                        "    {} Together these allow data exfiltration — only install if you trust the source.",
                        style("").yellow().bold()
                    );
                }
            }
            if has_hooks {
                println!("\n  {} Lifecycle hooks:", style("*").cyan().bold());
                for (name, cmd) in manifest.hooks.iter_defined() {
                    println!(
                        "    {} {}{}",
                        style("").yellow(),
                        name,
                        style(cmd).dim()
                    );
                }
            }
            println!();
        }
        if force {
            eprintln!(
                "  {} Permissions auto-granted via --force",
                style("WARN").yellow()
            );
        } else if !crate::utils::is_interactive() {
            fs::remove_dir_all(&plugin_dir).ok();
            bail!(
                "Plugin permissions require confirmation in non-interactive mode.\n  \
                 Use --yes or --force to auto-grant."
            );
        } else {
            let prompt_msg = if needs_cap_prompt && has_hooks {
                "Grant capabilities and approve hooks?"
            } else if needs_cap_prompt {
                "Grant these capabilities?"
            } else {
                "Approve these hooks?"
            };
            let confirm =
                dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
                    .with_prompt(prompt_msg)
                    .default(true)
                    .interact()?;
            if !confirm {
                fs::remove_dir_all(&plugin_dir).ok();
                bail!("Plugin installation cancelled.");
            }
        }
    }

    run_build(&plugin_dir, &manifest)?;

    if manifest.plugin.is_wasm() {
        for cmd in &manifest.commands {
            let wasm_path = plugin_dir.join(&cmd.binary);
            if wasm_path.exists() {
                println!(
                    "  {} Pre-compiling WASM module...",
                    style("").cyan().bold()
                );
                super::wasm::compile_and_cache(&wasm_path)?;
            } else {
                fs::remove_dir_all(&plugin_dir).ok();
                bail!(
                    "WASM binary '{}' not found after build.\n  \
                     Check that the build hook produces a .wasm file at the path declared in plugin.toml.\n  \
                     Expected: {}",
                    cmd.binary,
                    wasm_path.display()
                );
            }
        }
    }

    let command_names = link_commands(&plugin_dir, &bin_dir, &manifest).inspect_err(|_| {
        fs::remove_dir_all(&plugin_dir).ok();
    })?;

    let (base_source, _) = parse_source_ref(source);
    let granted_caps = if manifest.plugin.protocol.is_some() {
        Some(manifest.capabilities.clone())
    } else {
        None
    };
    let entry = PluginEntry {
        name: repo_name.clone(),
        source: base_source.to_string(),
        version: manifest.plugin.version.clone(),
        installed: chrono::Local::now().format("%Y-%m-%d").to_string(),
        commands: command_names.clone(),
        pinned_ref: git_ref.map(String::from),
        capabilities: granted_caps,
        runtime: manifest.plugin.runtime.clone(),
    };

    if let Some(idx) = existing {
        registry.plugins[idx] = entry.clone();
    } else {
        registry.plugins.push(entry.clone());
    }
    save_registry(&registry)?;

    if !json {
        if let Some(ref pinned) = git_ref {
            println!(
                "{} Installed {} v{} (pinned to {})",
                style("").green().bold(),
                style(&manifest.plugin.name).green(),
                manifest.plugin.version,
                style(pinned).cyan()
            );
        } else {
            println!(
                "{} Installed {} v{}",
                style("").green().bold(),
                style(&manifest.plugin.name).green(),
                manifest.plugin.version
            );
        }
        if !command_names.is_empty() {
            println!("  Commands: {}", style(command_names.join(", ")).cyan());
        }
    }

    if let Some(hook) = &manifest.hooks.post_install {
        run_hook(&plugin_dir, hook, "post_install")?;
    }

    Ok(serde_json::json!({
        "name": entry.name,
        "source": entry.source,
        "version": entry.version,
        "trust_tier": tier.label(),
        "commands": entry.commands,
        "pinned_ref": entry.pinned_ref,
        "capabilities": entry.capabilities,
    }))
}