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
+61 -6
View File
@@ -7,6 +7,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/event"
@@ -33,6 +34,7 @@ type AgentEngine struct {
contextManager interfaces.ContextManager // Context manager for writing agent conversation to LLM context
sessionID string // Session ID for context management
systemPromptTemplate string // System prompt template (optional, uses default if empty)
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
}
// listToolNames returns tool.function names for logging
@@ -72,6 +74,44 @@ func NewAgentEngine(
}
}
// NewAgentEngineWithSkills creates a new agent engine with skills support
func NewAgentEngineWithSkills(
config *types.AgentConfig,
chatModel chat.Chat,
toolRegistry *tools.ToolRegistry,
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
contextManager interfaces.ContextManager,
sessionID string,
systemPromptTemplate string,
skillsManager *skills.Manager,
) *AgentEngine {
engine := NewAgentEngine(
config,
chatModel,
toolRegistry,
eventBus,
knowledgeBasesInfo,
selectedDocs,
contextManager,
sessionID,
systemPromptTemplate,
)
engine.skillsManager = skillsManager
return engine
}
// SetSkillsManager sets the skills manager for the engine
func (e *AgentEngine) SetSkillsManager(manager *skills.Manager) {
e.skillsManager = manager
}
// GetSkillsManager returns the skills manager
func (e *AgentEngine) GetSkillsManager() *skills.Manager {
return e.skillsManager
}
// Execute executes the agent with conversation history and streaming output
// All events are emitted to EventBus and handled by subscribers (like Handler layer)
func (e *AgentEngine) Execute(
@@ -102,12 +142,27 @@ func (e *AgentEngine) Execute(
}
// Build system prompt using progressive RAG prompt
systemPrompt := BuildSystemPrompt(
e.knowledgeBasesInfo,
e.config.WebSearchEnabled,
e.selectedDocs,
e.systemPromptTemplate,
)
// If skills are enabled, include skills metadata (Level 1 - Progressive Disclosure)
var systemPrompt string
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
skillsMetadata := e.skillsManager.GetAllMetadata()
systemPrompt = BuildSystemPromptWithOptions(
e.knowledgeBasesInfo,
e.config.WebSearchEnabled,
e.selectedDocs,
&BuildSystemPromptOptions{
SkillsMetadata: skillsMetadata,
},
e.systemPromptTemplate,
)
} else {
systemPrompt = BuildSystemPrompt(
e.knowledgeBasesInfo,
e.config.WebSearchEnabled,
e.selectedDocs,
e.systemPromptTemplate,
)
}
logger.Debugf(ctx, "[Agent] SystemPrompt Length: %d characters", len(systemPrompt))
logger.Debugf(ctx, "[Agent] SystemPrompt (stream)\n----\n%s\n----", systemPrompt)
+50
View File
@@ -5,6 +5,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -193,6 +194,28 @@ func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseIn
return result
}
// formatSkillsMetadata formats skills metadata for the system prompt (Level 1 - Progressive Disclosure)
// This is a lightweight representation that only includes skill name and description
func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
if len(skillsMetadata) == 0 {
return ""
}
var builder strings.Builder
builder.WriteString("\n### Available Skills\n\n")
builder.WriteString("The following skills are available. When a user request matches a skill's description, ")
builder.WriteString("use the `read_skill` tool to load its full instructions before proceeding.\n\n")
for i, skill := range skillsMetadata {
builder.WriteString(fmt.Sprintf("%d. **%s**: %s\n", i+1, skill.Name, skill.Description))
}
builder.WriteString("\nUse `read_skill` with the skill name to load detailed instructions when needed.\n")
builder.WriteString("Use `execute_skill_script` to run utility scripts bundled with a skill.\n")
return builder.String()
}
// formatSelectedDocuments formats selected documents for the prompt (summary only, no content)
func formatSelectedDocuments(docs []*SelectedDocumentInfo) string {
if len(docs) == 0 {
@@ -230,6 +253,7 @@ func formatSelectedDocuments(docs []*SelectedDocumentInfo) string {
// - {{knowledge_bases}}
// - {{web_search_status}} -> "Enabled" or "Disabled"
// - {{current_time}} -> current time string
// - {{skills}} -> formatted skills metadata (if any)
func renderPromptPlaceholdersWithStatus(
template string,
knowledgeBases []*KnowledgeBaseInfo,
@@ -247,6 +271,11 @@ func renderPromptPlaceholdersWithStatus(
if strings.Contains(result, "{{current_time}}") {
result = strings.ReplaceAll(result, "{{current_time}}", currentTime)
}
// Remove {{skills}} placeholder if present but no skills provided
// (it will be appended separately if skills exist)
if strings.Contains(result, "{{skills}}") {
result = strings.ReplaceAll(result, "{{skills}}", "")
}
return result
}
@@ -298,6 +327,11 @@ func BuildPureAgentSystemPrompt(
return renderPromptPlaceholdersWithStatus(template, []*KnowledgeBaseInfo{}, webSearchEnabled, currentTime)
}
// BuildSystemPromptOptions contains optional parameters for BuildSystemPrompt
type BuildSystemPromptOptions struct {
SkillsMetadata []*skills.SkillMetadata
}
// BuildSystemPrompt builds the progressive RAG system prompt
// This is the main function to use - it uses a unified template with dynamic web search status
func BuildSystemPrompt(
@@ -305,6 +339,17 @@ func BuildSystemPrompt(
webSearchEnabled bool,
selectedDocs []*SelectedDocumentInfo,
systemPromptTemplate ...string,
) string {
return BuildSystemPromptWithOptions(knowledgeBases, webSearchEnabled, selectedDocs, nil, systemPromptTemplate...)
}
// BuildSystemPromptWithOptions builds the system prompt with additional options like skills
func BuildSystemPromptWithOptions(
knowledgeBases []*KnowledgeBaseInfo,
webSearchEnabled bool,
selectedDocs []*SelectedDocumentInfo,
options *BuildSystemPromptOptions,
systemPromptTemplate ...string,
) string {
var basePrompt string
var template string
@@ -326,6 +371,11 @@ func BuildSystemPrompt(
basePrompt += formatSelectedDocuments(selectedDocs)
}
// Append skills metadata if available (Level 1 - Progressive Disclosure)
if options != nil && len(options.SkillsMetadata) > 0 {
basePrompt += formatSkillsMetadata(options.SkillsMetadata)
}
return basePrompt
}
+161
View File
@@ -0,0 +1,161 @@
package skills
import (
"context"
"path/filepath"
"runtime"
"testing"
)
// TestExampleSkillsIntegration tests with the actual example skills in examples/skills
func TestExampleSkillsIntegration(t *testing.T) {
// Get the path to examples/skills relative to this test file
_, filename, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("Failed to get current file path")
}
// Navigate from internal/agent/skills to examples/skills
skillsDir := filepath.Join(filepath.Dir(filename), "..", "..", "..", "examples", "skills")
// Create loader
loader := NewLoader([]string{skillsDir})
// Discover skills
metadata, err := loader.DiscoverSkills()
if err != nil {
t.Fatalf("Failed to discover skills: %v", err)
}
if len(metadata) == 0 {
t.Skip("No example skills found in examples/skills directory")
}
t.Logf("Discovered %d example skills:", len(metadata))
for _, m := range metadata {
t.Logf(" - %s: %s", m.Name, truncate(m.Description, 60))
}
// Test loading the pdf-processing skill
pdfSkill, err := loader.LoadSkillInstructions("pdf-processing")
if err != nil {
t.Fatalf("Failed to load pdf-processing skill: %v", err)
}
// Verify metadata
if pdfSkill.Name != "pdf-processing" {
t.Errorf("Expected name 'pdf-processing', got '%s'", pdfSkill.Name)
}
if pdfSkill.Instructions == "" {
t.Error("Expected instructions to be non-empty")
}
t.Logf("PDF Processing skill instructions length: %d characters", len(pdfSkill.Instructions))
// Test loading additional file (FORMS.md)
formsFile, err := loader.LoadSkillFile("pdf-processing", "FORMS.md")
if err != nil {
t.Fatalf("Failed to load FORMS.md: %v", err)
}
if formsFile.Content == "" {
t.Error("Expected FORMS.md content to be non-empty")
}
t.Logf("FORMS.md content length: %d characters", len(formsFile.Content))
// Test loading script
scriptFile, err := loader.LoadSkillFile("pdf-processing", "scripts/analyze_form.py")
if err != nil {
t.Fatalf("Failed to load analyze_form.py: %v", err)
}
if !scriptFile.IsScript {
t.Error("analyze_form.py should be marked as script")
}
t.Logf("analyze_form.py content length: %d characters", len(scriptFile.Content))
// Test list files
files, err := loader.ListSkillFiles("pdf-processing")
if err != nil {
t.Fatalf("Failed to list skill files: %v", err)
}
t.Logf("Files in pdf-processing skill:")
for _, f := range files {
t.Logf(" - %s (script: %v)", f, IsScript(f))
}
}
// TestManagerWithExampleSkills tests the Manager with example skills
func TestManagerWithExampleSkills(t *testing.T) {
// Get the path to examples/skills
_, filename, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("Failed to get current file path")
}
skillsDir := filepath.Join(filepath.Dir(filename), "..", "..", "..", "examples", "skills")
// Create manager
config := &ManagerConfig{
SkillDirs: []string{skillsDir},
AllowedSkills: []string{}, // Allow all
Enabled: true,
}
manager := NewManager(config, nil)
// Initialize
ctx := context.Background()
if err := manager.Initialize(ctx); err != nil {
t.Fatalf("Failed to initialize manager: %v", err)
}
// Get metadata for system prompt
metadata := manager.GetAllMetadata()
if len(metadata) == 0 {
t.Skip("No example skills found")
}
t.Logf("Manager discovered %d skills for system prompt injection", len(metadata))
// Simulate what the agent would do:
// 1. First, get metadata (Level 1 - already in system prompt)
for _, m := range metadata {
t.Logf("Level 1 (metadata): %s - %s", m.Name, truncate(m.Description, 50))
}
// 2. When user request matches, load full skill instructions (Level 2)
skill, err := manager.LoadSkill(ctx, "pdf-processing")
if err != nil {
t.Fatalf("Failed to load skill: %v", err)
}
t.Logf("Level 2 (instructions): Loaded %d characters of instructions", len(skill.Instructions))
// 3. If skill references additional files, read them (Level 3)
formsContent, err := manager.ReadSkillFile(ctx, "pdf-processing", "FORMS.md")
if err != nil {
t.Fatalf("Failed to read skill file: %v", err)
}
t.Logf("Level 3 (resources): Loaded FORMS.md with %d characters", len(formsContent))
// Test GetSkillInfo
info, err := manager.GetSkillInfo(ctx, "pdf-processing")
if err != nil {
t.Fatalf("Failed to get skill info: %v", err)
}
t.Logf("Skill info: name=%s, files=%d", info.Name, len(info.Files))
}
func truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen] + "..."
}
+307
View File
@@ -0,0 +1,307 @@
package skills
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// Loader handles skill discovery and loading from the filesystem
// It implements the Progressive Disclosure pattern by separating
// metadata discovery (Level 1) from instructions loading (Level 2/3)
type Loader struct {
// skillDirs are the directories to search for skills
skillDirs []string
// discoveredSkills caches discovered skill metadata
discoveredSkills map[string]*Skill
}
// NewLoader creates a new skill loader with the specified search directories
func NewLoader(skillDirs []string) *Loader {
return &Loader{
skillDirs: skillDirs,
discoveredSkills: make(map[string]*Skill),
}
}
// DiscoverSkills scans all configured directories for SKILL.md files
// and extracts their metadata (Level 1). This is a lightweight operation
// that only reads the frontmatter of each skill file.
func (l *Loader) DiscoverSkills() ([]*SkillMetadata, error) {
var allMetadata []*SkillMetadata
for _, dir := range l.skillDirs {
metadata, err := l.discoverInDirectory(dir)
if err != nil {
// Log warning but continue with other directories
continue
}
allMetadata = append(allMetadata, metadata...)
}
return allMetadata, nil
}
// discoverInDirectory scans a single directory for skill subdirectories
func (l *Loader) discoverInDirectory(dir string) ([]*SkillMetadata, error) {
var metadata []*SkillMetadata
// Check if directory exists
info, err := os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil // Directory doesn't exist, skip silently
}
return nil, fmt.Errorf("failed to access skill directory %s: %w", dir, err)
}
if !info.IsDir() {
return nil, fmt.Errorf("%s is not a directory", dir)
}
// Read directory entries
entries, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("failed to read skill directory %s: %w", dir, err)
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
skillPath := filepath.Join(dir, entry.Name())
skillFile := filepath.Join(skillPath, SkillFileName)
// Check if SKILL.md exists
if _, err := os.Stat(skillFile); os.IsNotExist(err) {
continue
}
// Read and parse SKILL.md
content, err := os.ReadFile(skillFile)
if err != nil {
continue
}
skill, err := ParseSkillFile(string(content))
if err != nil {
continue
}
// Set filesystem paths
skill.BasePath = skillPath
skill.FilePath = skillFile
// Cache the skill
l.discoveredSkills[skill.Name] = skill
metadata = append(metadata, skill.ToMetadata())
}
return metadata, nil
}
// LoadSkillInstructions loads the full instructions of a skill (Level 2)
// Returns the cached skill if already loaded
func (l *Loader) LoadSkillInstructions(skillName string) (*Skill, error) {
// Check cache first
if skill, ok := l.discoveredSkills[skillName]; ok {
if skill.Loaded {
return skill, nil
}
}
// Search for the skill in all directories
for _, dir := range l.skillDirs {
skill, err := l.loadSkillFromDirectory(dir, skillName)
if err == nil {
l.discoveredSkills[skillName] = skill
return skill, nil
}
}
return nil, fmt.Errorf("skill not found: %s", skillName)
}
// loadSkillFromDirectory attempts to load a skill from a specific directory
func (l *Loader) loadSkillFromDirectory(dir, skillName string) (*Skill, error) {
// First, check if we can find by directory name matching skill name
skillPath := filepath.Join(dir, skillName)
skillFile := filepath.Join(skillPath, SkillFileName)
if _, err := os.Stat(skillFile); err == nil {
return l.loadSkillFile(skillPath, skillFile)
}
// Otherwise, scan all subdirectories to find the skill by name
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
skillPath := filepath.Join(dir, entry.Name())
skillFile := filepath.Join(skillPath, SkillFileName)
if _, err := os.Stat(skillFile); os.IsNotExist(err) {
continue
}
content, err := os.ReadFile(skillFile)
if err != nil {
continue
}
skill, err := ParseSkillFile(string(content))
if err != nil {
continue
}
if skill.Name == skillName {
skill.BasePath = skillPath
skill.FilePath = skillFile
return skill, nil
}
}
return nil, fmt.Errorf("skill not found in %s: %s", dir, skillName)
}
// loadSkillFile reads and parses a SKILL.md file
func (l *Loader) loadSkillFile(basePath, filePath string) (*Skill, error) {
content, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read skill file: %w", err)
}
skill, err := ParseSkillFile(string(content))
if err != nil {
return nil, err
}
skill.BasePath = basePath
skill.FilePath = filePath
return skill, nil
}
// LoadSkillFile loads an additional file from a skill directory (Level 3)
// The filePath should be relative to the skill's base directory
func (l *Loader) LoadSkillFile(skillName, relativePath string) (*SkillFile, error) {
// Get the skill first
skill, ok := l.discoveredSkills[skillName]
if !ok {
// Try to load the skill
var err error
skill, err = l.LoadSkillInstructions(skillName)
if err != nil {
return nil, fmt.Errorf("skill not found: %s", skillName)
}
}
// Validate and resolve the file path
cleanPath := filepath.Clean(relativePath)
// Security: prevent path traversal
if strings.HasPrefix(cleanPath, "..") || filepath.IsAbs(cleanPath) {
return nil, fmt.Errorf("invalid file path: %s", relativePath)
}
fullPath := filepath.Join(skill.BasePath, cleanPath)
// Verify the file is within the skill directory
absSkillPath, err := filepath.Abs(skill.BasePath)
if err != nil {
return nil, err
}
absFilePath, err := filepath.Abs(fullPath)
if err != nil {
return nil, err
}
if !strings.HasPrefix(absFilePath, absSkillPath) {
return nil, fmt.Errorf("file path outside skill directory: %s", relativePath)
}
// Read the file
content, err := os.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
return &SkillFile{
Name: relativePath,
Path: fullPath,
Content: string(content),
IsScript: IsScript(relativePath),
}, nil
}
// ListSkillFiles lists all files in a skill directory
func (l *Loader) ListSkillFiles(skillName string) ([]string, error) {
skill, ok := l.discoveredSkills[skillName]
if !ok {
var err error
skill, err = l.LoadSkillInstructions(skillName)
if err != nil {
return nil, fmt.Errorf("skill not found: %s", skillName)
}
}
var files []string
err := filepath.Walk(skill.BasePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
// Get relative path
relPath, err := filepath.Rel(skill.BasePath, path)
if err != nil {
return err
}
files = append(files, relPath)
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to list skill files: %w", err)
}
return files, nil
}
// GetSkillByName returns a cached skill by name
func (l *Loader) GetSkillByName(name string) (*Skill, bool) {
skill, ok := l.discoveredSkills[name]
return skill, ok
}
// GetSkillBasePath returns the base path for a skill
func (l *Loader) GetSkillBasePath(skillName string) (string, error) {
skill, ok := l.discoveredSkills[skillName]
if !ok {
var err error
skill, err = l.LoadSkillInstructions(skillName)
if err != nil {
return "", fmt.Errorf("skill not found: %s", skillName)
}
}
return skill.BasePath, nil
}
// Reload clears the cache and rediscovers all skills
func (l *Loader) Reload() ([]*SkillMetadata, error) {
l.discoveredSkills = make(map[string]*Skill)
return l.DiscoverSkills()
}
+282
View File
@@ -0,0 +1,282 @@
package skills
import (
"context"
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/sandbox"
)
// Manager manages skills lifecycle including discovery, loading, and script execution
// It coordinates between the Loader (filesystem operations) and Sandbox (script execution)
type Manager struct {
loader *Loader
sandboxMgr sandbox.Manager
// Configuration
skillDirs []string
allowedSkills []string // Empty means all skills are allowed
enabled bool
// Cache
metadataCache []*SkillMetadata
mu sync.RWMutex
}
// ManagerConfig holds configuration for the skill manager
type ManagerConfig struct {
SkillDirs []string // Directories to search for skills
AllowedSkills []string // Skill names whitelist (empty = allow all)
Enabled bool // Whether skills are enabled
}
// NewManager creates a new skill manager with the given configuration
func NewManager(config *ManagerConfig, sandboxMgr sandbox.Manager) *Manager {
if config == nil {
config = &ManagerConfig{
Enabled: false,
}
}
return &Manager{
loader: NewLoader(config.SkillDirs),
sandboxMgr: sandboxMgr,
skillDirs: config.SkillDirs,
allowedSkills: config.AllowedSkills,
enabled: config.Enabled,
}
}
// IsEnabled returns whether skills are enabled
func (m *Manager) IsEnabled() bool {
return m.enabled
}
// Initialize discovers all skills and caches their metadata
// This should be called at startup
func (m *Manager) Initialize(ctx context.Context) error {
if !m.enabled {
return nil
}
metadata, err := m.loader.DiscoverSkills()
if err != nil {
return fmt.Errorf("failed to discover skills: %w", err)
}
// Filter by allowed skills if specified
if len(m.allowedSkills) > 0 {
metadata = m.filterAllowedSkills(metadata)
}
m.mu.Lock()
m.metadataCache = metadata
m.mu.Unlock()
return nil
}
// filterAllowedSkills filters metadata to only include allowed skills
func (m *Manager) filterAllowedSkills(metadata []*SkillMetadata) []*SkillMetadata {
if len(m.allowedSkills) == 0 {
return metadata
}
allowedSet := make(map[string]bool)
for _, name := range m.allowedSkills {
allowedSet[name] = true
}
var filtered []*SkillMetadata
for _, meta := range metadata {
if allowedSet[meta.Name] {
filtered = append(filtered, meta)
}
}
return filtered
}
// GetAllMetadata returns metadata for all discovered skills
// This is used for system prompt injection (Level 1)
func (m *Manager) GetAllMetadata() []*SkillMetadata {
if !m.enabled {
return nil
}
m.mu.RLock()
defer m.mu.RUnlock()
// Return a copy to prevent external modification
result := make([]*SkillMetadata, len(m.metadataCache))
copy(result, m.metadataCache)
return result
}
// LoadSkill loads the full instructions of a skill (Level 2)
func (m *Manager) LoadSkill(ctx context.Context, skillName string) (*Skill, error) {
if !m.enabled {
return nil, fmt.Errorf("skills are not enabled")
}
// Check if skill is allowed
if !m.isSkillAllowed(skillName) {
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
return m.loader.LoadSkillInstructions(skillName)
}
// isSkillAllowed checks if a skill is in the allowed list
func (m *Manager) isSkillAllowed(skillName string) bool {
if len(m.allowedSkills) == 0 {
return true
}
for _, name := range m.allowedSkills {
if name == skillName {
return true
}
}
return false
}
// ReadSkillFile reads an additional file from a skill directory (Level 3)
func (m *Manager) ReadSkillFile(ctx context.Context, skillName, filePath string) (string, error) {
if !m.enabled {
return "", fmt.Errorf("skills are not enabled")
}
if !m.isSkillAllowed(skillName) {
return "", fmt.Errorf("skill not allowed: %s", skillName)
}
file, err := m.loader.LoadSkillFile(skillName, filePath)
if err != nil {
return "", err
}
return file.Content, nil
}
// ListSkillFiles lists all files in a skill directory
func (m *Manager) ListSkillFiles(ctx context.Context, skillName string) ([]string, error) {
if !m.enabled {
return nil, fmt.Errorf("skills are not enabled")
}
if !m.isSkillAllowed(skillName) {
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
return m.loader.ListSkillFiles(skillName)
}
// ExecuteScript executes a script from a skill in the sandbox
func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath string, args []string) (*sandbox.ExecuteResult, error) {
if !m.enabled {
return nil, fmt.Errorf("skills are not enabled")
}
if !m.isSkillAllowed(skillName) {
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
// Verify sandbox manager is available
if m.sandboxMgr == nil {
return nil, fmt.Errorf("sandbox is not configured")
}
// Get the skill base path
basePath, err := m.loader.GetSkillBasePath(skillName)
if err != nil {
return nil, err
}
// Load the script file to verify it exists and is a script
file, err := m.loader.LoadSkillFile(skillName, scriptPath)
if err != nil {
return nil, fmt.Errorf("failed to load script: %w", err)
}
if !file.IsScript {
return nil, fmt.Errorf("file is not an executable script: %s", scriptPath)
}
// Prepare execution config
config := &sandbox.ExecuteConfig{
Script: file.Path,
Args: args,
WorkDir: basePath,
}
// Execute in sandbox
return m.sandboxMgr.Execute(ctx, config)
}
// GetSkillInfo returns detailed information about a skill
func (m *Manager) GetSkillInfo(ctx context.Context, skillName string) (*SkillInfo, error) {
if !m.enabled {
return nil, fmt.Errorf("skills are not enabled")
}
if !m.isSkillAllowed(skillName) {
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
skill, err := m.loader.LoadSkillInstructions(skillName)
if err != nil {
return nil, err
}
files, err := m.loader.ListSkillFiles(skillName)
if err != nil {
files = []string{} // Non-fatal error
}
return &SkillInfo{
Name: skill.Name,
Description: skill.Description,
BasePath: skill.BasePath,
Instructions: skill.Instructions,
Files: files,
}, nil
}
// SkillInfo provides detailed information about a skill
type SkillInfo struct {
Name string `json:"name"`
Description string `json:"description"`
BasePath string `json:"base_path"`
Instructions string `json:"instructions"`
Files []string `json:"files"`
}
// Reload refreshes the skill cache by rediscovering all skills
func (m *Manager) Reload(ctx context.Context) error {
if !m.enabled {
return nil
}
metadata, err := m.loader.Reload()
if err != nil {
return err
}
if len(m.allowedSkills) > 0 {
metadata = m.filterAllowedSkills(metadata)
}
m.mu.Lock()
m.metadataCache = metadata
m.mu.Unlock()
return nil
}
// Cleanup releases resources
func (m *Manager) Cleanup(ctx context.Context) error {
if m.sandboxMgr != nil {
return m.sandboxMgr.Cleanup(ctx)
}
return nil
}
+218
View File
@@ -0,0 +1,218 @@
// Package skills provides Agent Skills functionality following Claude's Progressive Disclosure pattern.
// Skills are modular capabilities that extend the agent's functionality through instruction files.
package skills
import (
"bufio"
"errors"
"fmt"
"path/filepath"
"regexp"
"strings"
"gopkg.in/yaml.v3"
)
// Skill validation constants following Claude's specification
const (
MaxNameLength = 64
MaxDescriptionLength = 1024
SkillFileName = "SKILL.md"
)
// Reserved words that cannot be used in skill names
var reservedWords = []string{"anthropic", "claude"}
// namePattern validates skill names: lowercase letters, numbers, and hyphens only
var namePattern = regexp.MustCompile(`^[a-z0-9-]+$`)
// xmlTagPattern detects XML tags in content
var xmlTagPattern = regexp.MustCompile(`<[^>]+>`)
// Skill represents a loaded skill with its metadata and content
// It follows the Progressive Disclosure pattern:
// - Level 1 (Metadata): Name and Description are always loaded
// - Level 2 (Instructions): The main body of SKILL.md, loaded on demand
// - Level 3 (Resources): Additional files in the skill directory, loaded as needed
type Skill struct {
// Metadata (Level 1) - always loaded
Name string `yaml:"name"`
Description string `yaml:"description"`
// Filesystem information
BasePath string // Absolute path to the skill directory
FilePath string // Absolute path to SKILL.md
// Instructions (Level 2) - loaded on demand
Instructions string // The main body of SKILL.md (after frontmatter)
Loaded bool // Whether Level 2 instructions have been loaded
}
// SkillMetadata represents the minimal metadata for system prompt injection (Level 1)
// This is the lightweight representation used during skill discovery
type SkillMetadata struct {
Name string
Description string
BasePath string // Path to skill directory for later loading
}
// SkillFile represents an additional file within a skill directory (Level 3)
type SkillFile struct {
Name string // Filename (e.g., "FORMS.md", "scripts/validate.py")
Path string // Absolute path to the file
Content string // File content
IsScript bool // Whether this is an executable script
}
// Validate checks if the skill metadata is valid according to Claude's specification
func (s *Skill) Validate() error {
// Validate name
if s.Name == "" {
return errors.New("skill name is required")
}
if len(s.Name) > MaxNameLength {
return fmt.Errorf("skill name exceeds maximum length of %d characters", MaxNameLength)
}
if !namePattern.MatchString(s.Name) {
return errors.New("skill name must contain only lowercase letters, numbers, and hyphens")
}
for _, reserved := range reservedWords {
if strings.Contains(s.Name, reserved) {
return fmt.Errorf("skill name cannot contain reserved word: %s", reserved)
}
}
if xmlTagPattern.MatchString(s.Name) {
return errors.New("skill name cannot contain XML tags")
}
// Validate description
if s.Description == "" {
return errors.New("skill description is required")
}
if len(s.Description) > MaxDescriptionLength {
return fmt.Errorf("skill description exceeds maximum length of %d characters", MaxDescriptionLength)
}
if xmlTagPattern.MatchString(s.Description) {
return errors.New("skill description cannot contain XML tags")
}
return nil
}
// ToMetadata converts a Skill to its lightweight metadata representation
func (s *Skill) ToMetadata() *SkillMetadata {
return &SkillMetadata{
Name: s.Name,
Description: s.Description,
BasePath: s.BasePath,
}
}
// ParseSkillFile parses a SKILL.md file content and extracts metadata and body
// It handles YAML frontmatter enclosed in --- delimiters
func ParseSkillFile(content string) (*Skill, error) {
skill := &Skill{}
// Check for YAML frontmatter
if !strings.HasPrefix(strings.TrimSpace(content), "---") {
return nil, errors.New("SKILL.md must start with YAML frontmatter (---)")
}
// Find the end of frontmatter
scanner := bufio.NewScanner(strings.NewReader(content))
var frontmatterLines []string
var bodyLines []string
inFrontmatter := false
frontmatterEnded := false
for scanner.Scan() {
line := scanner.Text()
if !inFrontmatter && !frontmatterEnded && strings.TrimSpace(line) == "---" {
inFrontmatter = true
continue
}
if inFrontmatter && strings.TrimSpace(line) == "---" {
inFrontmatter = false
frontmatterEnded = true
continue
}
if inFrontmatter {
frontmatterLines = append(frontmatterLines, line)
} else if frontmatterEnded {
bodyLines = append(bodyLines, line)
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading SKILL.md: %w", err)
}
if !frontmatterEnded {
return nil, errors.New("SKILL.md frontmatter is not properly closed with ---")
}
// Parse YAML frontmatter
frontmatter := strings.Join(frontmatterLines, "\n")
if err := yaml.Unmarshal([]byte(frontmatter), skill); err != nil {
return nil, fmt.Errorf("failed to parse YAML frontmatter: %w", err)
}
// Set body instructions
skill.Instructions = strings.TrimSpace(strings.Join(bodyLines, "\n"))
skill.Loaded = true
// Validate
if err := skill.Validate(); err != nil {
return nil, fmt.Errorf("skill validation failed: %w", err)
}
return skill, nil
}
// ParseSkillMetadata parses only the metadata from a SKILL.md file content
// This is a lightweight operation for skill discovery (Level 1 only)
func ParseSkillMetadata(content string) (*SkillMetadata, error) {
skill, err := ParseSkillFile(content)
if err != nil {
return nil, err
}
return skill.ToMetadata(), nil
}
// IsScript checks if a file path represents an executable script
func IsScript(path string) bool {
ext := strings.ToLower(filepath.Ext(path))
scriptExtensions := map[string]bool{
".py": true,
".sh": true,
".bash": true,
".js": true,
".ts": true,
".rb": true,
".pl": true,
".php": true,
}
return scriptExtensions[ext]
}
// GetScriptLanguage returns the language/interpreter for a script file
func GetScriptLanguage(path string) string {
ext := strings.ToLower(filepath.Ext(path))
languages := map[string]string{
".py": "python",
".sh": "bash",
".bash": "bash",
".js": "node",
".ts": "ts-node",
".rb": "ruby",
".pl": "perl",
".php": "php",
}
if lang, ok := languages[ext]; ok {
return lang
}
return "unknown"
}
+392
View File
@@ -0,0 +1,392 @@
package skills
import (
"context"
"os"
"path/filepath"
"testing"
)
func TestParseSkillFile(t *testing.T) {
content := `---
name: test-skill
description: A test skill for unit testing purposes.
---
# Test Skill
This is the content of the test skill.
## Usage
Use this skill when testing.
`
skill, err := ParseSkillFile(content)
if err != nil {
t.Fatalf("Failed to parse skill file: %v", err)
}
if skill.Name != "test-skill" {
t.Errorf("Expected name 'test-skill', got '%s'", skill.Name)
}
if skill.Description != "A test skill for unit testing purposes." {
t.Errorf("Expected description 'A test skill for unit testing purposes.', got '%s'", skill.Description)
}
if skill.Instructions == "" {
t.Error("Expected instructions to be non-empty")
}
if !skill.Loaded {
t.Error("Expected Loaded to be true after parsing")
}
t.Logf("Parsed skill: name=%s, description=%s, instructions_len=%d",
skill.Name, skill.Description, len(skill.Instructions))
}
func TestSkillValidation(t *testing.T) {
tests := []struct {
name string
skillName string
description string
wantErr bool
errContains string
}{
{
name: "valid skill",
skillName: "my-skill",
description: "A valid skill",
wantErr: false,
},
{
name: "empty name",
skillName: "",
description: "A skill",
wantErr: true,
errContains: "name is required",
},
{
name: "invalid characters in name",
skillName: "My Skill",
description: "A skill",
wantErr: true,
errContains: "lowercase letters",
},
{
name: "reserved word in name",
skillName: "my-claude-skill",
description: "A skill",
wantErr: true,
errContains: "reserved word",
},
{
name: "empty description",
skillName: "my-skill",
description: "",
wantErr: true,
errContains: "description is required",
},
{
name: "name too long",
skillName: "this-is-a-very-long-skill-name-that-exceeds-the-maximum-allowed-length-of-64-characters",
description: "A skill",
wantErr: true,
errContains: "exceeds maximum length",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
skill := &Skill{
Name: tt.skillName,
Description: tt.description,
}
err := skill.Validate()
if tt.wantErr {
if err == nil {
t.Errorf("Expected error containing '%s', got nil", tt.errContains)
} else if tt.errContains != "" && !containsString(err.Error(), tt.errContains) {
t.Errorf("Expected error containing '%s', got '%s'", tt.errContains, err.Error())
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
})
}
}
func containsString(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsSubstring(s, substr))
}
func containsSubstring(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
func TestLoaderDiscoverSkills(t *testing.T) {
// Create a temporary skills directory
tmpDir, err := os.MkdirTemp("", "skills-test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a test skill directory
skillDir := filepath.Join(tmpDir, "test-skill")
if err := os.MkdirAll(skillDir, 0755); err != nil {
t.Fatalf("Failed to create skill dir: %v", err)
}
// Write SKILL.md
skillContent := `---
name: test-skill
description: A test skill for loader testing.
---
# Test Skill
This is the test skill content.
`
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(skillContent), 0644); err != nil {
t.Fatalf("Failed to write SKILL.md: %v", err)
}
// Create loader and discover skills
loader := NewLoader([]string{tmpDir})
metadata, err := loader.DiscoverSkills()
if err != nil {
t.Fatalf("Failed to discover skills: %v", err)
}
if len(metadata) != 1 {
t.Fatalf("Expected 1 skill, got %d", len(metadata))
}
if metadata[0].Name != "test-skill" {
t.Errorf("Expected skill name 'test-skill', got '%s'", metadata[0].Name)
}
t.Logf("Discovered %d skills: %v", len(metadata), metadata[0].Name)
}
func TestLoaderLoadSkillInstructions(t *testing.T) {
// Create a temporary skills directory
tmpDir, err := os.MkdirTemp("", "skills-test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a test skill directory
skillDir := filepath.Join(tmpDir, "test-skill")
if err := os.MkdirAll(skillDir, 0755); err != nil {
t.Fatalf("Failed to create skill dir: %v", err)
}
// Write SKILL.md
skillContent := `---
name: test-skill
description: A test skill for content loading.
---
# Test Skill
This is the main content.
## Section 1
More content here.
`
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(skillContent), 0644); err != nil {
t.Fatalf("Failed to write SKILL.md: %v", err)
}
// Create loader and load skill instructions
loader := NewLoader([]string{tmpDir})
skill, err := loader.LoadSkillInstructions("test-skill")
if err != nil {
t.Fatalf("Failed to load skill instructions: %v", err)
}
if skill.Name != "test-skill" {
t.Errorf("Expected skill name 'test-skill', got '%s'", skill.Name)
}
if skill.Instructions == "" {
t.Error("Expected instructions to be non-empty")
}
if !skill.Loaded {
t.Error("Expected Loaded to be true")
}
t.Logf("Loaded skill: name=%s, instructions_len=%d", skill.Name, len(skill.Instructions))
}
func TestLoaderLoadSkillFile(t *testing.T) {
// Create a temporary skills directory
tmpDir, err := os.MkdirTemp("", "skills-test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a test skill directory with additional files
skillDir := filepath.Join(tmpDir, "test-skill")
scriptsDir := filepath.Join(skillDir, "scripts")
if err := os.MkdirAll(scriptsDir, 0755); err != nil {
t.Fatalf("Failed to create skill dir: %v", err)
}
// Write SKILL.md
skillContent := `---
name: test-skill
description: A test skill with additional files.
---
# Test Skill
See [GUIDE.md](GUIDE.md) for more info.
`
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(skillContent), 0644); err != nil {
t.Fatalf("Failed to write SKILL.md: %v", err)
}
// Write additional file
guideContent := "# Guide\n\nThis is the guide content."
if err := os.WriteFile(filepath.Join(skillDir, "GUIDE.md"), []byte(guideContent), 0644); err != nil {
t.Fatalf("Failed to write GUIDE.md: %v", err)
}
// Write a script
scriptContent := "#!/usr/bin/env python3\nprint('Hello from script')"
if err := os.WriteFile(filepath.Join(scriptsDir, "hello.py"), []byte(scriptContent), 0644); err != nil {
t.Fatalf("Failed to write script: %v", err)
}
// Create loader and discover skills first
loader := NewLoader([]string{tmpDir})
_, err = loader.DiscoverSkills()
if err != nil {
t.Fatalf("Failed to discover skills: %v", err)
}
// Load additional file
file, err := loader.LoadSkillFile("test-skill", "GUIDE.md")
if err != nil {
t.Fatalf("Failed to load skill file: %v", err)
}
if file.Content != guideContent {
t.Errorf("Expected guide content, got '%s'", file.Content)
}
if file.IsScript {
t.Error("GUIDE.md should not be marked as script")
}
// Load script file
scriptFile, err := loader.LoadSkillFile("test-skill", "scripts/hello.py")
if err != nil {
t.Fatalf("Failed to load script file: %v", err)
}
if !scriptFile.IsScript {
t.Error("hello.py should be marked as script")
}
t.Logf("Loaded files: GUIDE.md=%d bytes, hello.py=%d bytes (isScript=%v)",
len(file.Content), len(scriptFile.Content), scriptFile.IsScript)
}
func TestManagerIntegration(t *testing.T) {
// Create a temporary skills directory
tmpDir, err := os.MkdirTemp("", "skills-test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a test skill directory
skillDir := filepath.Join(tmpDir, "test-skill")
if err := os.MkdirAll(skillDir, 0755); err != nil {
t.Fatalf("Failed to create skill dir: %v", err)
}
// Write SKILL.md
skillContent := `---
name: test-skill
description: A test skill for manager integration testing.
---
# Test Skill
Integration test content.
`
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(skillContent), 0644); err != nil {
t.Fatalf("Failed to write SKILL.md: %v", err)
}
// Create manager with config
config := &ManagerConfig{
SkillDirs: []string{tmpDir},
AllowedSkills: []string{}, // Allow all
Enabled: true,
}
manager := NewManager(config, nil) // No sandbox for this test
// Initialize
ctx := context.Background()
if err := manager.Initialize(ctx); err != nil {
t.Fatalf("Failed to initialize manager: %v", err)
}
// Get all metadata
metadata := manager.GetAllMetadata()
if len(metadata) != 1 {
t.Fatalf("Expected 1 skill, got %d", len(metadata))
}
// Load skill
skill, err := manager.LoadSkill(ctx, "test-skill")
if err != nil {
t.Fatalf("Failed to load skill: %v", err)
}
if skill.Name != "test-skill" {
t.Errorf("Expected skill name 'test-skill', got '%s'", skill.Name)
}
t.Logf("Manager integration test passed: %d skills discovered", len(metadata))
}
func TestIsScript(t *testing.T) {
tests := []struct {
path string
expected bool
}{
{"script.py", true},
{"script.sh", true},
{"script.bash", true},
{"script.js", true},
{"script.ts", true},
{"script.rb", true},
{"README.md", false},
{"data.json", false},
{"config.yaml", false},
}
for _, tt := range tests {
result := IsScript(tt.path)
if result != tt.expected {
t.Errorf("IsScript(%s) = %v, expected %v", tt.path, result, tt.expected)
}
}
}
+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
}