use std::sync::Mutex;
use std::time::Duration;
use mlua::{Lua, LuaSerdeExt, MultiValue, Value};
use serde_json::Value as Json;
use yk_core::{Error, Result, Tool, ToolDef};
use crate::{ExecutionBudget, Hook};
const BUILTINS: [&str; 4] = ["read", "write", "edit", "bash"];
#[must_use]
pub fn is_builtin(name: &str) -> bool {
BUILTINS.contains(&name)
}
pub struct HookGuardedTool<'a> {
pub(crate) inner: &'a dyn Tool,
pub(crate) lua: &'a Lua,
pub(crate) hooks: &'a [Hook],
pub(crate) budget: &'a Mutex<ExecutionBudget>,
}
impl HookGuardedTool<'_> {
async fn veto(&self, name: &str, args: &Json) -> Result<Option<String>> {
for hook in self.hooks {
let converted = self.lua.to_value(args).map_err(|error| Error::Tool {
tool: name.to_owned(),
reason: format!("arguments could not be passed to a hook: {error}"),
})?;
let name_value = self.lua.create_string(name).map_err(|error| Error::Tool {
tool: name.to_owned(),
reason: format!("the tool name could not be passed to a hook: {error}"),
})?;
let returned = hook
.callback
.call_async::<MultiValue>(MultiValue::from_iter([
Value::String(name_value),
converted,
]))
.await;
let values = match returned {
Ok(values) => values,
Err(error) => {
return Err(Error::Tool {
tool: name.to_owned(),
reason: format!(
"{} blocked the call: {}",
hook.source,
error_for_model(&error)
),
});
}
};
for value in values {
match value {
Value::Nil => {}
Value::String(text) if text.as_bytes().is_empty() => {}
Value::String(text) => return Ok(Some(text.to_string_lossy())),
other => {
return Err(Error::Tool {
tool: name.to_owned(),
reason: format!(
"{} returned {other:?} from on_tool_call; \
return nil or a reason string",
hook.source
),
});
}
}
}
}
Ok(None)
}
fn arm(&self, tool: &str) -> Result<()> {
budget_for(self.budget, tool)?.arm(crate::TOOL_TIMEOUT);
Ok(())
}
fn clear(&self, tool: &str) -> Result<()> {
budget_for(self.budget, tool)?.clear();
Ok(())
}
}
#[async_trait::async_trait]
impl Tool for HookGuardedTool<'_> {
fn def(&self) -> ToolDef {
self.inner.def()
}
async fn run(&self, args: &Json) -> Result<String> {
let name = self.def().name;
self.arm(&name)?;
let outcome = match self.veto(&name, args).await {
Ok(Some(reason)) => Err(Error::Tool {
tool: name.clone(),
reason,
}),
Ok(None) => self.inner.run(args).await,
Err(error) => Err(error),
};
self.clear(&name)?;
outcome
}
}
#[derive(Clone)]
pub struct LuaTool<'a> {
lua: &'a Lua,
name: String,
description: String,
schema: Json,
callback: &'a mlua::Function,
timeout: Duration,
budget: &'a Mutex<ExecutionBudget>,
}
impl<'a> LuaTool<'a> {
#[must_use]
pub const fn new(
lua: &'a Lua,
name: String,
description: String,
schema: Json,
callback: &'a mlua::Function,
budget: &'a Mutex<ExecutionBudget>,
) -> Self {
Self {
lua,
name,
description,
schema,
callback,
timeout: crate::TOOL_TIMEOUT,
budget,
}
}
#[must_use]
pub const fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
}
#[async_trait::async_trait]
impl Tool for LuaTool<'_> {
fn def(&self) -> ToolDef {
ToolDef {
name: self.name.clone(),
description: self.description.clone(),
schema: self.schema.clone(),
}
}
async fn run(&self, args: &Json) -> Result<String> {
let converted = self.lua.to_value(args).map_err(|error| Error::Tool {
tool: self.name.clone(),
reason: format!("arguments could not be passed to lua: {error}"),
})?;
budget_for(self.budget, &self.name)?.arm(self.timeout);
let returned = self
.callback
.call_async::<mlua::MultiValue>(converted)
.await
.map_err(|error| Error::Tool {
tool: self.name.clone(),
reason: error_for_model(&error),
})?;
budget_for(self.budget, &self.name)?.clear();
match returned.into_iter().next() {
None | Some(Value::Nil) => Ok(String::new()),
Some(Value::String(text)) => Ok(text.to_string_lossy()),
Some(other) => Ok(format!("{other:?}")),
}
}
}
fn budget_for<'a>(
budget: &'a Mutex<ExecutionBudget>,
tool: &str,
) -> Result<std::sync::MutexGuard<'a, ExecutionBudget>> {
budget.lock().map_err(|_| Error::Tool {
tool: tool.to_owned(),
reason: "the execution lock was poisoned".to_owned(),
})
}
#[must_use]
fn error_for_model(error: &mlua::Error) -> String {
match error {
mlua::Error::RuntimeError(message) => message.clone(),
mlua::Error::CallbackError { traceback, cause } => {
let traceback = traceback.trim();
if traceback.is_empty() {
cause.to_string()
} else {
format!("{cause}\n{traceback}")
}
}
mlua::Error::ExternalError(inner) => inner.to_string(),
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use std::sync::Arc;
use yk_core::Tool as _;
use super::{error_for_model, is_builtin};
use crate::{DenyHost, Host, Registry};
fn denying() -> Arc<dyn Host> {
Arc::new(DenyHost)
}
struct Echo;
#[async_trait::async_trait]
impl yk_core::Tool for Echo {
fn def(&self) -> yk_core::ToolDef {
yk_core::ToolDef {
name: "echo".to_owned(),
description: "Returns its argument".to_owned(),
schema: serde_json::json!({"type": "object"}),
}
}
async fn run(&self, args: &serde_json::Value) -> yk_core::Result<String> {
Ok(args.to_string())
}
}
#[test]
fn the_four_builtins_are_recognised() {
for name in ["read", "write", "edit", "bash"] {
assert!(is_builtin(name), "{name}");
}
assert!(!is_builtin("shout"));
}
#[test]
fn a_builtin_name_is_not_a_prefix_match() {
assert!(!is_builtin("bash_history"));
assert!(!is_builtin("readme"));
}
#[test]
fn a_runtime_error_keeps_its_message() {
let text = error_for_model(&mlua::Error::RuntimeError("boom".to_owned()));
assert!(text.contains("boom"), "{text}");
}
#[test]
fn a_syntax_error_keeps_its_message() {
let error = mlua::Error::SyntaxError {
message: "unexpected token".to_owned(),
incomplete_input: false,
};
let text = error_for_model(&error);
assert!(text.contains("unexpected token"), "{text}");
}
#[tokio::test]
async fn a_registered_tool_returns_its_string() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"
host.register_tool("shout", "Shout", {}, function(args)
return string.upper(args.word)
end)
"#,
"shout.lua",
)
.expect("loads");
let tools = registry.tools();
let shouting = tools.first().expect("the tool is registered");
let out = shouting
.run(&serde_json::json!({"word": "hi"}))
.await
.expect("runs");
assert_eq!(out, "HI");
}
#[tokio::test]
async fn a_tool_returning_nothing_is_empty_rather_than_an_error() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"host.register_tool("quiet", "Says nothing", {}, function() end)"#,
"quiet.lua",
)
.expect("loads");
let tools = registry.tools();
let quiet = tools.first().expect("the tool is registered");
let out = quiet.run(&serde_json::json!({})).await.expect("runs");
assert_eq!(out, "");
}
#[tokio::test]
async fn a_tool_that_raises_reaches_the_model_as_an_error() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"host.register_tool("boom", "Raises", {}, function() error("kaboom") end)"#,
"boom.lua",
)
.expect("loads");
let tools = registry.tools();
let boom = tools.first().expect("the tool is registered");
let error = boom
.run(&serde_json::json!({}))
.await
.expect_err("must fail");
assert!(error.to_string().contains("kaboom"), "{error}");
}
#[tokio::test]
async fn a_hook_returning_nil_lets_the_call_through() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(r"on_tool_call(function() end)", "pass.lua")
.expect("loads");
let echo = Echo;
let guarded = registry.guard(&echo);
let out = guarded
.run(&serde_json::json!({"a": 1}))
.await
.expect("runs");
assert!(out.contains('a'), "{out}");
}
#[tokio::test]
async fn a_hook_returning_a_reason_blocks_the_call() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"on_tool_call(function(name)
if name == "echo" then return "block: this repo is read-only" end
end)"#,
"guard.lua",
)
.expect("loads");
let echo = Echo;
let guarded = registry.guard(&echo);
let error = guarded
.run(&serde_json::json!({}))
.await
.expect_err("must be blocked");
let text = error.to_string();
assert!(text.contains("read-only"), "{text}");
assert!(text.contains("echo"), "{text}");
}
#[tokio::test]
async fn a_hook_that_raises_blocks_rather_than_failing_open() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"on_tool_call(function() error("hook is broken") end)"#,
"broken.lua",
)
.expect("loads");
let echo = Echo;
let guarded = registry.guard(&echo);
let error = guarded
.run(&serde_json::json!({}))
.await
.expect_err("must fail safe");
let text = error.to_string();
assert!(text.contains("broken.lua"), "{text}");
assert!(text.contains("hook is broken"), "{text}");
}
#[tokio::test]
async fn the_first_hook_with_an_opinion_wins() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(r"on_tool_call(function() end)", "first.lua")
.expect("loads");
registry
.load_source(
r#"on_tool_call(function() return "block: second says no" end)"#,
"second.lua",
)
.expect("loads");
assert_eq!(registry.hooks().len(), 2);
let echo = Echo;
let guarded = registry.guard(&echo);
let error = guarded
.run(&serde_json::json!({}))
.await
.expect_err("must be blocked");
assert!(error.to_string().contains("second says no"), "{error}");
}
#[tokio::test]
async fn a_hook_only_sees_the_tool_it_was_wired_to() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"on_tool_call(function(name)
if name == "bash" then return "block: no shells here" end
end)"#,
"only_bash.lua",
)
.expect("loads");
let echo = Echo;
let guarded = registry.guard(&echo);
guarded
.run(&serde_json::json!({}))
.await
.expect("a different tool still runs");
}
#[tokio::test]
async fn a_hook_receives_the_name_and_the_arguments() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"on_tool_call(function(name, args)
if args.path == "/etc/passwd" then
return "block: " .. name
end
end)"#,
"reads_args.lua",
)
.expect("loads");
let echo = Echo;
let guarded = registry.guard(&echo);
let error = guarded
.run(&serde_json::json!({"path": "/etc/passwd"}))
.await
.expect_err("must be blocked");
assert!(error.to_string().contains("echo"), "{error}");
guarded
.run(&serde_json::json!({"path": "Cargo.toml"}))
.await
.expect("another path still runs");
}
#[tokio::test]
async fn a_hook_returning_a_non_string_is_refused_rather_than_permitted() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(r"on_tool_call(function() return true end)", "wrong.lua")
.expect("loads");
let echo = Echo;
let guarded = registry.guard(&echo);
let error = guarded
.run(&serde_json::json!({}))
.await
.expect_err("must not silently allow");
assert!(error.to_string().contains("wrong.lua"), "{error}");
}
#[tokio::test]
async fn the_guarded_tool_reports_the_same_definition_as_the_inner_one() {
let registry = Registry::new(&denying()).expect("builds");
let echo = Echo;
let guarded = registry.guard(&echo);
assert_eq!(guarded.def().name, echo.def().name);
assert_eq!(guarded.def().schema, echo.def().schema);
}
#[tokio::test]
async fn a_runaway_loop_is_interrupted_rather_than_hanging_the_agent() {
let mut registry = Registry::new(&denying()).expect("builds");
registry
.load_source(
r#"host.register_tool("spin", "Never returns", {}, function() while true do end end)"#,
"spin.lua",
)
.expect("loads");
let tools = registry.tools();
let spinning = tools
.iter()
.find(|tool| tool.name() == "spin")
.expect("the tool is registered");
let error = spinning
.clone()
.with_timeout(std::time::Duration::from_secs(5))
.run(&serde_json::json!({}))
.await
.expect_err("must be interrupted");
assert!(
error.to_string().contains("spin"),
"the error should name the tool: {error}"
);
}
}