fauna-api 1.0.858

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
//! A machine agent on a repository's machine, through Termite's agent socket: it boots or joins
//! the machine, works on what it's asked with the real models, keeps the photos and recordings
//! it's asked for with the repository, and answers with its `done` frame.

use futures_util::{SinkExt, StreamExt};
use serde_json::{Value, json};
use tokio_tungstenite::tungstenite::Message;

use super::fail;
use crate::authentification::CredentialsOrApiKey;
use crate::error::Result;
use crate::http::{encode, websocket};

/// Runs a machine agent on `repository` that does `goal`, in at most `steps` steps, saving and
/// stopping the machine when it ends. Its `done` frame: ok, answer, reason, steps and media.
pub(super) async fn agent(
    key: &CredentialsOrApiKey,
    repository: u64,
    goal: &str,
    steps: u32,
) -> Result<Value> {
    let header = match key {
        CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
        CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
    };
    let headers = json!({ "Authorization": header });
    let url = format!(
        "{}/termite/repositories/agent?authorization={}",
        websocket(&crate::termite::get_url()),
        encode(&headers.to_string())
    );
    let start = json!({
        "event": "agent",
        "repository": repository,
        "content": { "role": "USER", "parts": [{ "type": "TEXT", "text": goal }] },
        "maxSteps": steps,
        "stop": true,
    });
    let (socket, _) = tokio_tungstenite::connect_async(url.as_str()).await?;
    let (mut sink, mut stream) = socket.split();
    sink.send(Message::Text(start.to_string().into())).await?;
    sink.send(Message::Text(
        json!({ "event": "start" }).to_string().into(),
    ))
    .await?;
    while let Some(message) = stream.next().await {
        let Message::Text(text) = message? else {
            continue;
        };
        let Ok(frame) = serde_json::from_str::<Value>(&text) else {
            continue;
        };
        match frame.get("event").and_then(Value::as_str) {
            Some("done") => return Ok(frame),
            Some("error") => {
                return fail(format!(
                    "The machine agent's socket answered: {}",
                    frame["message"].as_str().unwrap_or("an error")
                ));
            }
            _ => {}
        }
    }
    fail("The machine agent's socket closed before it was done.")
}