feat(wasm): C0/C1 browser Marqdo interpreter on wasm32

Feature-gate host/CLI deps for wasm-core, add run_source, and ship
crates/marqdo-wasm with a raw mq_run ABI plus examples/browser-hello.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-01 10:37:44 +08:00
1 parent f2fd4fb34e
commit a75b7a1c87
22 files changed
+904 -151

No files matched your search

+223 -51
View File
@@ -2,7 +2,11 @@
use std::collections::HashMap;
use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
#[cfg(feature = "plugin-host")]
use crate::host::plugin;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -648,22 +652,52 @@ pub fn call_host(
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::JsonQuote => json::quote(require(bound, "text")?),
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?, bound.get("headers")),
HostFn::HttpPost => net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
),
HostFn::HttpPostSse => net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
),
HostFn::HttpGet => {
#[cfg(feature = "net-host")]
{
net::http_get(ctx, require(bound, "url")?, bound.get("headers"))
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_get unavailable in browser wasm".into())
}
}
HostFn::HttpPost => {
#[cfg(feature = "net-host")]
{
net::http_post(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post unavailable in browser wasm".into())
}
}
HostFn::HttpPostSse => {
#[cfg(feature = "net-host")]
{
net::http_post_sse(
ctx,
require(bound, "url")?,
require(bound, "body")?,
bound.get("content_type"),
bound.get("headers"),
bound.get("echo"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_post_sse unavailable in browser wasm".into())
}
}
HostFn::OpenAiSseParse => {
net::openai_sse_parse(require(bound, "text")?, bound.get("echo"))
}
@@ -671,14 +705,24 @@ pub fn call_host(
crate::host::event_bus::publish(require(bound, "event")?);
Ok(Value::Bool(true))
}
HostFn::HttpRequest => net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
),
HostFn::HttpRequest => {
#[cfg(feature = "net-host")]
{
net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
)
}
#[cfg(not(feature = "net-host"))]
{
let _ = (ctx, bound);
Err("http_request unavailable in browser wasm".into())
}
}
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
HostFn::EConst => math::e_const(),
@@ -756,33 +800,111 @@ pub fn call_host(
bound.get("path"),
bound.get("grid"),
),
HostFn::ForeignSetCmd => foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
),
HostFn::ForeignRun => foreign::run(ctx, require(bound, "code")?, bound.get("stdin")),
HostFn::ForeignRunLang => foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
),
HostFn::ForeignLangs => foreign::langs(ctx),
HostFn::PluginLoad => plugin::load(ctx, require(bound, "path")?),
HostFn::PluginUnload => plugin::unload(ctx),
HostFn::PluginList => plugin::list(ctx),
HostFn::ForeignSetCmd => {
#[cfg(feature = "exec-host")]
{
foreign::set_cmd(
ctx,
require(bound, "lang")?,
require(bound, "cmd")?,
bound.get("args"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRun => {
#[cfg(feature = "exec-host")]
{
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRunLang => {
#[cfg(feature = "exec-host")]
{
foreign::run_lang(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignLangs => {
#[cfg(feature = "exec-host")]
{
foreign::langs(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::PluginLoad => {
#[cfg(feature = "plugin-host")]
{
plugin::load(ctx, require(bound, "path")?)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = (ctx, bound);
Err("plugin.load unavailable in browser wasm".into())
}
}
HostFn::PluginUnload => {
#[cfg(feature = "plugin-host")]
{
plugin::unload(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Err("plugin.unload unavailable in browser wasm".into())
}
}
HostFn::PluginList => {
#[cfg(feature = "plugin-host")]
{
plugin::list(ctx)
}
#[cfg(not(feature = "plugin-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::ExtNativePath => {
let name = require(bound, "name")?;
let s = match name {
Value::Text(t) => t.as_str(),
_ => return Err("name must be text".into()),
};
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
#[cfg(feature = "cli")]
{
Ok(match crate::ext_cli::installed_native_path(s) {
Some(p) => Value::Text(p.to_string_lossy().into_owned()),
None => Value::None,
})
}
#[cfg(not(feature = "cli"))]
{
let _ = s;
Ok(Value::None)
}
}
HostFn::MapSet => {
super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
@@ -899,11 +1021,61 @@ pub fn call_host(
bound.get("line"),
)
}
HostFn::SubtaskSpawn => subtask::spawn(ctx, bound),
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
HostFn::SubtaskWaitAll => subtask::wait_all(ctx),
HostFn::SubtaskSpawn => {
#[cfg(feature = "exec-host")]
{
subtask::spawn(ctx, bound)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskPoll => {
#[cfg(feature = "exec-host")]
{
subtask::poll(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskJoin => {
#[cfg(feature = "exec-host")]
{
subtask::join(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskKill => {
#[cfg(feature = "exec-host")]
{
subtask::kill(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("subtask unavailable in browser wasm".into())
}
}
HostFn::SubtaskWaitAll => {
#[cfg(feature = "exec-host")]
{
subtask::wait_all(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Err("subtask unavailable in browser wasm".into())
}
}
}
}
+10
View File
@@ -8,12 +8,21 @@ pub mod agent_rt;
pub mod collection;
mod dispatch;
pub mod event_bus;
#[cfg(feature = "exec-host")]
pub mod foreign;
mod fs;
pub(crate) mod json;
pub mod math;
mod net;
#[cfg(feature = "plugin-host")]
pub mod plugin;
#[cfg(not(feature = "plugin-host"))]
#[path = "plugin_stub.rs"]
pub mod plugin;
#[cfg(feature = "exec-host")]
pub mod subtask;
#[cfg(not(feature = "exec-host"))]
#[path = "subtask_stub.rs"]
pub mod subtask;
mod sys;
mod time;
@@ -80,6 +89,7 @@ pub struct HostContext {
/// Entry-file line of each active user call (for writeback anchoring).
pub call_site_lines: Vec<u32>,
/// Concurrent subtasks (`lib/subtask`): file / function / foreign.
#[cfg_attr(not(feature = "exec-host"), allow(dead_code))]
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
pub subtask_seq: u64,
}
+14 -2
View File
@@ -1,10 +1,14 @@
//! HTTP host primitives (HTTP and HTTPS via ureq).
use std::io::{BufRead, BufReader, Write};
use std::io::Write;
#[cfg(feature = "net-host")]
use std::io::{BufRead, BufReader};
#[cfg(feature = "net-host")]
use std::time::Duration;
use crate::host::HostContext;
use crate::value::Value;
#[cfg(feature = "net-host")]
use crate::host::HostContext;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
@@ -13,6 +17,7 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
}
}
#[cfg(feature = "net-host")]
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
let Some(h) = headers else {
return Ok(Vec::new());
@@ -27,6 +32,7 @@ fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>,
}
}
#[cfg(feature = "net-host")]
fn http_exchange(
method: &str,
url: &str,
@@ -84,6 +90,7 @@ fn http_exchange(
}
}
#[cfg(feature = "net-host")]
fn response_map(status: u16, body: String) -> Value {
Value::Map(vec![
("status".into(), Value::Int(status as i64)),
@@ -91,6 +98,7 @@ fn response_map(status: u16, body: String) -> Value {
])
}
#[cfg(feature = "net-host")]
pub fn http_get(
ctx: &HostContext,
url: &Value,
@@ -105,6 +113,7 @@ pub fn http_get(
Ok(response_map(status, body))
}
#[cfg(feature = "net-host")]
pub fn http_post(
ctx: &HostContext,
url: &Value,
@@ -127,6 +136,7 @@ pub fn http_post(
}
/// Generic request: method + url + optional body / content_type / headers.
#[cfg(feature = "net-host")]
pub fn http_request(
ctx: &HostContext,
method: &Value,
@@ -630,6 +640,7 @@ pub fn openai_sse_parse(text: &Value, echo: Option<&Value>) -> Result<Value, Str
Ok(Value::List(openai_chat_sse_events(text, echo)?))
}
#[cfg(feature = "net-host")]
fn read_sse_body_to_events<R: BufRead>(
mut reader: R,
echo: bool,
@@ -755,6 +766,7 @@ fn read_sse_body_to_events<R: BufRead>(
}
/// POST and consume OpenAI-compatible SSE; return `{status, events}` list of stream maps.
#[cfg(feature = "net-host")]
pub fn http_post_sse(
ctx: &HostContext,
url: &Value,
+57
View File
@@ -0,0 +1,57 @@
//! Stub plugin surface when `plugin-host` is disabled (browser wasm).
use std::collections::HashMap;
use crate::host::HostContext;
use crate::value::Value;
pub const ABI_VERSION: u32 = 2;
pub const ABI_VERSION_MIN: u32 = 1;
/// Hook: resolve bare `lib.member` (unused without native plugins).
pub struct LibPathCall {
pub call: fn(*mut (), &str) -> Result<Value, String>,
pub data: *mut (),
}
pub fn with_lib_path_call<R>(_hook: LibPathCall, body: impl FnOnce() -> R) -> R {
body()
}
#[derive(Clone)]
pub struct RegisteredFn {
pub params: Vec<String>,
}
#[derive(Debug, Default, Clone)]
pub struct PluginState;
impl PluginState {
pub fn get(&self, _name: &str) -> Option<&RegisteredFn> {
None
}
pub fn list_names(&self) -> Vec<String> {
Vec::new()
}
}
pub fn load(_ctx: &mut HostContext, _path: &Value) -> Result<Value, String> {
Err("plugin.load unavailable in browser wasm".into())
}
pub fn unload(_ctx: &mut HostContext) -> Result<Value, String> {
Err("plugin.unload unavailable in browser wasm".into())
}
pub fn list(_ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(Vec::new()))
}
pub fn call_registered(
_ctx: &mut HostContext,
name: &str,
_bound: &HashMap<String, Value>,
) -> Result<Value, String> {
Err(format!("plugin `{name}` unavailable in browser wasm"))
}
+9
View File
@@ -0,0 +1,9 @@
//! Stub subtask surface when `exec-host` is disabled (browser wasm).
use crate::host::HostContext;
/// Placeholder handle type so `HostContext.subtasks` still type-checks.
#[derive(Debug)]
pub(crate) struct Handle;
pub fn kill_all(_ctx: &mut HostContext) {}
+17 -1
View File
@@ -1,5 +1,6 @@
//! System / process host primitives.
#[cfg(feature = "exec-host")]
use std::process::Command;
use crate::host::HostContext;
@@ -97,10 +98,24 @@ pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
if ctx.soft_side_effects {
return Err(format!("exit {c} (soft mode does not terminate process)"));
}
std::process::exit(c as i32);
#[cfg(target_arch = "wasm32")]
{
return Err(format!("exit {c} unavailable in browser wasm"));
}
#[cfg(not(target_arch = "wasm32"))]
{
std::process::exit(c as i32);
}
}
pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Value, String> {
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, cmd, args);
return Err("exec unavailable in browser wasm".into());
}
#[cfg(feature = "exec-host")]
{
if !ctx.allow_exec() {
return Err("exec denied by host policy".into());
}
@@ -123,6 +138,7 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
.status()
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
}
#[cfg(test)]
+37 -13
View File
@@ -1,7 +1,8 @@
//! Time host primitives.
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use std::time::{SystemTime, UNIX_EPOCH};
use chrono::{DateTime, NaiveDateTime, Utc};
@@ -9,19 +10,34 @@ use crate::host::HostContext;
use crate::value::Value;
pub fn now_unix() -> Result<Value, String> {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
#[cfg(target_arch = "wasm32")]
{
// No wall clock on wasm32-unknown-unknown without JS bridge (C4).
return Err("now_unix unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_unix: {e}"))?
.as_secs();
Ok(Value::Int(secs as i64))
}
}
pub fn now_ms() -> Result<Value, String> {
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
#[cfg(target_arch = "wasm32")]
{
return Err("now_ms unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("now_ms: {e}"))?
.as_millis();
Ok(Value::Int(ms as i64))
}
}
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
@@ -65,7 +81,15 @@ pub fn sleep_ms(ctx: &HostContext, ms: &Value) -> Result<Value, String> {
}
}
if n > 0 {
thread::sleep(Duration::from_millis(n));
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::sleep(Duration::from_millis(n));
}
#[cfg(target_arch = "wasm32")]
{
let _ = Duration::from_millis(n);
// Browser wasm has no blocking sleep; ignore (C0/C1).
}
}
Ok(Value::None)
}