agent-loadout 1.0.0

Loadout CLI: manage MCP servers, skills and secret references for AI coding clients
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
//! `loadout scanner ls|status|setup|prepare|enable|disable|run|remove`
//! (#30, M52): the optional external scanner, NVIDIA SkillSpector, run
//! locally from the user's own uv or `skillspector`, else from a private uv
//! `setup` downloads into Loadout's data folder. `loadout skills scan` already
//! names the classification of client skill folders, so the scanners get
//! their own noun; there is one optional scanner, so the subcommands take
//! no scanner name. `remove` deletes the private uv and cleans up a 0.7.0
//! Snyk Agent Scan install.
//!
//! Also the helpers `skills add` and `skills update` use for
//! `--external` / `--no-external`: one bounded run per skill, its report
//! printed beside the built-in scan's.

use agent_loadout_core::scan::Verdict;
use agent_loadout_core::scan::external::skillspector::{
    self, Availability, DISCLOSURE, PYTHON, Runner, Runtime, RuntimeKind, SetupStep, UvSource,
    VERSION,
};
use agent_loadout_core::scan::external::snyk_leftover;
use agent_loadout_core::scan::external::{Choice, ExternalReport, ExternalStatus};
use agent_loadout_core::skills::{SkillFiles, content_hash, store as skill_store};
use agent_loadout_core::{CoreError, ErrorCode};
use clap::{Args, Subcommand};
use serde_json::{Value, json};

use super::{Context, JSON_SCHEMA, path_json, print_json, require_store};
use crate::interrupt::Busy;

#[derive(Debug, Args)]
pub struct ScannerArgs {
    #[command(subcommand)]
    command: ScannerCommand,
}

#[derive(Debug, Subcommand)]
enum ScannerCommand {
    /// List the scanners: the built-in scanner (always on) and SkillSpector
    /// (optional, local).
    Ls,
    /// Show SkillSpector on this machine: how it runs (uvx or on PATH),
    /// its version, on or off, the timeout, and what leaves the machine.
    Status,
    /// Set SkillSpector up: when no uv is on PATH, download the pinned uv
    /// into Loadout's data folder (checked against SHA-256 values built into
    /// Loadout), then prepare SkillSpector with it. Does not turn it on;
    /// `loadout scanner remove` undoes it.
    Setup,
    /// Download the pinned SkillSpector into uv's cache once (runs `uvx
    /// --python 3.13 --from skillspector==2.13.7 skillspector --version`).
    /// Needs uv on PATH; scans never download anything.
    Prepare,
    /// Run SkillSpector on skill installs and updates on this machine
    /// (locally; see `loadout scanner status`).
    Enable,
    /// Stop running SkillSpector on skill installs and updates.
    Disable,
    /// Scan a library skill (its store content) with SkillSpector now;
    /// reports only. Exits 0 when it was scanned, 1 otherwise.
    Run {
        /// Skill id.
        skill: String,
    },
    /// Delete the uv `loadout scanner setup` installed (with its cache,
    /// Python and SkillSpector's environment), and a Snyk Agent Scan
    /// install left by Loadout 0.7.0 and its settings.
    Remove,
}

pub fn run(ctx: &Context, args: &ScannerArgs) -> Result<u8, CoreError> {
    match &args.command {
        ScannerCommand::Ls => list(ctx),
        ScannerCommand::Status => status(ctx),
        ScannerCommand::Setup => setup(ctx),
        ScannerCommand::Prepare => prepare(ctx),
        ScannerCommand::Enable => switch(ctx, true),
        ScannerCommand::Disable => switch(ctx, false),
        ScannerCommand::Run { skill } => run_on_library(ctx, skill),
        ScannerCommand::Remove => remove(ctx),
    }
}

fn remove(ctx: &Context) -> Result<u8, CoreError> {
    let private_uv = skillspector::remove_private_uv(&ctx.home)?;
    let snyk = snyk_leftover::remove(ctx.fs(), &ctx.home)?;
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "removed": private_uv || snyk,
            "private_uv": private_uv,
            "snyk": snyk,
        }));
        return Ok(0);
    }
    if private_uv {
        println!(
            "Removed the uv Loadout installed in its data folder (with its cache, Python and \
             SkillSpector's environment)."
        );
    }
    if snyk {
        println!("Removed Snyk Agent Scan (from Loadout 0.7.0) and its settings.");
    }
    if !private_uv && !snyk {
        println!("Nothing to remove.");
    }
    Ok(0)
}

fn scanner_status(ctx: &Context) -> Result<skillspector::Status, CoreError> {
    skillspector::status(&ctx.env, ctx.fs(), &ctx.home)
}

/// `scanner status --json` (also `prepare`, `enable` and `disable`).
fn status_json(status: &skillspector::Status) -> Value {
    let availability = &status.availability;
    let runtime = availability.runtime();
    let (kind, program) = match availability {
        Availability::Ready(runtime) => (Some(runtime.kind), Some(path_json(&runtime.program))),
        Availability::NeedsPrepare { uv, .. } => (Some(RuntimeKind::Uvx), Some(path_json(uv))),
        Availability::NotAvailable => (None, None),
    };
    let uv_source = match availability {
        Availability::Ready(runtime) => runtime.uv,
        Availability::NeedsPrepare { source, .. } => Some(*source),
        Availability::NotAvailable => None,
    };
    json!({
        "schema": JSON_SCHEMA,
        "name": skillspector::SCANNER.as_str(),
        "tested_version": VERSION,
        "python": PYTHON,
        "availability": availability.as_str(),
        "runtime": kind.map(RuntimeKind::as_str),
        "program": program,
        "version": runtime.map(|runtime| runtime.version.as_str()),
        "version_tested": runtime.is_none_or(Runtime::tested),
        "note": runtime.and_then(Runtime::note),
        "enabled": status.enabled,
        "timeout_secs": status.timeout.as_secs(),
        "sends": DISCLOSURE,
        "setup": matches!(availability, Availability::NotAvailable)
            .then(|| skillspector::setup_text(status.setup_supported)),
        "snyk_installed": status.snyk_installed,
        "private_uv": status.private_uv,
        "private_uv_present": status.private_uv_present,
        "setup_supported": status.setup_supported,
        "uv_source": uv_source.map(UvSource::as_str),
    })
}

fn on_off(value: bool) -> &'static str {
    if value { "on " } else { "off" }
}

/// How SkillSpector runs here, in a few words.
fn availability_text(availability: &Availability) -> String {
    match availability {
        Availability::Ready(runtime) => match runtime.kind {
            RuntimeKind::Uvx => format!("SkillSpector {} (ready, uvx)", runtime.version),
            RuntimeKind::Path => format!("SkillSpector {} (ready, on PATH)", runtime.version),
        },
        Availability::NeedsPrepare { .. } => {
            format!("SkillSpector {VERSION} (needs `loadout scanner prepare`)")
        }
        Availability::NotAvailable => {
            format!("SkillSpector {VERSION} (not found; see `loadout scanner status`)")
        }
    }
}

fn list(ctx: &Context) -> Result<u8, CoreError> {
    let status = scanner_status(ctx)?;
    let runtime = status.availability.runtime();
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "scanners": [
                { "name": "builtin", "enabled": true, "availability": "ready", "local": true },
                {
                    "name": skillspector::SCANNER.as_str(),
                    "enabled": status.enabled,
                    "availability": status.availability.as_str(),
                    "runtime": runtime.map(|runtime| runtime.kind.as_str()),
                    "version": runtime.map(|runtime| runtime.version.as_str()),
                    "local": true,
                },
            ],
        }));
        return Ok(0);
    }
    println!("builtin        on   Loadout's own rules; runs locally, nothing leaves this machine");
    println!(
        "{:<14} {}  {}; runs locally",
        skillspector::SCANNER.as_str(),
        on_off(status.enabled),
        availability_text(&status.availability)
    );
    Ok(0)
}

fn status(ctx: &Context) -> Result<u8, CoreError> {
    let status = scanner_status(ctx)?;
    if ctx.json {
        print_json(&status_json(&status));
        return Ok(0);
    }
    println!("SkillSpector (optional, runs locally; tested version {VERSION})");
    match &status.availability {
        Availability::Ready(runtime) => {
            match runtime.kind {
                RuntimeKind::Uvx => {
                    let by = if runtime.uv == Some(UvSource::Private) {
                        ", uv installed by Loadout"
                    } else {
                        ""
                    };
                    println!("  Runtime:   uvx{by} ({})", runtime.command_line());
                }
                RuntimeKind::Path => {
                    println!("  Runtime:   on PATH ({})", runtime.program.display());
                }
            }
            println!("  Version:   {}", runtime.version);
            if let Some(note) = runtime.note() {
                println!("  Note:      {note}");
            }
        }
        Availability::NeedsPrepare { uv, .. } => {
            println!(
                "  Runtime:   uvx ({}); SkillSpector {VERSION} is not downloaded yet",
                uv.display()
            );
        }
        Availability::NotAvailable => {
            println!("  Runtime:   not found (neither uv nor skillspector is on PATH)")
        }
    }
    println!("  Turned on: {}", if status.enabled { "yes" } else { "no" });
    println!("  Timeout:   {} s", status.timeout.as_secs());
    if let Some(version) = &status.private_uv {
        println!(
            "  Private uv: uv {version} installed by Loadout in its data folder; `loadout \
             scanner remove` deletes it"
        );
    } else if status.private_uv_present {
        println!(
            "  Private uv: an incomplete uv setup remains in Loadout's data folder; `loadout \
             scanner remove` deletes it"
        );
    }
    println!();
    println!("{DISCLOSURE}");
    print_next_step(&status);
    if status.snyk_installed {
        println!();
        println!(
            "A Snyk Agent Scan install from Loadout 0.7.0 remains (it never runs): `loadout \
             scanner remove` deletes it."
        );
    }
    Ok(0)
}

/// What to do when SkillSpector is not ready: prepare it, or set it up.
fn print_next_step(status: &skillspector::Status) {
    match &status.availability {
        Availability::Ready(_) => {}
        Availability::NeedsPrepare { .. } => {
            println!();
            println!("SkillSpector is not downloaded yet: run `loadout scanner prepare` (once).");
        }
        Availability::NotAvailable => {
            println!();
            // Without a pinned uv for this platform, only the manual routes.
            println!("{}", skillspector::setup_text(status.setup_supported));
        }
    }
}

fn setup(ctx: &Context) -> Result<u8, CoreError> {
    eprintln!("{DISCLOSURE}");
    let download = skillspector::uv_download(&ctx.env);
    // Ctrl+C stops the download (partial files removed) or kills uv's whole
    // process tree and removes the run folder.
    let busy = Busy::start();
    let mut downloading = false;
    let mut shown = 0;
    let mut preparing = false;
    let set_up = skillspector::setup(
        &ctx.env,
        &ctx.home,
        download.as_ref(),
        &mut |step| match step {
            SetupStep::Download { received, total } => {
                if !downloading {
                    downloading = true;
                    eprintln!("Downloading uv from GitHub ({} MB)...", mb(total));
                }
                // A line per quarter, so a log stays short.
                let quarter = (received.saturating_mul(4)).checked_div(total).unwrap_or(4);
                if quarter > shown {
                    shown = quarter;
                    eprintln!("  {} of {} MB", mb(received), mb(total));
                }
            }
            SetupStep::Prepare { line } => {
                if !preparing {
                    preparing = true;
                    eprintln!(
                        "Preparing SkillSpector {VERSION}: uv downloads it and its dependencies \
                         from PyPI, and a Python {PYTHON} build when it has none."
                    );
                }
                eprintln!("  {line}");
            }
        },
        Some(busy.flag()),
    );
    drop(busy);
    let runtime = set_up?;
    let status = scanner_status(ctx)?;
    if ctx.json {
        let mut doc = status_json(&status);
        doc["set_up"] = json!(true);
        print_json(&doc);
    } else {
        let by = match runtime.uv {
            Some(UvSource::Private) => ", uv installed by Loadout",
            _ => "",
        };
        println!("SkillSpector {} is ready (uvx{by}).", runtime.version);
        if !status.enabled {
            println!("It is off: turn it on with `loadout scanner enable`.");
        }
    }
    Ok(0)
}

/// Bytes in decimal MB (10^6, as "about 16 MB") with one decimal.
fn mb(bytes: u64) -> String {
    format!("{:.1}", bytes as f64 / 1_000_000.0)
}

fn prepare(ctx: &Context) -> Result<u8, CoreError> {
    if skillspector::find_uv(&ctx.env, &ctx.home).is_none() {
        // Nothing to download: a SkillSpector on PATH runs as it is.
        if let Availability::Ready(runtime) = skillspector::detect(&ctx.env, &ctx.home) {
            let status = scanner_status(ctx)?;
            if ctx.json {
                let mut doc = status_json(&status);
                doc["prepared"] = json!(false);
                print_json(&doc);
            } else {
                println!(
                    "uv is not on PATH, and SkillSpector {} on PATH ({}) is ready: there is \
                     nothing to prepare.",
                    runtime.version,
                    runtime.program.display()
                );
                if let Some(note) = runtime.note() {
                    println!("note: {note}");
                }
            }
            return Ok(0);
        }
        return Err(CoreError::new(
            ErrorCode::ScannerUnavailable,
            format!(
                "neither uv nor skillspector is on PATH, so there is nothing to prepare. {}",
                skillspector::setup_text(skillspector::setup_supported(&ctx.env, &ctx.home))
            ),
        ));
    }
    eprintln!(
        "Preparing SkillSpector {VERSION}: uv downloads it and its dependencies (a few hundred \
         MB) from PyPI, and a Python {PYTHON} build when uv has none. This happens once; scans \
         never download anything."
    );
    // Ctrl+C kills uv's whole process tree and removes the run folder.
    let busy = Busy::start();
    let prepared = skillspector::prepare(
        &ctx.env,
        &ctx.home,
        &mut |line| eprintln!("  {line}"),
        Some(busy.flag()),
    );
    drop(busy);
    let runtime = prepared?;
    let status = scanner_status(ctx)?;
    if ctx.json {
        let mut doc = status_json(&status);
        doc["prepared"] = json!(true);
        print_json(&doc);
    } else {
        println!("SkillSpector {} is ready (uvx).", runtime.version);
        if !status.enabled {
            println!("It is off: turn it on with `loadout scanner enable`.");
        }
    }
    Ok(0)
}

fn switch(ctx: &Context, on: bool) -> Result<u8, CoreError> {
    skillspector::set_enabled(ctx.fs(), &ctx.home, on)?;
    let status = scanner_status(ctx)?;
    if ctx.json {
        print_json(&status_json(&status));
        return Ok(0);
    }
    if on {
        println!("SkillSpector is on for skill installs and updates on this machine.");
        println!("{DISCLOSURE}");
        if let Some(note) = status.availability.runtime().and_then(Runtime::note) {
            println!("note: {note}");
        }
        print_next_step(&status);
    } else {
        println!("SkillSpector is off; installs and updates use the built-in scan only.");
    }
    Ok(0)
}

fn run_on_library(ctx: &Context, id: &str) -> Result<u8, CoreError> {
    let settings = skillspector::settings(ctx.fs(), &ctx.home)?;
    if !settings.enabled {
        return Err(CoreError::new(
            ErrorCode::ScannerUnavailable,
            "SkillSpector is off on this machine; turn it on with `loadout scanner enable`, or \
             pass --external to an install or update",
        ));
    }
    let store = require_store(ctx, "there is no skill to scan")?;
    let files = skill_store::read_content(&store, id)?;
    let runner = skillspector::prepare_run(&ctx.env, ctx.fs(), &ctx.home);
    let report = report_for(ctx, &runner, &files, id);
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "id": id,
            "external": external_json(&report),
        }));
    } else {
        print_external(&report, "");
    }
    Ok(match report.status {
        ExternalStatus::Scanned => 0,
        _ => 1,
    })
}

/// `--external` / `--no-external` as a [`Choice`].
pub(super) fn choice(on: bool, off: bool) -> Choice {
    match (on, off) {
        (true, _) => Choice::On,
        (_, true) => Choice::Off,
        _ => Choice::Default,
    }
}

/// A runner when this command should run SkillSpector (`choice`, else the
/// switch): `None` when not; `Some(Err(report))` when it should but cannot
/// (not found, not prepared): every skill gets that report.
pub(super) fn wanted(
    ctx: &Context,
    choice: Choice,
) -> Result<Option<Result<Runner, ExternalReport>>, CoreError> {
    let settings = skillspector::settings(ctx.fs(), &ctx.home)?;
    if !skillspector::wanted(&settings, choice) {
        return Ok(None);
    }
    Ok(Some(skillspector::prepare_run(
        &ctx.env,
        ctx.fs(),
        &ctx.home,
    )))
}

/// One run on `files`, announced on stderr. Ctrl+C (or SIGTERM, SIGHUP)
/// kills the scanner's whole process tree, removes the run folder and ends
/// the command (exit 130).
fn scan(ctx: &Context, runner: &Runner, files: &SkillFiles, name: &str) -> ExternalReport {
    if !ctx.json {
        eprintln!("Running SkillSpector on {name}...");
    }
    let busy = Busy::start();
    let report = runner.scan_files(&ctx.env, &ctx.home, files, Some(busy.flag()));
    drop(busy);
    report
}

/// [`scan`] for a prepared run, or its not-scanned report.
pub(super) fn report_for(
    ctx: &Context,
    runner: &Result<Runner, ExternalReport>,
    files: &SkillFiles,
    name: &str,
) -> ExternalReport {
    match runner {
        Ok(runner) => scan(ctx, runner, files, name),
        Err(report) => {
            let mut report = report.clone();
            report.content_hash = Some(content_hash(files));
            report
        }
    }
}

/// An external report for `--json`.
pub(super) fn external_json(report: &ExternalReport) -> Value {
    json!({
        "scanner": report.scanner,
        "version": report.version,
        "status": report.status.as_str(),
        "reason": report.reason.map(|reason| reason.as_str()),
        // A report that wasn't scanned or wasn't understood has no verdict:
        // `null`, never "clean" (scripts and agents read this field).
        "verdict": (report.status == ExternalStatus::Scanned).then(|| report.verdict.as_str()),
        "incomplete": report.incomplete,
        "detail": report.detail,
        "findings": report.findings.iter().map(|finding| json!({
            "scanner": finding.scanner,
            "rule": finding.rule,
            "severity": finding.severity.as_str(),
            "file": finding.file,
            "line": finding.line,
            "message": finding.message,
            "excerpt": finding.excerpt,
        })).collect::<Vec<_>>(),
    })
}

/// `SkillSpector: <summary>`, then one line per finding.
pub(super) fn print_external(report: &ExternalReport, indent: &str) {
    println!("{indent}{}: {}", report.scanner.name(), report.summary());
    if let Some(detail) = &report.detail
        && report.status != ExternalStatus::Scanned
    {
        println!("{indent}  {detail}");
    }
    for finding in &report.findings {
        let place = match (&finding.file, finding.line) {
            (Some(file), Some(line)) => format!("{file}:{line}"),
            (Some(file), None) => file.clone(),
            _ => String::from("-"),
        };
        println!(
            "{indent}  {:<9} {:<26} {place}  {}",
            finding.severity.as_str(),
            finding.rule,
            finding.message
        );
        if let Some(excerpt) = &finding.excerpt {
            println!("{indent}    > {excerpt}");
        }
    }
    if report.status == ExternalStatus::Scanned && report.verdict == Verdict::Dangerous {
        println!(
            "{indent}  (a dangerous verdict needs --allow-dangerous, as for the built-in scan)"
        );
    }
}