Files
hx/crates/hx-core/src/tool.rs
T
hermes 359a5058d7
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
Subagents: task tool (explore on cheap model, general), child sessions, usage roll-up, stats
2026-10-02 11:57:59 +00:00

179 lines
5.2 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);
}
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 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"]
);
}
}