use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use agent_base::{AgentError, AgentResult, Content, Tool, ToolContext, ToolExposure, ToolMetadata};
use async_trait::async_trait;
use serde_json::Value;
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store, Trap};
use wasmtime_wasi::p2::pipe::MemoryOutputPipe;
use wasmtime_wasi::{FsPerms, ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
use wasmtime_wasi_http::p2::add_only_http_to_linker_async;
use wasmtime_wasi_http::{
Error as HttpError, RequestOptions, WasiBody, WasiHttpCtx, WasiHttpCtxView, WasiHttpHooks,
WasiHttpView,
};
use super::manifest::ResolvedCapability;
use crate::script_tool::{ParamSpec, parameters_envelope};
use std::collections::BTreeMap;
const EPOCH_TICK_MS: u64 = 10;
fn epoch_ticker_spawns_counter() -> &'static std::sync::atomic::AtomicUsize {
static SPAWNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
&SPAWNS
}
#[cfg(test)]
fn epoch_ticker_spawns() -> usize {
epoch_ticker_spawns_counter().load(std::sync::atomic::Ordering::SeqCst)
}
fn shared_engine() -> Result<Engine, WasmError> {
static ENGINE: std::sync::OnceLock<Result<Engine, String>> = std::sync::OnceLock::new();
let result = ENGINE.get_or_init(|| {
let mut config = Config::new();
config.wasm_component_model(true);
config.epoch_interruption(true);
if cfg!(target_os = "macos") {
config.macos_use_mach_ports(false);
}
let engine = Engine::new(&config).map_err(|e| e.to_string())?;
let ticker = engine.clone();
std::thread::Builder::new()
.name("plugin-wasm-epoch".into())
.spawn(move || {
loop {
std::thread::sleep(Duration::from_millis(EPOCH_TICK_MS));
ticker.increment_epoch();
}
})
.map_err(|e| e.to_string())?;
epoch_ticker_spawns_counter().fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(engine)
});
match result {
Ok(engine) => Ok(engine.clone()),
Err(err) => Err(WasmError::Host(err.clone())),
}
}
wasmtime::component::bindgen!({
path: "wit",
world: "tool-guest",
exports: { default: async },
});
#[derive(Debug)]
pub enum WasmError {
Io(std::io::Error),
Compile(String),
Timeout { timeout: Duration },
Trap(String),
Guest(String),
Denied(String),
Host(String),
}
impl std::fmt::Display for WasmError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => write!(f, "wasm io: {e}"),
Self::Compile(e) => write!(f, "wasm compile failed: {e}"),
Self::Timeout { timeout } => {
write!(f, "wasm call timed out after {}ms", timeout.as_millis())
}
Self::Trap(e) => write!(f, "wasm trapped: {e}"),
Self::Guest(e) => write!(f, "wasm tool error: {e}"),
Self::Denied(e) => write!(f, "wasm capability denied: {e}"),
Self::Host(e) => write!(f, "wasm host error: {e}"),
}
}
}
impl std::error::Error for WasmError {}
pub struct WasmCall<'a> {
pub tool: &'a str,
pub args_json: &'a str,
pub capabilities: &'a [ResolvedCapability],
pub timeout: Duration,
}
pub struct WasmRuntime {
engine: Engine,
}
impl WasmRuntime {
pub fn new() -> Result<Self, WasmError> {
Ok(Self {
engine: shared_engine()?,
})
}
pub fn compile(&self, module_path: &Path) -> Result<Component, WasmError> {
Component::from_file(&self.engine, module_path)
.map_err(|e| WasmError::Compile(e.to_string()))
}
pub async fn invoke(
&self,
component: &Component,
call: &WasmCall<'_>,
) -> Result<String, WasmError> {
let state = HostState::new(call.capabilities)?;
let mut linker: Linker<HostState> = Linker::new(&self.engine);
wasmtime_wasi::p2::add_to_linker_async(&mut linker)
.map_err(|e| WasmError::Host(e.to_string()))?;
if call
.capabilities
.iter()
.any(|c| matches!(c, ResolvedCapability::NetHttp { .. }))
{
add_only_http_to_linker_async(&mut linker)
.map_err(|e| WasmError::Host(e.to_string()))?;
}
let mut store = Store::new(&self.engine, state);
let ticks = (call.timeout.as_millis() as u64 / EPOCH_TICK_MS).max(1);
store.set_epoch_deadline(ticks);
let bindings = ToolGuest::instantiate_async(&mut store, component, &linker)
.await
.map_err(classify_host_error)?;
let args = translate_args_for_guest(call.args_json, call.capabilities, cfg!(windows));
let result = bindings
.phi_tool_executor()
.call_invoke(&mut store, call.tool, &args)
.await;
match result {
Ok(Ok(json)) => Ok(json),
Ok(Err(message)) => Err(WasmError::Guest(message)),
Err(e) => Err(classify_trap(e, call.timeout)),
}
}
}
fn as_trap(e: &wasmtime::Error) -> Option<Trap> {
e.downcast_ref::<Trap>()
.copied()
.or_else(|| e.root_cause().downcast_ref::<Trap>().copied())
}
fn classify_trap(e: wasmtime::Error, timeout: Duration) -> WasmError {
match as_trap(&e) {
Some(Trap::Interrupt) => WasmError::Timeout { timeout },
Some(trap) => WasmError::Trap(trap.to_string()),
None => WasmError::Host(e.to_string()),
}
}
fn classify_host_error(e: wasmtime::Error) -> WasmError {
match as_trap(&e) {
Some(trap) => WasmError::Trap(trap.to_string()),
None => WasmError::Host(e.to_string()),
}
}
fn wasi_guest_path(path: &str) -> String {
guest_path_for(path, cfg!(windows))
}
fn guest_path_for(path: &str, windows: bool) -> String {
if windows {
path.replace('\\', "/")
} else {
path.to_string()
}
}
fn translate_args_for_guest(
args_json: &str,
capabilities: &[ResolvedCapability],
windows: bool,
) -> String {
let pinned: Vec<(String, String)> = capabilities
.iter()
.filter_map(|c| match c {
ResolvedCapability::FsRead { paths } => Some(paths),
_ => None,
})
.flatten()
.map(|p| (p.clone(), guest_path_for(p, windows)))
.collect();
if pinned.is_empty() {
return args_json.to_string();
}
let rewrite = |s: &str| -> Option<String> {
for (native, guest) in &pinned {
if native == guest {
continue; }
let (head, rest) = match s.strip_prefix(native.as_str()) {
Some(rest) if rest.is_empty() => (guest.as_str(), rest),
Some(rest) if rest.starts_with('\\') || rest.starts_with('/') => {
(guest.as_str(), rest)
}
Some(_) => continue,
None => match s.strip_prefix(guest.as_str()) {
Some(rest) if rest.is_empty() => (guest.as_str(), rest),
Some(rest) if rest.starts_with('/') => (guest.as_str(), rest),
Some(_) => continue,
None => continue,
},
};
let rest = if windows {
rest.replace('\\', "/")
} else {
rest.to_string()
};
return Some(format!("{head}{rest}"));
}
None
};
if let Ok(value) = serde_json::from_str::<Value>(args_json) {
let rewritten = rewrite_value(value.clone(), &rewrite);
if rewritten == value {
return args_json.to_string();
}
return serde_json::to_string(&rewritten).unwrap_or_else(|_| args_json.to_string());
}
rewrite(args_json).unwrap_or_else(|| args_json.to_string())
}
fn rewrite_value(value: Value, rewrite: &impl Fn(&str) -> Option<String>) -> Value {
match value {
Value::String(s) => rewrite(&s).map(Value::String).unwrap_or(Value::String(s)),
Value::Array(items) => Value::Array(
items
.into_iter()
.map(|v| rewrite_value(v, rewrite))
.collect(),
),
Value::Object(map) => Value::Object(
map.into_iter()
.map(|(k, v)| (k, rewrite_value(v, rewrite)))
.collect(),
),
other => other,
}
}
struct HostState {
wasi: WasiCtx,
table: ResourceTable,
http: WasiHttpCtx,
hooks: HostFilterHooks,
}
impl HostState {
fn new(capabilities: &[ResolvedCapability]) -> Result<Self, WasmError> {
let mut builder = WasiCtxBuilder::new();
builder.stdout(MemoryOutputPipe::new(64 * 1024));
builder.stderr(MemoryOutputPipe::new(16 * 1024));
for cap in capabilities {
if let ResolvedCapability::FsRead { paths } = cap {
for path in paths {
let guest_name = wasi_guest_path(path);
builder
.preopened_dir(path, &guest_name, FsPerms::ReadOnly)
.map_err(|e| WasmError::Host(format!("preopen {path}: {e}")))?;
}
}
}
let mut allowed_hosts = Vec::new();
for cap in capabilities {
if let ResolvedCapability::NetHttp { hosts } = cap {
allowed_hosts.extend(hosts.iter().cloned());
}
}
Ok(Self {
wasi: builder.build(),
table: ResourceTable::new(),
http: WasiHttpCtx::new(),
hooks: HostFilterHooks { allowed_hosts },
})
}
}
impl WasiView for HostState {
fn ctx(&mut self) -> WasiCtxView<'_> {
WasiCtxView {
ctx: &mut self.wasi,
table: &mut self.table,
}
}
}
impl WasiHttpView for HostState {
fn http(&mut self) -> WasiHttpCtxView<'_> {
WasiHttpCtxView {
hooks: &mut self.hooks,
table: &mut self.table,
ctx: &mut self.http,
}
}
}
struct HostFilterHooks {
allowed_hosts: Vec<String>,
}
impl WasiHttpHooks for HostFilterHooks {
fn send_request(
&mut self,
request: http::Request<WasiBody>,
options: Option<RequestOptions>,
fut: Box<dyn std::future::Future<Output = Result<(), HttpError>> + Send>,
) -> Box<
dyn std::future::Future<
Output = Result<
(
http::Response<WasiBody>,
Box<dyn std::future::Future<Output = Result<(), HttpError>> + Send>,
),
HttpError,
>,
> + Send,
> {
let Some(host) = request.uri().host().map(str::to_ascii_lowercase) else {
return Box::new(std::future::ready(Err(HttpError::InternalError(Some(
"plugin net:http: request has no host".to_string(),
)))));
};
if !host_allowed(&self.allowed_hosts, &host) {
tracing::warn!(target: "plugin", host = %host, "net:http denied by capability whitelist");
return Box::new(std::future::ready(Err(HttpError::HttpRequestDenied)));
}
DefaultHooks.send_request(request, options, fut)
}
}
struct DefaultHooks;
impl WasiHttpHooks for DefaultHooks {}
pub fn host_allowed(allowed_hosts: &[String], host: &str) -> bool {
let host = host.trim().to_ascii_lowercase();
!host.is_empty() && allowed_hosts.contains(&host)
}
pub struct WasmTool {
name: &'static str,
description: &'static str,
schema: Value,
runtime: Arc<WasmRuntime>,
component: Component,
tool: String,
capabilities: Vec<ResolvedCapability>,
timeout: Duration,
}
impl WasmTool {
#[allow(clippy::too_many_arguments)]
pub fn new(
identity_key: &str,
description: &str,
parameters: &BTreeMap<String, ParamSpec>,
runtime: Arc<WasmRuntime>,
component: Component,
tool: &str,
capabilities: Vec<ResolvedCapability>,
timeout: Duration,
) -> Self {
Self {
name: Box::leak(identity_key.to_string().into_boxed_str()),
description: Box::leak(description.to_string().into_boxed_str()),
schema: parameters_envelope(parameters),
runtime,
component,
tool: tool.to_string(),
capabilities,
timeout,
}
}
async fn invoke(&self, args_json: &str) -> Result<String, WasmError> {
self.runtime
.invoke(
&self.component,
&WasmCall {
tool: &self.tool,
args_json,
capabilities: &self.capabilities,
timeout: self.timeout,
},
)
.await
}
}
fn wasm_error_to_agent(name: &str, e: WasmError) -> AgentError {
match e {
WasmError::Timeout { .. } => AgentError::ToolTimeout,
other => AgentError::ToolExecution {
name: name.to_string(),
source: Box::new(AgentError::Internal(other.to_string())),
},
}
}
#[async_trait]
impl Tool for WasmTool {
fn name(&self) -> &'static str {
self.name
}
fn description(&self) -> &'static str {
self.description
}
fn schema(&self) -> Value {
self.schema.clone()
}
async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
let json = self
.invoke(&args.to_string())
.await
.map_err(|e| wasm_error_to_agent(self.name, e))?;
Ok(vec![Content::text(json)])
}
fn timeout_ms(&self) -> Option<u64> {
Some(self.timeout.as_millis() as u64)
}
fn metadata(&self) -> ToolMetadata {
ToolMetadata {
name: self.name.to_string(),
description: self.description.to_string(),
origin: "plugin-wasm".to_string(),
version: "unknown".to_string(),
requirements: vec![],
}
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> std::path::PathBuf {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/dispatcher.wasm")
}
fn runtime() -> WasmRuntime {
WasmRuntime::new().expect("runtime")
}
async fn echo(rt: &WasmRuntime, component: &Component) -> String {
rt.invoke(
component,
&WasmCall {
tool: "echo",
args_json: "{\"hello\":\"wasm\"}",
capabilities: &[],
timeout: Duration::from_secs(5),
},
)
.await
.expect("echo")
}
#[test]
fn repeated_runtimes_share_one_engine_and_one_ticker() {
let first = WasmRuntime::new().expect("runtime");
let second = WasmRuntime::new().expect("runtime");
let third = WasmRuntime::new().expect("runtime");
assert!(
Engine::same(&first.engine, &second.engine),
"runtimes must share one wasmtime engine"
);
assert!(
Engine::same(&second.engine, &third.engine),
"runtimes must share one wasmtime engine"
);
let before = epoch_ticker_spawns();
let _many: Vec<WasmRuntime> = (0..16)
.map(|_| WasmRuntime::new().expect("runtime"))
.collect();
assert_eq!(
before,
epoch_ticker_spawns(),
"constructing runtimes must not spawn extra epoch ticker threads"
);
}
#[test]
fn host_allowlist_is_fail_closed_exact_match() {
let allow = vec!["api.example.com".to_string()];
assert!(host_allowed(&allow, "api.example.com"));
assert!(host_allowed(&allow, "API.Example.com"), "case normalized");
assert!(!host_allowed(&allow, "evil.com"));
assert!(!host_allowed(&allow, "example.com"), "no suffix wildcards");
assert!(
!host_allowed(&allow, "api.example.com.evil"),
"no suffix wildcards"
);
assert!(
!host_allowed(&[], "api.example.com"),
"empty list denies all"
);
assert!(!host_allowed(&allow, ""), "empty host denied");
}
fn empty_body() -> WasiBody {
use http_body_util::BodyExt;
http_body_util::Empty::<bytes::Bytes>::new()
.map_err(|never: std::convert::Infallible| match never {})
.boxed_unsync()
}
fn ready_fut() -> Box<dyn std::future::Future<Output = Result<(), HttpError>> + Send> {
Box::new(std::future::ready(Ok(())))
}
async fn deny_reason(
hooks: &mut HostFilterHooks,
request: http::Request<WasiBody>,
) -> HttpError {
Box::into_pin(hooks.send_request(request, None, ready_fut()))
.await
.err()
.expect("expected rejection")
}
#[tokio::test]
async fn net_whitelist_denies_unlisted_host_at_send_request() {
let mut hooks = HostFilterHooks {
allowed_hosts: vec!["api.example.com".to_string()],
};
let request = http::Request::builder()
.uri("https://evil.example.net/x")
.body(empty_body())
.unwrap();
let err = deny_reason(&mut hooks, request).await;
assert!(
matches!(err, HttpError::HttpRequestDenied),
"deny must be HttpRequestDenied: {err:?}"
);
let mut hooks = HostFilterHooks {
allowed_hosts: Vec::new(),
};
let request = http::Request::builder()
.uri("https://api.example.com/x")
.body(empty_body())
.unwrap();
let err = deny_reason(&mut hooks, request).await;
assert!(matches!(err, HttpError::HttpRequestDenied), "{err:?}");
let request = http::Request::builder()
.uri("/relative-only")
.body(empty_body())
.unwrap();
let err = deny_reason(&mut hooks, request).await;
assert!(matches!(err, HttpError::InternalError(_)), "{err:?}");
}
#[tokio::test]
async fn net_whitelist_passes_allowed_host_downstream() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::path("/ok"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_string("fine"))
.mount(&server)
.await;
let mut hooks = HostFilterHooks {
allowed_hosts: vec!["127.0.0.1".to_string()],
};
let request = http::Request::builder()
.uri(format!("http://127.0.0.1:{}/ok", server.address().port()))
.body(empty_body())
.unwrap();
let (response, _io) = Box::into_pin(hooks.send_request(request, None, ready_fut()))
.await
.unwrap_or_else(|e| panic!("allowed host must reach the wire: {e:?}"));
assert_eq!(response.status(), 200);
}
#[tokio::test]
async fn echo_roundtrips_json() {
let rt = runtime();
let component = rt.compile(&fixture()).expect("compile fixture");
assert_eq!(echo(&rt, &component).await, "{\"hello\":\"wasm\"}");
}
#[tokio::test]
async fn fs_without_preopen_reads_nothing() {
let rt = runtime();
let component = rt.compile(&fixture()).expect("compile fixture");
let err = rt
.invoke(
&component,
&WasmCall {
tool: "read_file",
args_json: "/etc/passwd",
capabilities: &[],
timeout: Duration::from_secs(5),
},
)
.await
.expect_err("no preopen = no reads");
assert!(matches!(err, WasmError::Guest(_)), "{err}");
assert_eq!(echo(&rt, &component).await, "{\"hello\":\"wasm\"}");
}
#[tokio::test]
async fn fs_preopen_grants_only_pinned_path() {
let rt = runtime();
let component = rt.compile(&fixture()).expect("compile fixture");
let dir = tempfile::tempdir().unwrap();
let pinned = dir.path().join("data");
std::fs::create_dir(&pinned).unwrap();
let file = pinned.join("ok.txt");
std::fs::write(&file, "from-preopen").unwrap();
let outside = dir.path().join("outside.txt");
std::fs::write(&outside, "secret").unwrap();
let caps = vec![ResolvedCapability::FsRead {
paths: vec![pinned.to_string_lossy().into_owned()],
}];
let read = |path: std::path::PathBuf| {
let caps = ∩︀
let rt = &rt;
let component = &component;
async move {
let args = path.to_string_lossy().into_owned();
rt.invoke(
component,
&WasmCall {
tool: "read_file",
args_json: &args,
capabilities: caps,
timeout: Duration::from_secs(5),
},
)
.await
}
};
assert_eq!(read(file).await.expect("preopen read"), "from-preopen");
let err = read(outside).await.expect_err("outside preopen");
assert!(matches!(err, WasmError::Guest(_)), "{err}");
}
#[test]
fn windows_paths_reach_the_guest_with_the_wasi_separator() {
assert_eq!(guest_path_for(r"C:\data", true), "C:/data");
assert_eq!(guest_path_for(r"C:\a\b\c.txt", true), "C:/a/b/c.txt");
assert_eq!(guest_path_for("/data", false), "/data");
assert_eq!(guest_path_for(r"/data\weird", false), r"/data\weird");
}
#[test]
fn args_are_translated_into_the_guest_spelling() {
let caps = vec![ResolvedCapability::FsRead {
paths: vec![r"C:\data".to_string()],
}];
let out = translate_args_for_guest(r"C:\data\ok.txt", &caps, true);
assert_eq!(out, "C:/data/ok.txt");
let out = translate_args_for_guest(r#"{"path":"C:\\data\\ok.txt"}"#, &caps, true);
assert_eq!(out, r#"{"path":"C:/data/ok.txt"}"#);
let out = translate_args_for_guest(r"C:\other\ok.txt", &caps, true);
assert_eq!(out, r"C:\other\ok.txt");
let out = translate_args_for_guest(r"C:\data2\ok.txt", &caps, true);
assert_eq!(out, r"C:\data2\ok.txt");
}
#[test]
fn unix_args_are_untouched() {
let caps = vec![ResolvedCapability::FsRead {
paths: vec!["/data".to_string()],
}];
let out = translate_args_for_guest(r#"{"path":"/data/ok.txt"}"#, &caps, false);
assert_eq!(out, r#"{"path":"/data/ok.txt"}"#);
}
#[test]
fn args_without_fs_capability_are_untouched() {
let out = translate_args_for_guest(r#"{"path":"C:\data\ok.txt"}"#, &[], true);
assert_eq!(out, r#"{"path":"C:\data\ok.txt"}"#);
}
#[tokio::test]
async fn timeout_kills_call_not_host() {
let rt = runtime();
let component = rt.compile(&fixture()).expect("compile fixture");
let err = rt
.invoke(
&component,
&WasmCall {
tool: "spin",
args_json: "{}",
capabilities: &[],
timeout: Duration::from_millis(200),
},
)
.await
.expect_err("spin must time out");
assert!(matches!(err, WasmError::Timeout { .. }), "{err}");
assert_eq!(echo(&rt, &component).await, "{\"hello\":\"wasm\"}");
}
#[tokio::test]
async fn panic_traps_call_not_host() {
let rt = runtime();
let component = rt.compile(&fixture()).expect("compile fixture");
let err = rt
.invoke(
&component,
&WasmCall {
tool: "boom",
args_json: "{}",
capabilities: &[],
timeout: Duration::from_secs(5),
},
)
.await
.expect_err("boom must trap");
assert!(matches!(err, WasmError::Trap(_)), "{err}");
assert_eq!(echo(&rt, &component).await, "{\"hello\":\"wasm\"}");
}
#[tokio::test]
async fn corrupt_wasm_fails_at_compile() {
let rt = runtime();
let dir = tempfile::tempdir().unwrap();
let bogus = dir.path().join("bogus.wasm");
std::fs::write(&bogus, b"not a wasm component").unwrap();
let err = rt.compile(&bogus).expect_err("garbage must not compile");
assert!(matches!(err, WasmError::Compile(_)), "{err}");
}
}