Add object primitives, official ext/llm, and HTTPS/dotenv platform.

Introduce # objects with ## methods (handles + ` x.method `), ship OpenAI-compatible ext/llm, and upgrade net/sys for HTTPS headers and dotenv loading.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-06 11:53:14 +08:00
1 parent b974f10c6e
commit b00b018056
55 files changed
+1741 -291

No files matched your search

+34 -5
View File
@@ -74,6 +74,9 @@ pub enum HostFn {
ForeignRun = 63,
ForeignRunLang = 64,
ForeignLangs = 65,
DotenvLoad = 66,
HttpRequest = 67,
JsonQuote = 68,
}
impl HostFn {
@@ -144,6 +147,9 @@ impl HostFn {
63 => Self::ForeignRun,
64 => Self::ForeignRunLang,
65 => Self::ForeignLangs,
66 => Self::DotenvLoad,
67 => Self::HttpRequest,
68 => Self::JsonQuote,
_ => return None,
})
}
@@ -172,8 +178,9 @@ impl HostFn {
"host_json_stringify" => Self::JsonStringify,
"host_json_get" => Self::JsonGet,
"host_json_keys" => Self::JsonKeys,
"host_http_get" => Self::HttpGet,
"host_http_post" => Self::HttpPost,
// Aliases so optional `headers` / `content_type` bind like plot.
"host_http_get" | "http_get" => Self::HttpGet,
"host_http_post" | "http_post" => Self::HttpPost,
"host_url_encode" => Self::UrlEncode,
"host_pi" => Self::Pi,
"host_e" => Self::EConst,
@@ -217,6 +224,9 @@ impl HostFn {
"host_foreign_run" => Self::ForeignRun,
"host_foreign_run_lang" => Self::ForeignRunLang,
"host_foreign_langs" => Self::ForeignLangs,
"host_dotenv_load" | "load_dotenv" => Self::DotenvLoad,
"host_http_request" | "http_request" => Self::HttpRequest,
"host_json_quote" | "quote" => Self::JsonQuote,
_ => return None,
})
}
@@ -292,6 +302,9 @@ impl HostFn {
Self::ForeignRun => "host_foreign_run",
Self::ForeignRunLang => "host_foreign_run_lang",
Self::ForeignLangs => "host_foreign_langs",
Self::DotenvLoad => "host_dotenv_load",
Self::HttpRequest => "host_http_request",
Self::JsonQuote => "host_json_quote",
}
}
@@ -309,11 +322,13 @@ impl HostFn {
Self::EnvSet => &["name", "value"],
Self::Exit => &["code"],
Self::Exec => &["cmd"],
Self::JsonParse | Self::UrlEncode => &["text"],
Self::JsonParse | Self::UrlEncode | Self::JsonQuote => &["text"],
Self::JsonStringify | Self::JsonKeys => &["value"],
Self::JsonGet => &["value", "key"],
Self::HttpGet => &["url"],
Self::HttpPost => &["url", "body"],
Self::HttpRequest => &["method", "url"],
Self::DotenvLoad => &[],
Self::Pi | Self::EConst | Self::Random => &[],
Self::Num | Self::MathNeg | Self::MathSin | Self::MathCos | Self::MathTan
| Self::MathAsin | Self::MathAcos | Self::MathAtan | Self::MathSqrt
@@ -338,7 +353,10 @@ impl HostFn {
pub fn optional_params(self) -> &'static [&'static str] {
match self {
Self::JsonStringify => &["indent"],
Self::HttpPost => &["content_type"],
Self::HttpGet => &["headers"],
Self::HttpPost => &["content_type", "headers"],
Self::HttpRequest => &["body", "content_type", "headers"],
Self::DotenvLoad => &["path"],
Self::Exec => &["args"],
Self::Solve => &["min", "max"],
Self::Plot => &["steps", "path", "derivative", "grid"],
@@ -385,6 +403,7 @@ pub fn call_host(
}
HostFn::EnvGet => sys::env_get(require(bound, "name")?),
HostFn::EnvSet => sys::env_set(require(bound, "name")?, require(bound, "value")?),
HostFn::DotenvLoad => sys::dotenv_load(ctx, bound.get("path")),
HostFn::Args => sys::args(ctx),
HostFn::Cwd => sys::cwd(ctx),
HostFn::Exit => sys::exit(ctx, require(bound, "code")?),
@@ -395,12 +414,22 @@ pub fn call_host(
}
HostFn::JsonGet => json::get(require(bound, "value")?, require(bound, "key")?),
HostFn::JsonKeys => json::keys(require(bound, "value")?),
HostFn::HttpGet => net::http_get(ctx, require(bound, "url")?),
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::HttpRequest => net::http_request(
ctx,
require(bound, "method")?,
require(bound, "url")?,
bound.get("body"),
bound.get("content_type"),
bound.get("headers"),
),
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
+22
View File
@@ -53,6 +53,17 @@ pub fn keys(value: &Value) -> Result<Value, String> {
}
}
/// JSON-encode a text value including surrounding quotes (for building request bodies).
pub fn quote(text: &Value) -> Result<Value, String> {
let s = match text {
Value::Text(s) => s.as_str(),
_ => return Err("json quote needs text".into()),
};
serde_json::to_string(s)
.map(Value::Text)
.map_err(|e| format!("json quote: {e}"))
}
fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
Ok(match v {
serde_json::Value::Null => Value::None,
@@ -111,3 +122,14 @@ fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
Value::Code(c) => serde_json::Value::String(c.source.clone()),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quote_escapes_text() {
let q = quote(&Value::Text("a\"b".into())).unwrap();
assert_eq!(q, Value::Text("\"a\\\"b\"".into()));
}
}
+127 -87
View File
@@ -1,7 +1,5 @@
//! Minimal HTTP host primitives (HTTP cleartext in v1; HTTPS deferred).
//! HTTP host primitives (HTTP and HTTPS via ureq).
use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;
use crate::host::HostContext;
@@ -14,104 +12,96 @@ fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
}
}
struct UrlParts {
host: String,
port: u16,
path: String,
}
fn parse_http_url(url: &str) -> Result<UrlParts, String> {
let rest = url
.strip_prefix("http://")
.ok_or_else(|| {
if url.starts_with("https://") {
"https is not supported yet (use http:// or wait for TLS)".to_string()
} else {
"url must start with http://".into()
}
})?;
let (hostport, path) = match rest.split_once('/') {
Some((h, p)) => (h, format!("/{p}")),
None => (rest, "/".into()),
fn headers_from_value(headers: Option<&Value>) -> Result<Vec<(String, String)>, String> {
let Some(h) = headers else {
return Ok(Vec::new());
};
let (host, port) = if let Some((h, p)) = hostport.split_once(':') {
let port: u16 = p
.parse()
.map_err(|_| format!("invalid port in url: {p}"))?;
(h.to_string(), port)
} else {
(hostport.to_string(), 80)
};
if host.is_empty() {
return Err("url missing host".into());
match h {
Value::None => Ok(Vec::new()),
Value::Map(entries) => Ok(entries
.iter()
.map(|(k, v)| (k.clone(), v.as_display()))
.collect()),
_ => Err("headers must be a map (e.g. from json parse)".into()),
}
Ok(UrlParts { host, port, path })
}
fn http_exchange(
method: &str,
url: &str,
body: Option<&str>,
content_type: &str,
content_type: Option<&str>,
extra_headers: &[(String, String)],
) -> Result<(u16, String), String> {
let parts = parse_http_url(url)?;
let addr = format!("{}:{}", parts.host, parts.port);
let mut stream = TcpStream::connect(&addr).map_err(|e| format!("http connect {addr}: {e}"))?;
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.ok();
stream
.set_write_timeout(Some(Duration::from_secs(10)))
.ok();
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("url must start with http:// or https://".into());
}
let agent = ureq::AgentBuilder::new()
.timeout_connect(Duration::from_secs(15))
.timeout_read(Duration::from_secs(120))
.build();
let body = body.unwrap_or("");
let mut req = format!(
"{method} {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: marqdo\r\n",
path = parts.path,
host = parts.host,
);
if method == "POST" {
req.push_str(&format!(
"Content-Type: {content_type}\r\nContent-Length: {}\r\n",
body.len()
));
let mut req = match method {
"GET" => agent.get(url),
"POST" => agent.post(url),
"PUT" => agent.put(url),
"DELETE" => agent.request("DELETE", url),
other => return Err(format!("unsupported http method: {other}")),
};
req = req.set("User-Agent", "marqdo");
if let Some(ct) = content_type {
if !ct.is_empty() {
req = req.set("Content-Type", ct);
}
}
req.push_str("\r\n");
if method == "POST" {
req.push_str(body);
for (k, v) in extra_headers {
req = req.set(k, v);
}
stream
.write_all(req.as_bytes())
.map_err(|e| format!("http write: {e}"))?;
let mut buf = Vec::new();
stream
.read_to_end(&mut buf)
.map_err(|e| format!("http read: {e}"))?;
if buf.len() > 2 * 1024 * 1024 {
return Err("http response exceeds 2MiB limit".into());
let resp = if let Some(b) = body {
req.send_string(b)
} else {
req.call()
};
match resp {
Ok(r) => {
let status = r.status();
let text = r
.into_string()
.map_err(|e| format!("http read body: {e}"))?;
if text.len() > 8 * 1024 * 1024 {
return Err("http response exceeds 8MiB limit".into());
}
Ok((status, text))
}
Err(ureq::Error::Status(code, r)) => {
let text = r.into_string().unwrap_or_default();
Ok((code, text))
}
Err(e) => Err(format!("http {method} {url}: {e}")),
}
let text = String::from_utf8_lossy(&buf);
let (header, body) = text.split_once("\r\n\r\n").unwrap_or((text.as_ref(), ""));
let status = header
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|s| s.parse::<u16>().ok())
.unwrap_or(0);
Ok((status, body.to_string()))
}
pub fn http_get(ctx: &HostContext, url: &Value) -> Result<Value, String> {
fn response_map(status: u16, body: String) -> Value {
Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(body)),
])
}
pub fn http_get(
ctx: &HostContext,
url: &Value,
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_get denied by host policy".into());
}
let url = as_text(url, "url")?;
let (status, body) = http_exchange("GET", url, None, "")?;
Ok(Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(body)),
]))
let hdrs = headers_from_value(headers)?;
let (status, body) = http_exchange("GET", url, None, None, &hdrs)?;
Ok(response_map(status, body))
}
pub fn http_post(
@@ -119,6 +109,7 @@ pub fn http_post(
url: &Value,
body: &Value,
content_type: Option<&Value>,
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_post denied by host policy".into());
@@ -127,13 +118,44 @@ pub fn http_post(
let body = as_text(body, "body")?;
let ct = match content_type {
Some(v) => as_text(v, "content_type")?,
None => "text/plain; charset=utf-8",
None => "application/json; charset=utf-8",
};
let (status, resp) = http_exchange("POST", url, Some(body), ct)?;
Ok(Value::Map(vec![
("status".into(), Value::Int(status as i64)),
("body".into(), Value::Text(resp)),
]))
let hdrs = headers_from_value(headers)?;
let (status, resp) = http_exchange("POST", url, Some(body), Some(ct), &hdrs)?;
Ok(response_map(status, resp))
}
/// Generic request: method + url + optional body / content_type / headers.
pub fn http_request(
ctx: &HostContext,
method: &Value,
url: &Value,
body: Option<&Value>,
content_type: Option<&Value>,
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
return Err("http_request denied by host policy".into());
}
let method = as_text(method, "method")?.to_uppercase();
let url = as_text(url, "url")?;
let body_s = match body {
None | Some(Value::None) => None,
Some(v) => Some(as_text(v, "body")?),
};
let ct = match content_type {
None | Some(Value::None) => {
if body_s.is_some() && method == "POST" {
Some("application/json; charset=utf-8")
} else {
None
}
}
Some(v) => Some(as_text(v, "content_type")?),
};
let hdrs = headers_from_value(headers)?;
let (status, resp) = http_exchange(&method, url, body_s, ct, &hdrs)?;
Ok(response_map(status, resp))
}
pub fn url_encode(text: &Value) -> Result<Value, String> {
@@ -150,3 +172,21 @@ pub fn url_encode(text: &Value) -> Result<Value, String> {
.collect(),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn headers_from_map() {
let m = Value::Map(vec![
("Authorization".into(), Value::Text("Bearer x".into())),
("X-Test".into(), Value::Int(1)),
]);
let h = headers_from_value(Some(&m)).unwrap();
assert_eq!(h.len(), 2);
assert!(h
.iter()
.any(|(k, v)| k == "Authorization" && v == "Bearer x"));
}
}
+82
View File
@@ -34,6 +34,54 @@ pub fn env_set(name: &Value, value: &Value) -> Result<Value, String> {
Ok(Value::None)
}
/// Load KEY=VALUE pairs from a `.env` file into the process environment.
/// Existing variables are **not** overridden. Default path: `.env` under host cwd.
pub fn dotenv_load(ctx: &HostContext, path: Option<&Value>) -> Result<Value, String> {
let rel = match path {
None | Some(Value::None) => ".env".to_string(),
Some(v) => as_text(v, "path")?.to_string(),
};
let file = if std::path::Path::new(&rel).is_absolute() {
std::path::PathBuf::from(&rel)
} else {
ctx.cwd.join(&rel)
};
let text = match std::fs::read_to_string(&file) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Value::Int(0)),
Err(e) => {
return Err(format!("dotenv_load {}: {e}", file.display()));
}
};
let mut loaded = 0i64;
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line.strip_prefix("export ").unwrap_or(line).trim();
let Some((k, v)) = line.split_once('=') else {
continue;
};
let key = k.trim();
if key.is_empty() {
continue;
}
if std::env::var_os(key).is_some() {
continue;
}
let mut val = v.trim();
if (val.starts_with('"') && val.ends_with('"'))
|| (val.starts_with('\'') && val.ends_with('\''))
{
val = &val[1..val.len() - 1];
}
std::env::set_var(key, val);
loaded += 1;
}
Ok(Value::Int(loaded))
}
pub fn args(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(
ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(),
@@ -77,3 +125,37 @@ pub fn exec(ctx: &HostContext, cmd: &Value, args: Option<&Value>) -> Result<Valu
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::host::HostContext;
use std::io::Write;
#[test]
fn dotenv_loads_without_override() {
let dir = std::env::temp_dir().join(format!("marqdo-dotenv-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("sample.env");
{
let mut f = std::fs::File::create(&path).unwrap();
writeln!(f, "# comment").unwrap();
writeln!(f, "MARQDO_DOTENV_A=one").unwrap();
writeln!(f, "export MARQDO_DOTENV_B=\"two\"").unwrap();
}
std::env::set_var("MARQDO_DOTENV_A", "keep");
std::env::remove_var("MARQDO_DOTENV_B");
let mut ctx = HostContext::default();
ctx.cwd = dir.clone();
let n = dotenv_load(&ctx, Some(&Value::Text("sample.env".into()))).unwrap();
assert_eq!(n, Value::Int(1));
assert_eq!(std::env::var("MARQDO_DOTENV_A").unwrap(), "keep");
assert_eq!(std::env::var("MARQDO_DOTENV_B").unwrap(), "two");
assert_eq!(
dotenv_load(&ctx, Some(&Value::Text("missing.env".into()))).unwrap(),
Value::Int(0)
);
let _ = std::fs::remove_dir_all(&dir);
}
}