brainwires-tools 0.10.0

Built-in tool implementations for the Brainwires Agent Framework
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
//! Common types for code execution

use serde::{Deserialize, Serialize};

/// Maximum string length for the relaxed execution limits profile (100MB).
const RELAXED_MAX_STRING_LENGTH: usize = 104_857_600;

/// Supported programming languages
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
    /// Rhai - Native Rust scripting language (fastest, lightweight)
    Rhai,
    /// Lua 5.4 - Small, fast scripting language
    Lua,
    /// JavaScript - ECMAScript via Boa engine
    JavaScript,
    /// Python - CPython 3.12 compatible via RustPython
    Python,
}

impl Language {
    /// Get the language name as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            Language::Rhai => "rhai",
            Language::Lua => "lua",
            Language::JavaScript => "javascript",
            Language::Python => "python",
        }
    }

    /// Parse a language from string (case-insensitive)
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "rhai" => Some(Language::Rhai),
            "lua" => Some(Language::Lua),
            "javascript" | "js" => Some(Language::JavaScript),
            "python" | "py" => Some(Language::Python),
            _ => None,
        }
    }

    /// Get the typical file extension for this language
    pub fn extension(&self) -> &'static str {
        match self {
            Language::Rhai => "rhai",
            Language::Lua => "lua",
            Language::JavaScript => "js",
            Language::Python => "py",
        }
    }
}

impl std::fmt::Display for Language {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Request to execute code
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionRequest {
    /// Programming language to use
    pub language: Language,

    /// Source code to execute
    pub code: String,

    /// Standard input to provide (optional)
    #[serde(default)]
    pub stdin: Option<String>,

    /// Execution timeout in milliseconds (default: 30000)
    #[serde(default = "default_timeout_ms")]
    pub timeout_ms: u64,

    /// Memory limit in MB (default: 256)
    #[serde(default = "default_memory_mb")]
    pub memory_limit_mb: u32,

    /// Context variables to inject as globals (optional)
    #[serde(default)]
    pub context: Option<serde_json::Value>,

    /// Execution limits profile (optional, overrides individual limits)
    #[serde(default)]
    pub limits: Option<ExecutionLimits>,
}

fn default_timeout_ms() -> u64 {
    30_000
}

fn default_memory_mb() -> u32 {
    256
}

impl Default for ExecutionRequest {
    fn default() -> Self {
        Self {
            language: Language::Rhai,
            code: String::new(),
            stdin: None,
            timeout_ms: default_timeout_ms(),
            memory_limit_mb: default_memory_mb(),
            context: None,
            limits: None,
        }
    }
}

/// Result of code execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
    /// Whether execution completed successfully
    pub success: bool,

    /// Standard output from the program
    pub stdout: String,

    /// Standard error from the program
    pub stderr: String,

    /// Return value of the code (if any), serialized as JSON
    #[serde(default)]
    pub result: Option<serde_json::Value>,

    /// Error message if execution failed
    #[serde(default)]
    pub error: Option<String>,

    /// Execution time in milliseconds
    pub timing_ms: u64,

    /// Memory used in bytes (if available)
    #[serde(default)]
    pub memory_used_bytes: Option<u64>,

    /// Number of operations executed (if tracked)
    #[serde(default)]
    pub operations_count: Option<u64>,
}

impl ExecutionResult {
    /// Create a successful result
    pub fn success(stdout: String, result: Option<serde_json::Value>, timing_ms: u64) -> Self {
        Self {
            success: true,
            stdout,
            stderr: String::new(),
            result,
            error: None,
            timing_ms,
            memory_used_bytes: None,
            operations_count: None,
        }
    }

    /// Create a failed result
    pub fn error(error: String, timing_ms: u64) -> Self {
        Self {
            success: false,
            stdout: String::new(),
            stderr: String::new(),
            result: None,
            error: Some(error),
            timing_ms,
            memory_used_bytes: None,
            operations_count: None,
        }
    }

    /// Create a failed result with captured output
    pub fn error_with_output(
        error: String,
        stdout: String,
        stderr: String,
        timing_ms: u64,
    ) -> Self {
        Self {
            success: false,
            stdout,
            stderr,
            result: None,
            error: Some(error),
            timing_ms,
            memory_used_bytes: None,
            operations_count: None,
        }
    }
}

impl Default for ExecutionResult {
    fn default() -> Self {
        Self::error("No execution performed".to_string(), 0)
    }
}

/// Execution limits for sandboxing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionLimits {
    /// Maximum execution time in milliseconds
    #[serde(default = "ExecutionLimits::default_timeout_ms")]
    pub max_timeout_ms: u64,

    /// Maximum memory usage in MB
    #[serde(default = "ExecutionLimits::default_memory_mb")]
    pub max_memory_mb: u32,

    /// Maximum output size in bytes
    #[serde(default = "ExecutionLimits::default_output_bytes")]
    pub max_output_bytes: usize,

    /// Maximum number of operations (for loop prevention)
    #[serde(default = "ExecutionLimits::default_operations")]
    pub max_operations: u64,

    /// Maximum call stack depth
    #[serde(default = "ExecutionLimits::default_call_depth")]
    pub max_call_depth: u32,

    /// Maximum string length
    #[serde(default = "ExecutionLimits::default_string_length")]
    pub max_string_length: usize,

    /// Maximum array/list length
    #[serde(default = "ExecutionLimits::default_array_length")]
    pub max_array_length: usize,

    /// Maximum map/dict entries
    #[serde(default = "ExecutionLimits::default_map_size")]
    pub max_map_size: usize,
}

impl ExecutionLimits {
    fn default_timeout_ms() -> u64 {
        30_000
    }
    fn default_memory_mb() -> u32 {
        256
    }
    fn default_output_bytes() -> usize {
        1_048_576 // 1MB
    }
    fn default_operations() -> u64 {
        1_000_000
    }
    fn default_call_depth() -> u32 {
        64
    }
    fn default_string_length() -> usize {
        10_485_760 // 10MB
    }
    fn default_array_length() -> usize {
        100_000
    }
    fn default_map_size() -> usize {
        10_000
    }

    /// Create strict limits for untrusted code
    pub fn strict() -> Self {
        Self {
            max_timeout_ms: 5_000,
            max_memory_mb: 64,
            max_output_bytes: 65_536, // 64KB
            max_operations: 100_000,
            max_call_depth: 32,
            max_string_length: 1_048_576, // 1MB
            max_array_length: 10_000,
            max_map_size: 1_000,
        }
    }

    /// Create relaxed limits for trusted code
    pub fn relaxed() -> Self {
        Self {
            max_timeout_ms: 120_000, // 2 minutes
            max_memory_mb: 512,
            max_output_bytes: 10_485_760, // 10MB
            max_operations: 10_000_000,
            max_call_depth: 128,
            max_string_length: RELAXED_MAX_STRING_LENGTH,
            max_array_length: 1_000_000,
            max_map_size: 100_000,
        }
    }
}

impl Default for ExecutionLimits {
    fn default() -> Self {
        Self {
            max_timeout_ms: Self::default_timeout_ms(),
            max_memory_mb: Self::default_memory_mb(),
            max_output_bytes: Self::default_output_bytes(),
            max_operations: Self::default_operations(),
            max_call_depth: Self::default_call_depth(),
            max_string_length: Self::default_string_length(),
            max_array_length: Self::default_array_length(),
            max_map_size: Self::default_map_size(),
        }
    }
}

/// Error types for code execution
#[derive(Debug, Clone, thiserror::Error, Serialize, Deserialize)]
pub enum ExecutionError {
    /// The requested language is not supported or not enabled.
    #[error("Language '{0}' is not supported or not enabled")]
    UnsupportedLanguage(String),

    /// Execution timed out after the given number of milliseconds.
    #[error("Execution timed out after {0}ms")]
    Timeout(u64),

    /// Memory limit exceeded (in MB).
    #[error("Memory limit exceeded: {0}MB")]
    MemoryLimitExceeded(u32),

    /// Operation limit exceeded.
    #[error("Operation limit exceeded: {0} operations")]
    OperationLimitExceeded(u64),

    /// Output exceeded the maximum size (in bytes).
    #[error("Output too large: {0} bytes")]
    OutputTooLarge(usize),

    /// Syntax error in the submitted code.
    #[error("Syntax error: {0}")]
    SyntaxError(String),

    /// Runtime error during execution.
    #[error("Runtime error: {0}")]
    RuntimeError(String),

    /// Internal executor error.
    #[error("Internal error: {0}")]
    InternalError(String),
}

impl ExecutionError {
    /// Convert this error into an [`ExecutionResult`] with the given timing.
    pub fn to_result(&self, timing_ms: u64) -> ExecutionResult {
        ExecutionResult::error(self.to_string(), timing_ms)
    }
}

/// Sandbox profile presets
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SandboxProfile {
    /// Minimal - No I/O, basic math only
    Minimal,
    /// Standard - Console output, JSON, basic stdlib
    #[default]
    Standard,
    /// Extended - More stdlib, regex, datetime
    Extended,
}

impl SandboxProfile {
    /// Get allowed modules for this profile
    pub fn allowed_modules(&self) -> Vec<&'static str> {
        match self {
            SandboxProfile::Minimal => vec!["math"],
            SandboxProfile::Standard => vec!["math", "json", "string", "array", "print"],
            SandboxProfile::Extended => vec![
                "math", "json", "string", "array", "print", "datetime", "regex", "base64",
            ],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_language_parsing() {
        assert_eq!(Language::parse("python"), Some(Language::Python));
        assert_eq!(Language::parse("py"), Some(Language::Python));
        assert_eq!(Language::parse("JAVASCRIPT"), Some(Language::JavaScript));
        assert_eq!(Language::parse("js"), Some(Language::JavaScript));
        assert_eq!(Language::parse("lua"), Some(Language::Lua));
        assert_eq!(Language::parse("rhai"), Some(Language::Rhai));
        assert_eq!(Language::parse("unknown"), None);
    }

    #[test]
    fn test_execution_limits_profiles() {
        let strict = ExecutionLimits::strict();
        let relaxed = ExecutionLimits::relaxed();

        assert!(strict.max_timeout_ms < relaxed.max_timeout_ms);
        assert!(strict.max_memory_mb < relaxed.max_memory_mb);
        assert!(strict.max_operations < relaxed.max_operations);
    }

    #[test]
    fn test_execution_result_creation() {
        let success =
            ExecutionResult::success("Hello".to_string(), Some(serde_json::json!(42)), 100);
        assert!(success.success);
        assert_eq!(success.stdout, "Hello");

        let error = ExecutionResult::error("Failed".to_string(), 50);
        assert!(!error.success);
        assert_eq!(error.error, Some("Failed".to_string()));
    }
}