yk-lua 0.1.0

Extensions written in Lua, running in an embedded Luau VM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! A tool whose body is a Lua function.
//!
//! The borrow is the design. A Lua callback only exists while its VM does, so
//! [`LuaTool`] holds references rather than cloned values and the tools cannot
//! outlive the registry that made them.

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};
/// The built-in tool names, which a script may not shadow.
///
/// Redefining `read` or `bash` would let an extension intercept every call the
/// agent makes, which turns "an extension adds a tool" into "an extension owns
/// the agent". Replacement is refused rather than given precedence.
const BUILTINS: [&str; 4] = ["read", "write", "edit", "bash"];

/// Whether `name` is one of the built-in tools.
#[must_use]
pub fn is_builtin(name: &str) -> bool {
    BUILTINS.contains(&name)
}

/// Any tool wrapped so an extension's `on_tool_call` hooks see it.
///
/// This is the reduction primitive adds. Before it, an extension could
/// only add a tool; now one can refuse a call, including a call to a built-in.
/// The wrapper is transparent in both directions: `def` is the inner tool's, so
/// the model sees an unchanged tool list, and `run` only differs when a hook
/// vetoes.
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<'_> {
    /// Ask each hook, in load order, whether this call may proceed.
    ///
    /// The first hook with an opinion wins. A hook that raises blocks the call,
    /// matching pi's fail-safe on its own `tool_call` event: a guard that cannot
    /// decide has not allowed anything.
    ///
    /// # Errors
    ///
    /// [`Error::Tool`] when a hook refuses the call or raises.
    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 {
                    // No opinion, or an empty reason, which is not a reason.
                    Value::Nil => {}
                    Value::String(text) if text.as_bytes().is_empty() => {}
                    Value::String(text) => return Ok(Some(text.to_string_lossy())),
                    // Anything else is unusable rather than permissive.
                    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)
    }

    /// Arm this registry's budget for one call, so a hook is bounded too.
    fn arm(&self, tool: &str) -> Result<()> {
        budget_for(self.budget, tool)?.arm(crate::TOOL_TIMEOUT);
        Ok(())
    }

    /// Clear this registry's budget after one call.
    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;

        // Arm around the veto too. A hook is Lua the script registered, so a
        // `while true do end` in one would otherwise wedge the agent: the tool
        // call below arms the budget, but the hook runs before it.
        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
    }
}

/// A Lua function exposed to the loop as a tool.
///
/// The description and schema come from the manifest at construction, because
/// `def` is what the model reads and a tool that arrives with an empty one is a
/// bare name the model cannot call.
#[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,
        }
    }

    /// Cap how long one call may run.
    ///
    /// Best effort, not a guarantee: the Luau interrupt fires at any call or
    /// loop iteration, so a single long native function still finishes. The
    /// interrupt is best effort, not a guarantee.
    #[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<'_> {
    /// What the model is told about this tool.
    ///
    /// A `Lua`-registered tool and a built-in one are the same `ToolDef`, which
    /// holds only if this returns the manifest's own description and schema.
    /// Returning an empty pair made every extension tool a bare name, in print
    /// mode, the terminal, and ACP alike.
    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}"),
        })?;

        // Arm the budget for this call. The lock is released immediately; the
        // interrupt takes it briefly, so nothing awaits while it is held.
        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:?}")),
        }
    }
}

/// This registry's execution budget, or the error for a poisoned lock.
///
/// A poisoned lock means a thread panicked while holding it, which in practice
/// means a Lua execution panicked. The budget is global to the registry, so the
/// inner value is still usable and the error says what happened.
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(),
    })
}

/// A Lua error as a model can act on.
#[must_use]
fn error_for_model(error: &mlua::Error) -> String {
    match error {
        mlua::Error::RuntimeError(message) => message.clone(),
        mlua::Error::CallbackError { traceback, cause } => {
            // The cause carries the message the script actually raised; the
            // traceback only says where. Dropping the cause is how a failing
            // callback reaches the model as a bare traceback with no reason.
            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};
    // `Host` is imported under its own name: `as _` would leave `Arc<dyn Host>`
    // with no trait to resolve to.
    use crate::{DenyHost, Host, Registry};

    fn denying() -> Arc<dyn Host> {
        Arc::new(DenyHost)
    }

    /// A stand-in for a built-in, so the guard can be tested against something
    /// that is not a Lua tool.
    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}");
    }

    // ---- on_tool_call, ----

    #[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();
        // Fail safe, as pi does, and the message names the file.
        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");

        // A different name passes, which is the property that makes a targeted
        // guard usable rather than a blanket deny.
        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() {
        // The single reason yk chose Luau over PUC Lua. On PUC Lua there
        // is no interrupt at all and this test would hang rather than fail.
        //
        // This test was ignored once: the old interrupt yielded on expiry, and
        // a yield in a coroutine that wakes itself is an infinite poll loop, so
        // it wedged the suite instead of failing. The interrupt now raises, so
        // the loop ends at the instruction limit. The timeout is long enough
        // that the instruction limit is what fires, which is the point.
        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}"
        );
    }
}