Add v0.2 surface syntax, writeback/subtask stdlib, and view input deferral.

Use + for parameters, ordered-list branches, backtick identifiers, and quoted strings with escapes. Add writeback and subtask host libs, optional parameter defaults, narrative-bold comment fix, and defer view execution until preset stdin is submitted.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-06 17:52:33 +08:00
1 parent 92d88fe761
commit 63e5be80ab
116 files changed
+2226 -559

No files matched your search

+62 -1
View File
@@ -2,7 +2,7 @@
use std::collections::HashMap;
use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, sys, time, HostContext};
use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -92,6 +92,15 @@ pub enum HostFn {
AgentHistoryAppend = 81,
FormatToolsForLlm = 82,
ToolAllowed = 83,
WritebackRecord = 84,
WritebackGet = 85,
WritebackClear = 86,
WritebackList = 87,
SubtaskSpawn = 88,
SubtaskPoll = 89,
SubtaskJoin = 90,
SubtaskKill = 91,
SubtaskWaitAll = 92,
}
impl HostFn {
@@ -180,6 +189,15 @@ impl HostFn {
81 => Self::AgentHistoryAppend,
82 => Self::FormatToolsForLlm,
83 => Self::ToolAllowed,
84 => Self::WritebackRecord,
85 => Self::WritebackGet,
86 => Self::WritebackClear,
87 => Self::WritebackList,
88 => Self::SubtaskSpawn,
89 => Self::SubtaskPoll,
90 => Self::SubtaskJoin,
91 => Self::SubtaskKill,
92 => Self::SubtaskWaitAll,
_ => return None,
})
}
@@ -272,6 +290,15 @@ impl HostFn {
"host_agent_history_append" | "agent_history_append" => Self::AgentHistoryAppend,
"host_format_tools_for_llm" | "format_tools_for_llm" => Self::FormatToolsForLlm,
"host_tool_allowed" | "tool_allowed" => Self::ToolAllowed,
"host_writeback_record" | "writeback_record" => Self::WritebackRecord,
"host_writeback_get" | "writeback_get" => Self::WritebackGet,
"host_writeback_clear" | "writeback_clear" => Self::WritebackClear,
"host_writeback_list" | "writeback_list" => Self::WritebackList,
"host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn,
"host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll,
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
"host_subtask_kill" | "subtask_kill" => Self::SubtaskKill,
"host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll,
_ => return None,
})
}
@@ -365,6 +392,15 @@ impl HostFn {
Self::AgentHistoryAppend => "host_agent_history_append",
Self::FormatToolsForLlm => "host_format_tools_for_llm",
Self::ToolAllowed => "host_tool_allowed",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
Self::WritebackList => "host_writeback_list",
Self::SubtaskSpawn => "host_subtask_spawn",
Self::SubtaskPoll => "host_subtask_poll",
Self::SubtaskJoin => "host_subtask_join",
Self::SubtaskKill => "host_subtask_kill",
Self::SubtaskWaitAll => "host_subtask_wait_all",
}
}
@@ -417,6 +453,12 @@ impl HostFn {
Self::AgentHistoryAppend => &["id", "item"],
Self::FormatToolsForLlm => &["tools"],
Self::ToolAllowed => &["tools", "name"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
Self::SubtaskSpawn => &["path"],
Self::SubtaskPoll | Self::SubtaskJoin | Self::SubtaskKill => &["id"],
Self::SubtaskWaitAll => &[],
}
}
@@ -434,6 +476,8 @@ impl HostFn {
Self::PlotConic => &["b", "h", "k", "path", "grid"],
Self::ForeignSetCmd => &["args"],
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => &["at_end"],
Self::SubtaskSpawn => &["args"],
_ => &[],
}
}
@@ -632,6 +676,23 @@ pub fn call_host(
require(bound, "tools")?,
require(bound, "name")?,
),
HostFn::WritebackRecord => writeback::record(
ctx,
require(bound, "value")?,
bound.get("at_end"),
),
HostFn::WritebackGet => writeback::get(ctx, bound.get("at_end")),
HostFn::WritebackClear => writeback::clear(ctx, bound.get("at_end")),
HostFn::WritebackList => writeback::list(ctx),
HostFn::SubtaskSpawn => subtask::spawn(
ctx,
require(bound, "path")?,
bound.get("args"),
),
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),
}
}
+26 -1
View File
@@ -12,8 +12,10 @@ mod json;
pub mod math;
mod net;
pub mod plugin;
pub mod subtask;
mod sys;
mod time;
pub mod writeback;
pub use dispatch::{call_host, HostFn};
pub use fs::path_under_root;
@@ -21,6 +23,7 @@ pub use plugin::PluginState;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Child;
use crate::value::Value;
@@ -52,7 +55,7 @@ pub struct PlotArtifact {
pub svg: String,
}
#[derive(Debug, Clone)]
#[derive(Debug)]
pub struct HostContext {
pub caps: HostCaps,
pub fs_root: Option<PathBuf>,
@@ -78,6 +81,11 @@ pub struct HostContext {
pub agent_seq: u64,
/// Last statement line (updated by interpreters for `host_call_site`).
pub current_line: u32,
/// Entry-file line of each active user call (for writeback anchoring).
pub call_site_lines: Vec<u32>,
/// OS subprocess subtasks (`lib/subtask`).
pub subtasks: HashMap<u64, Child>,
pub subtask_seq: u64,
}
impl Default for HostContext {
@@ -99,10 +107,19 @@ impl Default for HostContext {
agent_histories: HashMap::new(),
agent_seq: 0,
current_line: 1,
call_site_lines: Vec::new(),
subtasks: HashMap::new(),
subtask_seq: 0,
}
}
}
impl Drop for HostContext {
fn drop(&mut self) {
subtask::kill_all(self);
}
}
impl HostContext {
pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec<String>) -> Self {
let mut ctx = Self::default();
@@ -142,6 +159,14 @@ impl HostContext {
self.caps.net
}
pub fn push_call_site_line(&mut self, line: u32) {
self.call_site_lines.push(line);
}
pub fn pop_call_site_line(&mut self) {
self.call_site_lines.pop();
}
pub fn allow_plugin(&self) -> bool {
self.caps.plugin
}
+116
View File
@@ -0,0 +1,116 @@
//! OS subprocess subtasks (`marqdo run` children); parent exit kills all children.
use std::process::{Command, Stdio};
use crate::host::HostContext;
use crate::value::Value;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} must be text")),
}
}
fn child_id(_ctx: &HostContext, id: &Value) -> Result<u64, String> {
match id {
Value::Int(n) if *n > 0 => Ok(*n as u64),
_ => Err("subtask id must be positive int".into()),
}
}
pub fn kill_all(ctx: &mut HostContext) {
for (_, mut child) in ctx.subtasks.drain() {
let _ = child.kill();
let _ = child.wait();
}
}
pub fn spawn(
ctx: &mut HostContext,
path: &Value,
args: Option<&Value>,
) -> Result<Value, String> {
if !ctx.caps.exec {
return Err("subtask spawn disabled (exec capability off)".into());
}
let rel = as_text(path, "path")?;
let file = if std::path::Path::new(rel).is_absolute() {
std::path::PathBuf::from(rel)
} else {
ctx.cwd.join(rel)
};
let exe = std::env::current_exe().map_err(|e| format!("subtask: current_exe: {e}"))?;
let mut cmd = Command::new(&exe);
cmd.arg("run").arg(&file);
cmd.current_dir(&ctx.cwd);
cmd.stdin(Stdio::null());
if let Some(Value::List(items)) = args {
for item in items {
cmd.arg(as_text(item, "arg")?);
}
}
let child = cmd
.spawn()
.map_err(|e| format!("subtask spawn {}: {e}", file.display()))?;
ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1);
let id = ctx.subtask_seq;
ctx.subtasks.insert(id, child);
Ok(Value::Int(id as i64))
}
pub fn poll(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = child_id(ctx, id)?;
let child = ctx
.subtasks
.get_mut(&id)
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
match child.try_wait().map_err(|e| format!("subtask poll: {e}"))? {
None => Ok(Value::Map(vec![("status".into(), Value::Text("running".into()))])),
Some(status) => {
let code = status.code().unwrap_or(-1);
let st = if status.success() {
"done"
} else {
"failed"
};
Ok(Value::Map(vec![
("status".into(), Value::Text(st.into())),
("code".into(), Value::Int(code as i64)),
]))
}
}
}
pub fn join(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = child_id(ctx, id)?;
let mut child = ctx
.subtasks
.remove(&id)
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
let status = child
.wait()
.map_err(|e| format!("subtask join: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(-1) as i64))
}
pub fn kill(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = child_id(ctx, id)?;
let mut child = ctx
.subtasks
.remove(&id)
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
child.kill().map_err(|e| format!("subtask kill: {e}"))?;
let _ = child.wait();
Ok(Value::None)
}
pub fn wait_all(ctx: &mut HostContext) -> Result<Value, String> {
let ids: Vec<u64> = ctx.subtasks.keys().copied().collect();
let mut codes = Vec::new();
for id in ids {
let code = join(ctx, &Value::Int(id as i64))?;
codes.push(code);
}
Ok(Value::List(codes))
}
+345
View File
@@ -0,0 +1,345 @@
//! Jupyter-style output persistence in `.mq.md` (`<!-- marqdo-out … -->`).
use std::collections::HashMap;
use crate::host::HostContext;
use crate::value::Value;
const MAGIC: &str = "marqdo-out";
#[derive(Debug, Clone, PartialEq, Eq)]
struct BlockSpan {
start: usize,
end: usize,
body: String,
start_line: u32,
}
fn display_value(v: &Value) -> String {
match v {
Value::Text(s) => s.clone(),
other => other.as_display(),
}
}
fn is_truthy(v: Option<&Value>) -> bool {
match v {
None | Some(Value::None) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Int(n)) => *n != 0,
_ => false,
}
}
fn call_line(ctx: &HostContext) -> Result<u32, String> {
ctx.call_site_lines
.last()
.copied()
.ok_or_else(|| "writeback: no call site line".into())
}
fn line_number_at(source: &str, byte: usize) -> u32 {
source[..byte.min(source.len())]
.bytes()
.filter(|b| *b == b'\n')
.count() as u32
+ 1
}
fn format_block(body: &str) -> String {
format!("<!-- {MAGIC}\n{body}\n-->")
}
fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<BlockSpan> {
let inner = block
.strip_prefix("<!--")?
.strip_suffix("-->")?
.trim();
if !inner.contains(MAGIC) {
return None;
}
let mut lines: Vec<&str> = inner.lines().collect();
if lines.is_empty() {
return None;
}
let header = lines.remove(0).trim();
if !header.split_whitespace().any(|t| t == MAGIC) {
return None;
}
let body = lines.join("\n");
let end = start_byte + block.len();
Some(BlockSpan {
start: start_byte,
end,
body,
start_line: line_number_at(source, start_byte),
})
}
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
let mut out = Vec::new();
let mut i = 0usize;
while i < source.len() {
let rest = &source[i..];
let Some(start) = rest.find("<!--") else {
break;
};
let abs = i + start;
let after = &source[abs..];
if !after.contains(MAGIC) {
i = abs + 4;
continue;
}
let Some(end_rel) = after.find("-->") else {
break;
};
let block = &after[..end_rel + 3];
if let Some(b) = parse_one_block(block, abs, source) {
out.push(b);
}
i = abs + end_rel + 3;
}
out
}
fn strip_span(source: &str, start: usize, end: usize) -> String {
let mut out = String::with_capacity(source.len());
out.push_str(&source[..start]);
out.push_str(&source[end..]);
out
}
fn line_start_byte(source: &str, line_no: u32) -> Option<usize> {
if line_no == 0 {
return None;
}
let mut cur = 1u32;
for (i, b) in source.bytes().enumerate() {
if cur == line_no {
return Some(i);
}
if b == b'\n' {
cur += 1;
}
}
if cur == line_no {
Some(source.len())
} else {
None
}
}
fn line_end_byte(source: &str, line_no: u32) -> Option<usize> {
let start = line_start_byte(source, line_no)?;
let rest = &source[start..];
match rest.find('\n') {
Some(off) => Some(start + off + 1),
None => Some(source.len()),
}
}
fn is_blank_line(source: &str, line_no: u32) -> bool {
let start = match line_start_byte(source, line_no) {
Some(s) => s,
None => return true,
};
let end = line_end_byte(source, line_no).unwrap_or(source.len());
source[start..end].trim().is_empty()
}
fn find_adjacent_block(source: &str, after_line: u32) -> Option<BlockSpan> {
let mut line = after_line.saturating_add(1);
let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
while line <= total && is_blank_line(source, line) {
line += 1;
}
for b in scan_blocks(source) {
if b.start_line == line {
return Some(b);
}
}
None
}
fn is_eof_block(source: &str, block: &BlockSpan) -> bool {
source[block.end..].trim().is_empty()
}
fn find_eof_block(source: &str) -> Option<BlockSpan> {
scan_blocks(source)
.into_iter()
.rev()
.find(|b| is_eof_block(source, b))
}
fn insert_after_line(source: &str, line_no: u32, block: &str) -> Result<String, String> {
let insert_at = line_end_byte(source, line_no)
.ok_or_else(|| format!("writeback: line {line_no} out of range"))?;
let mut out = String::with_capacity(source.len() + block.len() + 2);
out.push_str(&source[..insert_at]);
if !block.starts_with('\n') && !source[..insert_at].ends_with('\n') {
out.push('\n');
}
out.push_str(block);
if !block.ends_with('\n') {
out.push('\n');
}
out.push_str(&source[insert_at..]);
Ok(out)
}
fn append_eof(source: &str, block: &str) -> String {
let mut trimmed = source.trim_end().to_string();
if !trimmed.is_empty() {
trimmed.push('\n');
}
trimmed.push_str(block);
if !block.ends_with('\n') {
trimmed.push('\n');
}
trimmed
}
fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> {
if !ctx.allow_fs_write() {
return Err("writeback disabled (fs_write capability off)".into());
}
let path = ctx
.entry_path
.as_ref()
.ok_or_else(|| "writeback: no entry file".to_string())?;
std::fs::write(path, source).map_err(|e| format!("writeback write {}: {e}", path.display()))?;
ctx.entry_source = Some(source.to_string());
Ok(())
}
fn anchor_line_above(source: &str, block_start_line: u32) -> u32 {
let mut line = block_start_line.saturating_sub(1);
while line > 0 && is_blank_line(source, line) {
line -= 1;
}
line.max(1)
}
pub fn record(
ctx: &mut HostContext,
value: &Value,
at_end: Option<&Value>,
) -> Result<Value, String> {
let body = display_value(value);
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let next = if is_truthy(at_end) {
let stripped = find_eof_block(source)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string());
append_eof(&stripped, &format_block(&body))
} else {
let line = call_line(ctx)?;
let stripped = find_adjacent_block(source, line)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string());
insert_after_line(&stripped, line, &format_block(&body))?
};
persist(ctx, &next)?;
Ok(Value::Text(body))
}
pub fn get(ctx: &HostContext, at_end: Option<&Value>) -> Result<Value, String> {
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let body = if is_truthy(at_end) {
find_eof_block(source).map(|b| b.body)
} else {
let line = call_line(ctx)?;
find_adjacent_block(source, line).map(|b| b.body)
};
Ok(match body {
Some(s) => Value::Text(s),
None => Value::None,
})
}
pub fn clear(ctx: &mut HostContext, at_end: Option<&Value>) -> Result<Value, String> {
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let next = if is_truthy(at_end) {
find_eof_block(source)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string())
} else {
let line = call_line(ctx)?;
find_adjacent_block(source, line)
.map(|b| strip_span(source, b.start, b.end))
.unwrap_or_else(|| source.to_string())
};
if next != source {
persist(ctx, &next)?;
}
Ok(Value::None)
}
pub fn list(ctx: &HostContext) -> Result<Value, String> {
let source = ctx
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
let items: Vec<Value> = scan_blocks(source)
.into_iter()
.map(|b| {
let anchor = anchor_line_above(source, b.start_line);
let at_eof = is_eof_block(source, &b);
Value::Map(vec![
("line".into(), Value::Int(anchor as i64)),
("body".into(), Value::Text(b.body)),
("at_end".into(), Value::Bool(at_eof)),
])
})
.collect();
Ok(Value::List(items))
}
/// Map statement line → body for adjacent blocks; EOF blocks use key `0`.
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
let mut map = HashMap::new();
for b in scan_blocks(source) {
if is_eof_block(source, &b) {
map.insert(0, b.body);
} else {
map.insert(anchor_line_above(source, b.start_line), b.body);
}
}
map
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_and_insert_adjacent() {
let src = "# main\n\n*`x` = 1*\n";
let block = format_block("1");
let next = insert_after_line(src, 3, &block).unwrap();
assert!(next.contains("marqdo-out"));
assert!(!next.contains("@line"));
let blocks = scan_blocks(&next);
assert_eq!(blocks.len(), 1);
assert_eq!(blocks[0].body, "1");
let replaced = strip_span(&next, blocks[0].start, blocks[0].end);
assert!(!replaced.contains("marqdo-out"));
}
#[test]
fn writeback_map_uses_line_above() {
let src = "# main\n\n*`x` = 1*\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
let map = writeback_map(src);
assert_eq!(map.get(&3), Some(&"42".to_string()));
}
}