fauna-api 1.0.816

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use std::sync::Arc;

use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

use crate::error::Result;
use crate::marmot::browser::tool;
use crate::marmot::web::WebRoom;
use crate::parrot::generative::Tool;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageToolName {
    ReadPageHtml,
    ReadPageText,
    ReadSelection,
}

/// Runs one page tool with its parameters and returns its result as text.
pub type PageToolHandler = Arc<
    dyn Fn(PageToolName, Map<String, Value>) -> BoxFuture<'static, Result<String>> + Send + Sync,
>;

/// Parrot tools wired through a web-room invoke (or a local host handler).
pub fn page_tools(invoke: PageToolHandler) -> Vec<Tool> {
    let html = invoke.clone();
    let text = invoke.clone();
    vec![
        tool(
            "read_page_html",
            "Read the cleaned HTML of the currently shared page.",
            json!({ "type": "OBJECT", "properties": {} }),
            move |_| html(PageToolName::ReadPageHtml, Map::new()),
        ),
        tool(
            "read_page_text",
            "Read the visible text of the currently shared page.",
            json!({ "type": "OBJECT", "properties": {} }),
            move |_| text(PageToolName::ReadPageText, Map::new()),
        ),
        tool(
            "read_selection",
            "Read the host's current text selection on the shared page.",
            json!({
                "type": "OBJECT",
                "properties": {
                    "max": { "type": "INTEGER", "description": "Max characters to return." },
                },
            }),
            move |params: Value| {
                invoke(
                    PageToolName::ReadSelection,
                    params.as_object().cloned().unwrap_or_default(),
                )
            },
        ),
    ]
}

/// Bind host tool fulfillment on a connected WebRoom. Returns a function that unbinds it.
pub fn attach_host_tools(
    room: &WebRoom,
    handler: PageToolHandler,
) -> Box<dyn FnOnce() + Send + Sync> {
    room.set_tool_handler(Arc::new(move |name: String, params: Map<String, Value>| {
        match serde_json::from_value::<PageToolName>(Value::from(name.as_str())) {
            Ok(tool) => handler(tool, params),
            Err(_) => Box::pin(async move { Ok(format!("Unknown page tool: {name}")) }),
        }
    }))
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use serde_json::{Map, json};
    use tokio::sync::mpsc;

    use super::*;
    use crate::authentification::{ApiKey, CredentialsOrApiKey};
    use crate::shared::server::{Authorization, Room};

    #[tokio::test]
    async fn page_tools_reach_the_host_handler() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = seen.clone();
        let handler: PageToolHandler = Arc::new(move |name, params| {
            sink.lock().unwrap().push((name, params));
            Box::pin(async { Ok("page".to_string()) })
        });
        let tools = page_tools(handler.clone());
        assert_eq!(
            (tools[2].evaluate)(json!({ "max": 5 })).await.unwrap(),
            "page"
        );
        assert_eq!(seen.lock().unwrap()[0].0, PageToolName::ReadSelection);
        assert_eq!(seen.lock().unwrap()[0].1["max"], 5);

        let (ws, _outbox) = mpsc::unbounded_channel();
        let room = Room::new(
            "http://localhost/extensions/web/live".to_string(),
            ws,
            Authorization::AccessCode {
                authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
                access_code: "code".to_string(),
            },
            "web".to_string(),
        );
        let web = WebRoom::from_parent(&room, None, &json!({}));
        let detach = attach_host_tools(&web, handler);
        assert_eq!(
            web.invoke_tool("read_page_text", Map::new(), None)
                .await
                .unwrap(),
            "page"
        );
        assert_eq!(
            web.invoke_tool("open_tab", Map::new(), None).await.unwrap(),
            "Unknown page tool: open_tab"
        );
        detach();
        assert_eq!(seen.lock().unwrap()[1].0, PageToolName::ReadPageText);
    }
}