feat: support agent skills

feat:support agent skills
This commit is contained in:
nullkey
2026-02-03 12:18:37 +08:00
committed by lyingbug
parent 6e03f1ea79
commit 33f7e7da66
26 changed files with 4349 additions and 6 deletions
+5
View File
@@ -14,6 +14,9 @@ const (
ToolDataSchema = "data_schema"
ToolWebSearch = "web_search"
ToolWebFetch = "web_fetch"
// Skills-related tools (only available when skills are enabled)
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
)
// AvailableTool defines a simple tool metadata used by settings APIs.
@@ -37,6 +40,8 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolDatabaseQuery, Label: "查询数据库", Description: "查询数据库中的信息"},
{Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析"},
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
}
}
+189
View File
@@ -0,0 +1,189 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// Tool name constant for execute_skill_script
var executeSkillScriptTool = BaseTool{
name: ToolExecuteSkillScript,
description: `Execute a script from a skill in a sandboxed environment.
## Usage
- Use this tool to run utility scripts bundled with a skill
- Scripts are executed in an isolated sandbox for security
- Only scripts from loaded skills can be executed
## When to Use
- When a skill's instructions reference a utility script (e.g., "Run scripts/analyze_form.py")
- When automation or data processing is needed as part of skill workflow
- For deterministic operations where script execution is more reliable than generating code
## Security
- Scripts run in a sandboxed environment with limited permissions
- Network access is disabled by default
- File access is restricted to the skill directory
## Returns
- Script stdout and stderr output
- Exit code indicating success (0) or failure (non-zero)`,
schema: utils.GenerateSchema[ExecuteSkillScriptInput](),
}
// ExecuteSkillScriptInput defines the input parameters for the execute_skill_script tool
type ExecuteSkillScriptInput struct {
SkillName string `json:"skill_name" jsonschema:"Name of the skill containing the script"`
ScriptPath string `json:"script_path" jsonschema:"Relative path to the script within the skill directory (e.g. scripts/analyze.py)"`
Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments to pass to the script"`
}
// ExecuteSkillScriptTool allows the agent to execute skill scripts in a sandbox
type ExecuteSkillScriptTool struct {
BaseTool
skillManager *skills.Manager
}
// NewExecuteSkillScriptTool creates a new execute_skill_script tool instance
func NewExecuteSkillScriptTool(skillManager *skills.Manager) *ExecuteSkillScriptTool {
return &ExecuteSkillScriptTool{
BaseTool: executeSkillScriptTool,
skillManager: skillManager,
}
}
// Execute executes the execute_skill_script tool
func (t *ExecuteSkillScriptTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][ExecuteSkillScript] Execute started")
// Parse input
var input ExecuteSkillScriptInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][ExecuteSkillScript] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, nil
}
// Validate required fields
if input.SkillName == "" {
return &types.ToolResult{
Success: false,
Error: "skill_name is required",
}, nil
}
if input.ScriptPath == "" {
return &types.ToolResult{
Success: false,
Error: "script_path is required",
}, nil
}
// Check if skill manager is available
if t.skillManager == nil || !t.skillManager.IsEnabled() {
return &types.ToolResult{
Success: false,
Error: "Skills are not enabled",
}, nil
}
// Execute the script in sandbox
logger.Infof(ctx, "[Tool][ExecuteSkillScript] Executing script: %s/%s with args: %v",
input.SkillName, input.ScriptPath, input.Args)
result, err := t.skillManager.ExecuteScript(ctx, input.SkillName, input.ScriptPath, input.Args)
if err != nil {
logger.Errorf(ctx, "[Tool][ExecuteSkillScript] Script execution failed: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Script execution failed: %v", err),
}, nil
}
// Build output
var builder strings.Builder
builder.WriteString(fmt.Sprintf("=== Script Execution: %s/%s ===\n\n", input.SkillName, input.ScriptPath))
if len(input.Args) > 0 {
builder.WriteString(fmt.Sprintf("**Arguments**: %v\n", input.Args))
}
builder.WriteString(fmt.Sprintf("**Exit Code**: %d\n", result.ExitCode))
builder.WriteString(fmt.Sprintf("**Duration**: %v\n\n", result.Duration))
if result.Killed {
builder.WriteString("**Warning**: Script was terminated (timeout or killed)\n\n")
}
if result.Stdout != "" {
builder.WriteString("## Standard Output\n\n")
builder.WriteString("```\n")
builder.WriteString(result.Stdout)
if !strings.HasSuffix(result.Stdout, "\n") {
builder.WriteString("\n")
}
builder.WriteString("```\n\n")
}
if result.Stderr != "" {
builder.WriteString("## Standard Error\n\n")
builder.WriteString("```\n")
builder.WriteString(result.Stderr)
if !strings.HasSuffix(result.Stderr, "\n") {
builder.WriteString("\n")
}
builder.WriteString("```\n\n")
}
if result.Error != "" {
builder.WriteString("## Error\n\n")
builder.WriteString(result.Error)
builder.WriteString("\n")
}
// Determine success based on exit code
success := result.IsSuccess()
resultData := map[string]interface{}{
"skill_name": input.SkillName,
"script_path": input.ScriptPath,
"args": input.Args,
"exit_code": result.ExitCode,
"stdout": result.Stdout,
"stderr": result.Stderr,
"duration_ms": result.Duration.Milliseconds(),
"killed": result.Killed,
}
logger.Infof(ctx, "[Tool][ExecuteSkillScript] Script completed with exit code: %d", result.ExitCode)
return &types.ToolResult{
Success: success,
Output: builder.String(),
Data: resultData,
Error: func() string {
if !success {
if result.Error != "" {
return result.Error
}
return fmt.Sprintf("Script exited with code %d", result.ExitCode)
}
return ""
}(),
}, nil
}
// Cleanup releases any resources
func (t *ExecuteSkillScriptTool) Cleanup(ctx context.Context) error {
return nil
}
+165
View File
@@ -0,0 +1,165 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// Tool name constant for read_skill
var readSkillTool = BaseTool{
name: ToolReadSkill,
description: `Read skill content on demand to learn specialized capabilities.
## Usage
- Use this tool when a user request matches an available skill's description
- Provide the skill_name to load the skill's full instructions (SKILL.md content)
- Optionally provide file_path to read additional files within the skill directory
## When to Use
- When the system prompt shows an available skill that matches the user's request
- Before performing tasks that match a skill's description
- To read additional documentation or reference files within a skill
## Returns
- Skill instructions and guidance for completing the task
- File content if file_path is specified`,
schema: utils.GenerateSchema[ReadSkillInput](),
}
// ReadSkillInput defines the input parameters for the read_skill tool
type ReadSkillInput struct {
SkillName string `json:"skill_name" jsonschema:"Name of the skill to read"`
FilePath string `json:"file_path,omitempty" jsonschema:"Optional relative path to a specific file within the skill directory"`
}
// ReadSkillTool allows the agent to read skill content on demand
type ReadSkillTool struct {
BaseTool
skillManager *skills.Manager
}
// NewReadSkillTool creates a new read_skill tool instance
func NewReadSkillTool(skillManager *skills.Manager) *ReadSkillTool {
return &ReadSkillTool{
BaseTool: readSkillTool,
skillManager: skillManager,
}
}
// Execute executes the read_skill tool
func (t *ReadSkillTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][ReadSkill] Execute started")
// Parse input
var input ReadSkillInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][ReadSkill] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, nil
}
// Validate skill name
if input.SkillName == "" {
return &types.ToolResult{
Success: false,
Error: "skill_name is required",
}, nil
}
// Check if skill manager is available
if t.skillManager == nil || !t.skillManager.IsEnabled() {
return &types.ToolResult{
Success: false,
Error: "Skills are not enabled",
}, nil
}
var builder strings.Builder
var resultData = make(map[string]interface{})
if input.FilePath != "" {
// Read a specific file from the skill directory
content, err := t.skillManager.ReadSkillFile(ctx, input.SkillName, input.FilePath)
if err != nil {
logger.Errorf(ctx, "[Tool][ReadSkill] Failed to read skill file: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to read skill file: %v", err),
}, nil
}
builder.WriteString(fmt.Sprintf("=== Skill File: %s/%s ===\n\n", input.SkillName, input.FilePath))
builder.WriteString(content)
resultData["skill_name"] = input.SkillName
resultData["file_path"] = input.FilePath
resultData["content"] = content
resultData["content_length"] = len(content)
} else {
// Read the main skill instructions (SKILL.md)
skill, err := t.skillManager.LoadSkill(ctx, input.SkillName)
if err != nil {
logger.Errorf(ctx, "[Tool][ReadSkill] Failed to load skill: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to load skill: %v", err),
}, nil
}
// List available files in the skill directory
files, err := t.skillManager.ListSkillFiles(ctx, input.SkillName)
if err != nil {
files = []string{} // Non-fatal error
}
builder.WriteString(fmt.Sprintf("=== Skill: %s ===\n\n", skill.Name))
builder.WriteString(fmt.Sprintf("**Description**: %s\n\n", skill.Description))
builder.WriteString("## Instructions\n\n")
builder.WriteString(skill.Instructions)
// Add available files section
if len(files) > 1 { // More than just SKILL.md
builder.WriteString("\n\n## Available Files\n\n")
builder.WriteString("The following files are available in this skill directory. Use `read_skill` with `file_path` to read them:\n\n")
for _, file := range files {
if file != skills.SkillFileName { // Don't list SKILL.md again
if skills.IsScript(file) {
builder.WriteString(fmt.Sprintf("- `%s` (script - can be executed)\n", file))
} else {
builder.WriteString(fmt.Sprintf("- `%s`\n", file))
}
}
}
}
resultData["skill_name"] = skill.Name
resultData["description"] = skill.Description
resultData["instructions"] = skill.Instructions
resultData["instructions_length"] = len(skill.Instructions)
resultData["files"] = files
}
logger.Infof(ctx, "[Tool][ReadSkill] Successfully read skill: %s", input.SkillName)
return &types.ToolResult{
Success: true,
Output: builder.String(),
Data: resultData,
}, nil
}
// Cleanup releases any resources (implements Tool interface if needed)
func (t *ReadSkillTool) Cleanup(ctx context.Context) error {
return nil
}