eryx 0.4.8

A Python sandbox with async callbacks powered by WebAssembly
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
//! Runtime library for composable callbacks with Python wrappers and type stubs.

use std::fmt;

use crate::callback::Callback;

/// A composable set of callbacks with Python wrappers and type stubs.
///
/// Runtime libraries bundle together:
/// - Callbacks that Python code can invoke
/// - Python preamble code (wrapper classes, helpers, etc.)
/// - Type stubs (.pyi content) for LLM context windows
#[derive(Default)]
pub struct RuntimeLibrary {
    /// Callbacks provided by this library.
    pub callbacks: Vec<Box<dyn Callback>>,

    /// Python code injected before user code (wrapper classes, etc.).
    pub python_preamble: String,

    /// Type stubs (.pyi content) for LLM context.
    pub type_stubs: String,
}

impl RuntimeLibrary {
    /// Create a new empty runtime library.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a callback to this library.
    #[must_use]
    pub fn with_callback<C: Callback + 'static>(mut self, callback: C) -> Self {
        self.callbacks.push(Box::new(callback));
        self
    }

    /// Add multiple callbacks to this library.
    #[must_use]
    pub fn with_callbacks(mut self, callbacks: Vec<Box<dyn Callback>>) -> Self {
        self.callbacks.extend(callbacks);
        self
    }

    /// Set the Python preamble code.
    #[must_use]
    pub fn with_preamble(mut self, preamble: impl Into<String>) -> Self {
        self.python_preamble = preamble.into();
        self
    }

    /// Set the type stubs content.
    #[must_use]
    pub fn with_stubs(mut self, stubs: impl Into<String>) -> Self {
        self.type_stubs = stubs.into();
        self
    }

    /// Merge another library into this one.
    #[must_use]
    pub fn merge(mut self, other: Self) -> Self {
        self.callbacks.extend(other.callbacks);

        if !other.python_preamble.is_empty() {
            if !self.python_preamble.is_empty() {
                self.python_preamble.push_str("\n\n");
            }
            self.python_preamble.push_str(&other.python_preamble);
        }

        if !other.type_stubs.is_empty() {
            if !self.type_stubs.is_empty() {
                self.type_stubs.push_str("\n\n");
            }
            self.type_stubs.push_str(&other.type_stubs);
        }

        self
    }
}

impl fmt::Debug for RuntimeLibrary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RuntimeLibrary")
            .field(
                "callbacks",
                &format!("[{} callbacks]", self.callbacks.len()),
            )
            .field("python_preamble", &self.python_preamble)
            .field("type_stubs", &self.type_stubs)
            .finish()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::callback::{CallbackError, TypedCallback};
    use crate::schema::JsonSchema;
    use serde::Deserialize;
    use serde_json::{Value, json};
    use std::future::Future;
    use std::pin::Pin;

    // Test callbacks for use in tests
    #[derive(Deserialize, JsonSchema)]
    struct EchoArgs {
        message: String,
    }

    struct EchoCallback;

    impl TypedCallback for EchoCallback {
        type Args = EchoArgs;

        fn name(&self) -> &str {
            "echo"
        }

        fn description(&self) -> &str {
            "Echoes the message"
        }

        fn invoke_typed(
            &self,
            args: EchoArgs,
        ) -> Pin<Box<dyn Future<Output = Result<Value, CallbackError>> + Send + '_>> {
            Box::pin(async move { Ok(json!({ "echoed": args.message })) })
        }
    }

    struct GetTimeCallback;

    impl TypedCallback for GetTimeCallback {
        type Args = ();

        fn name(&self) -> &str {
            "get_time"
        }

        fn description(&self) -> &str {
            "Returns the current time"
        }

        fn invoke_typed(
            &self,
            _args: (),
        ) -> Pin<Box<dyn Future<Output = Result<Value, CallbackError>> + Send + '_>> {
            Box::pin(async move { Ok(json!(12345)) })
        }
    }

    struct AddCallback;

    impl TypedCallback for AddCallback {
        type Args = ();

        fn name(&self) -> &str {
            "add"
        }

        fn description(&self) -> &str {
            "Adds numbers"
        }

        fn invoke_typed(
            &self,
            _args: (),
        ) -> Pin<Box<dyn Future<Output = Result<Value, CallbackError>> + Send + '_>> {
            Box::pin(async move { Ok(json!(42)) })
        }
    }

    #[test]
    fn new_creates_empty_library() {
        let lib = RuntimeLibrary::new();

        assert!(lib.callbacks.is_empty());
        assert!(lib.python_preamble.is_empty());
        assert!(lib.type_stubs.is_empty());
    }

    #[test]
    fn default_creates_empty_library() {
        let lib = RuntimeLibrary::default();

        assert!(lib.callbacks.is_empty());
        assert!(lib.python_preamble.is_empty());
        assert!(lib.type_stubs.is_empty());
    }

    #[test]
    fn with_callback_adds_single_callback() {
        let lib = RuntimeLibrary::new().with_callback(EchoCallback);

        assert_eq!(lib.callbacks.len(), 1);
        assert_eq!(lib.callbacks[0].name(), "echo");
    }

    #[test]
    fn with_callback_chains_multiple_callbacks() {
        let lib = RuntimeLibrary::new()
            .with_callback(EchoCallback)
            .with_callback(GetTimeCallback);

        assert_eq!(lib.callbacks.len(), 2);
        assert_eq!(lib.callbacks[0].name(), "echo");
        assert_eq!(lib.callbacks[1].name(), "get_time");
    }

    #[test]
    fn with_callbacks_adds_multiple_at_once() {
        let callbacks: Vec<Box<dyn Callback>> =
            vec![Box::new(EchoCallback), Box::new(GetTimeCallback)];

        let lib = RuntimeLibrary::new().with_callbacks(callbacks);

        assert_eq!(lib.callbacks.len(), 2);
    }

    #[test]
    fn with_preamble_sets_python_code() {
        let preamble = "import json\n\ndef helper(): pass";
        let lib = RuntimeLibrary::new().with_preamble(preamble);

        assert_eq!(lib.python_preamble, preamble);
    }

    #[test]
    fn with_preamble_accepts_string() {
        let lib = RuntimeLibrary::new().with_preamble(String::from("# Python code"));

        assert_eq!(lib.python_preamble, "# Python code");
    }

    #[test]
    fn with_stubs_sets_type_stubs() {
        let stubs = "def echo(message: str) -> dict: ...";
        let lib = RuntimeLibrary::new().with_stubs(stubs);

        assert_eq!(lib.type_stubs, stubs);
    }

    #[test]
    fn with_stubs_accepts_string() {
        let lib = RuntimeLibrary::new().with_stubs(String::from("# Type stubs"));

        assert_eq!(lib.type_stubs, "# Type stubs");
    }

    #[test]
    fn builder_pattern_chains_all_methods() {
        let lib = RuntimeLibrary::new()
            .with_callback(EchoCallback)
            .with_callback(GetTimeCallback)
            .with_preamble("# Preamble")
            .with_stubs("# Stubs");

        assert_eq!(lib.callbacks.len(), 2);
        assert_eq!(lib.python_preamble, "# Preamble");
        assert_eq!(lib.type_stubs, "# Stubs");
    }

    #[test]
    fn merge_combines_callbacks() {
        let lib1 = RuntimeLibrary::new().with_callback(EchoCallback);
        let lib2 = RuntimeLibrary::new().with_callback(GetTimeCallback);

        let merged = lib1.merge(lib2);

        assert_eq!(merged.callbacks.len(), 2);
        assert_eq!(merged.callbacks[0].name(), "echo");
        assert_eq!(merged.callbacks[1].name(), "get_time");
    }

    #[test]
    fn merge_combines_preambles_with_separator() {
        let lib1 = RuntimeLibrary::new().with_preamble("# Part 1");
        let lib2 = RuntimeLibrary::new().with_preamble("# Part 2");

        let merged = lib1.merge(lib2);

        assert!(merged.python_preamble.contains("# Part 1"));
        assert!(merged.python_preamble.contains("# Part 2"));
        assert!(merged.python_preamble.contains("\n\n"));
    }

    #[test]
    fn merge_combines_stubs_with_separator() {
        let lib1 = RuntimeLibrary::new().with_stubs("def foo(): ...");
        let lib2 = RuntimeLibrary::new().with_stubs("def bar(): ...");

        let merged = lib1.merge(lib2);

        assert!(merged.type_stubs.contains("def foo(): ..."));
        assert!(merged.type_stubs.contains("def bar(): ..."));
        assert!(merged.type_stubs.contains("\n\n"));
    }

    #[test]
    fn merge_empty_preamble_no_extra_newlines() {
        let lib1 = RuntimeLibrary::new().with_preamble("# Only preamble");
        let lib2 = RuntimeLibrary::new(); // Empty preamble

        let merged = lib1.merge(lib2);

        assert_eq!(merged.python_preamble, "# Only preamble");
        assert!(!merged.python_preamble.ends_with("\n\n"));
    }

    #[test]
    fn merge_into_empty_preamble_no_extra_newlines() {
        let lib1 = RuntimeLibrary::new(); // Empty preamble
        let lib2 = RuntimeLibrary::new().with_preamble("# Only preamble");

        let merged = lib1.merge(lib2);

        assert_eq!(merged.python_preamble, "# Only preamble");
        assert!(!merged.python_preamble.starts_with("\n\n"));
    }

    #[test]
    fn merge_empty_stubs_no_extra_newlines() {
        let lib1 = RuntimeLibrary::new().with_stubs("# Only stubs");
        let lib2 = RuntimeLibrary::new(); // Empty stubs

        let merged = lib1.merge(lib2);

        assert_eq!(merged.type_stubs, "# Only stubs");
    }

    #[test]
    fn merge_both_empty_preambles() {
        let lib1 = RuntimeLibrary::new();
        let lib2 = RuntimeLibrary::new();

        let merged = lib1.merge(lib2);

        assert!(merged.python_preamble.is_empty());
    }

    #[test]
    fn merge_is_chainable() {
        let lib1 = RuntimeLibrary::new().with_callback(EchoCallback);
        let lib2 = RuntimeLibrary::new().with_callback(GetTimeCallback);
        let lib3 = RuntimeLibrary::new().with_callback(AddCallback);

        let merged = lib1.merge(lib2).merge(lib3);

        assert_eq!(merged.callbacks.len(), 3);
    }

    #[test]
    fn debug_format_shows_callback_count() {
        let lib = RuntimeLibrary::new()
            .with_callback(EchoCallback)
            .with_callback(GetTimeCallback);

        let debug = format!("{:?}", lib);

        assert!(debug.contains("RuntimeLibrary"));
        assert!(debug.contains("[2 callbacks]"));
    }

    #[test]
    fn debug_format_shows_preamble() {
        let lib = RuntimeLibrary::new().with_preamble("# Test preamble");

        let debug = format!("{:?}", lib);

        assert!(debug.contains("# Test preamble"));
    }

    #[test]
    fn debug_format_shows_stubs() {
        let lib = RuntimeLibrary::new().with_stubs("# Test stubs");

        let debug = format!("{:?}", lib);

        assert!(debug.contains("# Test stubs"));
    }

    #[test]
    fn empty_library_debug() {
        let lib = RuntimeLibrary::new();

        let debug = format!("{:?}", lib);

        assert!(debug.contains("[0 callbacks]"));
    }

    #[test]
    fn callbacks_are_accessible() {
        let lib = RuntimeLibrary::new()
            .with_callback(EchoCallback)
            .with_callback(GetTimeCallback);

        // Can iterate over callbacks
        let names: Vec<&str> = lib.callbacks.iter().map(|c| c.name()).collect();
        assert_eq!(names, vec!["echo", "get_time"]);
    }

    #[test]
    fn preamble_is_accessible() {
        let lib = RuntimeLibrary::new().with_preamble("test preamble");

        assert_eq!(lib.python_preamble, "test preamble");
    }

    #[test]
    fn stubs_are_accessible() {
        let lib = RuntimeLibrary::new().with_stubs("test stubs");

        assert_eq!(lib.type_stubs, "test stubs");
    }
}