Skip to main content

agentstategraph_policy_wasm/
lib.rs

1//! WASM host runner for AgentStateGraph policies (0.7.5 §4b).
2//!
3//! This crate is a host-side [`ExternalEvaluator`] that loads a WASM
4//! policy module via `wasmtime` and invokes it through a small,
5//! documented ABI. It is NOT compiled to WASM itself — it runs a
6//! WASM module inside the host process.
7//!
8//! # ABI
9//!
10//! The module MUST export a linear memory named `memory` plus three
11//! functions:
12//!
13//! ```text
14//! (func (export "asg_alloc")
15//!   (param $size i32) (result i32))
16//!
17//! (func (export "asg_free")
18//!   (param $ptr i32) (param $size i32))
19//!
20//! (func (export "asg_evaluate")
21//!   (param $input_ptr i32) (param $input_len i32)
22//!   (result i64))     ;; high 32 bits = output_ptr, low 32 bits = output_len
23//! ```
24//!
25//! The host:
26//!
27//! 1. Instantiates the module (no imports required).
28//! 2. Calls `asg_alloc(input_len)` and writes the input JSON bytes
29//!    into linear memory at the returned pointer.
30//! 3. Calls `asg_evaluate(input_ptr, input_len)`. The return value
31//!    packs the output pointer in the high 32 bits and the output
32//!    length in the low 32 bits of the `i64`.
33//! 4. Reads `output_len` bytes from `output_ptr` in linear memory and
34//!    parses them as JSON of [`Decision`].
35//! 5. Calls `asg_free` on both the input and the output buffers.
36//!
37//! # Input JSON
38//!
39//! ```json
40//! {
41//!   "situation": { "<fact-key>": "<fact-value>", ... },
42//!   "action": "<action-name>",
43//!   "agent_id": "<agent-id>"
44//! }
45//! ```
46//!
47//! # Output JSON
48//!
49//! Serde tagged union matching [`Decision`] — see the
50//! `agentstategraph-policy` crate.
51//!
52//! # Source variants
53//!
54//! - [`EvaluatorSource::Inline`] — `body` is interpreted as the raw
55//!   bytes of the WASM module (as a string, so binary modules should
56//!   be embedded via `FilePath` instead in practice; `Inline` is
57//!   useful mainly for WAT fixtures).
58//! - [`EvaluatorSource::FilePath`] — read the module bytes from disk.
59//! - [`EvaluatorSource::CommitRef`] — not supported by this runner;
60//!   returns [`ExternalError::SourceResolution`]. The dispatcher is
61//!   responsible for resolving commit refs in a future milestone.
62
63use std::collections::HashMap;
64
65use agentstategraph_policy::external::{ExternalError, ExternalEvaluator};
66use agentstategraph_policy::selector::Situation;
67use agentstategraph_policy::types::{Decision, EvaluatorSource};
68
69/// Host-side WASM runner.
70///
71/// Shares a single [`wasmtime::Engine`] across evaluations so module
72/// compilation caches are reused. Each call instantiates a fresh
73/// [`wasmtime::Store`] — modules are expected to be pure and
74/// stateless across invocations.
75pub struct WasmEvaluator {
76    engine: wasmtime::Engine,
77}
78
79impl WasmEvaluator {
80    /// Construct a runner with the default wasmtime engine config.
81    pub fn new() -> Self {
82        Self {
83            engine: wasmtime::Engine::default(),
84        }
85    }
86}
87
88impl Default for WasmEvaluator {
89    fn default() -> Self {
90        Self::new()
91    }
92}
93
94/// Convert a [`Situation`] (transparent over `HashMap<String,String>`)
95/// into a plain `HashMap` for JSON serialization.
96fn situation_to_map(s: &Situation) -> HashMap<String, String> {
97    s.0.clone()
98}
99
100impl ExternalEvaluator for WasmEvaluator {
101    fn kind(&self) -> &'static str {
102        "wasm"
103    }
104
105    fn evaluate(
106        &self,
107        source: &EvaluatorSource,
108        situation: &Situation,
109        action: &str,
110        agent_id: &str,
111    ) -> Result<Decision, ExternalError> {
112        // 1. Resolve source -> module bytes.
113        let bytes: Vec<u8> = match source {
114            EvaluatorSource::Inline { body } => body.as_bytes().to_vec(),
115            EvaluatorSource::FilePath { path } => {
116                std::fs::read(path).map_err(|e| ExternalError::SourceResolution(e.to_string()))?
117            }
118            EvaluatorSource::CommitRef { .. } => {
119                return Err(ExternalError::SourceResolution(
120                    "commit_ref not supported by WasmEvaluator".into(),
121                ));
122            }
123        };
124
125        // 2. Compile + instantiate.
126        let mut store = wasmtime::Store::new(&self.engine, ());
127        let module = wasmtime::Module::new(&self.engine, &bytes)
128            .map_err(|e| ExternalError::Execution(format!("compile: {e}")))?;
129        let instance = wasmtime::Instance::new(&mut store, &module, &[])
130            .map_err(|e| ExternalError::Execution(format!("instantiate: {e}")))?;
131
132        let memory = instance
133            .get_memory(&mut store, "memory")
134            .ok_or_else(|| ExternalError::Execution("module missing `memory` export".into()))?;
135        let alloc = instance
136            .get_typed_func::<i32, i32>(&mut store, "asg_alloc")
137            .map_err(|e| ExternalError::Execution(format!("asg_alloc: {e}")))?;
138        let free = instance
139            .get_typed_func::<(i32, i32), ()>(&mut store, "asg_free")
140            .map_err(|e| ExternalError::Execution(format!("asg_free: {e}")))?;
141        let evaluate = instance
142            .get_typed_func::<(i32, i32), i64>(&mut store, "asg_evaluate")
143            .map_err(|e| ExternalError::Execution(format!("asg_evaluate: {e}")))?;
144
145        // 3. Serialize the input envelope.
146        let input = serde_json::json!({
147            "situation": situation_to_map(situation),
148            "action": action,
149            "agent_id": agent_id,
150        });
151        let input_bytes = serde_json::to_vec(&input)
152            .map_err(|e| ExternalError::Execution(format!("input serialize: {e}")))?;
153        let input_len = input_bytes.len() as i32;
154
155        // 4. Alloc + write.
156        let input_ptr = alloc
157            .call(&mut store, input_len)
158            .map_err(|e| ExternalError::Execution(format!("alloc input: {e}")))?;
159        memory
160            .write(&mut store, input_ptr as usize, &input_bytes)
161            .map_err(|e| ExternalError::Execution(format!("write input: {e}")))?;
162
163        // 5. Invoke.
164        let packed = evaluate
165            .call(&mut store, (input_ptr, input_len))
166            .map_err(|e| ExternalError::Execution(format!("evaluate: {e}")))?;
167        let out_ptr = (packed >> 32) as i32;
168        let out_len = (packed & 0xFFFF_FFFF) as i32;
169
170        if out_len < 0 {
171            return Err(ExternalError::Execution(format!(
172                "asg_evaluate returned negative output length ({out_len})"
173            )));
174        }
175
176        // 6. Read output.
177        let mut out_bytes = vec![0u8; out_len as usize];
178        memory
179            .read(&store, out_ptr as usize, &mut out_bytes)
180            .map_err(|e| ExternalError::Execution(format!("read output: {e}")))?;
181
182        // 7. Best-effort free; ignore errors (module may not care).
183        let _ = free.call(&mut store, (input_ptr, input_len));
184        let _ = free.call(&mut store, (out_ptr, out_len));
185
186        // 8. Parse decision.
187        let decision: Decision = serde_json::from_slice(&out_bytes)
188            .map_err(|e| ExternalError::Execution(format!("parse decision: {e}")))?;
189        Ok(decision)
190    }
191}