ferrik-core 0.0.4

Core runtime, triple-response engine, AI discovery, and testing framework for Ferrik
Documentation
//! Global AI Discovery Protocol (`/.well-known/ferrik-agent.json` and HTTP `Link` headers).

use axum::routing::get;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};

use crate::response::ActionAffordance;

/// Supported Ferrik AI Discovery protocol version.
pub const FERRIK_PROTOCOL_VERSION: &str = "1.0";

/// Well-known manifest path served by every Ferrik application.
pub const AGENT_MANIFEST_PATH: &str = "/.well-known/ferrik-agent.json";

/// Describes a discoverable `.ai` resource endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentEndpoint {
    pub name: String,
    pub path: String,
    pub method: String,
    pub description: String,
}

impl AgentEndpoint {
    pub fn new(
        name: impl Into<String>,
        method: impl Into<String>,
        path: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            method: method.into(),
            path: path.into(),
            description: description.into(),
        }
    }
}

/// JSON payload returned by `GET /.well-known/ferrik-agent.json`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentManifest {
    pub app_name: String,
    pub version: String,
    pub ferrik_protocol: String,
    pub ai_entrypoint: String,
    pub auth_schemes: Vec<String>,
    pub endpoints: Vec<AgentEndpoint>,
    pub actions: Vec<ActionAffordance>,
}

impl AgentManifest {
    /// Creates a new manifest with sensible defaults for a Ferrik application.
    pub fn new(app_name: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            app_name: app_name.into(),
            version: version.into(),
            ferrik_protocol: FERRIK_PROTOCOL_VERSION.to_string(),
            ai_entrypoint: "/ai".to_string(),
            auth_schemes: vec!["none".to_string()],
            endpoints: vec![
                AgentEndpoint::new("home", "GET", "/ai", "Application overview and AI entry point"),
                AgentEndpoint::new(
                    "health",
                    "GET",
                    "/index.json",
                    "JSON status and database connectivity check",
                ),
            ],
            actions: Vec::new(),
        }
    }

    pub fn with_endpoint(mut self, endpoint: AgentEndpoint) -> Self {
        self.endpoints.push(endpoint);
        self
    }

    pub fn with_action(mut self, action: ActionAffordance) -> Self {
        self.actions.push(action);
        self
    }

    pub fn with_auth_schemes(mut self, schemes: Vec<String>) -> Self {
        self.auth_schemes = schemes;
        self
    }
}

/// Builds the HTTP `Link` header value advertising the agent manifest and `.ai` alternate URL.
pub fn discovery_link_header(ai_alternate: &str) -> String {
    format!(
        "<{}>; rel=\"agent-manifest\", <{}>; rel=\"alternate\"; type=\"text/markdown\"",
        AGENT_MANIFEST_PATH, ai_alternate
    )
}

/// Returns an Axum router that serves `GET /.well-known/ferrik-agent.json`.
pub fn discovery_router<S>(manifest: AgentManifest) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    Router::new().route(
        AGENT_MANIFEST_PATH,
        get(move || {
            let manifest = manifest.clone();
            async move { Json(manifest) }
        }),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    #[test]
    fn builds_discovery_link_header() {
        let header = discovery_link_header("/posts.ai");
        assert_eq!(
            header,
            "</.well-known/ferrik-agent.json>; rel=\"agent-manifest\", </posts.ai>; rel=\"alternate\"; type=\"text/markdown\""
        );
    }

    #[tokio::test]
    async fn serves_well_known_agent_manifest() {
        let manifest = AgentManifest::new("hello_ferrik", "0.1.0")
            .with_auth_schemes(vec!["bearer".to_string()])
            .with_endpoint(AgentEndpoint::new("posts", "GET", "/posts.ai", "List posts"))
            .with_action(ActionAffordance::new(
                "create_post",
                "POST",
                "/posts",
                "Create a new post",
            ));

        let app: Router = discovery_router(manifest.clone());
        let resp = app
            .oneshot(
                Request::builder()
                    .uri(AGENT_MANIFEST_PATH)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let parsed: AgentManifest = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed.ferrik_protocol, "1.0");
        assert_eq!(parsed.app_name, "hello_ferrik");
        assert_eq!(parsed.endpoints.len(), 3);
        assert_eq!(parsed.actions.len(), 1);
    }
}