Move LLM and agent into ext/ai with host tool catalog and call_fn.
Consolidate official AI extensions under ext/ai/, add agent history/context host APIs, dynamic call_fn, and a first-pass TOOL:name loop so runbooks can list zero-arg tools in a table. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
c4ffb9473f
commit
92d88fe761
29 files changed
+1019
-558
No files matched your search
@@ -36,6 +36,7 @@ pub fn canonical_builtin(name: &str) -> Option<&'static str> {
|
||||
"split" => Some("split"),
|
||||
"join" => Some("join"),
|
||||
"at" => Some("at"),
|
||||
"call_fn" | "调用" => Some("call_fn"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -51,6 +52,7 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
|
||||
("split" | "join", "sep" | "分隔") => "sep".into(),
|
||||
("at", "value" | "值") => "value".into(),
|
||||
("at", "index" | "下标") => "index".into(),
|
||||
("call_fn", "name" | "名") => "name".into(),
|
||||
(
|
||||
"host_plot" | "host_plot_points" | "host_plot_conic",
|
||||
"grid" | "网格",
|
||||
|
||||
@@ -65,11 +65,16 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
|
||||
functions.push(compile_function(i, &flat, path_buf.as_deref())?);
|
||||
}
|
||||
|
||||
let parents: Vec<Option<usize>> = flat.iter().map(|f| f.parent).collect();
|
||||
let children: Vec<Vec<usize>> = flat.iter().map(|f| f.children.clone()).collect();
|
||||
|
||||
Ok(Program {
|
||||
functions,
|
||||
entry,
|
||||
objects,
|
||||
methods,
|
||||
parents,
|
||||
children,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -470,6 +475,17 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"call_fn" => {
|
||||
let name_expr = self
|
||||
.named_or_first(&call, "name")
|
||||
.ok_or_else(|| self.err("call_fn requires name"))?;
|
||||
self.compile_expr(name_expr)?;
|
||||
self.emit(Op::CallFn);
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
other if crate::host::HostFn::from_name(other).is_some() => {
|
||||
let hf = crate::host::HostFn::from_name(other).unwrap();
|
||||
let params = hf.all_params();
|
||||
|
||||
@@ -56,6 +56,8 @@ pub enum Op {
|
||||
GetIndex,
|
||||
/// Call function by index; argc values are on the stack (param order).
|
||||
Call(u16, u8),
|
||||
/// Pop function name text → call zero-arg top-level or lexically visible function.
|
||||
CallFn,
|
||||
/// After a constructor Call: tag top-of-stack map with `_type` = constants[idx].
|
||||
TagInstance(u16),
|
||||
/// Method call: stack has argc args (param order) then receiver on top.
|
||||
@@ -88,6 +90,10 @@ pub struct Program {
|
||||
pub objects: Vec<(String, usize)>,
|
||||
/// (object_fn_idx, method_name) → method fn idx
|
||||
pub methods: Vec<(usize, String, usize)>,
|
||||
/// Parallel to `functions`: parent fn index for dynamic `call_fn` lookup.
|
||||
pub parents: Vec<Option<usize>>,
|
||||
/// Parallel to `functions`: child fn indices.
|
||||
pub children: Vec<Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
|
||||
@@ -115,6 +115,8 @@ impl Vm {
|
||||
ip: 0,
|
||||
slots: vec![Value::None; program.functions[entry].locals.len().max(1)],
|
||||
}];
|
||||
self.host
|
||||
.push_call_frame(&program.functions[entry].name.clone());
|
||||
|
||||
loop {
|
||||
let frame = frames.last_mut().unwrap();
|
||||
@@ -127,6 +129,7 @@ impl Vm {
|
||||
let op = fun.code[ip];
|
||||
let span = fun.spans.get(ip).copied().unwrap_or(Span::new(1, 1));
|
||||
frame.ip += 1;
|
||||
self.host.current_line = span.line;
|
||||
|
||||
if self.trace {
|
||||
match op {
|
||||
@@ -347,11 +350,13 @@ impl Vm {
|
||||
for i in (0..argc).rev() {
|
||||
slots[i] = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
}
|
||||
let fname = program.functions[fid].name.clone();
|
||||
frames.push(Frame {
|
||||
fn_idx: fid,
|
||||
ip: 0,
|
||||
slots,
|
||||
});
|
||||
self.host.push_call_frame(&fname);
|
||||
}
|
||||
Op::TagInstance(idx) => {
|
||||
let type_name = match fun.constants.get(idx as usize) {
|
||||
@@ -410,11 +415,13 @@ impl Vm {
|
||||
slots[i] = recv.clone();
|
||||
}
|
||||
}
|
||||
let fname = callee.name.clone();
|
||||
frames.push(Frame {
|
||||
fn_idx: method_fid,
|
||||
ip: 0,
|
||||
slots,
|
||||
});
|
||||
self.host.push_call_frame(&fname);
|
||||
}
|
||||
Op::PluginCall(name_idx, argc) => {
|
||||
let argc = argc as usize;
|
||||
@@ -478,9 +485,35 @@ impl Vm {
|
||||
stack.push(result);
|
||||
}
|
||||
}
|
||||
Op::CallFn => {
|
||||
let name_v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let name = match name_v {
|
||||
Value::Text(s) => s,
|
||||
_ => return Err(self.err_at(span, "call_fn requires text name")),
|
||||
};
|
||||
let current = frames.last().unwrap().fn_idx;
|
||||
let fid = resolve_fn_dynamic(program, current, &name)
|
||||
.map_err(|m| self.err_at(span, m))?;
|
||||
let callee = &program.functions[fid];
|
||||
if !callee.params.is_empty() {
|
||||
return Err(self.err_at(
|
||||
span,
|
||||
format!("call_fn: `{name}` must have no parameters"),
|
||||
));
|
||||
}
|
||||
let slots = vec![Value::None; callee.locals.len().max(1)];
|
||||
let fname = callee.name.clone();
|
||||
frames.push(Frame {
|
||||
fn_idx: fid,
|
||||
ip: 0,
|
||||
slots,
|
||||
});
|
||||
self.host.push_call_frame(&fname);
|
||||
}
|
||||
Op::Return => {
|
||||
let ret = pop(&mut stack).unwrap_or(Value::None);
|
||||
frames.pop();
|
||||
self.host.pop_call_frame();
|
||||
if frames.is_empty() {
|
||||
return Ok(ret);
|
||||
}
|
||||
@@ -569,3 +602,26 @@ fn tag_instance_value(type_name: &str, value: Value) -> Value {
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_fn_dynamic(program: &Program, current: usize, name: &str) -> Result<usize, String> {
|
||||
for &cid in &program.children[current] {
|
||||
if program.functions[cid].name == name {
|
||||
return Ok(cid);
|
||||
}
|
||||
}
|
||||
let mut parent = program.parents[current];
|
||||
while let Some(pid) = parent {
|
||||
for &cid in &program.children[pid] {
|
||||
if program.functions[cid].name == name {
|
||||
return Ok(cid);
|
||||
}
|
||||
}
|
||||
parent = program.parents[pid];
|
||||
}
|
||||
for (i, f) in program.functions.iter().enumerate() {
|
||||
if program.parents[i].is_none() && f.name == name {
|
||||
return Ok(i);
|
||||
}
|
||||
}
|
||||
Err(format!("call_fn: unknown function `{name}`"))
|
||||
}
|
||||
+9
-5
@@ -20,15 +20,15 @@ pub struct ExtPackage {
|
||||
pub const CATALOG: &[ExtPackage] = &[
|
||||
ExtPackage {
|
||||
id: "llm",
|
||||
description: "OpenAI-compatible chat object (ext/llm)",
|
||||
mq_files: &["llm.mq.md", "大模型.mq.md"],
|
||||
description: "OpenAI-compatible chat object (ext/ai/llm)",
|
||||
mq_files: &["ai/llm.mq.md", "ai/大模型.mq.md"],
|
||||
native_crate: None,
|
||||
},
|
||||
ExtPackage {
|
||||
id: "agent",
|
||||
description: "Agent development framework (ext/agent + ABI plugin)",
|
||||
mq_files: &["agent.mq.md", "智能体.mq.md"],
|
||||
native_crate: Some("marqdo_plugin_agent"),
|
||||
description: "Agent development framework (ext/ai/agent)",
|
||||
mq_files: &["ai/agent.mq.md", "ai/智能体.mq.md"],
|
||||
native_crate: None,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -198,6 +198,10 @@ pub fn add_ext(id: &str) -> Result<()> {
|
||||
for f in pkg.mq_files {
|
||||
let src = find_source_file(f)?;
|
||||
let dest = root.join(f);
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.with_context(|| format!("create {}", parent.display()))?;
|
||||
}
|
||||
fs::copy(&src, &dest)
|
||||
.with_context(|| format!("copy {} → {}", src.display(), dest.display()))?;
|
||||
println!("installed {}", dest.display());
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Runtime support for `ext/agent`: module source, call site, skill text, history store.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
impl HostContext {
|
||||
pub fn set_entry_source(&mut self, path: Option<&Path>, source: &str) {
|
||||
self.entry_source = Some(source.to_string());
|
||||
self.entry_path = path.map(|p| p.to_path_buf());
|
||||
}
|
||||
|
||||
pub fn push_call_frame(&mut self, name: &str) {
|
||||
self.call_stack.push(name.to_string());
|
||||
}
|
||||
|
||||
pub fn pop_call_frame(&mut self) {
|
||||
self.call_stack.pop();
|
||||
}
|
||||
|
||||
pub fn alloc_agent_id(&mut self) -> String {
|
||||
self.agent_seq = self.agent_seq.wrapping_add(1);
|
||||
let id = format!("agent-{}", self.agent_seq);
|
||||
self.agent_histories.insert(id.clone(), Vec::new());
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
pub fn module_source(ctx: &HostContext) -> Result<Value, String> {
|
||||
Ok(match &ctx.entry_source {
|
||||
Some(s) => Value::Text(s.clone()),
|
||||
None => Value::Text(String::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn call_site(ctx: &HostContext, line: Option<u32>) -> Result<Value, String> {
|
||||
let path = ctx
|
||||
.entry_path
|
||||
.as_ref()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_default();
|
||||
let function = ctx
|
||||
.call_stack
|
||||
.last()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "main".into());
|
||||
let line_v = match line {
|
||||
Some(n) => Value::Int(n as i64),
|
||||
None => Value::None,
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("path".into(), Value::Text(path)),
|
||||
("function".into(), Value::Text(function)),
|
||||
("line".into(), line_v),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn marqdo_skill(ctx: &HostContext) -> Result<Value, String> {
|
||||
let text = load_marqdo_skill(ctx)?;
|
||||
Ok(Value::Text(text))
|
||||
}
|
||||
|
||||
fn load_marqdo_skill(ctx: &HostContext) -> Result<String, String> {
|
||||
if let Ok(p) = std::env::var("MARQDO_SKILL") {
|
||||
let path = PathBuf::from(p);
|
||||
if path.is_file() {
|
||||
return std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("MARQDO_SKILL read {}: {e}", path.display()));
|
||||
}
|
||||
let skill = path.join("SKILL.md");
|
||||
if skill.is_file() {
|
||||
return read_skill_pack(&path);
|
||||
}
|
||||
}
|
||||
|
||||
for root in skill_search_roots(ctx) {
|
||||
let pack = root.join("skills").join("marqdo");
|
||||
if pack.join("SKILL.md").is_file() {
|
||||
return read_skill_pack(&pack);
|
||||
}
|
||||
if root.join("SKILL.md").is_file() && root.ends_with("marqdo") {
|
||||
return read_skill_pack(&root);
|
||||
}
|
||||
}
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
fn read_skill_pack(dir: &Path) -> Result<String, String> {
|
||||
let mut out = String::new();
|
||||
for name in ["SKILL.md", "reference.md", "examples.md"] {
|
||||
let p = dir.join(name);
|
||||
if p.is_file() {
|
||||
let body = std::fs::read_to_string(&p)
|
||||
.map_err(|e| format!("skill read {}: {e}", p.display()))?;
|
||||
if !out.is_empty() {
|
||||
out.push_str("\n\n---\n\n");
|
||||
}
|
||||
out.push_str(&format!("# file: {name}\n\n"));
|
||||
out.push_str(&body);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn skill_search_roots(ctx: &HostContext) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
roots.push(dir.to_path_buf());
|
||||
if let Some(parent) = dir.parent() {
|
||||
roots.push(parent.to_path_buf());
|
||||
// target/debug → repo root
|
||||
if let Some(repo) = parent.parent() {
|
||||
roots.push(repo.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
roots.push(ctx.cwd.clone());
|
||||
if let Some(p) = &ctx.entry_path {
|
||||
if let Some(parent) = p.parent() {
|
||||
roots.push(parent.to_path_buf());
|
||||
// tests/ext → repo
|
||||
if let Some(repo) = parent.parent().and_then(|p| p.parent()) {
|
||||
roots.push(repo.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
|
||||
roots.push(PathBuf::from(manifest));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
pub fn agent_alloc(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
Ok(Value::Text(ctx.alloc_agent_id()))
|
||||
}
|
||||
|
||||
pub fn agent_history_get(ctx: &HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = text_id(id)?;
|
||||
Ok(Value::List(
|
||||
ctx.agent_histories
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn agent_history_clear(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = text_id(id)?;
|
||||
ctx.agent_histories.insert(id, Vec::new());
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn agent_history_append(
|
||||
ctx: &mut HostContext,
|
||||
id: &Value,
|
||||
item: &Value,
|
||||
) -> Result<Value, String> {
|
||||
let id = text_id(id)?;
|
||||
let list = ctx.agent_histories.entry(id).or_default();
|
||||
list.push(item.clone());
|
||||
Ok(Value::List(list.clone()))
|
||||
}
|
||||
|
||||
fn text_id(id: &Value) -> Result<String, String> {
|
||||
match id {
|
||||
Value::Text(s) if !s.is_empty() => Ok(s.clone()),
|
||||
_ => Err("agent history id must be non-empty text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result<Value, String> {
|
||||
let k = match key {
|
||||
Value::Text(s) => s.clone(),
|
||||
_ => return Err("map_set key must be text".into()),
|
||||
};
|
||||
match map {
|
||||
Value::Map(entries) => {
|
||||
let mut out = entries.clone();
|
||||
if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) {
|
||||
*slot = value.clone();
|
||||
} else {
|
||||
out.push((k, value.clone()));
|
||||
}
|
||||
Ok(Value::Map(out))
|
||||
}
|
||||
Value::None => Ok(Value::Map(vec![(k, value.clone())])),
|
||||
_ => Err("map_set needs map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_append(list: &Value, item: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.push(item.clone());
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![item.clone()])),
|
||||
_ => Err("list_append needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_name_from_row(row: &Value) -> Option<String> {
|
||||
match row {
|
||||
Value::Text(s) if !s.is_empty() => Some(s.clone()),
|
||||
Value::Map(entries) => ["工具", "tools", "name"]
|
||||
.iter()
|
||||
.find_map(|key| {
|
||||
entries.iter().find(|(k, _)| k == *key).and_then(|(_, v)| {
|
||||
if let Value::Text(s) = v {
|
||||
(!s.is_empty()).then(|| s.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tool_names(tools: &Value) -> Vec<String> {
|
||||
match tools {
|
||||
Value::List(rows) => rows.iter().filter_map(tool_name_from_row).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_tools_for_llm(tools: &Value) -> Result<Value, String> {
|
||||
let mut out = String::from("Available tools (invoke via TOOL:<name>):\n");
|
||||
for name in tool_names(tools) {
|
||||
out.push_str("- ");
|
||||
out.push_str(&name);
|
||||
out.push('\n');
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn tool_allowed(tools: &Value, name: &Value) -> Result<Value, String> {
|
||||
let name = match name {
|
||||
Value::Text(s) if !s.is_empty() => s.as_str(),
|
||||
_ => return Ok(Value::Bool(false)),
|
||||
};
|
||||
Ok(Value::Bool(
|
||||
tool_names(tools).iter().any(|n| n == name),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tool_catalog_from_table() {
|
||||
let tools = Value::List(vec![Value::Text("获取时间".into())]);
|
||||
let text = format_tools_for_llm(&tools).unwrap();
|
||||
assert!(matches!(text, Value::Text(s) if s.contains("获取时间")));
|
||||
assert!(tool_allowed(&tools, &Value::Text("获取时间".into())).unwrap().truthy());
|
||||
assert!(!tool_allowed(&tools, &Value::Text("nope".into())).unwrap().truthy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_set_and_history() {
|
||||
let mut ctx = HostContext::default();
|
||||
let id = ctx.alloc_agent_id();
|
||||
assert!(id.starts_with("agent-"));
|
||||
agent_history_append(&mut ctx, &Value::Text(id.clone()), &Value::Text("a".into()))
|
||||
.unwrap();
|
||||
let h = agent_history_get(&ctx, &Value::Text(id.clone())).unwrap();
|
||||
assert_eq!(h, Value::List(vec![Value::Text("a".into())]));
|
||||
agent_history_clear(&mut ctx, &Value::Text(id)).unwrap();
|
||||
let h2 = agent_history_get(&ctx, &Value::Text("agent-1".into())).unwrap();
|
||||
assert_eq!(h2, Value::List(vec![]));
|
||||
}
|
||||
}
|
||||
+78
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{foreign, fs, json, math, net, plugin, sys, time, HostContext};
|
||||
use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, sys, time, HostContext};
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -81,6 +81,17 @@ pub enum HostFn {
|
||||
PluginUnload = 70,
|
||||
PluginList = 71,
|
||||
ExtNativePath = 72,
|
||||
ModuleSource = 73,
|
||||
CallSite = 74,
|
||||
MarqdoSkill = 75,
|
||||
MapSet = 76,
|
||||
ListAppend = 77,
|
||||
AgentAlloc = 78,
|
||||
AgentHistoryGet = 79,
|
||||
AgentHistoryClear = 80,
|
||||
AgentHistoryAppend = 81,
|
||||
FormatToolsForLlm = 82,
|
||||
ToolAllowed = 83,
|
||||
}
|
||||
|
||||
impl HostFn {
|
||||
@@ -158,6 +169,17 @@ impl HostFn {
|
||||
70 => Self::PluginUnload,
|
||||
71 => Self::PluginList,
|
||||
72 => Self::ExtNativePath,
|
||||
73 => Self::ModuleSource,
|
||||
74 => Self::CallSite,
|
||||
75 => Self::MarqdoSkill,
|
||||
76 => Self::MapSet,
|
||||
77 => Self::ListAppend,
|
||||
78 => Self::AgentAlloc,
|
||||
79 => Self::AgentHistoryGet,
|
||||
80 => Self::AgentHistoryClear,
|
||||
81 => Self::AgentHistoryAppend,
|
||||
82 => Self::FormatToolsForLlm,
|
||||
83 => Self::ToolAllowed,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -239,6 +261,17 @@ impl HostFn {
|
||||
"host_plugin_unload" | "plugin_unload" => Self::PluginUnload,
|
||||
"host_plugin_list" | "plugin_list" => Self::PluginList,
|
||||
"host_ext_native_path" | "ext_native_path" => Self::ExtNativePath,
|
||||
"host_module_source" | "module_source" => Self::ModuleSource,
|
||||
"host_call_site" | "call_site" => Self::CallSite,
|
||||
"host_marqdo_skill" | "marqdo_skill" => Self::MarqdoSkill,
|
||||
"host_map_set" | "map_set" => Self::MapSet,
|
||||
"host_list_append" | "list_append" => Self::ListAppend,
|
||||
"host_agent_alloc" | "agent_alloc" => Self::AgentAlloc,
|
||||
"host_agent_history_get" | "agent_history_get" => Self::AgentHistoryGet,
|
||||
"host_agent_history_clear" | "agent_history_clear" => Self::AgentHistoryClear,
|
||||
"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,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -321,6 +354,17 @@ impl HostFn {
|
||||
Self::PluginUnload => "host_plugin_unload",
|
||||
Self::PluginList => "host_plugin_list",
|
||||
Self::ExtNativePath => "host_ext_native_path",
|
||||
Self::ModuleSource => "host_module_source",
|
||||
Self::CallSite => "host_call_site",
|
||||
Self::MarqdoSkill => "host_marqdo_skill",
|
||||
Self::MapSet => "host_map_set",
|
||||
Self::ListAppend => "host_list_append",
|
||||
Self::AgentAlloc => "host_agent_alloc",
|
||||
Self::AgentHistoryGet => "host_agent_history_get",
|
||||
Self::AgentHistoryClear => "host_agent_history_clear",
|
||||
Self::AgentHistoryAppend => "host_agent_history_append",
|
||||
Self::FormatToolsForLlm => "host_format_tools_for_llm",
|
||||
Self::ToolAllowed => "host_tool_allowed",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,6 +410,13 @@ impl HostFn {
|
||||
Self::PluginLoad => &["path"],
|
||||
Self::PluginUnload | Self::PluginList => &[],
|
||||
Self::ExtNativePath => &["name"],
|
||||
Self::ModuleSource | Self::CallSite | Self::MarqdoSkill | Self::AgentAlloc => &[],
|
||||
Self::MapSet => &["map", "key", "value"],
|
||||
Self::ListAppend => &["list", "item"],
|
||||
Self::AgentHistoryGet | Self::AgentHistoryClear => &["id"],
|
||||
Self::AgentHistoryAppend => &["id", "item"],
|
||||
Self::FormatToolsForLlm => &["tools"],
|
||||
Self::ToolAllowed => &["tools", "name"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,6 +606,32 @@ pub fn call_host(
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
HostFn::ModuleSource => agent_rt::module_source(ctx),
|
||||
HostFn::CallSite => {
|
||||
agent_rt::call_site(ctx, Some(ctx.current_line))
|
||||
}
|
||||
HostFn::MarqdoSkill => agent_rt::marqdo_skill(ctx),
|
||||
HostFn::MapSet => {
|
||||
agent_rt::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?)
|
||||
}
|
||||
HostFn::ListAppend => {
|
||||
agent_rt::list_append(require(bound, "list")?, require(bound, "item")?)
|
||||
}
|
||||
HostFn::AgentAlloc => agent_rt::agent_alloc(ctx),
|
||||
HostFn::AgentHistoryGet => agent_rt::agent_history_get(ctx, require(bound, "id")?),
|
||||
HostFn::AgentHistoryClear => {
|
||||
agent_rt::agent_history_clear(ctx, require(bound, "id")?)
|
||||
}
|
||||
HostFn::AgentHistoryAppend => {
|
||||
agent_rt::agent_history_append(ctx, require(bound, "id")?, require(bound, "item")?)
|
||||
}
|
||||
HostFn::FormatToolsForLlm => {
|
||||
agent_rt::format_tools_for_llm(require(bound, "tools")?)
|
||||
}
|
||||
HostFn::ToolAllowed => agent_rt::tool_allowed(
|
||||
require(bound, "tools")?,
|
||||
require(bound, "name")?,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! Capabilities default **on** (importing a lib means you intend to use it).
|
||||
//! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only.
|
||||
|
||||
pub mod agent_rt;
|
||||
mod dispatch;
|
||||
pub mod foreign;
|
||||
mod fs;
|
||||
@@ -21,6 +22,8 @@ pub use plugin::PluginState;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
/// Host capability flags. Default: all enabled.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostCaps {
|
||||
@@ -65,6 +68,16 @@ pub struct HostContext {
|
||||
pub foreign_cmds: HashMap<String, Vec<String>>,
|
||||
/// Loaded native plugins (ABI v1).
|
||||
pub plugins: PluginState,
|
||||
/// Entry `.mq.md` source text (for agent context injection).
|
||||
pub entry_source: Option<String>,
|
||||
pub entry_path: Option<PathBuf>,
|
||||
/// Active function names (outer → inner) for call-site injection.
|
||||
pub call_stack: Vec<String>,
|
||||
/// Per-agent conversation history (id → turns).
|
||||
pub agent_histories: HashMap<String, Vec<Value>>,
|
||||
pub agent_seq: u64,
|
||||
/// Last statement line (updated by interpreters for `host_call_site`).
|
||||
pub current_line: u32,
|
||||
}
|
||||
|
||||
impl Default for HostContext {
|
||||
@@ -80,6 +93,12 @@ impl Default for HostContext {
|
||||
plots: Vec::new(),
|
||||
foreign_cmds: HashMap::new(),
|
||||
plugins: PluginState::default(),
|
||||
entry_source: None,
|
||||
entry_path: None,
|
||||
call_stack: Vec::new(),
|
||||
agent_histories: HashMap::new(),
|
||||
agent_seq: 0,
|
||||
current_line: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+29
-6
@@ -166,13 +166,18 @@ impl Interpreter {
|
||||
}
|
||||
}
|
||||
|
||||
let mut ret = Value::None;
|
||||
for stmt in &fun.body {
|
||||
if let Some(v) = self.exec_stmt(module, fun, &mut env, stmt)? {
|
||||
ret = v;
|
||||
break;
|
||||
let ret = Value::None;
|
||||
self.host.push_call_frame(&fun.name);
|
||||
let body_result = (|| -> Result<Value> {
|
||||
for stmt in &fun.body {
|
||||
if let Some(v) = self.exec_stmt(module, fun, &mut env, stmt)? {
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ret)
|
||||
})();
|
||||
self.host.pop_call_frame();
|
||||
let ret = body_result?;
|
||||
if self.trace {
|
||||
let display = ret.as_display();
|
||||
emit_trace(
|
||||
@@ -194,6 +199,7 @@ impl Interpreter {
|
||||
) -> Result<Option<Value>> {
|
||||
let span = stmt_span(stmt);
|
||||
self.current_span = span;
|
||||
self.host.current_line = span.line;
|
||||
if let Some(dbg) = &self.debug {
|
||||
dbg.on_stmt(span.line, &fun.name, &env.vars, &self.captured_stdout)
|
||||
.map_err(|m| self.err(m))?;
|
||||
@@ -557,6 +563,23 @@ impl Interpreter {
|
||||
.ok_or_else(|| self.err("at requires index"))?;
|
||||
return builtin_at(value, index).map_err(|m| self.err(m));
|
||||
}
|
||||
"call_fn" => {
|
||||
let bound = bind_args(&["name".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let name = match bound.get("name") {
|
||||
Some(Value::Text(s)) => s.as_str(),
|
||||
_ => return Err(self.err("call_fn requires text name")),
|
||||
};
|
||||
let target = lookup_function(module, fun, name).ok_or_else(|| {
|
||||
self.err(format!("call_fn: unknown function `{name}`"))
|
||||
})?;
|
||||
if !target.params.is_empty() {
|
||||
return Err(self.err(format!(
|
||||
"call_fn: `{name}` must have no parameters"
|
||||
)));
|
||||
}
|
||||
return self.run_function(module, target, Env::new(), &[]);
|
||||
}
|
||||
other if HostFn::from_name(other).is_some() => {
|
||||
let hf = HostFn::from_name(other).unwrap();
|
||||
let mut params: Vec<String> =
|
||||
|
||||
+6
-2
@@ -171,7 +171,8 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
|
||||
let mut host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
|
||||
host.set_entry_source(Some(path), &source);
|
||||
let mut interp = Interpreter::new(Some(path), opts.trace_eval)
|
||||
.with_stdin(stdin_lines.clone())
|
||||
.with_host(host);
|
||||
@@ -190,7 +191,8 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
if opts.dump_bytecode {
|
||||
print!("{}", program.disassemble());
|
||||
}
|
||||
let host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
|
||||
let mut host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
|
||||
host.set_entry_source(Some(path), &source);
|
||||
let mut vm = Vm::new(Some(path))
|
||||
.with_stdin(stdin_lines)
|
||||
.with_trace(opts.trace_eval)
|
||||
@@ -225,6 +227,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let mut host = HostContext::for_capture(Some(path), opts.host_caps());
|
||||
host.set_entry_source(Some(path), &source);
|
||||
host.argv = opts.argv.clone();
|
||||
if let Some(root) = &opts.fs_root {
|
||||
host.fs_root = Some(root.clone());
|
||||
@@ -246,6 +249,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
Backend::Bytecode => {
|
||||
let program = compile_module(Some(path), &module)?;
|
||||
let mut host = HostContext::for_capture(Some(path), opts.host_caps());
|
||||
host.set_entry_source(Some(path), &source);
|
||||
host.argv = opts.argv.clone();
|
||||
if let Some(root) = &opts.fs_root {
|
||||
host.fs_root = Some(root.clone());
|
||||
|
||||
Reference in new issue
Block a user