navi-plugin-runtime 0.3.5

Local agentic engine and terminal-first coding agent.
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use crate::error::RuntimeError;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use wasmtime::*;

/// Data stored in the WASM store, holding resource limits and host callbacks.
struct StoreData {
    limits: StoreLimits,
    callbacks: HostCallbacks,
}

/// Host callback functions that the WASM module can call.
///
/// Each callback receives a string input and returns a string output.
/// Errors are returned as JSON: `{"error": "message"}`.
#[derive(Clone)]
pub struct HostCallbacks {
    /// Read a project file. Input: path. Output: file content or error JSON.
    pub fs_read: Arc<dyn Fn(&str) -> String + Send + Sync>,
    /// List a project directory. Input: path. Output: JSON array of names or error JSON.
    pub fs_list: Arc<dyn Fn(&str) -> String + Send + Sync>,
    /// Make an HTTP request. Input: JSON `{method, url, body}`. Output: JSON response or error JSON.
    pub http_request: Arc<dyn Fn(&str) -> String + Send + Sync>,
    /// Get git status. Input: empty. Output: git status text or error JSON.
    pub git_status: Arc<dyn Fn() -> String + Send + Sync>,
    /// Get git diff. Input: empty. Output: git diff text or error JSON.
    pub git_diff: Arc<dyn Fn() -> String + Send + Sync>,
}

impl Default for HostCallbacks {
    fn default() -> Self {
        Self {
            fs_read: Arc::new(|_| r#"{"error":"not implemented"}"#.into()),
            fs_list: Arc::new(|_| r#"{"error":"not implemented"}"#.into()),
            http_request: Arc::new(|_| r#"{"error":"not implemented"}"#.into()),
            git_status: Arc::new(|| r#"{"error":"not implemented"}"#.into()),
            git_diff: Arc::new(|| r#"{"error":"not implemented"}"#.into()),
        }
    }
}

/// Configuration for the WASM plugin runtime.
/// All limits are mandatory and cannot be disabled.
#[derive(Debug, Clone)]
pub struct ToolRuntimeConfig {
    /// Wall-clock timeout per invocation.
    pub timeout: Duration,
    /// Linear memory limit in bytes.
    pub memory_limit_bytes: u64,
    /// Fuel (instruction budget) per invocation.
    pub fuel: u64,
    /// Max tool output size in bytes.
    pub max_output_bytes: usize,
    /// Stack size in bytes.
    pub stack_size_bytes: usize,
}

impl Default for ToolRuntimeConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(30),
            memory_limit_bytes: 64 * 1024 * 1024, // 64 MB
            fuel: 10_000_000,
            max_output_bytes: 32 * 1024,   // 32 KB
            stack_size_bytes: 1024 * 1024, // 1 MB
        }
    }
}

/// Result of a tool invocation.
#[derive(Debug, Clone)]
pub struct RunResult {
    /// The JSON output string from the plugin.
    pub output: String,
    /// Fuel consumed during execution.
    pub fuel_consumed: u64,
    /// Wall-clock duration of execution.
    pub duration: Duration,
}

/// WASM plugin runtime with mandatory resource limits.
pub struct PluginRuntime {
    config: ToolRuntimeConfig,
}

impl PluginRuntime {
    /// Create a new runtime with the given configuration.
    pub fn new(config: ToolRuntimeConfig) -> Self {
        Self { config }
    }

    /// Create a runtime with default security limits.
    pub fn with_defaults() -> Self {
        Self::new(ToolRuntimeConfig::default())
    }

    /// Execute a tool in a WASM module with host callbacks.
    pub fn execute(
        &self,
        wasm_bytes: &[u8],
        tool_name: &str,
        input_json: &str,
        callbacks: HostCallbacks,
    ) -> Result<RunResult, RuntimeError> {
        let start = Instant::now();

        let mut engine_config = Config::new();
        engine_config.consume_fuel(true);

        let engine = Engine::new(&engine_config)?;

        let limits = StoreLimitsBuilder::new()
            .memory_size(self.config.memory_limit_bytes as usize)
            .build();
        let mut store = Store::new(&engine, StoreData { limits, callbacks });

        store.set_fuel(self.config.fuel)?;
        store.limiter(|data: &mut StoreData| &mut data.limits);

        let module = Module::new(&engine, wasm_bytes)?;
        let mut linker = Linker::new(&engine);

        // Register host imports
        add_host_imports(&mut linker)?;

        let instance = linker.instantiate(&mut store, &module)?;

        let run_tool = instance
            .get_typed_func::<(i32, i32, i32, i32), i32>(&mut store, "run_tool")
            .map_err(|_| RuntimeError::ToolNotFound {
                tool_name: tool_name.into(),
            })?;

        let memory = instance.get_memory(&mut store, "memory").ok_or_else(|| {
            RuntimeError::ToolNotFound {
                tool_name: "memory".into(),
            }
        })?;

        // Write tool_name and input_json into WASM memory
        let tool_name_bytes = tool_name.as_bytes();
        let input_bytes = input_json.as_bytes();

        let tool_name_ptr = 0i32;
        let input_ptr = tool_name_bytes.len() as i32;

        let total_needed = tool_name_bytes.len() + input_bytes.len();
        let pages_needed = total_needed.div_ceil(65536);
        let current_pages = memory.size(&store) as usize;
        if total_needed > current_pages * 65536 {
            memory.grow(&mut store, pages_needed as u64)?;
        }

        let mem_data = memory.data_mut(&mut store);
        mem_data[..tool_name_bytes.len()].copy_from_slice(tool_name_bytes);
        mem_data[tool_name_bytes.len()..tool_name_bytes.len() + input_bytes.len()]
            .copy_from_slice(input_bytes);

        // Timeout thread
        let timed_out = Arc::new(AtomicBool::new(false));
        let timed_out_clone = timed_out.clone();
        let timeout = self.config.timeout;
        let timeout_thread = std::thread::spawn(move || {
            std::thread::sleep(timeout);
            timed_out_clone.store(true, Ordering::Relaxed);
        });

        let result = run_tool.call(
            &mut store,
            (
                tool_name_ptr,
                tool_name_bytes.len() as i32,
                input_ptr,
                input_bytes.len() as i32,
            ),
        );

        let timed_out_flag = timed_out.load(Ordering::Relaxed);
        drop(timeout_thread);

        let fuel_after = self
            .config
            .fuel
            .saturating_sub(store.get_fuel().unwrap_or(0));
        let duration = start.elapsed();

        match result {
            Ok(output_ptr) => {
                let mem_data = memory.data(&store);
                let ptr = output_ptr as usize;

                if ptr + 4 > mem_data.len() {
                    return Err(RuntimeError::PluginError("invalid output pointer".into()));
                }

                let len = u32::from_le_bytes([
                    mem_data[ptr],
                    mem_data[ptr + 1],
                    mem_data[ptr + 2],
                    mem_data[ptr + 3],
                ]) as usize;

                if ptr + 4 + len > mem_data.len() {
                    return Err(RuntimeError::PluginError(
                        "output extends beyond memory".into(),
                    ));
                }

                let output_bytes = &mem_data[ptr + 4..ptr + 4 + len];
                let output = String::from_utf8_lossy(output_bytes).to_string();

                if output.len() > self.config.max_output_bytes {
                    return Err(RuntimeError::OutputTooLarge {
                        size_bytes: output.len(),
                        limit_bytes: self.config.max_output_bytes,
                    });
                }

                Ok(RunResult {
                    output,
                    fuel_consumed: fuel_after,
                    duration,
                })
            }
            Err(e) => {
                if timed_out_flag {
                    return Err(RuntimeError::Timeout {
                        timeout_secs: self.config.timeout.as_secs(),
                    });
                }

                let e_str = format!("{:?}", e);
                if e_str.contains("fuel") || e_str.contains("all fuel consumed") {
                    return Err(RuntimeError::FuelExhausted);
                }

                if e_str.contains("memory") || e_str.contains("out of bounds") {
                    return Err(RuntimeError::MemoryLimitExceeded {
                        limit_mb: self.config.memory_limit_bytes / (1024 * 1024),
                    });
                }

                Err(RuntimeError::Engine(e.to_string()))
            }
        }
    }
}

/// Helper: read a string from WASM memory.
fn read_wasm_string(mem: &[u8], ptr: i32, len: i32) -> String {
    let start = ptr as usize;
    let end = start + len as usize;
    if end > mem.len() {
        return String::new();
    }
    String::from_utf8_lossy(&mem[start..end]).to_string()
}

/// Helper: write a string to WASM memory and return the pointer.
/// Format: [4 bytes length LE][content bytes]
fn write_wasm_string(mem: &mut [u8], content: &str, offset: usize) -> i32 {
    let bytes = content.as_bytes();
    let len = bytes.len() as u32;
    mem[offset..offset + 4].copy_from_slice(&len.to_le_bytes());
    mem[offset + 4..offset + 4 + bytes.len()].copy_from_slice(bytes);
    offset as i32
}

/// Register host imports with real implementations backed by HostCallbacks.
fn add_host_imports(linker: &mut Linker<StoreData>) -> Result<(), RuntimeError> {
    // fs.read-project-file(path_ptr, path_len) -> result_ptr
    linker.func_wrap(
        "fs",
        "read-project-file",
        |mut caller: Caller<'_, StoreData>, ptr: i32, len: i32| -> i32 {
            let path = {
                let mem = caller.get_export("memory").and_then(|e| e.into_memory());
                match mem {
                    Some(m) => read_wasm_string(m.data(&caller), ptr, len),
                    None => return -1,
                }
            };

            let result = (caller.data().callbacks.fs_read)(&path);

            let mem = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                Some(m) => m,
                None => return -1,
            };
            // Write result at the end of current memory (after input area)
            let offset = mem.data_size(&caller).saturating_sub(4096);
            write_wasm_string(mem.data_mut(&mut caller), &result, offset)
        },
    )?;

    // fs.list-project-dir(path_ptr, path_len) -> result_ptr
    linker.func_wrap(
        "fs",
        "list-project-dir",
        |mut caller: Caller<'_, StoreData>, ptr: i32, len: i32| -> i32 {
            let path = {
                let mem = caller.get_export("memory").and_then(|e| e.into_memory());
                match mem {
                    Some(m) => read_wasm_string(m.data(&caller), ptr, len),
                    None => return -1,
                }
            };

            let result = (caller.data().callbacks.fs_list)(&path);

            let mem = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                Some(m) => m,
                None => return -1,
            };
            let offset = mem.data_size(&caller).saturating_sub(4096);
            write_wasm_string(mem.data_mut(&mut caller), &result, offset)
        },
    )?;

    // http.request(method_ptr, method_len, url_ptr, url_len, body_ptr, body_len) -> result_ptr
    linker.func_wrap(
        "http",
        "request",
        |mut caller: Caller<'_, StoreData>,
         m_ptr: i32,
         m_len: i32,
         u_ptr: i32,
         u_len: i32,
         b_ptr: i32,
         b_len: i32|
         -> i32 {
            let (method, url, body) = {
                let mem = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };
                let data = mem.data(&caller);
                let method = read_wasm_string(data, m_ptr, m_len);
                let url = read_wasm_string(data, u_ptr, u_len);
                let body = if b_ptr >= 0 && b_len > 0 {
                    read_wasm_string(data, b_ptr, b_len)
                } else {
                    String::new()
                };
                (method, url, body)
            };

            let input = if body.is_empty() {
                format!(r#"{{"method":"{}","url":"{}"}}"#, method, url)
            } else {
                format!(
                    r#"{{"method":"{}","url":"{}","body":"{}"}}"#,
                    method, url, body
                )
            };

            let result = (caller.data().callbacks.http_request)(&input);

            let mem = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                Some(m) => m,
                None => return -1,
            };
            let offset = mem.data_size(&caller).saturating_sub(4096);
            write_wasm_string(mem.data_mut(&mut caller), &result, offset)
        },
    )?;

    // git.status() -> result_ptr
    linker.func_wrap(
        "git",
        "status",
        |mut caller: Caller<'_, StoreData>| -> i32 {
            let result = (caller.data().callbacks.git_status)();

            let mem = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                Some(m) => m,
                None => return -1,
            };
            let offset = mem.data_size(&caller).saturating_sub(4096);
            write_wasm_string(mem.data_mut(&mut caller), &result, offset)
        },
    )?;

    // git.diff() -> result_ptr
    linker.func_wrap("git", "diff", |mut caller: Caller<'_, StoreData>| -> i32 {
        let result = (caller.data().callbacks.git_diff)();

        let mem = match caller.get_export("memory").and_then(|e| e.into_memory()) {
            Some(m) => m,
            None => return -1,
        };
        let offset = mem.data_size(&caller).saturating_sub(4096);
        write_wasm_string(mem.data_mut(&mut caller), &result, offset)
    })?;

    Ok(())
}

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

    #[test]
    fn default_config_matches_spec() {
        let config = ToolRuntimeConfig::default();
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.memory_limit_bytes, 64 * 1024 * 1024);
        assert_eq!(config.fuel, 10_000_000);
        assert_eq!(config.max_output_bytes, 32 * 1024);
        assert_eq!(config.stack_size_bytes, 1024 * 1024);
    }

    #[test]
    fn runtime_creation() {
        let runtime = PluginRuntime::with_defaults();
        assert_eq!(runtime.config.timeout, Duration::from_secs(30));
    }

    #[test]
    fn runtime_with_custom_config() {
        let config = ToolRuntimeConfig {
            timeout: Duration::from_secs(5),
            memory_limit_bytes: 16 * 1024 * 1024,
            fuel: 1_000_000,
            max_output_bytes: 8192,
            stack_size_bytes: 512 * 1024,
        };
        let runtime = PluginRuntime::new(config.clone());
        assert_eq!(runtime.config.timeout, Duration::from_secs(5));
        assert_eq!(runtime.config.memory_limit_bytes, 16 * 1024 * 1024);
    }

    #[test]
    fn execute_echo_plugin() {
        let wasm = wat::parse_str(
            r#"
            (module
                (memory (export "memory") 1)

                (func $write_u32 (param $ptr i32) (param $val i32)
                    (i32.store (local.get $ptr) (local.get $val))
                )

                (func (export "run_tool")
                    (param $name_ptr i32) (param $name_len i32)
                    (param $input_ptr i32) (param $input_len i32)
                    (result i32)

                    (local $output_ptr i32)
                    (local $i i32)

                    (local.set $output_ptr
                        (i32.add (local.get $input_ptr) (local.get $input_len))
                    )

                    (call $write_u32 (local.get $output_ptr) (local.get $input_len))

                    (local.set $i (i32.const 0))
                    (block $break
                        (loop $copy
                            (br_if $break (i32.ge_u (local.get $i) (local.get $input_len)))
                            (i32.store8
                                (i32.add (i32.add (local.get $output_ptr) (i32.const 4)) (local.get $i))
                                (i32.load8_u (i32.add (local.get $input_ptr) (local.get $i)))
                            )
                            (local.set $i (i32.add (local.get $i) (i32.const 1)))
                            (br $copy)
                        )
                    )

                    (local.get $output_ptr)
                )
            )
            "#,
        )
        .expect("valid WAT");

        let runtime = PluginRuntime::with_defaults();
        let result = runtime.execute(
            &wasm,
            "echo",
            r#"{"text":"hello"}"#,
            HostCallbacks::default(),
        );
        assert!(
            result.is_ok(),
            "execution should succeed: {:?}",
            result.err()
        );
        let result = result.unwrap();
        assert_eq!(result.output, r#"{"text":"hello"}"#);
    }

    #[test]
    fn execute_fuel_exhaustion() {
        let wasm = wat::parse_str(
            r#"
            (module
                (memory (export "memory") 1)
                (func (export "run_tool")
                    (param $name_ptr i32) (param $name_len i32)
                    (param $input_ptr i32) (param $input_len i32)
                    (result i32)
                    (block $break
                        (loop $loop
                            (br $loop)
                        )
                    )
                    (i32.const 0)
                )
            )
            "#,
        )
        .expect("valid WAT");

        let config = ToolRuntimeConfig {
            fuel: 100,
            timeout: Duration::from_secs(3600),
            ..Default::default()
        };
        let runtime = PluginRuntime::new(config);
        let result = runtime.execute(&wasm, "loop", "{}", HostCallbacks::default());
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, RuntimeError::FuelExhausted),
            "should be fuel exhaustion, got: {:?}",
            err
        );
    }

    #[test]
    fn execute_timeout() {
        let wasm = wat::parse_str(
            r#"
            (module
                (memory (export "memory") 1)
                (func (export "run_tool")
                    (param $name_ptr i32) (param $name_len i32)
                    (param $input_ptr i32) (param $input_len i32)
                    (result i32)
                    (local $i i32)
                    (block $break
                        (loop $loop
                            (local.set $i (i32.add (local.get $i) (i32.const 1)))
                            (br_if $break (i32.ge_u (local.get $i) (i32.const 1000000000)))
                            (br $loop)
                        )
                    )
                    (i32.const 0)
                )
            )
            "#,
        )
        .expect("valid WAT");

        let config = ToolRuntimeConfig {
            timeout: Duration::from_millis(1),
            fuel: 100_000_000,
            ..Default::default()
        };
        let runtime = PluginRuntime::new(config);
        let result = runtime.execute(&wasm, "slow", "{}", HostCallbacks::default());
        if let Err(e) = result {
            assert!(
                matches!(e, RuntimeError::Timeout { .. }),
                "should be timeout"
            );
        }
    }

    #[test]
    fn tool_not_found_error() {
        let wasm = wat::parse_str(
            r#"
            (module
                (memory (export "memory") 1)
                (func (export "other_func") (result i32)
                    (i32.const 0)
                )
            )
            "#,
        )
        .expect("valid WAT");

        let runtime = PluginRuntime::with_defaults();
        let result = runtime.execute(&wasm, "test", "{}", HostCallbacks::default());
        assert!(result.is_err());
        assert!(
            matches!(result.unwrap_err(), RuntimeError::ToolNotFound { .. }),
            "should be tool not found"
        );
    }

    #[test]
    fn host_callback_fs_read() {
        // WASM module that calls fs.read-project-file and returns the result
        let wasm = wat::parse_str(
            r#"
            (module
                ;; Import fs.read-project-file BEFORE memory
                (import "fs" "read-project-file" (func $fs_read (param i32 i32) (result i32)))

                (memory (export "memory") 1)

                (func (export "run_tool")
                    (param $name_ptr i32) (param $name_len i32)
                    (param $input_ptr i32) (param $input_len i32)
                    (result i32)

                    ;; Write "test.txt" at address 0
                    (i32.store8 (i32.const 0) (i32.const 116))  ;; t
                    (i32.store8 (i32.const 1) (i32.const 101))  ;; e
                    (i32.store8 (i32.const 2) (i32.const 115))  ;; s
                    (i32.store8 (i32.const 3) (i32.const 116))  ;; t
                    (i32.store8 (i32.const 4) (i32.const 46))   ;; .
                    (i32.store8 (i32.const 5) (i32.const 116))  ;; t
                    (i32.store8 (i32.const 6) (i32.const 120))  ;; x
                    (i32.store8 (i32.const 7) (i32.const 116))  ;; t

                    ;; Call fs.read-project-file(0, 8)
                    (call $fs_read (i32.const 0) (i32.const 8))
                    ;; Return the result pointer
                )
            )
            "#,
        )
        .expect("valid WAT");

        let callbacks = HostCallbacks {
            fs_read: Arc::new(|path| {
                if path == "test.txt" {
                    r#"{"content":"hello from broker"}"#.into()
                } else {
                    r#"{"error":"not found"}"#.into()
                }
            }),
            ..Default::default()
        };

        let runtime = PluginRuntime::with_defaults();
        let result = runtime.execute(&wasm, "read", "{}", callbacks);
        assert!(result.is_ok(), "should succeed: {:?}", result.err());
    }
}