Files
hx/crates/hx-core/src/tool.rs
T
hermes 5fd7044a2f
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
TUI: permission prompt, /diff review, /stats dashboard, lens/context/MCP side panel
2026-10-02 23:31:55 +02:00

260 lines
7.9 KiB
Rust

//! Tools: trait, context, registry, argument validation, parallel dispatch.
use async_trait::async_trait;
use hx_ai::ToolSpec;
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
pub struct ToolResult {
pub content: String,
pub is_error: bool,
}
impl ToolResult {
pub fn ok(s: impl Into<String>) -> Self {
Self {
content: s.into(),
is_error: false,
}
}
pub fn err(s: impl Into<String>) -> Self {
Self {
content: s.into(),
is_error: true,
}
}
}
/// Per-call context. Shared state (read-tracking, seq log) hangs off `state`.
#[derive(Clone)]
pub struct ToolCtx {
pub cwd: PathBuf,
pub state: Arc<crate::State>,
}
#[async_trait]
pub trait Tool: Send + Sync {
fn spec(&self) -> ToolSpec;
async fn call(&self, args: Value, cx: &ToolCtx) -> ToolResult;
}
/// Minimal JSON-schema check: object type, required keys, primitive property types.
/// ponytail: no nested/enum/format checks; swap for `jsonschema` crate if models send bad nested args.
pub fn validate(schema: &Value, args: &Value) -> Result<(), String> {
let Some(obj) = args.as_object() else {
return Err("arguments must be a JSON object".into());
};
for r in schema["required"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
{
if !obj.contains_key(r) {
return Err(format!("missing required argument `{r}`"));
}
}
for (k, v) in obj {
let Some(want) = schema["properties"][k]["type"].as_str() else {
continue;
};
let ok = match want {
"string" => v.is_string(),
"integer" => v.is_i64() || v.is_u64(),
"number" => v.is_number(),
"boolean" => v.is_boolean(),
"array" => v.is_array(),
"object" => v.is_object(),
_ => true,
};
if !ok && !v.is_null() {
return Err(format!("argument `{k}` must be {want}"));
}
}
Ok(())
}
#[derive(Default, Clone)]
pub struct Registry {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
impl Registry {
pub fn add(&mut self, t: impl Tool + 'static) -> &mut Self {
self.tools.insert(t.spec().name, Arc::new(t));
self
}
/// Keep only tools for which `f(name)` holds.
pub fn retain(&mut self, f: impl Fn(&str) -> bool) {
self.tools.retain(|n, _| f(n));
}
pub fn specs(&self) -> Vec<ToolSpec> {
self.tools.values().map(|t| t.spec()).collect()
}
pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
self.tools.get(name).cloned()
}
pub async fn call(&self, name: &str, args: Value, cx: &ToolCtx) -> ToolResult {
let Some(t) = self.get(name) else {
return ToolResult::err(format!("unknown tool `{name}`"));
};
if let Err(e) = validate(&t.spec().input_schema, &args) {
return ToolResult::err(e);
}
if crate::permit::gated(name)
&& let Some(ask) = cx.state.permit.get()
{
let req = crate::permit::request(name, &args);
let known = cx
.state
.allow
.lock()
.unwrap_or_else(|e| e.into_inner())
.has(&req.rule);
if !known {
let rule = req.rule.clone();
match ask(req).await {
crate::permit::Decision::Once => {}
crate::permit::Decision::Always => cx
.state
.allow
.lock()
.unwrap_or_else(|e| e.into_inner())
.add(&rule),
crate::permit::Decision::Deny => {
return ToolResult::err(
"denied by the user; do not retry, ask what to do instead",
);
}
}
}
}
t.call(args, cx).await
}
/// Run calls concurrently; results keep input order.
pub async fn call_all(&self, calls: Vec<(String, Value)>, cx: &ToolCtx) -> Vec<ToolResult> {
futures::future::join_all(
calls
.into_iter()
.map(|(n, a)| async move { self.call(&n, a, cx).await }),
)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::time::{Duration, Instant};
struct Sleep;
#[async_trait]
impl Tool for Sleep {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "sleep".into(),
description: "sleep ms".into(),
input_schema: json!({"type":"object","properties":{"ms":{"type":"integer"}},"required":["ms"]}),
}
}
async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult {
let ms = a["ms"].as_u64().unwrap();
tokio::time::sleep(Duration::from_millis(ms)).await;
ToolResult::ok(ms.to_string())
}
}
pub(crate) fn cx() -> ToolCtx {
ToolCtx {
cwd: std::env::temp_dir(),
state: Default::default(),
}
}
#[tokio::test]
async fn gate_asks_remembers_and_denies() {
use crate::permit::{Decision, Permit};
struct Nop;
#[async_trait]
impl Tool for Nop {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "bash".into(),
description: String::new(),
input_schema: json!({"type":"object"}),
}
}
async fn call(&self, _: Value, _: &ToolCtx) -> ToolResult {
ToolResult::ok("ran")
}
}
let mut r = Registry::default();
r.add(Nop);
let c = cx();
// no frontend: runs
assert_eq!(
r.call("bash", json!({"command": "ls"}), &c).await.content,
"ran"
);
let asked = Arc::new(std::sync::Mutex::new(0));
let (n, next) = (
asked.clone(),
Arc::new(std::sync::Mutex::new(Decision::Always)),
);
let p: Permit = Arc::new(move |_| {
*n.lock().unwrap() += 1;
let d = *next.lock().unwrap();
*next.lock().unwrap() = Decision::Deny;
Box::pin(async move { d })
});
let _ = c.state.permit.set(p);
assert_eq!(
r.call("bash", json!({"command": "ls -l"}), &c)
.await
.content,
"ran"
);
// rule bash:ls remembered: no second prompt
assert_eq!(
r.call("bash", json!({"command": "ls"}), &c).await.content,
"ran"
);
assert_eq!(*asked.lock().unwrap(), 1);
let d = r.call("bash", json!({"command": "rm x"}), &c).await;
assert!(d.is_error && d.content.contains("denied"));
}
#[tokio::test]
async fn registry_validation_parallel() {
let mut r = Registry::default();
r.add(Sleep);
assert_eq!(r.specs().len(), 1);
assert!(r.call("nope", json!({}), &cx()).await.is_error);
let e = r.call("sleep", json!({}), &cx()).await;
assert!(e.is_error && e.content.contains("`ms`"));
let e = r.call("sleep", json!({"ms": "x"}), &cx()).await;
assert!(e.is_error && e.content.contains("integer"));
let t = Instant::now();
let out = r
.call_all(
vec![
("sleep".into(), json!({"ms": 150})),
("sleep".into(), json!({"ms": 10})),
],
&cx(),
)
.await;
assert!(t.elapsed() < Duration::from_millis(280), "not parallel");
assert_eq!(
out.iter().map(|r| r.content.as_str()).collect::<Vec<_>>(),
["150", "10"]
);
}
}