garage44.eu/jeroen/pinnacle

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

.. /ui/src/model.rs

raw

//! The `model` service (`docs/agent-environment.md`): the one program with
//! the network that talks to a model, the host the person chose in
//! Settings → Agent, and its protocol. Everything above it speaks one
//! conversation format whoever answers; the service speaks the provider's.
//!
//! On a channel to [`SERVICE`], in `records::verbs` pieces (JSON):
//!
//! - [`ASK`], client → service: `{"system", "messages", "tools",
//!   "max_tokens"}`. A message is `{"role": "user"|"assistant", "content"}`,
//!   its content text or blocks: `{"type": "text", "text"}`,
//!   `{"type": "tool_use", "id", "name", "input"}`, `{"type": "tool_result",
//!   "tool_use_id", "content", "is_error"}`. A tool is `{"name",
//!   "description", "input_schema"}`.
//! - Back, as the answer arrives: [`TEXT`] `{"text"}` a piece of its text;
//!   [`CALL`] `{"id", "name", "input"}` a whole tool call; then [`DONE`]
//!   `{"stop", "input_tokens", "output_tokens"}`, or [`ERROR`] `{"error"}`.
//!
//! Closing the channel stops the answer.

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_json::Value;
use pinnacle_records::verbs::Pieces;
use pinnacle_rt::{Channel, Received, fs};

/// The service, `system-…` so no installed app reaches it.
pub const SERVICE: &str = "system-model";

pub const ASK: u8 = 0xE0;
pub const TEXT: u8 = 0xE8;
pub const CALL: u8 = 0xE9;
pub const DONE: u8 = 0xEA;
pub const ERROR: u8 = 0xEB;

/// Where the host, the model and the switch are kept: `key=value` lines,
/// beside the device's other settings, which apps cannot reach.
pub const SETTINGS: &str = "system:/settings/agent";
/// The key, in the data vault only: no vault, no key, no agent.
pub const KEY: &str = "data:/agent/key";
/// A provider's API, the first host the study names.
pub const DEFAULT_HOST: &str = "https://api.anthropic.com";
pub const DEFAULT_MODEL: &str = "claude-sonnet-5";

/// What Settings → Agent says.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
    /// The host's base URL, `https://…` (or `http://` for one on this
    /// network, as the self-check's stand-in).
    pub host: String,
    pub model: String,
    /// Off until the person turns it on: off, nothing is sent anywhere.
    pub on: bool,
}

impl Config {
    pub fn read() -> Config {
        let text = fs::read_string(SETTINGS).unwrap_or_default();
        let field = |key: &str, default: &str| String::from(fs::field(&text, key).map_or(default, str::trim));
        Config {
            host: field("host", DEFAULT_HOST),
            model: field("model", DEFAULT_MODEL),
            on: fs::field(&text, "on").is_some_and(|v| v.trim() == "yes"),
        }
    }

    pub fn write(&self) -> bool {
        fs::create_dir("system:/settings");
        let on = if self.on { "yes" } else { "no" };
        let text = alloc::format!("host={}\nmodel={}\non={on}\n", self.host, self.model);
        fs::write(SETTINGS, text.as_bytes())
    }
}

/// The key, when the vault is open and one was given.
pub fn key() -> Option<String> {
    let key = fs::read_string(KEY)?;
    let key = String::from(key.trim());
    (!key.is_empty()).then_some(key)
}

/// Keeps the key in the vault; false without one.
pub fn set_key(key: &str) -> bool {
    if fs::disk("data").is_none() {
        return false;
    }
    fs::create_dir("data:/agent");
    fs::write(KEY, key.trim().as_bytes())
}

/// The log of every prompt sent, append-only (`records::log`): in the
/// vault, or beside the settings on a system without one.
pub fn sent_log() -> &'static str {
    if fs::disk("data").is_some() {
        "data:/agent/sent"
    } else {
        "system:/agent/sent"
    }
}

/// What was sent, oldest first: each `{"time", "host", "model", "bytes",
/// "request"}`.
pub fn sent() -> Vec<Value> {
    let data = fs::File::open(sent_log(), fs::READ)
        .and_then(|f| f.read())
        .unwrap_or_default();
    pinnacle_records::log::entries(&data)
        .unwrap_or_default()
        .into_iter()
        .filter_map(|e| pinnacle_json::parse(core::str::from_utf8(e).ok()?).ok())
        .collect()
}

/// One thing the service sends back.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    Text(String),
    Call {
        id: String,
        name: String,
        input: Value,
    },
    Done {
        stop: String,
        input_tokens: u64,
        output_tokens: u64,
    },
    Error(String),
}

/// The service, if it runs.
pub fn connect() -> Option<Channel> {
    pinnacle_rt::connect(SERVICE)
}

/// Asks the model through `channel` and hands each event to `event` as it
/// comes, until [`Event::Done`] or [`Event::Error`] (which it returns);
/// `event` returning false stops it. `timeout`: the longest silence.
pub fn ask(channel: &Channel, request: &Value, timeout: u64, mut event: impl FnMut(&Event) -> bool) -> Event {
    if !crate::verbs::send(channel, ASK, &alloc::format!("{request}"), Vec::new()) {
        return Event::Error("the model service is gone".into());
    }
    let mut pieces = Pieces::default();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    loop {
        let until = pinnacle_rt::time() + timeout;
        let (kind, v) = match pinnacle_rt::receive(&[channel], &mut buffer, Some(until)) {
            Received::Message { len, .. } => match pieces.push(&buffer[..len]) {
                Some(whole) => whole,
                None => continue,
            },
            Received::Closed { .. } => return Event::Error("the model service went".into()),
            Received::Timeout => return Event::Error("the model did not answer in time".into()),
        };
        let e = match kind {
            TEXT => Event::Text(v.get("text").as_str().unwrap_or("").into()),
            CALL => Event::Call {
                id: v.get("id").as_str().unwrap_or("").into(),
                name: v.get("name").as_str().unwrap_or("").into(),
                input: v.get("input").clone(),
            },
            DONE => Event::Done {
                stop: v.get("stop").as_str().unwrap_or("").into(),
                input_tokens: v.get("input_tokens").as_u64().unwrap_or(0),
                output_tokens: v.get("output_tokens").as_u64().unwrap_or(0),
            },
            ERROR => Event::Error(v.get("error").as_str().unwrap_or("").into()),
            _ => continue,
        };
        let last = matches!(e, Event::Done { .. } | Event::Error(_));
        if last {
            return e;
        }
        if !event(&e) {
            return Event::Error("stopped".into());
        }
    }
}