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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! The embedded Luau VM, and the sandbox around it.
//!
//! Everything here follows Roblox's published guidance for embedding Luau with
//! untrusted code, because Roblox runs millions of hostile scripts on this
//! exact VM and has written down what it took.
//!
//! **Library globals are read-only at the VM level.** `sandbox(true)` marks the
//! library tables, the string metatable, and the global table readonly in a way
//! that blocks `rawset` and `setmetatable` too, not just assignment. PUC Lua
//! has no equivalent primitive, which is one reason yk chose Luau.
//!
//! **The unsafe libraries are never loaded.** Seven libraries are requested:
//! `coroutine`, `table`, `string`, `math`, `utf8`, `bit32`, and `buffer`, so
//! `os`, `io`, `package`, `debug`, and `ffi` do not exist. That is a whitelist:
//! a blacklist leaves `package.loadlib` reachable, which is the documented
//! escape. `os` is not on the list: Luau's `os` registers exactly `clock`,
//! `date`, `difftime`, and `time`, with no `execute`, but the requirement is a
//! whitelist with no dangerous library in it and `os` is on the list. It comes
//! out.
//!
//! **Bytecode is never loaded.** `set_mode("t")` refuses binary chunks, which is
//! the escape Lua workshop documented for 5.1.
//!
//! **A runaway script is stopped by an instruction limit.** The interrupt
//! fires at any function call or loop iteration, and a counter bounds how many
//! firings one execution may have. `while true do end` returns an error
//! rather than wedging the agent. This is the other reason for Luau: `mlua`
//! exposes no equivalent on PUC Lua.
//!
//! **Memory is capped.** The interrupt does not stop a script that allocates
//! without calling anything.
//!
//! **The process gateway is `runner`.** An extension that needs a file, a
//! network service, or another binary asks the host to run a process. The
//! child is a separate OS process: isolated by the kernel, killable by the
//! host, and unable to touch agent memory. There is no FFI, no `ffi` library,
//! and no native module loading, in any dialect, ever.
//!
//! What this is *not*: a memory-isolated process. There is one heap per
//! `lua_State`, not per script. The session survives a crash because it is
//! append-only.

mod host;
mod runner;
mod tool;

use std::collections::BTreeMap;
use std::ops::BitOr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use mlua::{Lua, LuaSerdeExt, MultiValue, StdLib, VmState};
use yk_core::{Error, Result};

pub use host::{
    DenyHost, ExtensionSources, Host, HttpResponse, extension_sources, session_dir, user_dir,
};
pub use tool::{HookGuardedTool, LuaTool, is_builtin};

/// Cap on the Lua heap. The interrupt does not stop an allocating loop.
const MEMORY_LIMIT: usize = 64 * 1024 * 1024;

/// How many interrupt firings one execution may have.
///
/// The interrupt fires on every function call and loop iteration, so this is
/// not a true instruction count. It is a work limit: each firing is a call or
/// an iteration, and the count bounds how much of either a script can do
/// between checks. `while true do end` hits it in milliseconds; a script
/// that does real work does not.
///
/// The wall-clock deadline stays as a backstop for long-running native calls,
/// which the interrupt cannot reach. The instruction limit is the guarantee.
const INSTRUCTION_LIMIT: u64 = 1_000_000;

/// The libraries an extension may use.
///
/// Named one at a time rather than derived from `ALL_SAFE`, which under Luau is
/// `StdLib(u32::MAX)`: every flag, `debug` included. A derived set would hand a
/// script the debug library, which is the one omission here that is a real
/// capability rather than a build fact.
///
/// What is loaded and why:
///
/// - `utf8`, `bit32`, and `buffer` are pure.
/// - `os` is out. Luau's `os` registers exactly `clock`, `date`, `difftime`,
///   and `time`, with no `execute`, but the requirement is a whitelist with no
///   dangerous library in it and `os` is on the list. Redis reached the same
///   place from the other direction, running with no `os` at all until version
///   7.4 exposed `os.clock` alone.
/// - `debug` is out because Luau trims it to `traceback` and `info`, and the
///   reason is partly memory safety rather than reach.
/// - `io`, `package`, and `ffi` are not choices. `StdLib::IO` and
///   `StdLib::PACKAGE` are `#[cfg(not(feature = "luau"))]` and `StdLib::FFI` is
///   `LuaJIT`'s, so under the `luau` feature they are not constants at all.
///
/// None of this is an authority boundary. `bash` already reaches anything the
/// user can reach, and the docs say so plainly.
fn safe_libs() -> StdLib {
    StdLib::COROUTINE
        .bitor(StdLib::TABLE)
        .bitor(StdLib::STRING)
        .bitor(StdLib::MATH)
        .bitor(StdLib::UTF8)
        .bitor(StdLib::BIT)
        .bitor(StdLib::BUFFER)
}

/// The deadline a single execution gets by default.
///
/// The interrupt fires at any call or loop iteration, so the deadline is
/// checked when the script next runs; a native call already in progress is not
/// aborted. `runner` bounds its child at the same value, so a stuck child is
/// killed rather than waiting for the script to resume.
pub const TOOL_TIMEOUT: Duration = Duration::from_secs(10);

/// What an extension declared. Kept whole so the tool can borrow its callback.
#[derive(Clone, Debug)]
pub struct ToolInfo {
    pub name: String,
    pub description: String,
    pub schema: serde_json::Value,
    pub callback: mlua::Function,
}

/// A hook an extension registered through `on_tool_call`.
///
/// `source` is the script that registered it, so a hook that raises blocks the
/// call with a message naming the file rather than saying "a hook failed".
#[derive(Clone, Debug)]
pub struct Hook {
    pub source: String,
    pub callback: mlua::Function,
}

/// The embedded VM and everything registered against it.
pub struct Registry {
    lua: Lua,
    tools: BTreeMap<String, ToolInfo>,
    hooks: Vec<Hook>,
    budget: Arc<Mutex<ExecutionBudget>>,
}

/// The per-execution budget, shared between the registry and its tools.
///
/// One execution is one budget: a script load, a tool call, or a hook. The
/// budget is armed before the execution and cleared after, so the limits apply
/// to a single execution and not to the sum of every execution a script has
/// made.
///
/// There is one `ExecutionBudget` per registry, so exactly one execution may be
/// armed at a time. The agent loop dispatches tool calls one at a time, and
/// nothing else runs Lua concurrently, so that holds today. Two overlapping
/// executions would share the counter and the later `clear` would disarm the
/// earlier one; a stack of budgets would make overlap safe if the loop ever
/// runs calls in parallel.
#[derive(Default)]
pub struct ExecutionBudget {
    /// Wall-clock deadline, armed for one execution.
    deadline: Option<Instant>,
    /// How many times the interrupt has fired this budget. Each firing is a
    /// function call or loop iteration, so the count bounds the work a script
    /// can do between checks.
    instructions: u64,
}

impl ExecutionBudget {
    /// Arm the budget for one execution: a fresh deadline and a fresh count.
    pub(crate) fn arm(&mut self, timeout: Duration) {
        self.deadline = Instant::now().checked_add(timeout);
        self.instructions = 0;
    }

    /// Clear the budget after one execution.
    pub(crate) const fn clear(&mut self) {
        self.deadline = None;
        self.instructions = 0;
    }
}

impl Registry {
    /// Build a sandboxed VM. The `host` table is installed after this returns.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the VM cannot be created or sandboxed, which
    /// in practice means the Luau build is broken rather than anything here.
    pub fn new(host: &Arc<dyn Host>) -> Result<Self> {
        // `new_with` is the safe constructor: it cannot load C modules at all.
        let lua = Lua::new_with(safe_libs(), mlua::LuaOptions::default())
            .map_err(|e| Error::Malformed(format!("could not create the luau vm: {e}")))?;

        // VM-level readonly tables. This is the primitive PUC Lua does not have.
        lua.sandbox(true)
            .map_err(|e| Error::Malformed(format!("could not sandbox the vm: {e}")))?;

        // Best effort. A VM that refuses the cap is still correct, just less
        // bounded, so this must not be a hard failure.
        let _ = lua.set_memory_limit(MEMORY_LIMIT);

        let budget = Arc::new(Mutex::new(ExecutionBudget::default()));

        {
            let flag = Arc::clone(&budget);
            lua.set_interrupt(move |_lua| {
                let mut guard = flag.lock().map_err(|_| {
                    mlua::Error::RuntimeError("the execution lock was poisoned".to_owned())
                })?;

                // Only count when the budget is armed, which is during a load,
                // a tool call, or a hook. The interrupt fires at those points
                // and nowhere else.
                if guard.deadline.is_some() {
                    guard.instructions = guard.instructions.saturating_add(1);
                    if guard.instructions > INSTRUCTION_LIMIT {
                        return Err(mlua::Error::RuntimeError(format!(
                            "the script exceeded the instruction limit of {INSTRUCTION_LIMIT}"
                        )));
                    }
                }

                // An error, not a yield. A yield only happens at yieldable
                // points, and in a coroutine the async future wakes itself and
                // re-polls, resuming the loop, which hits the interrupt again.
                // That is an infinite poll loop, not a stop. An error
                // propagates through the Lua code and violently terminates
                // the script.
                if guard.deadline.is_some_and(|at| Instant::now() >= at) {
                    return Err(mlua::Error::RuntimeError("the script timed out".to_owned()));
                }

                drop(guard);
                Ok(VmState::Continue)
            });
        }

        let registry = Self {
            lua,
            tools: BTreeMap::new(),
            hooks: Vec::new(),
            budget,
        };
        registry.install_host(host)?;
        Ok(registry)
    }

    /// The one host member that is not a capability: `register_tool`.
    ///
    /// The documented form is positional. A table is also accepted, because
    /// it reads better when one script registers several tools.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the closure cannot be built.
    fn register_tool_function(&self) -> Result<mlua::Function> {
        let lua = &self.lua;
        lua.create_function(|lua, passed: MultiValue| {
            let mut it = passed.into_iter();
            let first = it.next().ok_or_else(|| {
                mlua::Error::RuntimeError("register_tool needs a name".to_owned())
            })?;

            // Positional is the documented form. A table is also accepted, because it
            // reads better when one script registers several tools.
            let (name, description, raw_schema, callback) = match &first {
                mlua::Value::Table(table) => (
                    table.get::<String>("name").map_err(|_| {
                        mlua::Error::RuntimeError("register_tool needs a name".to_owned())
                    })?,
                    table.get::<String>("description").unwrap_or_default(),
                    table
                        .get::<mlua::Value>("schema")
                        .unwrap_or(mlua::Value::Nil),
                    table.get::<mlua::Function>("callback").map_err(|_| {
                        mlua::Error::RuntimeError("register_tool needs a callback".to_owned())
                    })?,
                ),
                mlua::Value::String(name) => {
                    let name = name.to_string_lossy();
                    let description = it
                        .next()
                        .map_or_else(String::new, |value| value.to_string().unwrap_or_default());
                    let raw_schema = it.next().unwrap_or(mlua::Value::Nil);
                    let callback = it
                        .next()
                        .and_then(|value| value.as_function().cloned())
                        .ok_or_else(|| {
                            mlua::Error::RuntimeError("register_tool needs a callback".to_owned())
                        })?;
                    (name, description, raw_schema, callback)
                }
                _ => {
                    return Err(mlua::Error::RuntimeError(
                        "register_tool takes a name, or a table with one".to_owned(),
                    ));
                }
            };

            let schema = if raw_schema.is_nil() {
                serde_json::json!({"type": "object"})
            } else {
                lua.from_value(raw_schema)
                    .map_err(|e| mlua::Error::RuntimeError(format!("register_tool schema: {e}")))?
            };

            stage(
                &STAGED,
                ToolInfo {
                    name,
                    description,
                    schema,
                    callback,
                },
            );
            Ok::<(), mlua::Error>(())
        })
        .map_err(|e| lua_error(&e))
    }

    /// The one capability that is not: `on_tool_call`, which lets an extension
    /// refuse a call rather than only add one.
    ///
    /// A separate global rather than a fourth `host` member, because `host` is
    /// frozen at six capabilities plus `register_tool` and this is a different
    /// kind of thing: it is not reach, it is the absence of reach.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the closure cannot be built.
    fn on_tool_call_function(&self) -> Result<mlua::Function> {
        let lua = &self.lua;
        lua.create_function(|_, callback: mlua::Function| {
            stage(&STAGED_HOOKS, callback);
            Ok::<(), mlua::Error>(())
        })
        .map_err(|e| lua_error(&e))
    }

    /// Put the `host` table in front of scripts.
    ///
    /// Each of these is a capability the built-in tools can already do. Adding
    /// one is cheap and expected; renaming or repurposing one is a breaking
    /// change to every script ever written. Three of them, added later, turn
    /// a script from a reader into a participant.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the table cannot be built.
    fn install_host(&self, host: &Arc<dyn Host>) -> Result<()> {
        let lua = &self.lua;
        let table = lua.create_table().map_err(|e| lua_error(&e))?;
        // The closures capture the `Arc` directly. `mlua` requires them to be
        // `'static`, and an owned handle is both that and simpler than any
        // out-of-band lookup.
        {
            let host = Arc::clone(host);
            let read_file = lua
                // A plain closure that *returns* a future, not an `async`
                // closure: an async closure is not `Fn`, and mlua's bound is `Fn`.
                .create_async_function(move |_, path: String| {
                    let host = Arc::clone(&host);
                    async move {
                        host.read_file(Path::new(&path))
                            .await
                            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
                    }
                })
                .map_err(|e| lua_error(&e))?;
            set_capability(&table, "read_file", read_file)?;
        }

        {
            let host = Arc::clone(host);
            let http_get = lua
                .create_async_function(move |_, url: String| {
                    let host = Arc::clone(&host);
                    async move {
                        host.http_get(&url)
                            .await
                            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
                    }
                })
                .map_err(|e| lua_error(&e))?;
            table.set("http_get", http_get).map_err(|e| lua_error(&e))?;
        }

        {
            let post = self.post_json_function(host)?;
            set_capability(&table, "http_post_json", post)?;
        }

        {
            let env = self.env_function(host)?;
            set_capability(&table, "env", env)?;
        }

        {
            let parse = lua
                .create_function(move |lua, text: String| {
                    let parsed: serde_json::Value = serde_json::from_str(&text)
                        .map_err(|e| mlua::Error::RuntimeError(format!("bad json: {e}")))?;
                    lua.to_value(&parsed)
                })
                .map_err(|e| lua_error(&e))?;
            set_capability(&table, "json", parse)?;
        }

        {
            let encode = self.json_encode_function()?;
            set_capability(&table, "json_encode", encode)?;
        }

        set_capability(&table, "register_tool", self.register_tool_function()?)?;

        let globals = lua.globals();
        globals
            .set("host", table)
            .map_err(|e| Error::Malformed(format!("could not install host: {e}")))?;

        globals
            .set("on_tool_call", self.on_tool_call_function()?)
            .map_err(|e| Error::Malformed(format!("could not install on_tool_call: {e}")))?;

        // The process gateway. A separate global rather than a seventh `host`
        // member, because the requirement names a UserData struct and moving
        // it to `host` later is a small change in either direction.
        let runner = lua
            .create_userdata(crate::runner::ProcessRunner)
            .map_err(|e| lua_error(&e))?;
        globals
            .set("runner", runner)
            .map_err(|e| Error::Malformed(format!("could not install runner: {e}")))
    }

    /// `host.http_post_json(url, headers, body)`, returning `{status, body}`.
    ///
    /// A non-2xx status is a value rather than an error, because a script
    /// gating a tool call has to tell "the model answered" apart from "the
    /// vendor is rate-limiting you", and the second one is the case where
    /// failing open is correct.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the closure cannot be built.
    fn post_json_function(&self, host: &Arc<dyn Host>) -> Result<mlua::Function> {
        let host = Arc::clone(host);
        let lua = &self.lua;
        // `Lua` arrives by value and the future must be `'static`, so the VM
        // handle is moved in rather than borrowed. The argument is one tuple
        // because `create_async_function` is `Fn(Lua, FromLuaMulti)`, which is
        // not variadic.
        lua.create_async_function(
            move |lua: mlua::Lua, (url, headers, body): (String, mlua::Table, String)| {
                let host = Arc::clone(&host);
                async move {
                    let sent = lua
                        .from_value::<BTreeMap<String, String>>(mlua::Value::Table(headers))
                        .map_err(|e| {
                            mlua::Error::RuntimeError(format!("headers are not all strings: {e}"))
                        })?;

                    let reply = host
                        .http_post_json(&url, &sent, &body)
                        .await
                        .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;

                    let out = lua.create_table()?;
                    out.set("status", reply.status)?;
                    out.set("body", reply.body)?;
                    Ok(out)
                }
            },
        )
        .map_err(|e| lua_error(&e))
    }

    /// `host.env(name)`, returning a string or nil.
    ///
    /// Synchronous because the environment is already in memory. Making it
    /// `await`able would buy nothing and would cost every caller a `pcall`
    /// around a call that cannot fail.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the closure cannot be built.
    fn env_function(&self, host: &Arc<dyn Host>) -> Result<mlua::Function> {
        let host = Arc::clone(host);
        let lua = &self.lua;
        lua.create_function(move |_, name: String| Ok(host.env(&name)))
            .map_err(|e| lua_error(&e))
    }

    /// `host.json_encode(value)`, the mirror of `host.json`.
    ///
    /// `host.json` decodes and nothing encodes, which made every HTTP API
    /// unreachable without a hand-rolled serializer in the extension. This is
    /// not new reach; it is the other direction of a member that already exists.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the closure cannot be built.
    fn json_encode_function(&self) -> Result<mlua::Function> {
        let lua = &self.lua;
        lua.create_function(move |lua, value: mlua::Value| {
            let as_json: serde_json::Value = lua.from_value(value).map_err(|e| {
                mlua::Error::RuntimeError(format!("value is not representable as json: {e}"))
            })?;
            serde_json::to_string(&as_json)
                .map_err(|e| mlua::Error::RuntimeError(format!("could not encode: {e}")))
        })
        .map_err(|e| lua_error(&e))
    }

    /// Load every `.lua` file in `dir`, in name order.
    ///
    /// # Errors
    ///
    /// [`Error::Read`] when the directory cannot be read. A failing script inside
    /// it is reported by [`Registry::load_dir`] rather than aborting the rest.
    pub fn load_dir(&mut self, dir: &Path) -> Result<Vec<LoadedScript>> {
        if !dir.is_dir() {
            return Ok(Vec::new());
        }

        let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
            .map_err(|source| Error::Read {
                path: dir.display().to_string(),
                source,
            })?
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| path.extension().is_some_and(|ext| ext == "lua"))
            .collect();
        files.sort();

        let mut loaded = Vec::new();
        for file in files {
            // One broken extension must not cost the user every extension.
            match self.load_file(&file) {
                Ok(entry) => loaded.push(entry),
                Err(error) => eprintln!("yk: skipping {}: {error}", file.display()),
            }
        }
        Ok(loaded)
    }

    /// Load one script and register whatever it declared.
    ///
    /// # Errors
    ///
    /// [`Error::Read`] when the file cannot be read, and [`Error::Malformed`] when
    /// the script itself is bad.
    pub fn load_file(&mut self, path: &Path) -> Result<LoadedScript> {
        let source = std::fs::read_to_string(path).map_err(|source| Error::Read {
            path: path.display().to_string(),
            source,
        })?;

        self.load_source(&source, &path.display().to_string())
    }

    /// Load a script from memory.
    ///
    /// # Errors
    ///
    /// [`Error::Malformed`] when the script fails to load or registers something
    /// malformed. The script's name is in the message, so a model that wrote it
    /// can be told which one.
    pub fn load_source(&mut self, source: &str, name: &str) -> Result<LoadedScript> {
        // `set_mode("t")` refuses binary chunks. Without it a crafted bytecode
        // file is a way past every other control in this file.
        let chunk = self
            .lua
            .load(source)
            .set_name(name)
            .set_mode(mlua::chunk::ChunkMode::Text)
            .into_function()
            .map_err(|e| Error::Malformed(format!("{name}: {e}")))?;

        let hooks_before = self.hooks.len();

        take_staged_items(&STAGED);
        take_staged_items(&STAGED_HOOKS);

        // A load runs the script's top level, so it is an execution and gets
        // the same bounds as a tool call. Without this, a top-level
        // `while true do end` wedges startup.
        {
            let mut guard = self.budget.lock().map_err(|_| {
                Error::Malformed(format!("{name}: the execution lock was poisoned"))
            })?;
            guard.arm(TOOL_TIMEOUT);
        }
        let called = chunk.call::<MultiValue>(MultiValue::new());
        {
            let mut guard = self.budget.lock().map_err(|_| {
                Error::Malformed(format!("{name}: the execution lock was poisoned"))
            })?;
            guard.clear();
        }
        called.map_err(|e| Error::Malformed(format!("{name}: {e}")))?;

        for callback in take_staged_items(&STAGED_HOOKS) {
            self.hooks.push(Hook {
                source: name.to_owned(),
                callback,
            });
        }

        let mut tools: Vec<String> = Vec::new();
        for manifest in take_staged_items(&STAGED) {
            tools.push(manifest.name.clone());
            if let Err(error) = self.register(manifest) {
                return Err(Error::Malformed(format!("{name}: {error}")));
            }
        }

        Ok(LoadedScript {
            file: PathBuf::from(name),
            tools,
            hooks: self.hooks.len().saturating_sub(hooks_before),
        })
    }

    /// Wrap a tool so this registry's hooks see every call to it.
    ///
    /// The guard is what makes an extension able to *reduce* the agent's power
    /// rather than only add to it. `yk-core` knows nothing about Lua, so the
    /// check arrives as an ordinary `Tool` and the loop is unchanged.
    #[must_use]
    pub fn guard<'a>(&'a self, inner: &'a dyn yk_core::Tool) -> HookGuardedTool<'a> {
        HookGuardedTool {
            inner,
            lua: &self.lua,
            hooks: &self.hooks,
            budget: &self.budget,
        }
    }

    /// The hooks an extension registered, in load order.
    #[must_use]
    pub fn hooks(&self) -> &[Hook] {
        &self.hooks
    }

    /// The tools, borrowed from this registry.
    ///
    /// This is what the loop is given, so the manifest's description and schema
    /// travel with the tool rather than being read off the registry here. A
    /// second path that built a `ToolDef` from the same manifest is a second
    /// answer to the same question, and it is the one that went unread.
    #[must_use]
    pub fn tools(&self) -> Vec<LuaTool<'_>> {
        self.tools
            .values()
            .map(|manifest| {
                LuaTool::new(
                    &self.lua,
                    manifest.name.clone(),
                    manifest.description.clone(),
                    manifest.schema.clone(),
                    &manifest.callback,
                    &self.budget,
                )
            })
            .collect()
    }

    /// Register a tool, called from `Lua` by a script.
    ///
    /// # Errors
    ///
    /// [`Error::BadArgs`] when the four fields are missing, and
    /// [`Error::Malformed`] when a script tries to take over a built-in.
    pub fn register(&mut self, manifest: ToolInfo) -> Result<()> {
        if manifest.name.is_empty() {
            return Err(Error::BadArgs {
                tool: "register_tool".to_owned(),
                reason: "a tool needs a name".to_owned(),
            });
        }

        if is_builtin(&manifest.name) {
            return Err(Error::Malformed(format!(
                "`{}` is a built-in tool and cannot be replaced",
                manifest.name
            )));
        }

        self.tools.insert(manifest.name.clone(), manifest);
        Ok(())
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// The VM, for a caller that needs to read a value out.
    #[must_use]
    pub const fn lua(&self) -> &Lua {
        &self.lua
    }
}

thread_local! {
    /// Tool registrations a script registered, not yet in the registry.
    ///
    /// A Lua closure cannot borrow `&mut self`, and `register_tool` has to reach
    /// the same map the provider reads. Staging and draining after the script
    /// returns is the smallest thing that reconciles those two facts, and it has
    /// the useful side effect that a script which registers and then crashes
    /// leaves nothing behind.
    static STAGED: std::cell::RefCell<Vec<ToolInfo>> =
        const { std::cell::RefCell::new(Vec::new()) };

    /// Hooks a script registered, not yet in the registry. Same reconciliation
    /// as `STAGED`, and the same reason.
    static STAGED_HOOKS: std::cell::RefCell<Vec<mlua::Function>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Stage one item for the script's own thread to pick up when it returns.
fn stage<T>(slot: &'static std::thread::LocalKey<std::cell::RefCell<Vec<T>>>, item: T) {
    slot.with(|cell| cell.borrow_mut().push(item));
}

/// Take everything staged on this thread.
fn take_staged_items<T>(
    slot: &'static std::thread::LocalKey<std::cell::RefCell<Vec<T>>>,
) -> Vec<T> {
    slot.with(|cell| std::mem::take(&mut *cell.borrow_mut()))
}

/// A loaded script, for the startup message.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoadedScript {
    pub file: PathBuf,
    pub tools: Vec<String>,
    /// How many `on_tool_call` hooks the script registered.
    pub hooks: usize,
}

/// Put one host capability on the table, mapping a failure the same way.
fn set_capability(table: &mlua::Table, name: &str, function: mlua::Function) -> Result<()> {
    table.set(name, function).map_err(|e| lua_error(&e))
}

/// Turn a yk error into a Lua-facing one.
fn lua_error(error: &mlua::Error) -> Error {
    Error::Malformed(error.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 crate::{DenyHost, Host, Registry};

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

    fn registry() -> Registry {
        Registry::new(&denying()).expect("builds a vm")
    }

    #[test]
    fn a_fresh_registry_has_no_tools() {
        let registry = registry();
        assert!(registry.is_empty());
        assert!(registry.tools().is_empty());
    }

    #[test]
    fn io_is_not_reachable_from_a_script() {
        // Structural, not policy: `StdLib::IO` is `#[cfg(not(feature = "luau"))]`
        // in mlua and Luau's `linit.cpp` registers no `luaopen_io`. This asserts
        // something about the dependency, which is worth knowing and is not a
        // restriction yk applies.
        let mut registry = registry();
        let error = registry
            .load_source(r#"return io.open("/etc/passwd")"#, "escape.lua")
            .expect_err("must fail");
        assert!(error.to_string().contains("escape.lua"), "{error}");
    }

    #[test]
    fn os_is_not_reachable_from_a_script() {
        // `os` is not in the whitelist. Luau's `os` registers exactly `clock`,
        // `date`, `difftime`, and `time`, with no `execute`, but the requirement
        // is a whitelist with no dangerous library in it and `os` is on the
        // list. It comes out.
        let registry = registry();
        let kind: String = registry
            .lua()
            .load(r"return type(os)")
            .eval()
            .expect("evaluates");
        assert_eq!(kind, "nil");
    }

    #[test]
    fn package_is_not_reachable_from_a_script() {
        // Structural for the same reason as `io`: `StdLib::PACKAGE` is
        // `#[cfg(not(feature = "luau"))]`.
        let mut registry = registry();
        assert!(
            registry
                .load_source(r#"return package.loadlib("x", "y")"#, "escape.lua")
                .is_err()
        );
    }

    #[test]
    fn debug_is_not_reachable_from_a_script() {
        // Luau trims `debug` to `traceback` and `info`, and the whitelist does
        // not ask for it at all, so the table is nil rather than a reduced one.
        let registry = registry();
        let kind: String = registry
            .lua()
            .load(r"return type(debug)")
            .eval()
            .expect("evaluates");
        assert_eq!(kind, "nil");
    }

    #[test]
    fn ffi_is_not_reachable_from_a_script() {
        // `ffi` is LuaJIT's, so under the `luau` feature the global does not
        // exist. This is the capability #131 wanted and #132 refuses.
        let registry = registry();
        let kind: String = registry
            .lua()
            .load(r"return type(ffi)")
            .eval()
            .expect("evaluates");
        assert_eq!(kind, "nil");
    }

    #[test]
    fn rawset_cannot_reach_inside_a_sandboxed_library() {
        // The primitive PUC Lua does not have, and the reason a blacklisted
        // global table would not have been enough.
        let mut registry = registry();
        assert!(
            registry
                .load_source(r#"rawset(string, "upper", nil)"#, "escape.lua")
                .is_err()
        );
    }

    #[test]
    fn bytecode_is_refused() {
        let mut registry = registry();
        let error = registry
            .load_source("\u{1b}Lua\x52\x00", "chunk")
            .expect_err("must fail");
        assert!(error.to_string().contains("chunk"), "{error}");
    }

    #[test]
    fn a_syntax_error_names_the_script() {
        let mut registry = registry();
        let error = registry
            .load_source("this is not lua", "broken.lua")
            .expect_err("must fail");
        assert!(error.to_string().contains("broken.lua"), "{error}");
    }

    #[test]
    fn a_denying_host_reaches_the_script_as_an_error() {
        let mut registry = registry();
        let error = registry
            .load_source(r#"return host.read_file("/etc/passwd")"#, "read.lua")
            .expect_err("must fail");
        assert!(error.to_string().contains("read.lua"), "{error}");
    }

    #[test]
    fn the_host_table_has_exactly_the_members_the_records_name() {
        let registry = registry();
        let host = registry
            .lua()
            .globals()
            .get::<mlua::Table>("host")
            .expect("host table");

        let mut names = Vec::new();
        host.for_each(|name: String, _: mlua::Value| {
            names.push(name);
            Ok::<(), mlua::Error>(())
        })
        .expect("iterates");
        names.sort();

        // Six capability members plus the registration function.
        // freezes the set: adding a capability is cheap and expected, renaming
        // or repurposing one is a breaking change to every script ever written.
        // adds `env`, `http_post_json`, and `json_encode`.
        assert_eq!(
            names,
            [
                "env",
                "http_get",
                "http_post_json",
                "json",
                "json_encode",
                "read_file",
                "register_tool",
            ]
        );
    }

    #[test]
    fn the_runner_global_is_installed() {
        let registry = registry();
        let runner = registry
            .lua()
            .globals()
            .get::<mlua::Value>("runner")
            .expect("runner global");
        assert!(
            matches!(runner, mlua::Value::UserData(_)),
            "runner is userdata"
        );
    }

    #[test]
    fn json_round_trips_through_the_host() {
        // `json` without its mirror is a one-way door: any extension talking to
        // an HTTP API has to write a request body, and there was no way to do
        // it that did not mean hand-rolling an encoder.
        let registry = registry();
        let encoded: String = registry
            .lua()
            .load(r#"return host.json_encode({ a = 1, b = { c = "x" } })"#)
            .eval()
            .expect("evaluates");
        assert_eq!(encoded, r#"{"a":1,"b":{"c":"x"}}"#);
    }

    #[test]
    fn a_denying_host_reaches_a_post_as_an_error() {
        let mut registry = registry();
        let error = registry
            .load_source(
                r#"return host.http_post_json("https://example.com", {}, "{}")"#,
                "post.lua",
            )
            .expect_err("must fail");
        assert!(error.to_string().contains("post.lua"), "{error}");
    }

    #[test]
    fn an_unset_environment_variable_is_nil_rather_than_an_error() {
        // A script asking for a key it was not given has to be able to find that
        // out without handling an error.
        let registry = registry();
        let kind: String = registry
            .lua()
            .load(r#"return type(host.env("YK_DEFINITELY_NOT_SET_12345"))"#)
            .eval()
            .expect("evaluates");
        assert_eq!(kind, "nil");
    }

    #[test]
    fn json_decodes_into_a_lua_table() {
        let registry = registry();
        let decoded: String = registry
            .lua()
            .load(r#"return type(host.json('{"a":1}'))"#)
            .eval()
            .expect("evaluates");
        assert_eq!(decoded, "table");
    }

    #[test]
    fn a_missing_directory_loads_nothing_rather_than_failing() {
        let mut registry = registry();
        let loaded = registry
            .load_dir(Path::new("/nonexistent/yk/lua"))
            .expect("loads");
        assert!(loaded.is_empty());
    }

    #[tokio::test]
    async fn a_script_under_the_instruction_limit_runs_to_completion() {
        let mut registry = registry();
        registry
            .load_source(
                r#"host.register_tool("count", "Counts", {}, function()
                    local sum = 0
                    for i = 1, 100 do sum = sum + i end
                    return tostring(sum)
                end)"#,
                "count.lua",
            )
            .expect("loads");

        let tools = registry.tools();
        let counting = tools
            .iter()
            .find(|tool| tool.name() == "count")
            .expect("the tool is registered");

        let out = counting
            .clone()
            .with_timeout(std::time::Duration::from_secs(5))
            .run(&serde_json::json!({}))
            .await
            .expect("runs");
        assert_eq!(out, "5050");
    }

    #[tokio::test]
    async fn a_script_spawns_a_process_through_the_runner() {
        // The wiring, not just the Rust function: `runner` is a UserData global
        // and `spawn_tool` is an async method the script calls without await,
        // because mlua drives the future while the tool call is polled.
        let mut registry = registry();
        registry
            .load_source(
                r#"host.register_tool("echo", "Echo", {}, function()
                    local result = runner.spawn_tool("echo", { "hi" })
                    return result.stdout
                end)"#,
                "echo.lua",
            )
            .expect("loads");

        let tools = registry.tools();
        let echoing = tools
            .iter()
            .find(|tool| tool.name() == "echo")
            .expect("the tool is registered");

        let out = echoing
            .clone()
            .with_timeout(std::time::Duration::from_secs(5))
            .run(&serde_json::json!({}))
            .await
            .expect("runs");
        assert_eq!(out.trim(), "hi");
    }

    #[tokio::test]
    async fn a_non_coercible_argument_to_spawn_tool_is_an_error() {
        let mut registry = registry();
        registry
            .load_source(
                r#"host.register_tool("bad", "Bad", {}, function()
                    return runner.spawn_tool("echo", { true })
                end)"#,
                "bad.lua",
            )
            .expect("loads");

        let tools = registry.tools();
        let bad = tools
            .iter()
            .find(|tool| tool.name() == "bad")
            .expect("the tool is registered");

        let error = bad
            .clone()
            .run(&serde_json::json!({}))
            .await
            .expect_err("must fail");
        assert!(error.to_string().contains("args"), "{error}");
    }

    use std::path::Path;
}