garage44.eu/jeroen/pinnacle

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

.. /programs/src/bin/model.rs

raw

//! The `model` service (`docs/agent-environment.md`): owns the one
//! connection to the model the person chose in Settings → Agent, and is
//! the only part of the agent with the network. It takes a conversation in
//! one format (`pinnacle_ui::model`), sends it to the provider in the
//! provider's (Anthropic's Messages API, streamed, first), and sends back
//! the answer's text and tool calls as they arrive. It writes every prompt
//! it sends to an append-only log in the vault, which Settings shows; with
//! the agent off, or no key, it sends nothing.
//!
//! Started with [`arg::MODEL_STANDIN`], as the self-check does, it talks to
//! the stand-in provider beside the package source with the stand-in's
//! key, whatever the settings say, and ends when its last client goes.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_json::Value;
use pinnacle_records::verbs::Pieces;
use pinnacle_rt::abi::arg;
use pinnacle_rt::{Channel, Received, fs, println};
use pinnacle_ui::model::{self, CALL, Config, DONE, ERROR, TEXT};

/// The longest a provider may be silent.
const TIMEOUT: u64 = 120_000;
/// The longest answer asked for when the client names none.
const MAX_TOKENS: u64 = 4096;
/// The stand-in's key (xtask's `model.rs`).
const STANDIN_KEY: &str = "test-key";

#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
    let standin = argument == arg::MODEL_STANDIN;
    let Some(service) = pinnacle_rt::register(model::SERVICE) else {
        println!("model: {} is taken", model::SERVICE);
        return 1;
    };
    let mut clients: Vec<(Channel, Pieces)> = Vec::new();
    let mut served = false;
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    loop {
        let mut channels = alloc::vec![&service];
        channels.extend(clients.iter().map(|(c, _)| c));
        match pinnacle_rt::receive(&channels, &mut buffer, None) {
            Received::Message {
                index: 0,
                mut handles,
                ..
            } if !handles.is_empty() => {
                clients.push((Channel(handles.remove(0)), Pieces::default()));
                served = true;
            }
            Received::Message { index, len, .. } if index > 0 => {
                let (client, pieces) = &mut clients[index - 1];
                if let Some((model::ASK, request)) = pieces.push(&buffer[..len]) {
                    answer(client, &request, standin);
                }
            }
            Received::Closed { index } if index > 0 => {
                clients.remove(index - 1);
                if standin && served && clients.is_empty() {
                    return 0;
                }
            }
            _ => {}
        }
    }
}

fn send(client: &Channel, kind: u8, v: Value) -> bool {
    pinnacle_ui::verbs::send(client, kind, &alloc::format!("{v}"), Vec::new())
}

fn error(client: &Channel, why: &str) {
    println!("model: {why}");
    send(client, ERROR, Value::object([("error", why.into())]));
}

/// Where to, with which key, as the settings say (or the stand-in).
fn host(standin: bool) -> Result<(Config, String), &'static str> {
    if standin {
        let source = fs::read_string("system:/settings/store-url").ok_or("no package source")?;
        let config = Config {
            host: String::from(source.trim().trim_end_matches('/')),
            model: "stand-in".into(),
            on: true,
        };
        return Ok((config, STANDIN_KEY.into()));
    }
    let config = Config::read();
    if !config.on {
        return Err("The agent is off: Settings, Agent turns it on");
    }
    let key = model::key().ok_or("No key for the model: Settings, Agent")?;
    Ok((config, key))
}

/// One conversation, sent to the host and answered on `client`.
fn answer(client: &Channel, request: &Value, standin: bool) {
    let (config, key) = match host(standin) {
        Ok(host) => host,
        Err(why) => return error(client, why),
    };
    // Anthropic's Messages API: the conversation is already its shape.
    let mut body = Value::object([
        ("model", config.model.as_str().into()),
        (
            "max_tokens",
            request.get("max_tokens").as_u64().unwrap_or(MAX_TOKENS).into(),
        ),
        ("stream", true.into()),
    ]);
    for field in ["system", "messages", "tools"] {
        if !request.get(field).is_null() {
            body.set(field, request.get(field).clone());
        }
    }
    let body = alloc::format!("{body}");
    // Every prompt that leaves the device, before it leaves.
    keep_sent(&config, &body);
    let url = alloc::format!("{}/v1/messages", config.host.trim_end_matches('/'));
    let headers = [
        ("x-api-key", key.as_str()),
        ("anthropic-version", "2023-06-01"),
        ("content-type", "application/json"),
    ];
    let mut reader = Reader::default();
    let mut gone = false;
    let result = pinnacle_rt::net::request("POST", &url, &headers, body.as_bytes(), TIMEOUT, |piece| {
        reader.events.receive(piece);
        let room = 4096usize.saturating_sub(reader.raw.len());
        reader.raw.extend_from_slice(&piece[..piece.len().min(room)]);
        while let Some(event) = reader.events.take() {
            let data = pinnacle_json::parse(&event.data).unwrap_or(Value::Null);
            if let Some((kind, v)) = reader.event(&event.event, &data)
                && !send(client, kind, v)
            {
                // The client went: the answer is not wanted.
                gone = true;
                return false;
            }
        }
        true
    });
    if gone {
        return;
    }
    match result {
        Ok(head) if head.status == 200 && reader.failed.is_none() => {
            send(
                client,
                DONE,
                Value::object([
                    ("stop", reader.stop.as_str().into()),
                    ("input_tokens", reader.input_tokens.into()),
                    ("output_tokens", reader.output_tokens.into()),
                ]),
            );
        }
        Ok(head) if head.status == 200 => error(client, &reader.failed.unwrap_or_default()),
        Ok(head) => {
            // The provider's error is JSON: its message says why.
            let said = core::str::from_utf8(&reader.raw)
                .ok()
                .and_then(|t| pinnacle_json::parse(t).ok())
                .and_then(|v| v.get("error").get("message").as_str().map(String::from))
                .unwrap_or_default();
            error(
                client,
                &alloc::format!("{} answered {}: {said}", config.host, head.status),
            );
        }
        Err(e) => error(
            client,
            &alloc::format!("{} could not be reached: {e:?}", config.host),
        ),
    }
}

/// The log of what was sent: the whole request but the key, which travels
/// in a header.
fn keep_sent(config: &Config, body: &str) {
    let log = model::sent_log();
    if !log.starts_with("data:") {
        fs::create_dir("system:/agent");
    } else {
        fs::create_dir("data:/agent");
    }
    let Some(file) = fs::File::open(log, fs::READ | fs::APPEND) else {
        println!("model: could not open {log}");
        return;
    };
    let entry = Value::object([
        ("time", pinnacle_rt::clock().into()),
        ("host", config.host.as_str().into()),
        ("model", config.model.as_str().into()),
        ("bytes", (body.len() as u64).into()),
        ("request", pinnacle_json::parse(body).unwrap_or(Value::Null)),
    ]);
    let empty = file.stat().is_some_and(|s| s.size == 0);
    file.append(&pinnacle_records::log::entry(
        alloc::format!("{entry}").as_bytes(),
        empty,
    ));
}

/// Anthropic's streamed answer, read event by event into the service's.
#[derive(Default)]
struct Reader {
    events: pinnacle_rt::net::Events,
    /// The start of the body, for an error's JSON.
    raw: Vec<u8>,
    /// The tool call being streamed: its id, name and input so far.
    call: Option<(String, String, String)>,
    stop: String,
    input_tokens: u64,
    output_tokens: u64,
    failed: Option<String>,
}

impl Reader {
    fn event(&mut self, name: &str, data: &Value) -> Option<(u8, Value)> {
        match name {
            "message_start" => {
                self.input_tokens = data
                    .get("message")
                    .get("usage")
                    .get("input_tokens")
                    .as_u64()
                    .unwrap_or(0);
                None
            }
            "content_block_start" => {
                let block = data.get("content_block");
                if block.get("type").as_str() == Some("tool_use") {
                    self.call = Some((
                        block.get("id").as_str().unwrap_or("").into(),
                        block.get("name").as_str().unwrap_or("").into(),
                        String::new(),
                    ));
                }
                None
            }
            "content_block_delta" => {
                let delta = data.get("delta");
                match delta.get("type").as_str() {
                    Some("text_delta") => Some((TEXT, Value::object([("text", delta.get("text").clone())]))),
                    Some("input_json_delta") => {
                        if let Some((_, _, input)) = &mut self.call {
                            input.push_str(delta.get("partial_json").as_str().unwrap_or(""));
                        }
                        None
                    }
                    _ => None,
                }
            }
            "content_block_stop" => {
                let (id, name, input) = self.call.take()?;
                // A model's input is untrusted text: what does not parse is
                // an empty object, which the gatekeeper's check refuses.
                let input = match input.trim() {
                    "" => Value::object::<&str>([]),
                    text => pinnacle_json::parse(text).unwrap_or(Value::Null),
                };
                Some((
                    CALL,
                    Value::object([("id", id.into()), ("name", name.into()), ("input", input)]),
                ))
            }
            "message_delta" => {
                if let Some(stop) = data.get("delta").get("stop_reason").as_str() {
                    self.stop = stop.into();
                }
                self.output_tokens = data
                    .get("usage")
                    .get("output_tokens")
                    .as_u64()
                    .unwrap_or(self.output_tokens);
                None
            }
            "error" => {
                self.failed = Some(
                    data.get("error")
                        .get("message")
                        .as_str()
                        .unwrap_or("an error")
                        .into(),
                );
                None
            }
            _ => None,
        }
    }
}