rpi-cli 1.0.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
Documentation
//! Resolve standalone Skills through the official collection's release index.
use std::collections::BTreeMap;

use reqwest::{Client, Url};
use semver::Version;
use serde::Deserialize;

use super::{
    identifier, read_release, release_client, stage_release, StagedRelease, RELEASE_TIMEOUT,
};
use crate::install_http;

const RELEASES: &str = "https://github.com/pi-rust/rpi-skills/releases/";

#[derive(Deserialize)]
struct Index {
    schema_version: u32,
    tag: String,
    zones: BTreeMap<String, Zone>,
}

#[derive(Deserialize)]
struct Zone {
    manifest: String,
    skills: Vec<String>,
}

pub(crate) async fn stage_skill(
    name: &str,
    version: Option<&str>,
) -> Result<StagedRelease, String> {
    if crate::args::offline_env_enabled() {
        return Err("Skill download is disabled in offline mode".into());
    }
    let version = version
        .map(Version::parse)
        .transpose()
        .map_err(|error| format!("invalid Skill collection version: {error}"))?;
    let client = release_client()?;
    stage(
        &client,
        &Url::parse(RELEASES).map_err(|e| e.to_string())?,
        name,
        version,
    )
    .await
}

async fn stage(
    client: &Client,
    releases: &Url,
    name: &str,
    requested: Option<Version>,
) -> Result<StagedRelease, String> {
    if !identifier(name) {
        return Err("invalid published Skill name".into());
    }
    let index_path = match &requested {
        Some(version) => format!("download/v{version}/index.json"),
        None => "latest/download/index.json".into(),
    };
    let index_url = releases.join(&index_path).map_err(|e| e.to_string())?;
    let bytes = install_http::download(
        || client.get(index_url.clone()),
        256 * 1024,
        RELEASE_TIMEOUT,
    )
    .await
    .map_err(|error| format!("Skill index at {index_url}: {error}"))?;
    let index: Index =
        serde_json::from_slice(&bytes).map_err(|e| format!("invalid Skill index: {e}"))?;
    let version = index
        .tag
        .strip_prefix('v')
        .and_then(|version| Version::parse(version).ok())
        .ok_or("invalid Skill index tag")?;
    if index.schema_version != 1
        || !version.pre.is_empty()
        || !version.build.is_empty()
        || requested.is_some_and(|requested| requested != version)
    {
        return Err("invalid Skill index schema or version".into());
    }
    let mut matches = index
        .zones
        .iter()
        .filter(|(_, zone)| zone.skills.iter().any(|skill| skill == name));
    let (zone, entry) = matches
        .next()
        .ok_or_else(|| format!("Skill {name} was not found in rpi-skills {}", index.tag))?;
    let package = format!("rpi-skills-{zone}");
    if matches.next().is_some()
        || !identifier(&package)
        || entry.manifest != format!("{package}.json")
    {
        return Err(format!("invalid Skill index entry for {name}"));
    }
    let manifest = releases
        .join(&format!("download/{}/{}", index.tag, entry.manifest))
        .map_err(|e| e.to_string())?;
    let release = read_release(client, &package, manifest, Some(version)).await?;
    let mut staged = stage_release(client, release).await?;
    staged.root = staged.root.join("skills").join(name);
    if !staged.root.join("SKILL.md").is_file() {
        return Err(format!("Skill {name} is missing from the verified archive"));
    }
    Ok(staged)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use sha2::{Digest, Sha256};
    use std::io::{Cursor, Write};
    use std::time::Duration;
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
    use tokio::net::TcpListener;

    #[tokio::test]
    async fn official_skill_lookup_pins_the_domain_archive_to_the_index_version() {
        let index = json!({"schema_version":1,"tag":"v0.1.4","zones":{
            "rust":{"manifest":"rpi-skills-rust.json","skills":["demo", "neighbor"]}
        }})
        .to_string();
        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
        let options = zip::write::SimpleFileOptions::default();
        zip.start_file("rpi-package.json", options).unwrap();
        serde_json::to_writer(
            &mut zip,
            &json!({"schema_version":1,"name":"rpi-skills-rust","version":"0.1.4",
                "agent":{"instructions":[],"tools":[]}}),
        )
        .unwrap();
        for name in ["demo", "neighbor"] {
            zip.start_file(format!("skills/{name}/SKILL.md"), options)
                .unwrap();
            write!(zip, "---\nname: {name}\ndescription: Fixture\n---\n").unwrap();
        }
        let archive = zip.finish().unwrap().into_inner();
        let manifest = json!({"schema_version":1,"name":"rpi-skills-rust","version":"0.1.4",
            "asset":"rpi-skills-rust-0.1.4.zip","bytes":archive.len(),
            "sha256":format!("{:x}", Sha256::digest(&archive))})
        .to_string();

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let releases = Url::parse(&format!(
            "http://{}/releases/",
            listener.local_addr().unwrap()
        ))
        .unwrap();
        let client = Client::builder()
            .no_proxy()
            .timeout(Duration::from_secs(5))
            .build()
            .unwrap();
        let serve = async {
            for (path, body) in [
                ("latest/download/index.json", index.as_bytes()),
                ("download/v0.1.4/rpi-skills-rust.json", manifest.as_bytes()),
                ("download/v0.1.4/rpi-skills-rust-0.1.4.zip", &archive),
            ] {
                let (stream, _) = listener.accept().await.unwrap();
                let mut stream = BufReader::new(stream);
                let mut line = String::new();
                stream.read_line(&mut line).await.unwrap();
                assert!(
                    line.starts_with(&format!("GET /releases/{path} ")),
                    "{line}"
                );
                while line != "\r\n" {
                    line.clear();
                    assert!(stream.read_line(&mut line).await.unwrap() > 0);
                }
                let headers = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                stream
                    .get_mut()
                    .write_all(headers.as_bytes())
                    .await
                    .unwrap();
                stream.get_mut().write_all(body).await.unwrap();
            }
        };
        let ((), staged) = tokio::time::timeout(Duration::from_secs(6), async {
            tokio::join!(serve, stage(&client, &releases, "demo", None))
        })
        .await
        .unwrap();
        let staged = staged.unwrap();
        assert_eq!(staged.version, "0.1.4");
        assert!(staged
            .origin
            .ends_with("/download/v0.1.4/rpi-skills-rust.json"));
        assert!(std::fs::read_to_string(staged.root.join("SKILL.md"))
            .unwrap()
            .contains("name: demo"));
        assert!(!staged.root.join("neighbor").exists());
    }
}