Files
zclaw_openfang/crates/zclaw-skills/src/runner.rs
iven c1dea6e07a
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled
fix(growth,skills,kernel): Phase 0 地基修复 — 经验积累覆盖 + Skill 工具调用
Bug 1: ExperienceStore store_experience() 相同 pain_pattern 因确定性 URI
直接覆盖,新 Experience reuse_count=0 重置已有积累。修复为先检查 URI
是否已存在,若存在则合并(保留原 id/created_at,reuse_count+1)。

Bug 2: PromptOnlySkill::execute() 只做纯文本 complete(),75 个 Skill
的 tools 字段是装饰性的。修复为扩展 LlmCompleter 支持 complete_with_tools,
SkillContext 新增 tool_definitions,KernelSkillExecutor 从 ToolRegistry
解析 manifest 声明的工具定义传入 LLM function calling。
2026-04-21 01:12:35 +08:00

217 lines
7.2 KiB
Rust

//! Skill runners for different execution modes
use async_trait::async_trait;
use serde_json::Value;
use std::process::Command;
use std::time::Instant;
use tracing::warn;
use zclaw_types::Result;
use super::{Skill, SkillCompletion, SkillContext, SkillManifest, SkillResult};
/// Returns the platform-appropriate Python binary name.
/// On Windows, the standard installer provides `python.exe`, not `python3.exe`.
#[cfg(target_os = "windows")]
fn python_bin() -> &'static str { "python" }
#[cfg(not(target_os = "windows"))]
fn python_bin() -> &'static str { "python3" }
/// Prompt-only skill execution
pub struct PromptOnlySkill {
manifest: SkillManifest,
prompt_template: String,
}
impl PromptOnlySkill {
pub fn new(manifest: SkillManifest, prompt_template: String) -> Self {
Self { manifest, prompt_template }
}
fn format_prompt(&self, input: &Value) -> String {
let mut prompt = self.prompt_template.clone();
if let Value::String(s) = input {
prompt = prompt.replace("{{input}}", s);
} else {
prompt = prompt.replace("{{input}}", &serde_json::to_string_pretty(input).unwrap_or_default());
}
prompt
}
fn completion_to_result(&self, completion: SkillCompletion) -> SkillResult {
if completion.tool_calls.is_empty() {
return SkillResult::success(Value::String(completion.text));
}
// Include both text and tool calls so the caller can relay them.
SkillResult::success(serde_json::json!({
"text": completion.text,
"tool_calls": completion.tool_calls,
}))
}
}
#[async_trait]
impl Skill for PromptOnlySkill {
fn manifest(&self) -> &SkillManifest {
&self.manifest
}
async fn execute(&self, context: &SkillContext, input: Value) -> Result<SkillResult> {
let prompt = self.format_prompt(&input);
if let Some(completer) = &context.llm {
// If tool definitions are available and the manifest declares tools,
// use tool-augmented completion so the LLM can invoke tools.
if !context.tool_definitions.is_empty() && !self.manifest.tools.is_empty() {
match completer.complete_with_tools(&prompt, None, context.tool_definitions.clone()).await {
Ok(completion) => {
return Ok(self.completion_to_result(completion));
}
Err(e) => {
warn!("[PromptOnlySkill] Tool completion failed: {}, falling back", e);
}
}
}
// Plain completion (no tools or fallback)
match completer.complete(&prompt).await {
Ok(response) => return Ok(SkillResult::success(Value::String(response))),
Err(e) => {
warn!("[PromptOnlySkill] LLM completion failed: {}, falling back to raw prompt", e);
}
}
}
// No LLM available — return formatted prompt (backward compatible)
Ok(SkillResult::success(Value::String(prompt)))
}
}
/// Python script skill execution
pub struct PythonSkill {
manifest: SkillManifest,
script_path: std::path::PathBuf,
}
impl PythonSkill {
pub fn new(manifest: SkillManifest, script_path: std::path::PathBuf) -> Self {
Self { manifest, script_path }
}
}
#[async_trait]
impl Skill for PythonSkill {
fn manifest(&self) -> &SkillManifest {
&self.manifest
}
async fn execute(&self, context: &SkillContext, input: Value) -> Result<SkillResult> {
let start = Instant::now();
let input_json = serde_json::to_string(&input).unwrap_or_default();
// P2-20: Platform-aware Python binary (Windows has no python3)
let output = Command::new(python_bin())
.arg(&self.script_path)
.env("SKILL_INPUT", &input_json)
.env("AGENT_ID", &context.agent_id)
.env("SESSION_ID", &context.session_id)
.output()
.map_err(|e| zclaw_types::ZclawError::ToolError(format!("Failed to execute Python: {}", e)))?;
let duration_ms = start.elapsed().as_millis() as u64;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
let result = serde_json::from_str(&stdout)
.map(|v| SkillResult {
success: true,
output: v,
error: None,
duration_ms: Some(duration_ms),
tokens_used: None,
})
.unwrap_or_else(|_| SkillResult::success(Value::String(stdout.to_string())));
Ok(result)
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Ok(SkillResult::error(stderr))
}
}
}
/// Shell command skill execution
pub struct ShellSkill {
manifest: SkillManifest,
command: String,
}
impl ShellSkill {
pub fn new(manifest: SkillManifest, command: String) -> Self {
Self { manifest, command }
}
}
#[async_trait]
impl Skill for ShellSkill {
fn manifest(&self) -> &SkillManifest {
&self.manifest
}
async fn execute(&self, context: &SkillContext, input: Value) -> Result<SkillResult> {
let start = Instant::now();
let mut cmd = self.command.clone();
if let Value::String(s) = input {
// Shell-quote the input to prevent command injection
let quoted = shlex::try_quote(&s)
.map_err(|_| zclaw_types::ZclawError::ToolError(
"Input contains null bytes and cannot be safely quoted".to_string()
))?;
cmd = cmd.replace("{{input}}", &quoted);
}
#[cfg(target_os = "windows")]
let output = {
Command::new("cmd")
.args(["/C", &cmd])
.current_dir(context.working_dir.as_ref().unwrap_or(&std::path::PathBuf::from(".")))
.output()
.map_err(|e| zclaw_types::ZclawError::ToolError(format!("Failed to execute shell: {}", e)))?
};
#[cfg(not(target_os = "windows"))]
let output = {
Command::new("sh")
.args(["-c", &cmd])
.current_dir(context.working_dir.as_ref().unwrap_or(&std::path::PathBuf::from(".")))
.output()
.map_err(|e| zclaw_types::ZclawError::ToolError(format!("Failed to execute shell: {}", e)))?
};
// P3-08: Use duration_ms instead of discarding it
let duration_ms = start.elapsed().as_millis() as u64;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
Ok(SkillResult {
success: true,
output: Value::String(stdout.to_string()),
error: None,
duration_ms: Some(duration_ms),
tokens_used: None,
})
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Ok(SkillResult {
success: false,
output: Value::Null,
error: Some(stderr.to_string()),
duration_ms: Some(duration_ms),
tokens_used: None,
})
}
}
}