marona 2.0.0

Universal Model Gateway and MCP/Skill SDK with mandatory project-scoped Marona authentication
Documentation
use std::{collections::HashSet, sync::Arc};

use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};

use crate::{core::Core, Error, Result};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StepType {
    Reasoning,
    Approval,
    App,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Step {
    pub id: String,
    #[serde(rename = "type")]
    pub step_type: StepType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instruction: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capability: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub condition: Option<Value>,
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub inputs: Map<String, Value>,
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub outputs: Map<String, Value>,
}

impl Step {
    pub fn reasoning(id: impl Into<String>, instruction: impl Into<String>) -> Self {
        Self::base(id, StepType::Reasoning).instruction(instruction)
    }
    pub fn approval(id: impl Into<String>, message: impl Into<String>) -> Self {
        let mut value = Self::base(id, StepType::Approval);
        value.message = Some(message.into());
        value
    }
    pub fn app(
        id: impl Into<String>,
        app: impl Into<String>,
        capability: impl Into<String>,
        instruction: impl Into<String>,
    ) -> Self {
        let mut value = Self::base(id, StepType::App);
        value.app = Some(app.into());
        value.capability = Some(capability.into());
        value.instruction = Some(instruction.into());
        value
    }
    fn base(id: impl Into<String>, step_type: StepType) -> Self {
        Self {
            id: id.into(),
            step_type,
            instruction: None,
            message: None,
            app: None,
            capability: None,
            condition: None,
            inputs: Map::new(),
            outputs: Map::new(),
        }
    }
    pub fn instruction(mut self, value: impl Into<String>) -> Self {
        self.instruction = Some(value.into());
        self
    }
    pub fn input(mut self, name: impl Into<String>, value: Value) -> Self {
        self.inputs.insert(name.into(), value);
        self
    }
    pub fn output(mut self, name: impl Into<String>, output_type: impl Into<String>) -> Self {
        self.outputs
            .insert(name.into(), Value::String(output_type.into()));
        self
    }
    pub fn condition(mut self, value: Value) -> Self {
        self.condition = Some(value);
        self
    }
}

pub fn step(value: Step) -> Step {
    value
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillDefinition {
    pub name: String,
    pub description: String,
    pub visibility: String,
    #[serde(default)]
    pub governs: Vec<String>,
    #[serde(default)]
    pub steps: Vec<Step>,
}

impl SkillDefinition {
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            visibility: "private".into(),
            governs: vec![],
            steps: vec![],
        }
    }
    pub fn visibility(mut self, value: impl Into<String>) -> Self {
        self.visibility = value.into();
        self
    }
    pub fn governs(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.governs = values.into_iter().map(Into::into).collect();
        self
    }
    pub fn step(mut self, value: Step) -> Self {
        self.steps.push(value);
        self
    }
    pub fn manifest(&self, version: &str) -> Result<Value> {
        validate_slug(&self.name, "Skill name")?;
        if self.description.trim().is_empty() {
            return Err(Error::Validation("Skill description is required".into()));
        }
        if !matches!(self.visibility.as_str(), "public" | "private") {
            return Err(Error::Validation(
                "visibility must be public or private".into(),
            ));
        }
        if version.split('.').count() < 3 {
            return Err(Error::Validation(
                "version must use semantic versioning".into(),
            ));
        }
        if self.steps.is_empty() {
            return Err(Error::Validation("a Skill needs at least one step".into()));
        }
        let mut ids = HashSet::new();
        for item in &self.steps {
            validate_slug(&item.id, "Step id")?;
            if !ids.insert(&item.id) {
                return Err(Error::Validation(format!(
                    "duplicate Skill step '{}'",
                    item.id
                )));
            }
            if matches!(item.step_type, StepType::App) {
                let app = item.app.as_deref().unwrap_or("");
                let capability = item.capability.as_deref().unwrap_or("");
                if !capability.starts_with(&format!("{app}.")) {
                    return Err(Error::Validation(format!(
                        "capability '{capability}' does not belong to App '{app}'"
                    )));
                }
            }
        }
        Ok(
            json!({"schema_version":"1.0","name":self.name,"description":self.description,"visibility":self.visibility,"version":version,"governs":self.governs,"steps":self.steps}),
        )
    }
}

#[derive(Clone, Debug)]
pub struct Skills {
    pub(crate) core: Arc<Core>,
}

impl Skills {
    pub async fn publish(&self, definition: &SkillDefinition, version: &str) -> Result<Value> {
        let manifest = definition.manifest(version)?;
        self.core
            .json(
                &self.core.hub_url,
                Method::POST,
                "/hub/skills/publish",
                Some(&json!({"manifest":manifest})),
            )
            .await
    }
}

fn validate_slug(value: &str, label: &str) -> Result<()> {
    let valid = !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
        && !value.starts_with('-')
        && !value.ends_with('-');
    if valid {
        Ok(())
    } else {
        Err(Error::Validation(format!(
            "{label} must use lowercase kebab-case"
        )))
    }
}