liteforge 0.2.4

Rust SDK for LiteForge - LLM completions via OpenAI-compatible API
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
//! Sandbox for safe code execution.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::process::Output;
use std::time::Duration;

/// Result of code execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
    /// Exit code (0 = success).
    pub exit_code: i32,
    /// Standard output.
    pub stdout: String,
    /// Standard error.
    pub stderr: String,
    /// Execution time in milliseconds.
    pub execution_time_ms: u64,
    /// Whether execution was killed due to timeout.
    pub timed_out: bool,
    /// Any files created during execution.
    pub output_files: Vec<OutputFile>,
}

impl ExecutionResult {
    /// Check if execution was successful.
    pub fn success(&self) -> bool {
        self.exit_code == 0 && !self.timed_out
    }

    /// Get combined output (stdout + stderr).
    pub fn output(&self) -> String {
        if self.stderr.is_empty() {
            self.stdout.clone()
        } else if self.stdout.is_empty() {
            self.stderr.clone()
        } else {
            format!("{}\n{}", self.stdout, self.stderr)
        }
    }
}

/// An output file created during execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputFile {
    /// File path relative to working directory.
    pub path: String,
    /// File contents (if text) or base64-encoded (if binary).
    pub content: String,
    /// Whether content is base64-encoded.
    pub is_binary: bool,
}

/// Configuration for sandbox execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxConfig {
    /// Maximum execution time.
    #[serde(with = "humantime_serde")]
    pub timeout: Duration,
    /// Maximum memory in bytes.
    pub max_memory: usize,
    /// Maximum CPU time in seconds.
    pub max_cpu_time: u64,
    /// Working directory.
    pub working_dir: Option<String>,
    /// Environment variables.
    pub env: HashMap<String, String>,
    /// Whether to allow network access.
    pub allow_network: bool,
    /// Whether to allow file system writes.
    pub allow_fs_write: bool,
    /// Allowed paths for reading (if restricted).
    pub allowed_read_paths: Vec<String>,
    /// Allowed paths for writing (if restricted).
    pub allowed_write_paths: Vec<String>,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(30),
            max_memory: 256 * 1024 * 1024, // 256 MB
            max_cpu_time: 10,
            working_dir: None,
            env: HashMap::new(),
            allow_network: false,
            allow_fs_write: false,
            allowed_read_paths: Vec::new(),
            allowed_write_paths: Vec::new(),
        }
    }
}

impl SandboxConfig {
    /// Create a new sandbox config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set max memory.
    pub fn max_memory(mut self, bytes: usize) -> Self {
        self.max_memory = bytes;
        self
    }

    /// Set working directory.
    pub fn working_dir(mut self, dir: impl Into<String>) -> Self {
        self.working_dir = Some(dir.into());
        self
    }

    /// Add environment variable.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    /// Allow network access.
    pub fn allow_network(mut self, allow: bool) -> Self {
        self.allow_network = allow;
        self
    }

    /// Allow filesystem writes.
    pub fn allow_fs_write(mut self, allow: bool) -> Self {
        self.allow_fs_write = allow;
        self
    }
}

/// Supported programming languages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Language {
    Python,
    JavaScript,
    TypeScript,
    Ruby,
    Rust,
    Go,
    Shell,
}

impl Language {
    /// Get the file extension for this language.
    pub fn extension(&self) -> &'static str {
        match self {
            Language::Python => "py",
            Language::JavaScript => "js",
            Language::TypeScript => "ts",
            Language::Ruby => "rb",
            Language::Rust => "rs",
            Language::Go => "go",
            Language::Shell => "sh",
        }
    }

    /// Get the default interpreter/compiler command.
    pub fn command(&self) -> &'static str {
        match self {
            Language::Python => "python3",
            Language::JavaScript => "node",
            Language::TypeScript => "npx ts-node",
            Language::Ruby => "ruby",
            Language::Rust => "rustc",
            Language::Go => "go run",
            Language::Shell => "bash",
        }
    }

    /// Detect language from code content.
    pub fn detect(code: &str) -> Option<Language> {
        let code = code.trim();

        // Check for shebangs
        if code.starts_with("#!/usr/bin/env python") || code.starts_with("#!/usr/bin/python") {
            return Some(Language::Python);
        }
        if code.starts_with("#!/usr/bin/env node") || code.starts_with("#!/usr/bin/node") {
            return Some(Language::JavaScript);
        }
        if code.starts_with("#!/bin/bash") || code.starts_with("#!/bin/sh") {
            return Some(Language::Shell);
        }

        // Heuristics based on syntax
        if code.contains("def ") && code.contains(":") && !code.contains("{") {
            return Some(Language::Python);
        }
        if code.contains("import ") && code.contains("from ") && code.contains(":") {
            return Some(Language::Python);
        }
        if code.contains("function ") || code.contains("const ") || code.contains("let ") {
            if code.contains(": string") || code.contains(": number") || code.contains(": boolean")
            {
                return Some(Language::TypeScript);
            }
            return Some(Language::JavaScript);
        }
        if code.contains("fn ") && code.contains("->") {
            return Some(Language::Rust);
        }
        if code.contains("func ") && code.contains("package ") {
            return Some(Language::Go);
        }

        None
    }
}

/// Error from sandbox execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxError {
    /// Error message.
    pub message: String,
    /// Error kind.
    pub kind: SandboxErrorKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SandboxErrorKind {
    /// Timeout exceeded.
    Timeout,
    /// Memory limit exceeded.
    MemoryLimit,
    /// Security violation.
    SecurityViolation,
    /// Language not supported.
    UnsupportedLanguage,
    /// Execution failed.
    ExecutionFailed,
    /// Configuration error.
    ConfigError,
}

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

impl std::error::Error for SandboxError {}

impl SandboxError {
    pub fn new(kind: SandboxErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }

    pub fn timeout(message: impl Into<String>) -> Self {
        Self::new(SandboxErrorKind::Timeout, message)
    }

    pub fn security(message: impl Into<String>) -> Self {
        Self::new(SandboxErrorKind::SecurityViolation, message)
    }

    pub fn unsupported(message: impl Into<String>) -> Self {
        Self::new(SandboxErrorKind::UnsupportedLanguage, message)
    }

    pub fn execution(message: impl Into<String>) -> Self {
        Self::new(SandboxErrorKind::ExecutionFailed, message)
    }
}

/// Trait for sandbox implementations.
#[async_trait]
pub trait Sandbox: Send + Sync {
    /// Execute code in the sandbox.
    async fn execute(
        &self,
        code: &str,
        language: Language,
        config: &SandboxConfig,
    ) -> Result<ExecutionResult, SandboxError>;

    /// Check if a language is supported.
    fn supports_language(&self, language: Language) -> bool;

    /// Get supported languages.
    fn supported_languages(&self) -> Vec<Language>;
}

/// A simple process-based sandbox (not fully isolated).
///
/// WARNING: This is NOT a secure sandbox. For production use,
/// consider using Docker, gVisor, or WASM-based isolation.
#[derive(Debug, Clone, Default)]
pub struct ProcessSandbox {
    /// Base directory for temporary files.
    pub temp_dir: Option<String>,
}

impl ProcessSandbox {
    /// Create a new process sandbox.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the temp directory.
    pub fn with_temp_dir(mut self, dir: impl Into<String>) -> Self {
        self.temp_dir = Some(dir.into());
        self
    }

    async fn run_command(
        &self,
        cmd: &str,
        args: &[&str],
        config: &SandboxConfig,
    ) -> Result<Output, SandboxError> {
        use std::process::Command;

        let mut command = Command::new(cmd);
        command.args(args);

        // Set working directory
        if let Some(ref dir) = config.working_dir {
            command.current_dir(dir);
        }

        // Set environment
        command.env_clear();
        for (key, value) in &config.env {
            command.env(key, value);
        }

        // Add minimal required env vars
        command.env("PATH", "/usr/local/bin:/usr/bin:/bin");
        command.env("HOME", "/tmp");

        let output = command
            .output()
            .map_err(|e| SandboxError::execution(format!("Failed to execute: {}", e)))?;

        Ok(output)
    }
}

#[async_trait]
impl Sandbox for ProcessSandbox {
    async fn execute(
        &self,
        code: &str,
        language: Language,
        config: &SandboxConfig,
    ) -> Result<ExecutionResult, SandboxError> {
        use std::io::Write;
        use std::time::Instant;

        // Create temp file for the code
        let temp_dir = self.temp_dir.as_deref().unwrap_or("/tmp");
        let file_name = format!(
            "{}/sandbox_code_{}.{}",
            temp_dir,
            std::process::id(),
            language.extension()
        );

        // Write code to file
        let mut file = std::fs::File::create(&file_name)
            .map_err(|e| SandboxError::execution(format!("Failed to create temp file: {}", e)))?;
        file.write_all(code.as_bytes())
            .map_err(|e| SandboxError::execution(format!("Failed to write code: {}", e)))?;

        let start = Instant::now();

        // Execute based on language
        let output = match language {
            Language::Python => self.run_command("python3", &[&file_name], config).await?,
            Language::JavaScript => self.run_command("node", &[&file_name], config).await?,
            Language::Shell => self.run_command("bash", &[&file_name], config).await?,
            Language::Ruby => self.run_command("ruby", &[&file_name], config).await?,
            _ => {
                // Clean up temp file
                let _ = std::fs::remove_file(&file_name);
                return Err(SandboxError::unsupported(format!(
                    "{:?} is not supported by ProcessSandbox",
                    language
                )));
            }
        };

        let execution_time = start.elapsed();

        // Clean up temp file
        let _ = std::fs::remove_file(&file_name);

        Ok(ExecutionResult {
            exit_code: output.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            execution_time_ms: execution_time.as_millis() as u64,
            timed_out: false,
            output_files: Vec::new(),
        })
    }

    fn supports_language(&self, language: Language) -> bool {
        matches!(
            language,
            Language::Python | Language::JavaScript | Language::Shell | Language::Ruby
        )
    }

    fn supported_languages(&self) -> Vec<Language> {
        vec![
            Language::Python,
            Language::JavaScript,
            Language::Shell,
            Language::Ruby,
        ]
    }
}

/// A no-op sandbox that just returns mock results (for testing).
#[derive(Debug, Clone, Default)]
pub struct MockSandbox {
    /// Predefined result to return.
    pub result: Option<ExecutionResult>,
}

impl MockSandbox {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_result(mut self, result: ExecutionResult) -> Self {
        self.result = Some(result);
        self
    }
}

#[async_trait]
impl Sandbox for MockSandbox {
    async fn execute(
        &self,
        _code: &str,
        _language: Language,
        _config: &SandboxConfig,
    ) -> Result<ExecutionResult, SandboxError> {
        Ok(self.result.clone().unwrap_or(ExecutionResult {
            exit_code: 0,
            stdout: "Mock execution successful".to_string(),
            stderr: String::new(),
            execution_time_ms: 1,
            timed_out: false,
            output_files: Vec::new(),
        }))
    }

    fn supports_language(&self, _language: Language) -> bool {
        true
    }

    fn supported_languages(&self) -> Vec<Language> {
        vec![
            Language::Python,
            Language::JavaScript,
            Language::TypeScript,
            Language::Ruby,
            Language::Rust,
            Language::Go,
            Language::Shell,
        ]
    }
}

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

    #[test]
    fn test_execution_result() {
        let result = ExecutionResult {
            exit_code: 0,
            stdout: "Hello".to_string(),
            stderr: String::new(),
            execution_time_ms: 10,
            timed_out: false,
            output_files: Vec::new(),
        };

        assert!(result.success());
        assert_eq!(result.output(), "Hello");
    }

    #[test]
    fn test_execution_result_failed() {
        let result = ExecutionResult {
            exit_code: 1,
            stdout: String::new(),
            stderr: "Error".to_string(),
            execution_time_ms: 10,
            timed_out: false,
            output_files: Vec::new(),
        };

        assert!(!result.success());
        assert_eq!(result.output(), "Error");
    }

    #[test]
    fn test_sandbox_config() {
        let config = SandboxConfig::new()
            .timeout(Duration::from_secs(60))
            .max_memory(512 * 1024 * 1024)
            .working_dir("/tmp/sandbox")
            .env("FOO", "bar")
            .allow_network(true);

        assert_eq!(config.timeout, Duration::from_secs(60));
        assert_eq!(config.max_memory, 512 * 1024 * 1024);
        assert_eq!(config.working_dir, Some("/tmp/sandbox".to_string()));
        assert_eq!(config.env.get("FOO"), Some(&"bar".to_string()));
        assert!(config.allow_network);
    }

    #[test]
    fn test_language_extension() {
        assert_eq!(Language::Python.extension(), "py");
        assert_eq!(Language::JavaScript.extension(), "js");
        assert_eq!(Language::Rust.extension(), "rs");
    }

    #[test]
    fn test_language_detection() {
        assert_eq!(
            Language::detect("def foo():\n    pass"),
            Some(Language::Python)
        );
        assert_eq!(
            Language::detect("function foo() { }"),
            Some(Language::JavaScript)
        );
        assert_eq!(
            Language::detect("fn main() -> () { }"),
            Some(Language::Rust)
        );
        assert_eq!(
            Language::detect("#!/bin/bash\necho hello"),
            Some(Language::Shell)
        );
    }

    #[tokio::test]
    async fn test_mock_sandbox() {
        let sandbox = MockSandbox::new().with_result(ExecutionResult {
            exit_code: 0,
            stdout: "42".to_string(),
            stderr: String::new(),
            execution_time_ms: 5,
            timed_out: false,
            output_files: Vec::new(),
        });

        let config = SandboxConfig::default();
        let result = sandbox
            .execute("print(42)", Language::Python, &config)
            .await
            .unwrap();

        assert!(result.success());
        assert_eq!(result.stdout, "42");
    }

    #[test]
    fn test_sandbox_error() {
        let err = SandboxError::timeout("Execution took too long");
        assert_eq!(err.kind, SandboxErrorKind::Timeout);
        assert!(err.to_string().contains("Execution took too long"));
    }
}