garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /records/src/verbs.rs

raw

//! What a service can be asked, and asking it: `describe` and `call`
//! (`docs/terminal-and-agent.md`, `docs/agent-environment.md`).
//!
//! A service that speaks this answers [`DESCRIBE`] with its [`Description`]:
//! its verbs, their parameters' types, and for each the [`Effect`] it has
//! and the verb that undoes it. The terminal completes and checks a command
//! with it before sending; the agent's tool schema is the same answer, so
//! nothing is written twice. A [`CALL`] names a verb and its arguments and
//! is answered with a [`Result`] that carries, for a verb that can be
//! undone, the concrete call that undoes this one.
//!
//! On the service's channel, beside whatever else it speaks: the message's
//! first byte is its kind ([`DESCRIBE`], [`CALL`], [`DESCRIPTION`],
//! [`RESULT`]), the second whether more of it follows (1) or this is its
//! last piece (0), then JSON text: a long one travels in pieces of a
//! message each, which [`Pieces`] puts back together. Handles a call needs
//! (a file the person picked) travel on its last piece.

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_json::Value;

/// Client → service: what can you do? (No body.)
pub const DESCRIBE: u8 = 0xD0;
/// Client → service: `{"verb": …, "args": {…}}`.
pub const CALL: u8 = 0xD1;
/// Service → client: a [`Description`].
pub const DESCRIPTION: u8 = 0xD8;
/// Service → client: a [`Result`].
pub const RESULT: u8 = 0xD9;

/// What a verb does to the world, from least to most: what decides whether
/// the person is asked before an agent may use it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Effect {
    /// Changes nothing.
    Reads,
    /// Changes the service's own data, which only the person sees.
    Own,
    /// Changes something others see or other apps read.
    Shared,
    /// Sends something out of the device.
    Out,
    /// Cannot be undone (a payment, a deletion past the log).
    Final,
}

impl Effect {
    pub const ALL: [Effect; 5] = [
        Effect::Reads,
        Effect::Own,
        Effect::Shared,
        Effect::Out,
        Effect::Final,
    ];

    /// The name in a description and a manifest.
    pub fn name(self) -> &'static str {
        match self {
            Effect::Reads => "reads",
            Effect::Own => "own",
            Effect::Shared => "shared",
            Effect::Out => "out",
            Effect::Final => "final",
        }
    }

    pub fn from_name(name: &str) -> Option<Effect> {
        Effect::ALL.into_iter().find(|e| e.name() == name)
    }

    /// What the person reads about it (the Store, a confirmation).
    pub fn describe(self) -> &'static str {
        match self {
            Effect::Reads => "Only reads",
            Effect::Own => "Changes its own data",
            Effect::Shared => "Changes what others see",
            Effect::Out => "Sends out of the device",
            Effect::Final => "Does what cannot be undone",
        }
    }

    /// How often an agent must ask the person before it may use a verb of
    /// this effect.
    pub fn confirm(self) -> Confirm {
        match self {
            Effect::Reads | Effect::Own => Confirm::Never,
            Effect::Shared => Confirm::OncePerTask,
            Effect::Out | Effect::Final => Confirm::EachTime,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Confirm {
    Never,
    OncePerTask,
    EachTime,
}

/// A parameter's type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Type {
    Text,
    /// A whole number.
    Number,
    Bool,
    /// A contact, by name.
    Contact,
}

impl Type {
    pub fn name(self) -> &'static str {
        match self {
            Type::Text => "text",
            Type::Number => "number",
            Type::Bool => "bool",
            Type::Contact => "contact",
        }
    }

    pub fn from_name(name: &str) -> Option<Type> {
        [Type::Text, Type::Number, Type::Bool, Type::Contact]
            .into_iter()
            .find(|t| t.name() == name)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Param {
    pub name: String,
    pub kind: Type,
    pub required: bool,
    pub about: String,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Verb {
    pub name: String,
    pub about: String,
    pub params: Vec<Param>,
    pub effect: Effect,
    /// The verb that undoes this one; a [`Result`] carries the call. None
    /// for a verb that changes nothing, or cannot be undone.
    pub inverse: Option<String>,
    /// What it answers comes from outside the person's trust: the network,
    /// someone who is not a contact. A task that read it may not send out
    /// without asking (the taint rule).
    pub untrusted: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Description {
    pub service: String,
    pub about: String,
    pub verbs: Vec<Verb>,
}

impl Verb {
    /// A verb's [`Value`] in a description.
    pub fn to_json(&self) -> Value {
        let params = self
            .params
            .iter()
            .map(|p| {
                Value::object([
                    ("name", p.name.as_str().into()),
                    ("type", p.kind.name().into()),
                    ("required", p.required.into()),
                    ("about", p.about.as_str().into()),
                ])
            })
            .collect::<Vec<_>>();
        let mut v = Value::object([
            ("name", self.name.as_str().into()),
            ("about", self.about.as_str().into()),
            ("params", Value::Array(params)),
            ("effect", self.effect.name().into()),
        ]);
        if let Some(inverse) = &self.inverse {
            v.set("inverse", inverse.as_str().into());
        }
        if self.untrusted {
            v.set("untrusted", true.into());
        }
        v
    }

    pub fn from_json(v: &Value) -> Option<Verb> {
        let mut params = Vec::new();
        for p in v.get("params").as_array()? {
            params.push(Param {
                name: p.get("name").as_str()?.into(),
                kind: Type::from_name(p.get("type").as_str()?)?,
                required: p.get("required").as_bool().unwrap_or(false),
                about: p.get("about").as_str().unwrap_or("").into(),
            });
        }
        Some(Verb {
            name: v.get("name").as_str()?.into(),
            about: v.get("about").as_str().unwrap_or("").into(),
            params,
            effect: Effect::from_name(v.get("effect").as_str()?)?,
            inverse: v.get("inverse").as_str().map(String::from),
            untrusted: v.get("untrusted").as_bool().unwrap_or(false),
        })
    }

    /// Its parameters as a JSON Schema object, as a model's API takes a
    /// tool's input.
    pub fn input_schema(&self) -> Value {
        let properties = self
            .params
            .iter()
            .map(|p| {
                let kind = match p.kind {
                    Type::Text | Type::Contact => "string",
                    Type::Number => "integer",
                    Type::Bool => "boolean",
                };
                (
                    p.name.clone(),
                    Value::object([("type", kind.into()), ("description", p.about.as_str().into())]),
                )
            })
            .collect::<Vec<_>>();
        let required = self
            .params
            .iter()
            .filter(|p| p.required)
            .map(|p| Value::from(p.name.as_str()))
            .collect::<Vec<_>>();
        Value::object([
            ("type", "object".into()),
            ("properties", Value::Object(properties)),
            ("required", Value::Array(required)),
            ("additionalProperties", false.into()),
        ])
    }

    /// Whether `args` (an object) are this verb's: every required one
    /// there, none it does not take, each of its type. The reason if not.
    pub fn check(&self, args: &Value) -> core::result::Result<(), String> {
        let Some(fields) = args.as_object() else {
            return Err("the arguments are not an object".into());
        };
        for (name, value) in fields {
            let Some(p) = self.params.iter().find(|p| &p.name == name) else {
                return Err(alloc::format!("{} takes no “{name}”", self.name));
            };
            let fits = match p.kind {
                Type::Text | Type::Contact => value.as_str().is_some(),
                Type::Number => value.as_i64().is_some(),
                Type::Bool => value.as_bool().is_some(),
            };
            if !fits {
                return Err(alloc::format!("{name} must be {}", p.kind.name()));
            }
        }
        match self
            .params
            .iter()
            .find(|p| p.required && args.get(&p.name).is_null())
        {
            Some(p) => Err(alloc::format!("{} needs {}", self.name, p.name)),
            None => Ok(()),
        }
    }
}

impl Description {
    pub fn to_json(&self) -> Value {
        Value::object([
            ("service", self.service.as_str().into()),
            ("about", self.about.as_str().into()),
            (
                "verbs",
                Value::Array(self.verbs.iter().map(Verb::to_json).collect()),
            ),
        ])
    }

    pub fn from_json(v: &Value) -> Option<Description> {
        let verbs = v
            .get("verbs")
            .as_array()?
            .iter()
            .map(Verb::from_json)
            .collect::<Option<Vec<_>>>()?;
        Some(Description {
            service: v.get("service").as_str()?.into(),
            about: v.get("about").as_str().unwrap_or("").into(),
            verbs,
        })
    }

    pub fn verb(&self, name: &str) -> Option<&Verb> {
        self.verbs.iter().find(|v| v.name == name)
    }

    /// The most a verb of it does: what a package's manifest says beside
    /// its other rights.
    pub fn most(&self) -> Effect {
        self.verbs.iter().map(|v| v.effect).max().unwrap_or(Effect::Reads)
    }
}

/// What a call came to.
#[derive(Clone, Debug, PartialEq)]
pub struct Result {
    pub ok: bool,
    /// What it answers: text, or any JSON.
    pub value: Value,
    /// The call that undoes this one, `{"verb": …, "args": {…}}`, for a
    /// verb that has an inverse.
    pub undo: Option<Value>,
}

impl Result {
    pub fn ok(value: Value) -> Result {
        Result {
            ok: true,
            value,
            undo: None,
        }
    }

    pub fn error(why: &str) -> Result {
        Result {
            ok: false,
            value: why.into(),
            undo: None,
        }
    }

    /// With the call that undoes it.
    pub fn undone_by(mut self, verb: &str, args: Value) -> Result {
        self.undo = Some(call(verb, args));
        self
    }

    pub fn to_json(&self) -> Value {
        let mut v = Value::object([("ok", self.ok.into()), ("value", self.value.clone())]);
        if let Some(undo) = &self.undo {
            v.set("undo", undo.clone());
        }
        v
    }

    pub fn from_json(v: &Value) -> Option<Result> {
        Some(Result {
            ok: v.get("ok").as_bool()?,
            value: v.get("value").clone(),
            undo: (!v.get("undo").is_null()).then(|| v.get("undo").clone()),
        })
    }

    /// The value as text: a string as it is, anything else as JSON.
    pub fn text(&self) -> String {
        match &self.value {
            Value::String(s) => s.clone(),
            v => alloc::format!("{v}"),
        }
    }
}

/// A call's body.
pub fn call(verb: &str, args: Value) -> Value {
    Value::object([("verb", verb.into()), ("args", args)])
}

/// A message of `kind` with `json` as its body, in pieces that each fit a
/// message: every piece but the last says more follows.
pub fn pieces(kind: u8, json: &str) -> Vec<Vec<u8>> {
    let room = crate::MAX - 2;
    let mut out = Vec::new();
    let mut rest = json;
    loop {
        let mut end = rest.len().min(room);
        while !rest.is_char_boundary(end) {
            end -= 1;
        }
        let more = end < rest.len();
        let mut m = Vec::with_capacity(2 + end);
        m.push(kind);
        m.push(u8::from(more));
        m.extend_from_slice(&rest.as_bytes()[..end]);
        out.push(m);
        rest = &rest[end..];
        if !more {
            return out;
        }
    }
}

/// Puts pieces back together, as they arrive on a channel: of any kind
/// from 0xD0 to 0xEF, which this protocol and the model service's share.
#[derive(Default)]
pub struct Pieces {
    kind: u8,
    text: Vec<u8>,
}

/// The longest message put back together.
pub const MAX_WHOLE: usize = 1 << 20;

impl Pieces {
    /// Takes a message; a whole one's kind and JSON once its last piece came.
    /// None for a piece of something longer, a message of another protocol
    /// (its first byte not one of these), or one too long.
    pub fn push(&mut self, message: &[u8]) -> Option<(u8, Value)> {
        let (&kind, rest) = message.split_first()?;
        if !(0xD0..=0xEF).contains(&kind) {
            return None;
        }
        let (&more, body) = rest.split_first().unwrap_or((&0, &[]));
        if kind != self.kind {
            self.text.clear();
            self.kind = kind;
        }
        if self.text.len() + body.len() > MAX_WHOLE {
            self.text.clear();
            return None;
        }
        self.text.extend_from_slice(body);
        if more != 0 {
            return None;
        }
        let text = core::mem::take(&mut self.text);
        if kind == DESCRIBE {
            return Some((kind, Value::Null));
        }
        let value = core::str::from_utf8(&text)
            .ok()
            .and_then(|t| pinnacle_json::parse(t).ok())?;
        Some((kind, value))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    fn send_verb() -> Verb {
        Verb {
            name: "send".into(),
            about: "Send a text to a contact".into(),
            params: vec![
                Param {
                    name: "to".into(),
                    kind: Type::Contact,
                    required: true,
                    about: "who".into(),
                },
                Param {
                    name: "urgent".into(),
                    kind: Type::Bool,
                    required: false,
                    about: String::new(),
                },
            ],
            effect: Effect::Out,
            inverse: None,
            untrusted: false,
        }
    }

    #[test]
    fn a_description_round_trips() {
        let d = Description {
            service: "p2p".into(),
            about: "messages".into(),
            verbs: vec![
                send_verb(),
                Verb {
                    name: "keep".into(),
                    about: String::new(),
                    params: vec![],
                    effect: Effect::Own,
                    inverse: Some("forget".into()),
                    untrusted: true,
                },
            ],
        };
        let text = alloc::format!("{}", d.to_json());
        let back = Description::from_json(&pinnacle_json::parse(&text).unwrap()).unwrap();
        assert_eq!(back, d);
        assert_eq!(d.most(), Effect::Out);
    }

    #[test]
    fn arguments_are_checked() {
        let v = send_verb();
        let args = |t: &str| pinnacle_json::parse(t).unwrap();
        assert_eq!(v.check(&args(r#"{"to":"Anna"}"#)), Ok(()));
        assert_eq!(v.check(&args(r#"{"to":"Anna","urgent":true}"#)), Ok(()));
        assert!(v.check(&args(r#"{}"#)).unwrap_err().contains("needs to"));
        assert!(
            v.check(&args(r#"{"to":1}"#))
                .unwrap_err()
                .contains("must be contact")
        );
        assert!(
            v.check(&args(r#"{"to":"A","bcc":"x"}"#))
                .unwrap_err()
                .contains("no “bcc”")
        );
        assert!(v.check(&args("[]")).is_err());
        let schema = alloc::format!("{}", v.input_schema());
        assert_eq!(
            schema,
            r#"{"type":"object","properties":{"to":{"type":"string","description":"who"},"urgent":{"type":"boolean","description":""}},"required":["to"],"additionalProperties":false}"#
        );
    }

    #[test]
    fn effects_decide_what_is_asked() {
        assert_eq!(Effect::Reads.confirm(), Confirm::Never);
        assert_eq!(Effect::Own.confirm(), Confirm::Never);
        assert_eq!(Effect::Shared.confirm(), Confirm::OncePerTask);
        assert_eq!(Effect::Out.confirm(), Confirm::EachTime);
        assert_eq!(Effect::Final.confirm(), Confirm::EachTime);
        for e in Effect::ALL {
            assert_eq!(Effect::from_name(e.name()), Some(e));
        }
    }

    #[test]
    fn long_messages_travel_in_pieces() {
        let long = alloc::format!("\"{}\"", "é".repeat(5000));
        let messages = pieces(RESULT, &long);
        assert_eq!(messages.len(), 3);
        assert!(messages.iter().all(|m| m.len() <= crate::MAX));
        let mut p = Pieces::default();
        assert_eq!(p.push(&messages[0]), None);
        assert_eq!(p.push(&messages[1]), None);
        let (kind, value) = p.push(&messages[2]).unwrap();
        assert_eq!(kind, RESULT);
        assert_eq!(value.as_str().unwrap().chars().count(), 5000);
        assert_eq!(p.push(&[DESCRIBE, 0]), Some((DESCRIBE, Value::Null)));
        assert_eq!(p.push(&[1, 2, 3]), None);
    }

    #[test]
    fn a_result_carries_its_undo() {
        let r = Result::ok("kept".into()).undone_by("forget", Value::object([("id", Value::from(3u64))]));
        let back = Result::from_json(&pinnacle_json::parse(&alloc::format!("{}", r.to_json())).unwrap());
        assert_eq!(back, Some(r));
    }
}