- hx-core: Tool trait + registry (schema validation, parallel calls), event bus with Block/Mutate/Inject hooks, agent loop (abort, max turns, AgentEnd inject), JSONL session tree (fork, resume, torn-line tolerant), AGENTS.md/CLAUDE.md hierarchy, skills index (bodies on demand) - hx-tools: read (ranges, binary, images, caps), write/edit (exact match, ambiguity, CRLF, diff, read-guard), bash (merged output, timeout kills process group, tail truncation to temp file) - hx-cli: -p runs full agent loop, --session / --continue, Ctrl-C abort, HX_BASE_URL override - tests/e2e.sh: scripted fake Anthropic server drives write -> bash -> answer Closes #6, closes #7, closes #8, closes #9, closes #10, closes #11, closes #12, closes #13, closes #14
This commit is contained in:
1 parent
da9d5d1ae0
commit
21d4d2bb3d
15 files changed
+1752
-52
No files matched your search
@@ -0,0 +1,174 @@
|
||||
//! 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
|
||||
}
|
||||
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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user