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![]));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user