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::web::WebRoom;
use crate::parrot::generative::{Tool, tool};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageToolName {
ReadPageHtml,
ReadPageText,
ReadSelection,
}
pub type PageToolHandler = Arc<
dyn Fn(PageToolName, Map<String, Value>) -> BoxFuture<'static, Result<String>> + Send + Sync,
>;
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(),
)
},
),
]
}
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);
}
}