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
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user