Make file subtasks return #main value and expose it as plan.result.

Quiet spawn still hides child stdout; workbooks solidify to **returns**, agent-kb lives in the plugin, and multi-step follows OKF file relay rather than print-based answers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-07 17:53:14 +08:00
1 parent fbece725e1
commit d1b33c78c6
55 files changed
+3498 -169

No files matched your search

+26 -1
View File
@@ -94,6 +94,9 @@ pub enum HostFn {
SubtaskWaitAll = 92,
WritebackEnsure = 93,
OuterCallLine = 94,
TextPatch = 95,
ApplyPatchBlocks = 96,
WritebackScanPath = 97,
}
impl HostFn {
@@ -184,6 +187,9 @@ impl HostFn {
92 => Self::SubtaskWaitAll,
93 => Self::WritebackEnsure,
94 => Self::OuterCallLine,
95 => Self::TextPatch,
96 => Self::ApplyPatchBlocks,
97 => Self::WritebackScanPath,
_ => return None,
})
}
@@ -273,6 +279,9 @@ impl HostFn {
"host_writeback_list" | "writeback_list" => Self::WritebackList,
"host_writeback_ensure" | "writeback_ensure" => Self::WritebackEnsure,
"host_outer_call_line" | "outer_call_line" => Self::OuterCallLine,
"host_text_patch" | "text_patch" => Self::TextPatch,
"host_apply_patch_blocks" | "apply_patch_blocks" => Self::ApplyPatchBlocks,
"host_writeback_scan_path" | "writeback_scan_path" => Self::WritebackScanPath,
"host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn,
"host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll,
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
@@ -368,6 +377,9 @@ impl HostFn {
Self::WritebackList => "host_writeback_list",
Self::WritebackEnsure => "host_writeback_ensure",
Self::OuterCallLine => "host_outer_call_line",
Self::TextPatch => "host_text_patch",
Self::ApplyPatchBlocks => "host_apply_patch_blocks",
Self::WritebackScanPath => "host_writeback_scan_path",
Self::SubtaskSpawn => "host_subtask_spawn",
Self::SubtaskPoll => "host_subtask_poll",
Self::SubtaskJoin => "host_subtask_join",
@@ -419,6 +431,9 @@ impl HostFn {
Self::PluginUnload | Self::PluginList => &[],
Self::ExtNativePath => &["name"],
Self::OuterCallLine => &[],
Self::TextPatch => &["path", "find", "replace"],
Self::ApplyPatchBlocks => &["path", "text"],
Self::WritebackScanPath => &["path"],
Self::MapSet => &["map", "key", "value"],
Self::ListAppend => &["list", "item"],
Self::WritebackRecord => &["value"],
@@ -449,7 +464,7 @@ impl HostFn {
&["at_end", "key", "line"]
}
Self::WritebackEnsure => &["placeholder", "line"],
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin"],
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
_ => &[],
}
}
@@ -634,6 +649,16 @@ pub fn call_host(
.copied()
.unwrap_or(ctx.current_line) as i64,
)),
HostFn::TextPatch => fs::text_patch(
ctx,
require(bound, "path")?,
require(bound, "find")?,
require(bound, "replace")?,
),
HostFn::ApplyPatchBlocks => {
fs::apply_patch_blocks(ctx, require(bound, "path")?, require(bound, "text")?)
}
HostFn::WritebackScanPath => writeback::scan_path(ctx, require(bound, "path")?),
HostFn::WritebackRecord => writeback::record(
ctx,
require(bound, "value")?,
+185
View File
@@ -106,3 +106,188 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
}
Ok(Value::None)
}
/// Exact UTF-8 FIND→REPLACE on a file. `find` must occur exactly once.
pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("text_patch denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
let find = text_body(find)?;
let replace = text_body(replace)?;
if find.is_empty() {
return Err("text_patch: find must be non-empty".into());
}
let src = fs::read_to_string(&p).map_err(|e| format!("text_patch {}: {e}", p.display()))?;
let count = src.matches(find).count();
if count == 0 {
return Err(format!(
"text_patch: find not found in {}",
p.display()
));
}
if count > 1 {
return Err(format!(
"text_patch: find matched {count} times in {} (must be unique)",
p.display()
));
}
let next = src.replacen(find, replace, 1);
fs::write(&p, next).map_err(|e| format!("text_patch write {}: {e}", p.display()))?;
Ok(Value::Int(1))
}
/// Apply one or more FIND/REPLACE blocks from plan-reply text.
///
/// Blocks:
/// ```text
/// <<<
/// FIND
/// <old>
/// ===
/// REPLACE
/// <new>
/// >>>
/// ```
pub fn apply_patch_blocks(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
if !ctx.allow_fs_write() {
return Err("apply_patch_blocks denied by host policy".into());
}
let blocks = parse_patch_blocks(text_body(text)?)?;
if blocks.is_empty() {
return Ok(Value::Int(0));
}
let p = ctx.resolve_path(text_path(path)?)?;
let mut src = fs::read_to_string(&p).map_err(|e| format!("apply_patch_blocks {}: {e}", p.display()))?;
let mut applied = 0i64;
for (find, replace) in blocks {
if find.is_empty() {
return Err("apply_patch_blocks: empty FIND".into());
}
let count = src.matches(&find).count();
if count == 0 {
return Err(format!(
"apply_patch_blocks: FIND not found in {}",
p.display()
));
}
if count > 1 {
return Err(format!(
"apply_patch_blocks: FIND matched {count} times in {} (must be unique)",
p.display()
));
}
src = src.replacen(&find, &replace, 1);
applied += 1;
}
fs::write(&p, src).map_err(|e| format!("apply_patch_blocks write {}: {e}", p.display()))?;
Ok(Value::Int(applied))
}
fn parse_patch_blocks(text: &str) -> Result<Vec<(String, String)>, String> {
let mut out = Vec::new();
let mut rest = text;
while let Some(start) = rest.find("<<<") {
let after = &rest[start + 3..];
let end = after
.find(">>>")
.ok_or_else(|| "apply_patch_blocks: unclosed <<< block".to_string())?;
let body = after[..end].trim();
rest = &after[end + 3..];
let (find_part, replace_part) = body
.split_once("===")
.ok_or_else(|| "apply_patch_blocks: block missing ===".to_string())?;
let find = strip_labeled(find_part, "FIND")?;
let replace = strip_labeled(replace_part, "REPLACE")?;
out.push((find, replace));
}
Ok(out)
}
fn strip_labeled(chunk: &str, label: &str) -> Result<String, String> {
let t = chunk.trim();
let upper = t.to_ascii_uppercase();
let label_u = label.to_ascii_uppercase();
if upper.starts_with(&label_u) {
let after = t[label.len()..].trim_start_matches([':', ' ', '\t']);
let after = after.strip_prefix('\n').unwrap_or(after);
Ok(after.to_string())
} else {
Ok(t.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::host::{HostCaps, HostContext};
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
fn write_ctx(dir: &std::path::Path) -> HostContext {
let entry = dir.join("entry.mq.md");
let _ = fs::write(&entry, "# main\n");
let mut ctx = HostContext::for_run(Some(&entry), HostCaps::default(), vec![]);
ctx.cwd = dir.to_path_buf();
ctx.fs_root = Some(dir.to_path_buf());
ctx
}
fn temp_workspace(tag: &str) -> std::path::PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!("marqdo-fs-{tag}-{nanos}"));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn text_patch_unique() {
let dir = temp_workspace("patch");
let path = dir.join("a.md");
fs::write(&path, "hello OLD world").unwrap();
let ctx = write_ctx(&dir);
let n = text_patch(
&ctx,
&Value::Text("a.md".into()),
&Value::Text("OLD".into()),
&Value::Text("NEW".into()),
)
.unwrap();
assert_eq!(n, Value::Int(1));
assert_eq!(fs::read_to_string(&path).unwrap(), "hello NEW world");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn apply_patch_blocks_two() {
let dir = temp_workspace("blocks");
let path = dir.join("a.md");
fs::write(&path, "aa bb cc").unwrap();
let ctx = write_ctx(&dir);
let reply = r#"
DECISION: CONTINUE
PATCH:
<<<
FIND
aa
===
REPLACE
AA
>>>
<<<
FIND
cc
===
REPLACE
CC
>>>
"#;
let n = apply_patch_blocks(&ctx, &Value::Text("a.md".into()), &Value::Text(reply.into())).unwrap();
assert_eq!(n, Value::Int(2));
assert_eq!(fs::read_to_string(&path).unwrap(), "AA bb CC");
let _ = fs::remove_dir_all(&dir);
}
}
+2 -2
View File
@@ -8,7 +8,7 @@ pub mod agent_rt;
mod dispatch;
pub mod foreign;
mod fs;
mod json;
pub(crate) mod json;
pub mod math;
mod net;
pub mod plugin;
@@ -78,7 +78,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.
pub subtasks: HashMap<u64, subtask::Handle>,
pub(crate) subtasks: HashMap<u64, subtask::Handle>,
pub subtask_seq: u64,
}
+3
View File
@@ -243,6 +243,9 @@ unsafe extern "C" fn host_query(
"module_source" => agent_rt::module_source(ctx).and_then(|v| value_to_json(&v)),
"call_site" => agent_rt::call_site(ctx, Some(ctx.current_line)).and_then(|v| value_to_json(&v)),
"marqdo_skill" => agent_rt::marqdo_skill(ctx).and_then(|v| value_to_json(&v)),
"cwd" => Ok(serde_json::Value::String(
ctx.cwd.to_string_lossy().into_owned(),
)),
other => Err(format!("host_query: unknown `{other}`")),
};
+78 -16
View File
@@ -15,7 +15,7 @@ use crate::value::{CodeBlock, Value};
/// Stored subtask handle (tagged by spawn kind).
pub(crate) enum Handle {
File(Child),
File(FileTask),
Foreign(ForeignTask),
Function(FunctionTask),
}
@@ -30,7 +30,12 @@ impl std::fmt::Debug for Handle {
}
}
struct ForeignTask {
pub(crate) struct FileTask {
child: Child,
result_path: PathBuf,
}
pub(crate) struct ForeignTask {
child: Child,
temp_script: PathBuf,
stdout: JoinHandle<String>,
@@ -44,7 +49,7 @@ enum FnState {
Killed,
}
struct FunctionTask {
pub(crate) struct FunctionTask {
state: Arc<Mutex<FnState>>,
handle: Option<JoinHandle<()>>,
}
@@ -121,9 +126,10 @@ fn fn_args_from_value(args: Option<&Value>) -> Result<Vec<(String, Value)>, Stri
pub fn kill_all(ctx: &mut HostContext) {
for (_, handle) in ctx.subtasks.drain() {
match handle {
Handle::File(mut child) => {
let _ = child.kill();
let _ = child.wait();
Handle::File(mut task) => {
let _ = task.child.kill();
let _ = task.child.wait();
let _ = std::fs::remove_file(&task.result_path);
}
Handle::Foreign(mut task) => {
let _ = task.child.kill();
@@ -161,6 +167,7 @@ pub fn spawn(ctx: &mut HostContext, bound: &HashMap<String, Value>) -> Result<Va
ctx,
require(bound, "path")?,
bound.get("args"),
bound.get("quiet"),
)
} else if has_fn {
spawn_fn(ctx, require(bound, "fn")?, bound.get("args"))
@@ -180,21 +187,51 @@ fn spawn_file(
ctx: &mut HostContext,
path: &Value,
args: Option<&Value>,
quiet: 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() {
let joined = if std::path::Path::new(rel).is_absolute() {
std::path::PathBuf::from(rel)
} else {
ctx.cwd.join(rel)
};
// Absolutize so the child `for_run` cwd/parent resolution does not double-prefix
// a relative path like `tests/ext/.marqdo/...` when current_dir is already `tests/ext`.
let file = std::fs::canonicalize(&joined).unwrap_or_else(|_| {
if joined.is_absolute() {
joined.clone()
} else {
std::env::current_dir()
.unwrap_or_else(|_| std::path::PathBuf::from("."))
.join(&joined)
}
});
let exe = std::env::current_exe().map_err(|e| format!("subtask: current_exe: {e}"))?;
let id = next_id(ctx);
let result_path = std::env::temp_dir().join(format!(
"marqdo-subtask-{}-{}.json",
std::process::id(),
id
));
let mut cmd = Command::new(&exe);
cmd.arg("run").arg(&file);
cmd.arg("--emit-result").arg(&result_path);
cmd.current_dir(&ctx.cwd);
cmd.stdin(Stdio::null());
let quiet = match quiet {
None | Some(Value::None) => true,
Some(v) => v.truthy(),
};
if quiet {
cmd.stdout(Stdio::null());
cmd.stderr(Stdio::null());
} else {
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
}
if let Some(Value::List(items)) = args {
for item in items {
cmd.arg(as_text(item, "arg")?);
@@ -203,8 +240,13 @@ fn spawn_file(
let child = cmd
.spawn()
.map_err(|e| format!("subtask spawn {}: {e}", file.display()))?;
let id = next_id(ctx);
ctx.subtasks.insert(id, Handle::File(child));
ctx.subtasks.insert(
id,
Handle::File(FileTask {
child,
result_path,
}),
);
Ok(Value::Int(id as i64))
}
@@ -319,7 +361,7 @@ pub fn poll(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
.get_mut(&id)
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
match handle {
Handle::File(child) => poll_child(child),
Handle::File(task) => poll_child(&mut task.child),
Handle::Foreign(task) => poll_child(&mut task.child),
Handle::Function(task) => poll_function(&task.state),
}
@@ -364,17 +406,34 @@ pub fn join(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
.remove(&id)
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
match handle {
Handle::File(mut child) => {
let status = child
Handle::File(mut task) => {
let status = task
.child
.wait()
.map_err(|e| format!("subtask join: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(-1) as i64))
let code = status.code().unwrap_or(-1) as i64;
let value = read_emitted_result(&task.result_path);
let _ = std::fs::remove_file(&task.result_path);
Ok(Value::Map(vec![
("code".into(), Value::Int(code)),
("value".into(), value),
]))
}
Handle::Foreign(task) => join_foreign(task),
Handle::Function(task) => join_function(task),
}
}
fn read_emitted_result(path: &PathBuf) -> Value {
match std::fs::read_to_string(path) {
Ok(text) => match serde_json::from_str::<serde_json::Value>(text.trim()) {
Ok(j) => crate::host::json::json_to_value(&j).unwrap_or(Value::None),
Err(_) => Value::None,
},
Err(_) => Value::None,
}
}
fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
let status = task
.child
@@ -428,9 +487,12 @@ pub fn kill(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
.remove(&id)
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
match handle {
Handle::File(mut child) => {
child.kill().map_err(|e| format!("subtask kill: {e}"))?;
let _ = child.wait();
Handle::File(mut task) => {
task.child
.kill()
.map_err(|e| format!("subtask kill: {e}"))?;
let _ = task.child.wait();
let _ = std::fs::remove_file(&task.result_path);
}
Handle::Foreign(mut task) => {
task.child.kill().map_err(|e| format!("subtask kill: {e}"))?;
+17 -1
View File
@@ -528,6 +528,22 @@ pub fn list(ctx: &HostContext) -> Result<Value, String> {
.entry_source
.as_deref()
.ok_or_else(|| "writeback: no entry source".to_string())?;
Ok(slots_from_source(source))
}
/// Scan `path` for `<!-- marqdo-out … -->` slots (any file, not only the entry).
pub fn scan_path(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let rel = match path {
Value::Text(s) => s.as_str(),
_ => return Err("writeback scan_path: path must be text".into()),
};
let p = ctx.resolve_path(rel)?;
let source = std::fs::read_to_string(&p)
.map_err(|e| format!("writeback scan_path {}: {e}", p.display()))?;
Ok(slots_from_source(&source))
}
fn slots_from_source(source: &str) -> Value {
let items: Vec<Value> = scan_blocks(source)
.into_iter()
.map(|b| {
@@ -544,7 +560,7 @@ pub fn list(ctx: &HostContext) -> Result<Value, String> {
Value::Map(entries)
})
.collect();
Ok(Value::List(items))
Value::List(items)
}
/// Ensure named slots exist with a placeholder body; **does not** overwrite non-empty bodies.