|
| 1 | +# Introducing Terraphim RLM: Production-Ready Recursive Language Models with Firecracker Isolation |
| 2 | + |
| 3 | +**We're excited to announce the merge of PR #426, bringing production-ready Recursive Language Model (RLM) orchestration to Terraphim AI.** |
| 4 | + |
| 5 | +After months of development and rigorous testing, we're proud to introduce a complete RLM implementation that combines the conceptual elegance of recursive LLM architectures with enterprise-grade security and isolation. |
| 6 | + |
| 7 | +## What is a Recursive Language Model? |
| 8 | + |
| 9 | +Recursive Language Models represent a paradigm shift in how AI agents interact with their environment. Instead of traditional tool-calling patterns, RLMs return commands that execute in a sandboxed REPL environment—and can recursively invoke sub-LLMs to solve complex problems. |
| 10 | + |
| 11 | +Key advantages: |
| 12 | +- **Severely constrained capabilities** via sandboxed execution (much safer!) |
| 13 | +- **Stateful context** stored within the sandbox environment |
| 14 | +- **Recursive composition** - each sub-LLM is itself an RLM |
| 15 | +- **Natural reasoning** through iterative code execution |
| 16 | + |
| 17 | +## Production-Ready Features |
| 18 | + |
| 19 | +### 🔒 Multiple Isolation Backends |
| 20 | + |
| 21 | +**Firecracker MicroVMs** (Primary) |
| 22 | +- Full VM isolation with <500ms allocation time |
| 23 | +- Pre-warmed VM pools for instant response |
| 24 | +- Snapshot support for state versioning |
| 25 | +- Requires: KVM, Firecracker v1.1.0+ |
| 26 | + |
| 27 | +**Docker Containers** (Fallback) |
| 28 | +- gVisor/runsc support for enhanced isolation |
| 29 | +- Automatic detection and fallback |
| 30 | +- Perfect for development and CI |
| 31 | + |
| 32 | +**Mock Executor** (Testing) |
| 33 | +- Fast, deterministic execution for tests |
| 34 | +- CI-friendly without VM requirements |
| 35 | + |
| 36 | +### 🛠️ Six MCP Tools for AI Integration |
| 37 | + |
| 38 | +Our Model Context Protocol (MCP) implementation provides 6 specialized tools: |
| 39 | + |
| 40 | +1. **`rlm_code`** - Execute Python in isolated VM |
| 41 | +2. **`rlm_bash`** - Execute bash commands in isolated VM |
| 42 | +3. **`rlm_query`** - Query LLM recursively from VM context |
| 43 | +4. **`rlm_context`** - Get/set session context and budget |
| 44 | +5. **`rlm_snapshot`** - Create/restore VM snapshots |
| 45 | +6. **`rlm_status`** - Get session status and history |
| 46 | + |
| 47 | +### 💰 Dual Budget System |
| 48 | + |
| 49 | +Prevent runaway execution with: |
| 50 | +- **Token budget** - Maximum LLM tokens per session |
| 51 | +- **Time budget** - Maximum wall-clock execution time |
| 52 | +- **Recursion depth** - Maximum nested LLM calls |
| 53 | +- **Iteration limits** - Maximum query loop iterations |
| 54 | + |
| 55 | +### 🧠 Knowledge Graph Validation |
| 56 | + |
| 57 | +Configurable command validation: |
| 58 | +- **Strict mode** - Reject unknown terms |
| 59 | +- **Normal mode** - Warn on unknown terms with suggestions |
| 60 | +- **Permissive mode** - Log only, never block |
| 61 | +- Automatic retry with context escalation |
| 62 | + |
| 63 | +## Technical Architecture |
| 64 | + |
| 65 | +``` |
| 66 | +TerraphimRlm (public API) |
| 67 | + ├── SessionManager (VM affinity, snapshots, extensions) |
| 68 | + ├── QueryLoop (command parsing, execution, result handling) |
| 69 | + ├── BudgetTracker (token counting, time tracking, depth limits) |
| 70 | + └── KnowledgeGraphValidator (term matching, retry, strictness) |
| 71 | +
|
| 72 | +ExecutionEnvironment trait |
| 73 | + ├── FirecrackerExecutor (primary, KVM-based VMs) |
| 74 | + ├── DockerExecutor (fallback, container isolation) |
| 75 | + └── MockExecutor (testing, CI-friendly) |
| 76 | +
|
| 77 | +MCP Integration |
| 78 | + └── RlmMcpService (6 tools for AI tool use) |
| 79 | +``` |
| 80 | + |
| 81 | +## Comparison: Terraphim RLM vs rig-rlm |
| 82 | + |
| 83 | +| Feature | rig-rlm (Reference) | Terraphim RLM | |
| 84 | +|---------|-------------------|---------------| |
| 85 | +| **Python Execution** | PyO3 (in-process) | Firecracker VM ✅ | |
| 86 | +| **Bash Execution** | std::process | Firecracker VM ✅ | |
| 87 | +| **Isolation** | None | VM-level ✅ | |
| 88 | +| **Recursive LLM** | Basic function | MCP standard ✅ | |
| 89 | +| **Snapshots** | ❌ Not implemented | Full lifecycle ✅ | |
| 90 | +| **Budget Tracking** | ❌ Not implemented | Token + Time ✅ | |
| 91 | +| **KG Validation** | ❌ Not implemented | Configurable ✅ | |
| 92 | +| **Protocol** | Custom parsing | MCP standard ✅ | |
| 93 | +| **Production Ready** | Demo/prototype | Enterprise-grade ✅ | |
| 94 | + |
| 95 | +## Quick Start |
| 96 | + |
| 97 | +### Installation |
| 98 | + |
| 99 | +```bash |
| 100 | +git clone https://github.com/terraphim/terraphim-ai |
| 101 | +cd terraphim-ai |
| 102 | +cargo build -p terraphim_rlm --features firecracker,mcp |
| 103 | +``` |
| 104 | + |
| 105 | +### Basic Usage |
| 106 | + |
| 107 | +```rust |
| 108 | +use terraphim_rlm::{TerraphimRlm, RlmConfig}; |
| 109 | + |
| 110 | +#[tokio::main] |
| 111 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 112 | + // Create RLM instance |
| 113 | + let config = RlmConfig::default(); |
| 114 | + let rlm = TerraphimRlm::new(config).await?; |
| 115 | + |
| 116 | + // Create a session |
| 117 | + let session = rlm.create_session().await?; |
| 118 | + |
| 119 | + // Execute Python code |
| 120 | + let result = rlm.execute_code(&session, r#" |
| 121 | + data = [1, 2, 3, 4, 5] |
| 122 | + print(f"Sum: {sum(data)}") |
| 123 | + "#).await?; |
| 124 | + |
| 125 | + println!("Output: {}", result.stdout); |
| 126 | + |
| 127 | + // Execute bash command |
| 128 | + let result = rlm.execute_command(&session, "ls -la").await?; |
| 129 | + println!("Files: {}", result.stdout); |
| 130 | + |
| 131 | + // Create snapshot |
| 132 | + let snapshot = rlm.create_snapshot(&session, "checkpoint-1").await?; |
| 133 | + |
| 134 | + Ok(()) |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +### MCP Tool Example |
| 139 | + |
| 140 | +```rust |
| 141 | +use terraphim_rlm::mcp_tools::RlmMcpService; |
| 142 | + |
| 143 | +let mcp = RlmMcpService::new(); |
| 144 | +mcp.initialize(rlm).await; |
| 145 | + |
| 146 | +// Execute code via MCP |
| 147 | +let result = mcp.call_tool("rlm_code", Some(json!({ |
| 148 | + "code": "print('Hello from MCP!')", |
| 149 | + "session_id": session_id.to_string() |
| 150 | +}))).await?; |
| 151 | +``` |
| 152 | + |
| 153 | +## Security Features |
| 154 | + |
| 155 | +### Input Validation |
| 156 | +- Path traversal prevention (rejects `..`, `/`, `\` in snapshot names) |
| 157 | +- Code size limits (1MB max) |
| 158 | +- Session ID format validation (ULID) |
| 159 | +- Command injection prevention |
| 160 | + |
| 161 | +### Resource Limits |
| 162 | +- Memory limits per VM |
| 163 | +- Timeout enforcement |
| 164 | +- Parser recursion depth limits |
| 165 | +- Max snapshots per session (configurable) |
| 166 | + |
| 167 | +### Error Handling |
| 168 | +- Full error context preservation with `#[source]` |
| 169 | +- Proper error propagation via `?` operator |
| 170 | +- No silent failures or unwrap defaults |
| 171 | +- MCP-compatible error responses |
| 172 | + |
| 173 | +## Testing |
| 174 | + |
| 175 | +**144 tests passing:** |
| 176 | +- 132 unit tests |
| 177 | +- 9 integration tests (MCP + code execution) |
| 178 | +- 3 documentation tests |
| 179 | + |
| 180 | +```bash |
| 181 | +# Run all tests |
| 182 | +cargo test -p terraphim_rlm --features firecracker,mcp |
| 183 | + |
| 184 | +# Run with Firecracker VMs (requires KVM) |
| 185 | +cargo test -p terraphim_rlm --features firecracker -- --ignored |
| 186 | + |
| 187 | +# Mock-only (CI-friendly) |
| 188 | +cargo test -p terraphim_rlm |
| 189 | +``` |
| 190 | + |
| 191 | +## Feature Flags |
| 192 | + |
| 193 | +| Feature | Description | Default | |
| 194 | +|---------|-------------|---------| |
| 195 | +| `firecracker` | Firecracker VM execution | ❌ | |
| 196 | +| `docker-backend` | Docker container fallback | ❌ | |
| 197 | +| `e2b-backend` | E2B cloud execution | ❌ | |
| 198 | +| `mcp` | Model Context Protocol tools | ❌ | |
| 199 | +| `llm` | LLM service integration | ✅ | |
| 200 | +| `kg-validation` | Knowledge graph validation | ❌ | |
| 201 | +| `supervision` | Agent supervisor | ❌ | |
| 202 | + |
| 203 | +## Roadmap |
| 204 | + |
| 205 | +### Phase 1: Core ✅ (Complete) |
| 206 | +- Firecracker integration |
| 207 | +- MCP tools |
| 208 | +- Session management |
| 209 | +- Budget tracking |
| 210 | + |
| 211 | +### Phase 2: Enhanced Security (Next) |
| 212 | +- DNS security with allowlisting |
| 213 | +- gVisor integration |
| 214 | +- Seccomp profiles |
| 215 | + |
| 216 | +### Phase 3: Operations |
| 217 | +- Autoscaler for VM pools |
| 218 | +- Prometheus metrics |
| 219 | +- Distributed tracing |
| 220 | + |
| 221 | +### Phase 4: Advanced Features |
| 222 | +- Multi-region VM pools |
| 223 | +- Persistent volumes |
| 224 | +- Custom VM images |
| 225 | + |
| 226 | +## Acknowledgments |
| 227 | + |
| 228 | +This implementation was inspired by: |
| 229 | +- [rig-rlm](https://github.com/joshua-mo-143/rig-rlm) by Joshua Mo - Reference implementation |
| 230 | +- [Original RLM blog post](https://alexzhang13.github.io/blog/2025/rlm/) by Alex Zhang - Conceptual foundation |
| 231 | +- Firecracker team at AWS - MicroVM technology |
| 232 | + |
| 233 | +## Get Started Today |
| 234 | + |
| 235 | +```bash |
| 236 | +cargo add terraphim_rlm --features firecracker,mcp |
| 237 | +``` |
| 238 | + |
| 239 | +Or clone the repo and explore the examples: |
| 240 | + |
| 241 | +```bash |
| 242 | +git clone https://github.com/terraphim/terraphim-ai |
| 243 | +cd terraphim-ai/crates/terraphim_rlm |
| 244 | +cargo test --features firecracker,mcp -- --nocapture |
| 245 | +``` |
| 246 | + |
| 247 | +## Links |
| 248 | + |
| 249 | +- **Repository**: https://github.com/terraphim/terraphim-ai |
| 250 | +- **Documentation**: https://docs.terraphim.ai/rlm |
| 251 | +- **Issues**: https://github.com/terraphim/terraphim-ai/issues |
| 252 | +- **PR #426**: https://github.com/terraphim/terraphim-ai/pull/426 |
| 253 | + |
| 254 | +--- |
| 255 | + |
| 256 | +*Terraphim RLM: Where recursive AI meets production-grade isolation.* |
| 257 | + |
| 258 | +**What's your use case for RLM? We'd love to hear from you!** Drop us an issue or join the discussion on GitHub. |
0 commit comments