405 lines
13 KiB
Rust
405 lines
13 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>>,
|
|
}
|
|
|
|
/// Ask the user (unless a stored rule covers `req`); false = denied. No prompt hook = allowed.
|
|
pub async fn gate(cx: &ToolCtx, req: crate::permit::Request) -> bool {
|
|
gate_why(cx, req).await.is_ok()
|
|
}
|
|
|
|
/// Like [`gate`]; `Err` carries the message for the model. In auto mode dangerous calls are refused
|
|
/// here without a prompt (also with a stored "always" rule), safe ones run, the rest is judged or asked.
|
|
pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), String> {
|
|
use crate::danger::{Verdict, classify};
|
|
use crate::permit::Decision;
|
|
const DENIED: &str = "denied by the user; do not retry, ask what to do instead";
|
|
if matches!(req.tool.as_str(), "bash" | "write" | "edit")
|
|
&& cx
|
|
.state
|
|
.allow
|
|
.lock()
|
|
.unwrap_or_else(|e| e.into_inner())
|
|
.plan_on()
|
|
{
|
|
return Err("blocked by plan mode: read-only until the plan is approved. Explore with read/grep/ls, then call exit_plan with the full plan.".into());
|
|
}
|
|
let Some(ask) = cx.state.permit.get() else {
|
|
return Ok(());
|
|
};
|
|
let allow = || cx.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
|
// One prompt at a time; re-check after waiting, an earlier answer may cover this call.
|
|
let _turn = cx.state.asking.lock().await;
|
|
let auto = {
|
|
let a = allow();
|
|
a.auto_on() && !a.yolo_on() && matches!(req.tool.as_str(), "bash" | "write" | "edit")
|
|
};
|
|
let refuse = |why: &str| {
|
|
allow().note_block(format!("{}: {} ({why})", req.tool, req.detail));
|
|
Err(format!(
|
|
"blocked by auto mode: {why}. Do not retry this; use a safer way or ask the user."
|
|
))
|
|
};
|
|
if auto {
|
|
match classify(&req, &cx.cwd) {
|
|
Verdict::Block(why) => return refuse(&why),
|
|
Verdict::Allow => return Ok(()),
|
|
Verdict::Ask => {}
|
|
}
|
|
}
|
|
if allow().allows(&req) {
|
|
return Ok(());
|
|
}
|
|
if auto && let Some(j) = cx.state.judge.get() {
|
|
match j.check(&req, &cx.cwd).await {
|
|
Some(Ok(())) => return Ok(()),
|
|
Some(Err(why)) => return refuse(&format!("judged unsafe: {why}")),
|
|
None => {}
|
|
}
|
|
}
|
|
let rule = req.rule.clone();
|
|
match ask(req).await {
|
|
Decision::Once => {}
|
|
Decision::Always => allow().add(&rule),
|
|
Decision::Edits => allow().allow_edits(),
|
|
Decision::Deny => return Err(DENIED.into()),
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
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::needs_permit(name, &args)
|
|
&& let Err(e) = gate_why(cx, crate::permit::request(name, &args)).await
|
|
{
|
|
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 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": "mkdir -p a"}), &c)
|
|
.await
|
|
.content,
|
|
"ran"
|
|
);
|
|
// rule bash:mkdir remembered: no second prompt
|
|
assert_eq!(
|
|
r.call("bash", json!({"command": "mkdir b"}), &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 plan_mode_blocks_writes_even_without_prompt() {
|
|
let c = cx();
|
|
c.state.allow.lock().unwrap().set_plan(true);
|
|
let e = gate_why(
|
|
&c,
|
|
crate::permit::request("bash", &json!({"command":"touch x"})),
|
|
)
|
|
.await;
|
|
assert!(e.unwrap_err().contains("plan mode"));
|
|
c.state.allow.lock().unwrap().set_plan(false);
|
|
assert!(
|
|
gate_why(
|
|
&c,
|
|
crate::permit::request("bash", &json!({"command":"touch x"}))
|
|
)
|
|
.await
|
|
.is_ok()
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn auto_mode_blocks_allows_judges_without_prompting() {
|
|
use crate::danger::Judge;
|
|
use crate::permit::{Decision, Permit};
|
|
use hx_ai::{Message, Provider, Request, StopReason, StreamEvent, Usage};
|
|
struct Say(&'static str);
|
|
#[async_trait]
|
|
impl Provider for Say {
|
|
async fn stream(
|
|
&self,
|
|
_: Request,
|
|
) -> hx_ai::Result<futures::stream::BoxStream<'static, hx_ai::Result<StreamEvent>>>
|
|
{
|
|
let ev = StreamEvent::Done {
|
|
message: Message {
|
|
role: hx_ai::Role::Assistant,
|
|
content: vec![hx_ai::ContentBlock::Text {
|
|
text: self.0.into(),
|
|
}],
|
|
},
|
|
stop: StopReason::EndTurn,
|
|
usage: Usage::default(),
|
|
};
|
|
Ok(Box::pin(futures::stream::iter(vec![Ok(ev)])))
|
|
}
|
|
}
|
|
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();
|
|
let asked = Arc::new(std::sync::Mutex::new(0));
|
|
let n = asked.clone();
|
|
let p: Permit = Arc::new(move |_| {
|
|
*n.lock().unwrap() += 1;
|
|
Box::pin(async { Decision::Deny })
|
|
});
|
|
let _ = c.state.permit.set(p);
|
|
c.state.allow.lock().unwrap().set_auto(true);
|
|
// a stored always-rule does not beat a block
|
|
c.state.allow.lock().unwrap().add("bash:rm -rf /");
|
|
let run = |cmd: &'static str| {
|
|
let (r, c) = (r.clone(), c.clone());
|
|
async move { r.call("bash", json!({"command": cmd}), &c).await }
|
|
};
|
|
let b = run("rm -rf /").await;
|
|
assert!(
|
|
b.is_error && b.content.contains("blocked by auto mode"),
|
|
"{b:?}"
|
|
);
|
|
assert_eq!(run("mkdir -p out").await.content, "ran");
|
|
assert_eq!(*asked.lock().unwrap(), 0);
|
|
// unclear + no judge: asks the user
|
|
assert!(run("somebinary").await.content.contains("denied"));
|
|
assert_eq!(*asked.lock().unwrap(), 1);
|
|
// unclear + judge
|
|
let judge = |t| Judge {
|
|
provider: Arc::new(Say(t)),
|
|
model: "m".into(),
|
|
};
|
|
let _ = c.state.judge.set(judge("ALLOW"));
|
|
assert_eq!(run("somebinary").await.content, "ran");
|
|
assert_eq!(*asked.lock().unwrap(), 1);
|
|
assert_eq!(c.state.allow.lock().unwrap().blocks().len(), 1);
|
|
// yolo skips the classifier entirely
|
|
c.state.allow.lock().unwrap().toggle_yolo();
|
|
assert_eq!(run("rm -rf /").await.content, "ran");
|
|
}
|
|
|
|
#[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"]
|
|
);
|
|
}
|
|
}
|