yk-lua 0.1.0

Extensions written in Lua, running in an embedded Luau VM
Documentation
//! The capabilities a `Lua` extension can reach.
//!
//! Deliberately tiny, and defined here as a trait rather than assembled from
//! `reqwest` inside `yk-lua`. `yk-lua` knows about no HTTP, and
//! a trait is how that stays true: the binary implements [`Host`] with its
//! existing client, and `yk-lua` stays testable with a fake.
//!
//! Every member of this trait is a capability the agent already has through its
//! built-in tools. That is the bar: a capability that gives an extension reach
//! the built-in tools do not already have is a different conversation.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use yk_core::Result;

/// What an HTTP POST came back with.
///
/// A status and the body, deliberately not a parsed body: `host.json` is the
/// parser, and a host that guessed at a shape would be wrong for every service
/// that is not the one it was written for.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HttpResponse {
    /// The HTTP status code. Not an error at this layer, because the difference
    /// between "the model answered no" and "the vendor rate-limited you" is the
    /// caller's to make, not the transport's.
    pub status: u16,
    /// The response body, as text.
    pub body: String,
}

#[async_trait::async_trait]

/// What an extension can ask the host to do.
#[async_trait::async_trait]
pub trait Host: Send + Sync {
    /// Read a file, already resolved and checked against the working directory.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Read`] when the file cannot be read.
    async fn read_file(&self, path: &Path) -> Result<String>;

    /// Fetch a URL as text.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Provider`] when the request fails.
    async fn http_get(&self, url: &str) -> Result<String>;

    /// POST a JSON document and read the reply.
    ///
    /// The first write reach an extension has, and the reason it is here:
    /// `http_get` can read a URL and nothing else, which is enough for a
    /// document and not enough for any hosted API, because they authenticate
    /// with a request header and answer on POST.
    ///
    /// `headers` are the caller's, so the caller chooses the credentials and
    /// the body chooses the rest. The host sets `Content-Type: application/json`
    /// first and lets `headers` override it, because the name promises JSON and
    /// a caller talking to something else should be able to say so.
    ///
    /// # Errors
    ///
    /// [`yk_core::Error::Provider`] when the request fails or a header is one
    /// the HTTP client refuses. A response with a non-2xx status is not an
    /// error here.
    async fn http_post_json(
        &self,
        url: &str,
        headers: &BTreeMap<String, String>,
        body: &str,
    ) -> Result<HttpResponse>;

    /// Read one environment variable by name, or `None` when it is unset.
    ///
    /// `os.getenv` does not exist in this VM, so without this an extension
    /// cannot read a key at all, which puts every hosted API out of reach for a
    /// script that has no filesystem and no process to inherit one from.
    ///
    /// One name at a time rather than the whole table. A script that can dump
    /// the environment in one call is a much better exfiltration story than one
    /// that has to ask for each value it wants.
    fn env(&self, name: &str) -> Option<String>;
}

/// A host that refuses everything, for tests and for running with no network.
///
/// Useful beyond tests: it is what a caller gets if it does not supply one, so
/// forgetting to wire the real host fails closed rather than open.
#[derive(Clone, Copy, Debug, Default)]
pub struct DenyHost;

#[async_trait::async_trait]
impl Host for DenyHost {
    async fn read_file(&self, path: &Path) -> Result<String> {
        Err(yk_core::Error::Tool {
            tool: "host.read_file".to_owned(),
            reason: format!(
                "no host is configured, so `{}` was not read",
                path.display()
            ),
        })
    }

    async fn http_get(&self, url: &str) -> Result<String> {
        Err(yk_core::Error::Tool {
            tool: "host.http_get".to_owned(),
            reason: format!("no host is configured, so `{url}` was not fetched"),
        })
    }

    async fn http_post_json(
        &self,
        url: &str,
        _headers: &BTreeMap<String, String>,
        _body: &str,
    ) -> Result<HttpResponse> {
        Err(yk_core::Error::Tool {
            tool: "host.http_post_json".to_owned(),
            reason: format!("no host is configured, so nothing was posted to `{url}`"),
        })
    }

    fn env(&self, name: &str) -> Option<String> {
        let _ = name;
        None
    }
}

/// Where extensions are loaded from, and whether they may run.
///
/// The two directories are split deliberately. The user's own directory is
/// always loaded because the user put it there. A repository's directory is
/// not, and checking out a repository must never run code.
#[derive(Clone, Debug, Default)]
pub struct ExtensionSources {
    /// `~/.config/yk/lua`, always loaded.
    pub user: Option<PathBuf>,
    /// `<repo>/.yk/lua`, loaded only when `trust_repo` is set.
    pub repo: Option<PathBuf>,
    /// Whether the repository's scripts may run this session.
    pub trust_repo: bool,
}

impl ExtensionSources {
    /// The directories that will actually be read, in load order.
    ///
    /// User first so a user's own script can be overridden by a deliberate
    /// project-local one, rather than the other way round.
    #[must_use]
    pub fn active(&self) -> Vec<PathBuf> {
        let mut dirs: Vec<PathBuf> = self.user.iter().cloned().collect();
        if self.trust_repo
            && let Some(repo) = &self.repo
        {
            dirs.push(repo.clone());
        }
        dirs
    }

    /// The directories that were skipped, and why, for the startup message.
    #[must_use]
    pub fn skipped(&self) -> Vec<PathBuf> {
        if self.trust_repo {
            Vec::new()
        } else {
            self.repo.iter().cloned().collect()
        }
    }
}

/// The conventional user directory for extensions.
#[must_use]
pub fn user_dir() -> PathBuf {
    let base = std::env::var_os("XDG_CONFIG_HOME").map_or_else(
        || {
            std::env::var_os("HOME")
                .map_or_else(|| PathBuf::from("."), PathBuf::from)
                .join(".config")
        },
        PathBuf::from,
    );

    base.join("yk").join("lua")
}

/// Where extensions the model wrote live, inside a project.
///
/// Session-scoped: loaded for the current run, never promoted
/// without `yk promote`.
#[must_use]
pub fn session_dir(project_root: &Path) -> PathBuf {
    project_root.join(".yk").join("extensions")
}

/// The default `extension_sources` for a run in `project_root`.
///
/// # Errors
///
/// None today. It returns a value because a future trust check has somewhere to
/// report from.
#[must_use]
pub fn extension_sources(project_root: &Path, trust_repo: bool) -> ExtensionSources {
    ExtensionSources {
        user: Some(user_dir()),
        repo: Some(project_root.join(".yk").join("lua")),
        trust_repo,
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::indexing_slicing,
        clippy::as_conversions,
        clippy::arithmetic_side_effects
    )]

    use std::collections::BTreeMap;
    use std::path::{Path, PathBuf};

    use yk_core::Result;

    use super::{DenyHost, Host, HttpResponse, extension_sources, session_dir, user_dir};

    #[tokio::test]
    async fn a_denying_host_refuses_rather_than_pretending() {
        let host = DenyHost;
        let error = host
            .read_file(Path::new("a.txt"))
            .await
            .expect_err("must fail");
        assert!(
            error.to_string().contains("no host is configured"),
            "{error}"
        );

        let error = host
            .http_get("https://example.com")
            .await
            .expect_err("must fail");
        assert!(error.to_string().contains("no host"), "{error}");

        let error = host
            .http_post_json("https://example.com", &BTreeMap::new(), "{}")
            .await
            .expect_err("must fail");
        assert!(error.to_string().contains("nothing was posted"), "{error}");
    }

    #[test]
    fn a_denying_host_reports_no_environment_rather_than_an_empty_one() {
        // `None` and `Some("")` are different answers, and a caller that cannot
        // tell them apart treats "no key configured" as "the key is empty".
        assert_eq!(DenyHost.env("PATH"), None);
    }

    #[test]
    fn the_user_directory_is_always_active() {
        let found = extension_sources(Path::new("/project"), false);
        assert!(found.active().contains(&user_dir()));
    }

    #[test]
    fn a_repository_is_not_loaded_without_trust() {
        // The regression this whole split exists for: `git clone` must not run code.
        let found = extension_sources(Path::new("/project"), false);

        assert!(
            !found.active().iter().any(|dir| dir.starts_with("/project")),
            "project scripts loaded without trust: {:?}",
            found.active()
        );
        assert_eq!(found.skipped().len(), 1);
    }

    #[test]
    fn a_trusted_repository_is_loaded() {
        let found = extension_sources(Path::new("/project"), true);

        assert_eq!(found.active().len(), 2);
        assert!(found.skipped().is_empty());
    }

    #[test]
    fn the_user_directory_loads_before_the_project_one() {
        // So a project can deliberately override a user-wide script.
        let found = extension_sources(Path::new("/project"), true);
        let active = found.active();

        assert_eq!(active.first(), Some(&user_dir()));
    }

    #[test]
    fn model_written_extensions_live_under_dot_yk_extensions() {
        let dir = session_dir(Path::new("/project"));
        assert_eq!(dir, PathBuf::from("/project/.yk/extensions"));
    }

    #[test]
    fn a_trusted_repository_still_reports_nothing_skipped() {
        let found = extension_sources(Path::new("/project"), true);
        assert!(found.skipped().is_empty());
    }

    // A host that answers, to prove the trait is implementable from outside.
    struct Fixed(String);

    #[async_trait::async_trait]
    impl Host for Fixed {
        async fn read_file(&self, _path: &Path) -> Result<String> {
            Ok(self.0.clone())
        }

        async fn http_get(&self, _url: &str) -> Result<String> {
            Ok(self.0.clone())
        }

        async fn http_post_json(
            &self,
            _url: &str,
            headers: &BTreeMap<String, String>,
            body: &str,
        ) -> Result<HttpResponse> {
            // Header count in the hundreds and body length in the units, so a
            // test can tell "the headers did not arrive" from "the body did
            // not arrive" rather than seeing one number either way.
            let encoded = headers.len().saturating_mul(100).saturating_add(body.len());
            Ok(HttpResponse {
                status: 200,
                body: encoded.to_string(),
            })
        }

        fn env(&self, name: &str) -> Option<String> {
            (name == "SET").then(|| "value".to_owned())
        }
    }

    #[tokio::test]
    async fn a_host_can_be_implemented_outside_this_crate() {
        let host = Fixed("content".to_owned());
        assert_eq!(
            host.read_file(Path::new("a")).await.expect("reads"),
            "content"
        );
        assert_eq!(host.http_get("x").await.expect("fetches"), "content");

        let mut headers = BTreeMap::new();
        headers.insert("Authorization".to_owned(), "Bearer k".to_owned());
        let reply = host
            .http_post_json("x", &headers, "{}")
            .await
            .expect("posts");
        assert_eq!(reply.status, 200);
        // One header plus a two byte body, which is the only thing the fake
        // reports and enough to show both arguments arrive.
        assert_eq!(reply.body, "102");

        assert_eq!(host.env("SET").as_deref(), Some("value"));
        assert_eq!(host.env("UNSET"), None);
    }
}