Skip to main content

yk_lua/
tool.rs

1//! A tool whose body is a Lua function.
2//!
3//! The borrow is the design. A Lua callback only exists while its VM does, so
4//! [`LuaTool`] holds references rather than cloned values and the tools cannot
5//! outlive the registry that made them.
6
7use std::sync::Mutex;
8use std::time::Duration;
9
10use mlua::{Lua, LuaSerdeExt, MultiValue, Value};
11use serde_json::Value as Json;
12use yk_core::{Error, Result, Tool, ToolDef};
13
14use crate::{ExecutionBudget, Hook};
15/// The built-in tool names, which a script may not shadow.
16///
17/// Redefining `read` or `bash` would let an extension intercept every call the
18/// agent makes, which turns "an extension adds a tool" into "an extension owns
19/// the agent". Replacement is refused rather than given precedence.
20const BUILTINS: [&str; 4] = ["read", "write", "edit", "bash"];
21
22/// Whether `name` is one of the built-in tools.
23#[must_use]
24pub fn is_builtin(name: &str) -> bool {
25    BUILTINS.contains(&name)
26}
27
28/// Any tool wrapped so an extension's `on_tool_call` hooks see it.
29///
30/// This is the reduction primitive adds. Before it, an extension could
31/// only add a tool; now one can refuse a call, including a call to a built-in.
32/// The wrapper is transparent in both directions: `def` is the inner tool's, so
33/// the model sees an unchanged tool list, and `run` only differs when a hook
34/// vetoes.
35pub struct HookGuardedTool<'a> {
36    pub(crate) inner: &'a dyn Tool,
37    pub(crate) lua: &'a Lua,
38    pub(crate) hooks: &'a [Hook],
39    pub(crate) budget: &'a Mutex<ExecutionBudget>,
40}
41
42impl HookGuardedTool<'_> {
43    /// Ask each hook, in load order, whether this call may proceed.
44    ///
45    /// The first hook with an opinion wins. A hook that raises blocks the call,
46    /// matching pi's fail-safe on its own `tool_call` event: a guard that cannot
47    /// decide has not allowed anything.
48    ///
49    /// # Errors
50    ///
51    /// [`Error::Tool`] when a hook refuses the call or raises.
52    async fn veto(&self, name: &str, args: &Json) -> Result<Option<String>> {
53        for hook in self.hooks {
54            let converted = self.lua.to_value(args).map_err(|error| Error::Tool {
55                tool: name.to_owned(),
56                reason: format!("arguments could not be passed to a hook: {error}"),
57            })?;
58
59            let name_value = self.lua.create_string(name).map_err(|error| Error::Tool {
60                tool: name.to_owned(),
61                reason: format!("the tool name could not be passed to a hook: {error}"),
62            })?;
63
64            let returned = hook
65                .callback
66                .call_async::<MultiValue>(MultiValue::from_iter([
67                    Value::String(name_value),
68                    converted,
69                ]))
70                .await;
71
72            let values = match returned {
73                Ok(values) => values,
74                Err(error) => {
75                    return Err(Error::Tool {
76                        tool: name.to_owned(),
77                        reason: format!(
78                            "{} blocked the call: {}",
79                            hook.source,
80                            error_for_model(&error)
81                        ),
82                    });
83                }
84            };
85
86            for value in values {
87                match value {
88                    // No opinion, or an empty reason, which is not a reason.
89                    Value::Nil => {}
90                    Value::String(text) if text.as_bytes().is_empty() => {}
91                    Value::String(text) => return Ok(Some(text.to_string_lossy())),
92                    // Anything else is unusable rather than permissive.
93                    other => {
94                        return Err(Error::Tool {
95                            tool: name.to_owned(),
96                            reason: format!(
97                                "{} returned {other:?} from on_tool_call; \
98                                 return nil or a reason string",
99                                hook.source
100                            ),
101                        });
102                    }
103                }
104            }
105        }
106        Ok(None)
107    }
108
109    /// Arm this registry's budget for one call, so a hook is bounded too.
110    fn arm(&self, tool: &str) -> Result<()> {
111        budget_for(self.budget, tool)?.arm(crate::TOOL_TIMEOUT);
112        Ok(())
113    }
114
115    /// Clear this registry's budget after one call.
116    fn clear(&self, tool: &str) -> Result<()> {
117        budget_for(self.budget, tool)?.clear();
118        Ok(())
119    }
120}
121
122#[async_trait::async_trait]
123impl Tool for HookGuardedTool<'_> {
124    fn def(&self) -> ToolDef {
125        self.inner.def()
126    }
127
128    async fn run(&self, args: &Json) -> Result<String> {
129        let name = self.def().name;
130
131        // Arm around the veto too. A hook is Lua the script registered, so a
132        // `while true do end` in one would otherwise wedge the agent: the tool
133        // call below arms the budget, but the hook runs before it.
134        self.arm(&name)?;
135        let outcome = match self.veto(&name, args).await {
136            Ok(Some(reason)) => Err(Error::Tool {
137                tool: name.clone(),
138                reason,
139            }),
140            Ok(None) => self.inner.run(args).await,
141            Err(error) => Err(error),
142        };
143        self.clear(&name)?;
144        outcome
145    }
146}
147
148/// A Lua function exposed to the loop as a tool.
149///
150/// The description and schema come from the manifest at construction, because
151/// `def` is what the model reads and a tool that arrives with an empty one is a
152/// bare name the model cannot call.
153#[derive(Clone)]
154pub struct LuaTool<'a> {
155    lua: &'a Lua,
156    name: String,
157    description: String,
158    schema: Json,
159    callback: &'a mlua::Function,
160    timeout: Duration,
161    budget: &'a Mutex<ExecutionBudget>,
162}
163
164impl<'a> LuaTool<'a> {
165    #[must_use]
166    pub const fn new(
167        lua: &'a Lua,
168        name: String,
169        description: String,
170        schema: Json,
171        callback: &'a mlua::Function,
172        budget: &'a Mutex<ExecutionBudget>,
173    ) -> Self {
174        Self {
175            lua,
176            name,
177            description,
178            schema,
179            callback,
180            timeout: crate::TOOL_TIMEOUT,
181            budget,
182        }
183    }
184
185    /// Cap how long one call may run.
186    ///
187    /// Best effort, not a guarantee: the Luau interrupt fires at any call or
188    /// loop iteration, so a single long native function still finishes. The
189    /// interrupt is best effort, not a guarantee.
190    #[must_use]
191    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
192        self.timeout = timeout;
193        self
194    }
195
196    #[must_use]
197    pub fn name(&self) -> &str {
198        &self.name
199    }
200}
201
202#[async_trait::async_trait]
203impl Tool for LuaTool<'_> {
204    /// What the model is told about this tool.
205    ///
206    /// A `Lua`-registered tool and a built-in one are the same `ToolDef`, which
207    /// holds only if this returns the manifest's own description and schema.
208    /// Returning an empty pair made every extension tool a bare name, in print
209    /// mode, the terminal, and ACP alike.
210    fn def(&self) -> ToolDef {
211        ToolDef {
212            name: self.name.clone(),
213            description: self.description.clone(),
214            schema: self.schema.clone(),
215        }
216    }
217
218    async fn run(&self, args: &Json) -> Result<String> {
219        let converted = self.lua.to_value(args).map_err(|error| Error::Tool {
220            tool: self.name.clone(),
221            reason: format!("arguments could not be passed to lua: {error}"),
222        })?;
223
224        // Arm the budget for this call. The lock is released immediately; the
225        // interrupt takes it briefly, so nothing awaits while it is held.
226        budget_for(self.budget, &self.name)?.arm(self.timeout);
227
228        let returned = self
229            .callback
230            .call_async::<mlua::MultiValue>(converted)
231            .await
232            .map_err(|error| Error::Tool {
233                tool: self.name.clone(),
234                reason: error_for_model(&error),
235            })?;
236
237        budget_for(self.budget, &self.name)?.clear();
238
239        match returned.into_iter().next() {
240            None | Some(Value::Nil) => Ok(String::new()),
241            Some(Value::String(text)) => Ok(text.to_string_lossy()),
242            Some(other) => Ok(format!("{other:?}")),
243        }
244    }
245}
246
247/// This registry's execution budget, or the error for a poisoned lock.
248///
249/// A poisoned lock means a thread panicked while holding it, which in practice
250/// means a Lua execution panicked. The budget is global to the registry, so the
251/// inner value is still usable and the error says what happened.
252fn budget_for<'a>(
253    budget: &'a Mutex<ExecutionBudget>,
254    tool: &str,
255) -> Result<std::sync::MutexGuard<'a, ExecutionBudget>> {
256    budget.lock().map_err(|_| Error::Tool {
257        tool: tool.to_owned(),
258        reason: "the execution lock was poisoned".to_owned(),
259    })
260}
261
262/// A Lua error as a model can act on.
263#[must_use]
264fn error_for_model(error: &mlua::Error) -> String {
265    match error {
266        mlua::Error::RuntimeError(message) => message.clone(),
267        mlua::Error::CallbackError { traceback, cause } => {
268            // The cause carries the message the script actually raised; the
269            // traceback only says where. Dropping the cause is how a failing
270            // callback reaches the model as a bare traceback with no reason.
271            let traceback = traceback.trim();
272            if traceback.is_empty() {
273                cause.to_string()
274            } else {
275                format!("{cause}\n{traceback}")
276            }
277        }
278        mlua::Error::ExternalError(inner) => inner.to_string(),
279        other => other.to_string(),
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    #![allow(
286        clippy::unwrap_used,
287        clippy::expect_used,
288        clippy::indexing_slicing,
289        clippy::as_conversions,
290        clippy::arithmetic_side_effects
291    )]
292
293    use std::sync::Arc;
294
295    use yk_core::Tool as _;
296
297    use super::{error_for_model, is_builtin};
298    // `Host` is imported under its own name: `as _` would leave `Arc<dyn Host>`
299    // with no trait to resolve to.
300    use crate::{DenyHost, Host, Registry};
301
302    fn denying() -> Arc<dyn Host> {
303        Arc::new(DenyHost)
304    }
305
306    /// A stand-in for a built-in, so the guard can be tested against something
307    /// that is not a Lua tool.
308    struct Echo;
309
310    #[async_trait::async_trait]
311    impl yk_core::Tool for Echo {
312        fn def(&self) -> yk_core::ToolDef {
313            yk_core::ToolDef {
314                name: "echo".to_owned(),
315                description: "Returns its argument".to_owned(),
316                schema: serde_json::json!({"type": "object"}),
317            }
318        }
319
320        async fn run(&self, args: &serde_json::Value) -> yk_core::Result<String> {
321            Ok(args.to_string())
322        }
323    }
324
325    #[test]
326    fn the_four_builtins_are_recognised() {
327        for name in ["read", "write", "edit", "bash"] {
328            assert!(is_builtin(name), "{name}");
329        }
330        assert!(!is_builtin("shout"));
331    }
332
333    #[test]
334    fn a_builtin_name_is_not_a_prefix_match() {
335        assert!(!is_builtin("bash_history"));
336        assert!(!is_builtin("readme"));
337    }
338
339    #[test]
340    fn a_runtime_error_keeps_its_message() {
341        let text = error_for_model(&mlua::Error::RuntimeError("boom".to_owned()));
342        assert!(text.contains("boom"), "{text}");
343    }
344
345    #[test]
346    fn a_syntax_error_keeps_its_message() {
347        let error = mlua::Error::SyntaxError {
348            message: "unexpected token".to_owned(),
349            incomplete_input: false,
350        };
351        let text = error_for_model(&error);
352        assert!(text.contains("unexpected token"), "{text}");
353    }
354
355    #[tokio::test]
356    async fn a_registered_tool_returns_its_string() {
357        let mut registry = Registry::new(&denying()).expect("builds");
358        registry
359            .load_source(
360                r#"
361                host.register_tool("shout", "Shout", {}, function(args)
362                    return string.upper(args.word)
363                end)
364                "#,
365                "shout.lua",
366            )
367            .expect("loads");
368
369        let tools = registry.tools();
370        let shouting = tools.first().expect("the tool is registered");
371        let out = shouting
372            .run(&serde_json::json!({"word": "hi"}))
373            .await
374            .expect("runs");
375        assert_eq!(out, "HI");
376    }
377
378    #[tokio::test]
379    async fn a_tool_returning_nothing_is_empty_rather_than_an_error() {
380        let mut registry = Registry::new(&denying()).expect("builds");
381        registry
382            .load_source(
383                r#"host.register_tool("quiet", "Says nothing", {}, function() end)"#,
384                "quiet.lua",
385            )
386            .expect("loads");
387
388        let tools = registry.tools();
389        let quiet = tools.first().expect("the tool is registered");
390        let out = quiet.run(&serde_json::json!({})).await.expect("runs");
391        assert_eq!(out, "");
392    }
393
394    #[tokio::test]
395    async fn a_tool_that_raises_reaches_the_model_as_an_error() {
396        let mut registry = Registry::new(&denying()).expect("builds");
397        registry
398            .load_source(
399                r#"host.register_tool("boom", "Raises", {}, function() error("kaboom") end)"#,
400                "boom.lua",
401            )
402            .expect("loads");
403
404        let tools = registry.tools();
405        let boom = tools.first().expect("the tool is registered");
406        let error = boom
407            .run(&serde_json::json!({}))
408            .await
409            .expect_err("must fail");
410        assert!(error.to_string().contains("kaboom"), "{error}");
411    }
412
413    // ---- on_tool_call, ----
414
415    #[tokio::test]
416    async fn a_hook_returning_nil_lets_the_call_through() {
417        let mut registry = Registry::new(&denying()).expect("builds");
418        registry
419            .load_source(r"on_tool_call(function() end)", "pass.lua")
420            .expect("loads");
421
422        let echo = Echo;
423        let guarded = registry.guard(&echo);
424        let out = guarded
425            .run(&serde_json::json!({"a": 1}))
426            .await
427            .expect("runs");
428        assert!(out.contains('a'), "{out}");
429    }
430
431    #[tokio::test]
432    async fn a_hook_returning_a_reason_blocks_the_call() {
433        let mut registry = Registry::new(&denying()).expect("builds");
434        registry
435            .load_source(
436                r#"on_tool_call(function(name)
437                    if name == "echo" then return "block: this repo is read-only" end
438                end)"#,
439                "guard.lua",
440            )
441            .expect("loads");
442
443        let echo = Echo;
444        let guarded = registry.guard(&echo);
445        let error = guarded
446            .run(&serde_json::json!({}))
447            .await
448            .expect_err("must be blocked");
449        let text = error.to_string();
450        assert!(text.contains("read-only"), "{text}");
451        assert!(text.contains("echo"), "{text}");
452    }
453
454    #[tokio::test]
455    async fn a_hook_that_raises_blocks_rather_than_failing_open() {
456        let mut registry = Registry::new(&denying()).expect("builds");
457        registry
458            .load_source(
459                r#"on_tool_call(function() error("hook is broken") end)"#,
460                "broken.lua",
461            )
462            .expect("loads");
463
464        let echo = Echo;
465        let guarded = registry.guard(&echo);
466        let error = guarded
467            .run(&serde_json::json!({}))
468            .await
469            .expect_err("must fail safe");
470        let text = error.to_string();
471        // Fail safe, as pi does, and the message names the file.
472        assert!(text.contains("broken.lua"), "{text}");
473        assert!(text.contains("hook is broken"), "{text}");
474    }
475
476    #[tokio::test]
477    async fn the_first_hook_with_an_opinion_wins() {
478        let mut registry = Registry::new(&denying()).expect("builds");
479        registry
480            .load_source(r"on_tool_call(function() end)", "first.lua")
481            .expect("loads");
482        registry
483            .load_source(
484                r#"on_tool_call(function() return "block: second says no" end)"#,
485                "second.lua",
486            )
487            .expect("loads");
488
489        assert_eq!(registry.hooks().len(), 2);
490
491        let echo = Echo;
492        let guarded = registry.guard(&echo);
493        let error = guarded
494            .run(&serde_json::json!({}))
495            .await
496            .expect_err("must be blocked");
497        assert!(error.to_string().contains("second says no"), "{error}");
498    }
499
500    #[tokio::test]
501    async fn a_hook_only_sees_the_tool_it_was_wired_to() {
502        let mut registry = Registry::new(&denying()).expect("builds");
503        registry
504            .load_source(
505                r#"on_tool_call(function(name)
506                    if name == "bash" then return "block: no shells here" end
507                end)"#,
508                "only_bash.lua",
509            )
510            .expect("loads");
511
512        // A different name passes, which is the property that makes a targeted
513        // guard usable rather than a blanket deny.
514        let echo = Echo;
515        let guarded = registry.guard(&echo);
516        guarded
517            .run(&serde_json::json!({}))
518            .await
519            .expect("a different tool still runs");
520    }
521
522    #[tokio::test]
523    async fn a_hook_receives_the_name_and_the_arguments() {
524        let mut registry = Registry::new(&denying()).expect("builds");
525        registry
526            .load_source(
527                r#"on_tool_call(function(name, args)
528                    if args.path == "/etc/passwd" then
529                        return "block: " .. name
530                    end
531                end)"#,
532                "reads_args.lua",
533            )
534            .expect("loads");
535
536        let echo = Echo;
537        let guarded = registry.guard(&echo);
538        let error = guarded
539            .run(&serde_json::json!({"path": "/etc/passwd"}))
540            .await
541            .expect_err("must be blocked");
542        assert!(error.to_string().contains("echo"), "{error}");
543
544        guarded
545            .run(&serde_json::json!({"path": "Cargo.toml"}))
546            .await
547            .expect("another path still runs");
548    }
549
550    #[tokio::test]
551    async fn a_hook_returning_a_non_string_is_refused_rather_than_permitted() {
552        let mut registry = Registry::new(&denying()).expect("builds");
553        registry
554            .load_source(r"on_tool_call(function() return true end)", "wrong.lua")
555            .expect("loads");
556
557        let echo = Echo;
558        let guarded = registry.guard(&echo);
559        let error = guarded
560            .run(&serde_json::json!({}))
561            .await
562            .expect_err("must not silently allow");
563        assert!(error.to_string().contains("wrong.lua"), "{error}");
564    }
565
566    #[tokio::test]
567    async fn the_guarded_tool_reports_the_same_definition_as_the_inner_one() {
568        let registry = Registry::new(&denying()).expect("builds");
569        let echo = Echo;
570        let guarded = registry.guard(&echo);
571        assert_eq!(guarded.def().name, echo.def().name);
572        assert_eq!(guarded.def().schema, echo.def().schema);
573    }
574
575    #[tokio::test]
576    async fn a_runaway_loop_is_interrupted_rather_than_hanging_the_agent() {
577        // The single reason yk chose Luau over PUC Lua. On PUC Lua there
578        // is no interrupt at all and this test would hang rather than fail.
579        //
580        // This test was ignored once: the old interrupt yielded on expiry, and
581        // a yield in a coroutine that wakes itself is an infinite poll loop, so
582        // it wedged the suite instead of failing. The interrupt now raises, so
583        // the loop ends at the instruction limit. The timeout is long enough
584        // that the instruction limit is what fires, which is the point.
585        let mut registry = Registry::new(&denying()).expect("builds");
586        registry
587            .load_source(
588                r#"host.register_tool("spin", "Never returns", {}, function() while true do end end)"#,
589                "spin.lua",
590            )
591            .expect("loads");
592
593        let tools = registry.tools();
594        let spinning = tools
595            .iter()
596            .find(|tool| tool.name() == "spin")
597            .expect("the tool is registered");
598
599        let error = spinning
600            .clone()
601            .with_timeout(std::time::Duration::from_secs(5))
602            .run(&serde_json::json!({}))
603            .await
604            .expect_err("must be interrupted");
605
606        assert!(
607            error.to_string().contains("spin"),
608            "the error should name the tool: {error}"
609        );
610    }
611}