caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
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
//! WebAssembly runtime for managing agent lifecycle and execution

use anyhow::{Context, Result, bail};
use dashmap::DashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tracing::{debug, info, warn};
use wasmtime::{Config as WasmConfig, Engine, Module};

use crate::domain_types::{AgentId, AgentName, CpuFuel, MaxAgents, MemoryBytes, MessageCount};
use crate::resource_manager::{ResourceLimits, ResourceManager};
use crate::sandbox::Sandbox;
use crate::security::SecurityPolicy;

/// Result of executing an agent function
#[derive(Debug, Clone)]
pub struct ExecutionResult {
    /// Amount of fuel consumed during execution
    pub fuel_consumed: CpuFuel,
    /// Whether the execution completed successfully
    pub completed_successfully: bool,
    /// Output data from the execution
    pub output: Option<Vec<u8>>,
}

impl ExecutionResult {
    /// Creates a successful execution result
    pub fn success(fuel_consumed: CpuFuel, output: Option<Vec<u8>>) -> Self {
        Self {
            fuel_consumed,
            completed_successfully: true,
            output,
        }
    }

    /// Creates a failed execution result
    pub fn failure(fuel_consumed: CpuFuel) -> Self {
        Self {
            fuel_consumed,
            completed_successfully: false,
            output: None,
        }
    }
}

/// Configuration for the WebAssembly runtime
#[derive(Debug, Clone)]
pub struct WasmRuntimeConfig {
    /// Resource limits for agents
    pub resource_limits: ResourceLimits,
    /// Security policy for agent execution
    pub security_policy: SecurityPolicy,
    /// Maximum number of concurrent agents
    pub max_agents: MaxAgents,
    /// Enable debug mode
    pub enable_debug: bool,
}

impl Default for WasmRuntimeConfig {
    fn default() -> Self {
        Self {
            resource_limits: ResourceLimits::default(),
            security_policy: SecurityPolicy::default(),
            max_agents: MaxAgents::try_new(1000).unwrap(),
            enable_debug: false,
        }
    }
}

/// Main WebAssembly runtime for managing agents
pub struct WasmRuntime {
    engine: Arc<Engine>,
    agents: Arc<DashMap<AgentId, Agent>>,
    config: WasmRuntimeConfig,
    active_count: Arc<AtomicUsize>,
    resource_manager: Arc<ResourceManager>,
    initialized: bool,
}

#[allow(dead_code)]
struct Agent {
    id: AgentId,
    name: AgentName,
    sandbox: Sandbox,
    #[allow(dead_code)]
    module: Module,
    state: AgentState,
    resource_usage: ResourceUsage,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum AgentState {
    #[allow(dead_code)]
    Unloaded,
    Loaded,
    Running,
    Draining,
    Stopped,
}

#[derive(Debug)]
struct ResourceUsage {
    memory_bytes: MemoryBytes,
    cpu_fuel_consumed: CpuFuel,
    message_count: MessageCount,
}

impl Default for ResourceUsage {
    fn default() -> Self {
        Self {
            memory_bytes: MemoryBytes::zero(),
            cpu_fuel_consumed: CpuFuel::zero(),
            message_count: MessageCount::zero(),
        }
    }
}

impl Agent {
    fn id(&self) -> AgentId {
        self.id
    }

    fn name(&self) -> String {
        self.name.to_string()
    }
}

impl ResourceUsage {
    fn update_memory(&mut self, bytes: MemoryBytes) {
        self.memory_bytes = bytes;
    }

    fn update_cpu(&mut self, fuel: CpuFuel) {
        self.cpu_fuel_consumed = self.cpu_fuel_consumed.saturating_add(fuel);
    }

    fn increment_message_count(&mut self) {
        self.message_count = self.message_count.increment();
    }
}

impl WasmRuntime {
    /// Creates a new WebAssembly runtime with the given configuration
    ///
    /// # Errors
    ///
    /// Returns an error if the engine cannot be created
    pub fn new(config: WasmRuntimeConfig) -> Result<Self> {
        info!("Initializing WASM runtime with config: {:?}", config);

        let mut wasm_config = WasmConfig::new();

        wasm_config.async_support(true);
        wasm_config.consume_fuel(config.security_policy.enable_fuel_metering);

        // Note: Some WASM features have dependencies, so we need to be careful
        // For now, we'll use the defaults for most features to avoid conflicts
        if config.security_policy.disable_threads() {
            wasm_config.wasm_threads(false);
        }

        wasm_config.parallel_compilation(true);
        wasm_config
            .cache_config_load_default()
            .context("Failed to load cache config")?;

        let engine = Arc::new(Engine::new(&wasm_config).context("Failed to create WASM engine")?);

        let resource_manager = Arc::new(ResourceManager::new(config.resource_limits.clone()));

        Ok(Self {
            engine,
            agents: Arc::new(DashMap::new()),
            config,
            active_count: Arc::new(AtomicUsize::new(0)),
            resource_manager,
            initialized: true,
        })
    }

    /// Checks if the runtime is initialized
    pub fn is_initialized(&self) -> bool {
        self.initialized
    }

    /// Returns the number of active agents
    pub fn active_agent_count(&self) -> usize {
        self.active_count.load(Ordering::SeqCst)
    }

    /// Gets the resource manager for monitoring
    pub fn resource_manager(&self) -> &ResourceManager {
        &self.resource_manager
    }

    /// Deploys a new agent from WebAssembly bytecode
    ///
    /// # Errors
    ///
    /// Returns an error if the module is invalid or if agent limit is reached
    pub async fn deploy_agent(&mut self, name: &str, wasm_bytes: &[u8]) -> Result<AgentId> {
        info!("Deploying agent: {}", name);

        if self.active_agent_count() >= self.config.max_agents.into_inner() {
            bail!(
                "Maximum number of agents ({}) reached",
                self.config.max_agents
            );
        }

        let module = Module::new(&self.engine, wasm_bytes)
            .context("invalid WASM module: failed to compile")?;

        Self::validate_module(&module);

        let agent_id = AgentId::generate();

        let mut sandbox = Sandbox::new(
            agent_id,
            self.config.resource_limits.clone(),
            self.engine.clone(),
        )?;

        // Initialize the sandbox with the module immediately
        sandbox.initialize(&module).await?;

        // Start agents in Loaded state since sandbox is already initialized
        let agent_name = AgentName::try_new(name.to_string())
            .map_err(|e| anyhow::anyhow!("Invalid agent name: {}", e))?;
        let agent = Agent {
            id: agent_id,
            name: agent_name,
            sandbox,
            module,
            state: AgentState::Loaded,
            resource_usage: ResourceUsage::default(),
        };

        debug!(
            "Agent {:?} created and initialized in {:?} state",
            agent_id, agent.state
        );

        self.agents.insert(agent_id, agent);
        self.active_count.fetch_add(1, Ordering::SeqCst);

        // Use agent name and id for logging
        info!("Agent '{}' deployed with ID: {:?}", name, agent_id);
        debug!(
            "Agent {:?} is now in {:?} state",
            agent_id,
            AgentState::Loaded
        );
        Ok(agent_id)
    }

    /// Starts an agent that has been deployed (transitions from Loaded to Running)
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found or not in Loaded state
    pub fn start_agent(&mut self, agent_id: AgentId) -> Result<()> {
        let mut agent = self
            .agents
            .get_mut(&agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

        if agent.state != AgentState::Loaded {
            bail!(
                "Agent {:?} is not in Loaded state (current: {:?})",
                agent_id,
                agent.state
            );
        }

        // Agent sandbox is already initialized during deployment, just transition state
        agent.state = AgentState::Running;

        info!("Agent {:?} started", agent_id);
        Ok(())
    }

    /// Executes a function on an agent
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found or not running
    ///
    /// # Panics
    ///
    /// Panics if the fuel value cannot be created (should never happen with valid fuel values)
    pub async fn execute_agent(
        &mut self,
        agent_id: AgentId,
        function: &str,
        args: &[u8],
    ) -> Result<Vec<u8>> {
        let mut agent = self
            .agents
            .get_mut(&agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

        if agent.state != AgentState::Running {
            bail!("Agent {:?} is not running", agent_id);
        }

        let result = agent.sandbox.execute(function, args).await?;

        let fuel = result.fuel_consumed;
        agent.resource_usage.update_cpu(fuel);

        Ok(result.output.unwrap_or_default())
    }

    /// Executes a function on an agent with detailed fuel tracking
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found or execution fails
    ///
    /// # Panics
    ///
    /// Panics if the agent exists but cannot be retrieved after starting
    pub async fn execute_agent_with_fuel_tracking(
        &mut self,
        agent_id: AgentId,
        function: &str,
        args: &[u8],
    ) -> Result<ExecutionResult> {
        // Check if agent needs to be started
        {
            let agent = self
                .agents
                .get(&agent_id)
                .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

            if agent.state != AgentState::Running {
                drop(agent);
                self.start_agent(agent_id)?;
            }
        }

        // Now execute
        let mut agent = self.agents.get_mut(&agent_id).unwrap();
        let result = agent.sandbox.execute(function, args).await?;

        let fuel = result.fuel_consumed;
        agent.resource_usage.update_cpu(fuel);

        Ok(result)
    }

    /// Gets the memory usage of a specific agent
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found
    pub fn get_agent_memory_usage(&self, agent_id: AgentId) -> Result<MemoryBytes> {
        let agent = self
            .agents
            .get(&agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

        let usage = agent.sandbox.get_memory_usage();
        MemoryBytes::try_new(usage).map_err(|e| anyhow::anyhow!("Invalid memory value: {}", e))
    }

    /// Gets the CPU fuel usage of a specific agent
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found
    pub fn get_agent_cpu_usage(&self, agent_id: AgentId) -> Result<CpuFuel> {
        let agent = self
            .agents
            .get(&agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

        Ok(agent.resource_usage.cpu_fuel_consumed)
    }

    /// Gets the list of host functions exposed to an agent
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found
    pub fn get_exposed_host_functions(&self, agent_id: AgentId) -> Result<Vec<String>> {
        let agent = self
            .agents
            .get(&agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

        Ok(agent.sandbox.get_exposed_functions())
    }

    /// Gets the runtime's security policy
    pub fn get_security_policy(&self) -> &SecurityPolicy {
        &self.config.security_policy
    }

    fn validate_module(module: &Module) {
        debug!("Validating WASM module");

        let mut exports = module.exports();
        let has_memory = exports.any(|e| e.name() == "memory");

        if !has_memory {
            debug!("Module does not export memory, this is acceptable");
        }
    }

    /// Stops a running agent
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found or shutdown fails
    pub async fn stop_agent(&mut self, agent_id: AgentId) -> Result<()> {
        let mut agent = self
            .agents
            .get_mut(&agent_id)
            .ok_or_else(|| anyhow::anyhow!("Agent not found: {:?}", agent_id))?;

        // Transition through draining state
        let prev_state = agent.state.clone();
        agent.state = AgentState::Draining;
        info!(
            "Agent {:?} ({:?}) transitioning from {:?} to {:?}",
            agent.name(),
            agent.id(),
            prev_state,
            AgentState::Draining
        );

        agent.sandbox.shutdown().await?;

        agent.state = AgentState::Stopped;

        // Log resource usage on stop
        agent.resource_usage.increment_message_count();
        info!(
            "Agent {:?} ({:?}) stopped after processing messages",
            agent.name(),
            agent.id()
        );
        Ok(())
    }

    /// Removes an agent from the runtime
    ///
    /// # Errors
    ///
    /// Returns an error if the agent is not found
    pub fn remove_agent(&mut self, agent_id: AgentId) -> Result<()> {
        if let Some((_, mut agent)) = self.agents.remove(&agent_id) {
            match &agent.state {
                AgentState::Running => {
                    warn!(
                        "Removing running agent {:?} ({:?})",
                        agent.name(),
                        agent.id()
                    );
                }
                AgentState::Unloaded => {
                    debug!(
                        "Removing unloaded agent {:?} ({:?})",
                        agent.name(),
                        agent.id()
                    );
                }
                state => {
                    info!(
                        "Removing agent {:?} ({:?}) in state {:?}",
                        agent.name(),
                        agent.id(),
                        state
                    );
                }
            }

            // Track resource usage
            agent.resource_usage.update_memory(MemoryBytes::zero());

            self.active_count.fetch_sub(1, Ordering::SeqCst);
            self.resource_manager.cleanup_agent(agent_id);
            info!("Agent {:?} removed", agent_id);
            Ok(())
        } else {
            bail!("Agent not found: {:?}", agent_id)
        }
    }
}

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

    #[tokio::test]
    async fn test_wasm_runtime_config_default() {
        let config = WasmRuntimeConfig::default();
        assert_eq!(config.max_agents.as_usize(), 1000);
        assert!(!config.enable_debug);
    }

    #[test]
    fn test_wasm_runtime_new() {
        let config = WasmRuntimeConfig::default();
        let runtime = WasmRuntime::new(config);
        assert!(runtime.is_ok());
        let runtime = runtime.unwrap();
        assert!(runtime.is_initialized());
        assert_eq!(runtime.active_agent_count(), 0);
    }

    #[tokio::test]
    async fn test_agent_state_transitions() {
        let state = AgentState::Unloaded;
        assert_eq!(state, AgentState::Unloaded);

        let state = AgentState::Loaded;
        assert_eq!(state, AgentState::Loaded);

        let state = AgentState::Running;
        assert_eq!(state, AgentState::Running);
    }

    #[test]
    fn test_resource_usage_update_memory() {
        let mut usage = ResourceUsage::default();
        assert_eq!(usage.memory_bytes.as_usize(), 0);

        usage.update_memory(MemoryBytes::try_new(1024).unwrap());
        assert_eq!(usage.memory_bytes.as_usize(), 1024);

        usage.update_memory(MemoryBytes::try_new(2048).unwrap());
        assert_eq!(usage.memory_bytes.as_usize(), 2048);
    }

    #[test]
    fn test_resource_usage_update_cpu() {
        let mut usage = ResourceUsage::default();
        assert_eq!(usage.cpu_fuel_consumed.as_u64(), 0);

        usage.update_cpu(CpuFuel::try_new(100).unwrap());
        assert_eq!(usage.cpu_fuel_consumed.as_u64(), 100);

        usage.update_cpu(CpuFuel::try_new(50).unwrap());
        assert_eq!(usage.cpu_fuel_consumed.as_u64(), 150);
    }

    #[test]
    fn test_resource_usage_increment_message_count() {
        let mut usage = ResourceUsage::default();
        assert_eq!(usage.message_count.as_usize(), 0);

        usage.increment_message_count();
        assert_eq!(usage.message_count.as_usize(), 1);

        usage.increment_message_count();
        assert_eq!(usage.message_count.as_usize(), 2);
    }

    #[test]
    fn test_execution_result() {
        let result = ExecutionResult::success(CpuFuel::try_new(100).unwrap(), Some(vec![1, 2, 3]));

        assert_eq!(result.fuel_consumed.as_u64(), 100);
        assert!(result.completed_successfully);
        assert_eq!(result.output, Some(vec![1, 2, 3]));
    }

    #[test]
    fn test_wasm_runtime_max_agents() {
        let config = WasmRuntimeConfig {
            max_agents: MaxAgents::try_new(2).unwrap(),
            ..Default::default()
        };
        let runtime = WasmRuntime::new(config).unwrap();
        assert_eq!(runtime.config.max_agents.as_usize(), 2);
    }

    #[test]
    fn test_agent_state_equality() {
        assert_eq!(AgentState::Unloaded, AgentState::Unloaded);
        assert_ne!(AgentState::Unloaded, AgentState::Loaded);
        assert_ne!(AgentState::Running, AgentState::Stopped);
    }
}