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 {
Ls,
Status,
Setup,
Prepare,
Enable,
Disable,
Run {
skill: String,
},
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)
}
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" }
}
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)
}
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!();
println!("{}", skillspector::setup_text(status.setup_supported));
}
}
}
fn setup(ctx: &Context) -> Result<u8, CoreError> {
eprintln!("{DISCLOSURE}");
let download = skillspector::uv_download(&ctx.env);
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));
}
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)
}
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() {
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."
);
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,
})
}
pub(super) fn choice(on: bool, off: bool) -> Choice {
match (on, off) {
(true, _) => Choice::On,
(_, true) => Choice::Off,
_ => Choice::Default,
}
}
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,
)))
}
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
}
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
}
}
}
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()),
"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<_>>(),
})
}
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)"
);
}
}