skills.go

  1// Package skills implements the Agent Skills open standard.
  2// See https://agentskills.io for the specification.
  3package skills
  4
  5import (
  6	"context"
  7	"errors"
  8	"fmt"
  9	"log/slog"
 10	"os"
 11	"path/filepath"
 12	"regexp"
 13	"slices"
 14	"sort"
 15	"strings"
 16	"sync"
 17
 18	"github.com/charlievieth/fastwalk"
 19	"github.com/charmbracelet/crush/internal/pubsub"
 20	"gopkg.in/yaml.v3"
 21)
 22
 23const (
 24	SkillFileName          = "SKILL.md"
 25	MaxNameLength          = 64
 26	MaxDescriptionLength   = 1024
 27	MaxCompatibilityLength = 500
 28)
 29
 30var (
 31	namePattern    = regexp.MustCompile(`^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$`)
 32	promptReplacer = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", "\"", "&quot;", "'", "&apos;")
 33)
 34
 35// Skill represents a parsed SKILL.md file.
 36type Skill struct {
 37	Name          string            `yaml:"name" json:"name"`
 38	Description   string            `yaml:"description" json:"description"`
 39	License       string            `yaml:"license,omitempty" json:"license,omitempty"`
 40	Compatibility string            `yaml:"compatibility,omitempty" json:"compatibility,omitempty"`
 41	Metadata      map[string]string `yaml:"metadata,omitempty" json:"metadata,omitempty"`
 42	Instructions  string            `yaml:"-" json:"instructions"`
 43	Path          string            `yaml:"-" json:"path"`
 44	SkillFilePath string            `yaml:"-" json:"skill_file_path"`
 45	Builtin       bool              `yaml:"-" json:"builtin"`
 46}
 47
 48// DiscoveryState represents the outcome of discovering a single skill file.
 49type DiscoveryState int
 50
 51const (
 52	// StateNormal indicates the skill was parsed and validated successfully.
 53	StateNormal DiscoveryState = iota
 54	// StateError indicates discovery encountered a scan/parse/validate error.
 55	StateError
 56)
 57
 58// SkillState represents the latest discovery status of a skill file.
 59type SkillState struct {
 60	Name  string
 61	Path  string
 62	State DiscoveryState
 63	Err   error
 64}
 65
 66// Event is published when skill discovery completes.
 67type Event struct {
 68	States []*SkillState
 69}
 70
 71var broker = pubsub.NewBroker[Event]()
 72
 73// SubscribeEvents returns a channel that receives events when skill discovery state changes.
 74func SubscribeEvents(ctx context.Context) <-chan pubsub.Event[Event] {
 75	return broker.Subscribe(ctx)
 76}
 77
 78// Validate checks if the skill meets spec requirements.
 79func (s *Skill) Validate() error {
 80	var errs []error
 81
 82	if s.Name == "" {
 83		errs = append(errs, errors.New("name is required"))
 84	} else {
 85		if len(s.Name) > MaxNameLength {
 86			errs = append(errs, fmt.Errorf("name exceeds %d characters", MaxNameLength))
 87		}
 88		if !namePattern.MatchString(s.Name) {
 89			errs = append(errs, errors.New("name must be alphanumeric with hyphens, no leading/trailing/consecutive hyphens"))
 90		}
 91		if s.Path != "" && !strings.EqualFold(filepath.Base(s.Path), s.Name) {
 92			errs = append(errs, fmt.Errorf("name %q must match directory %q", s.Name, filepath.Base(s.Path)))
 93		}
 94	}
 95
 96	if s.Description == "" {
 97		errs = append(errs, errors.New("description is required"))
 98	} else if len(s.Description) > MaxDescriptionLength {
 99		errs = append(errs, fmt.Errorf("description exceeds %d characters", MaxDescriptionLength))
100	}
101
102	if len(s.Compatibility) > MaxCompatibilityLength {
103		errs = append(errs, fmt.Errorf("compatibility exceeds %d characters", MaxCompatibilityLength))
104	}
105
106	return errors.Join(errs...)
107}
108
109// Parse parses a SKILL.md file from disk.
110func Parse(path string) (*Skill, error) {
111	content, err := os.ReadFile(path)
112	if err != nil {
113		return nil, err
114	}
115
116	skill, err := ParseContent(content)
117	if err != nil {
118		return nil, err
119	}
120
121	skill.Path = filepath.Dir(path)
122	skill.SkillFilePath = path
123
124	return skill, nil
125}
126
127// ParseContent parses a SKILL.md from raw bytes.
128func ParseContent(content []byte) (*Skill, error) {
129	frontmatter, body, err := splitFrontmatter(string(content))
130	if err != nil {
131		return nil, err
132	}
133
134	var skill Skill
135	if err := yaml.Unmarshal([]byte(frontmatter), &skill); err != nil {
136		return nil, fmt.Errorf("parsing frontmatter: %w", err)
137	}
138
139	skill.Instructions = strings.TrimSpace(body)
140
141	return &skill, nil
142}
143
144// splitFrontmatter extracts YAML frontmatter and body from markdown content.
145func splitFrontmatter(content string) (frontmatter, body string, err error) {
146	// Strip UTF-8 BOM for compatibility with editors that include it.
147	content = strings.TrimPrefix(content, "\uFEFF")
148	// Normalize line endings to \n for consistent parsing.
149	content = strings.ReplaceAll(content, "\r\n", "\n")
150	content = strings.ReplaceAll(content, "\r", "\n")
151
152	lines := strings.Split(content, "\n")
153	start := slices.IndexFunc(lines, func(line string) bool {
154		return strings.TrimSpace(line) != ""
155	})
156	if start == -1 || strings.TrimSpace(lines[start]) != "---" {
157		return "", "", errors.New("no YAML frontmatter found")
158	}
159
160	endOffset := slices.IndexFunc(lines[start+1:], func(line string) bool {
161		return strings.TrimSpace(line) == "---"
162	})
163	if endOffset == -1 {
164		return "", "", errors.New("unclosed frontmatter")
165	}
166	end := start + 1 + endOffset
167
168	frontmatter = strings.Join(lines[start+1:end], "\n")
169	body = strings.Join(lines[end+1:], "\n")
170	return frontmatter, body, nil
171}
172
173// Discover finds all valid skills in the given paths.
174func Discover(paths []string) []*Skill {
175	var skills []*Skill
176	var states []*SkillState
177	var mu sync.Mutex
178	seen := make(map[string]bool)
179	addState := func(name, path string, state DiscoveryState, err error) {
180		mu.Lock()
181		states = append(states, &SkillState{
182			Name:  name,
183			Path:  path,
184			State: state,
185			Err:   err,
186		})
187		mu.Unlock()
188	}
189
190	for _, base := range paths {
191		// We use fastwalk with Follow: true instead of filepath.WalkDir because
192		// WalkDir doesn't follow symlinked directories at any depthโ€”only entry
193		// points. This ensures skills in symlinked subdirectories are discovered.
194		// fastwalk is concurrent, so we protect shared state (seen, skills) with mu.
195		conf := fastwalk.Config{
196			Follow:  true,
197			ToSlash: fastwalk.DefaultToSlash(),
198		}
199		err := fastwalk.Walk(&conf, base, func(path string, d os.DirEntry, err error) error {
200			if err != nil {
201				slog.Warn("Failed to walk skills path entry", "base", base, "path", path, "error", err)
202				addState("", path, StateError, err)
203				return nil
204			}
205			if d.IsDir() || d.Name() != SkillFileName {
206				return nil
207			}
208			mu.Lock()
209			if seen[path] {
210				mu.Unlock()
211				return nil
212			}
213			seen[path] = true
214			mu.Unlock()
215			skill, err := Parse(path)
216			if err != nil {
217				slog.Warn("Failed to parse skill file", "path", path, "error", err)
218				addState("", path, StateError, err)
219				return nil
220			}
221			if err := skill.Validate(); err != nil {
222				slog.Warn("Skill validation failed", "path", path, "error", err)
223				addState(skill.Name, path, StateError, err)
224				return nil
225			}
226			slog.Debug("Successfully loaded skill", "name", skill.Name, "path", path)
227			mu.Lock()
228			skills = append(skills, skill)
229			mu.Unlock()
230			addState(skill.Name, path, StateNormal, nil)
231			return nil
232		})
233		if err != nil {
234			slog.Warn("Failed to walk skills path", "path", base, "error", err)
235		}
236	}
237
238	// fastwalk traversal order is non-deterministic, so sort for stable output.
239	sort.SliceStable(skills, func(i, j int) bool {
240		left := strings.ToLower(skills[i].SkillFilePath)
241		right := strings.ToLower(skills[j].SkillFilePath)
242		if left == right {
243			return skills[i].SkillFilePath < skills[j].SkillFilePath
244		}
245		return left < right
246	})
247
248	broker.Publish(pubsub.UpdatedEvent, Event{States: states})
249	return skills
250}
251
252// ToPromptXML generates XML for injection into the system prompt.
253func ToPromptXML(skills []*Skill) string {
254	if len(skills) == 0 {
255		return ""
256	}
257
258	var sb strings.Builder
259	sb.WriteString("<available_skills>\n")
260	for _, s := range skills {
261		sb.WriteString("  <skill>\n")
262		fmt.Fprintf(&sb, "    <name>%s</name>\n", escape(s.Name))
263		fmt.Fprintf(&sb, "    <description>%s</description>\n", escape(s.Description))
264		fmt.Fprintf(&sb, "    <location>%s</location>\n", escape(s.SkillFilePath))
265		if s.Builtin {
266			sb.WriteString("    <type>builtin</type>\n")
267		}
268		sb.WriteString("  </skill>\n")
269	}
270	sb.WriteString("</available_skills>")
271	return sb.String()
272}
273
274func escape(s string) string {
275	return promptReplacer.Replace(s)
276}
277
278// Deduplicate removes duplicate skills by name. When duplicates exist, the
279// last occurrence wins. This means user skills (appended after builtins)
280// override builtin skills with the same name.
281func Deduplicate(all []*Skill) []*Skill {
282	seen := make(map[string]int, len(all))
283	for i, s := range all {
284		seen[s.Name] = i
285	}
286
287	result := make([]*Skill, 0, len(seen))
288	for i, s := range all {
289		if seen[s.Name] == i {
290			result = append(result, s)
291		}
292	}
293	return result
294}
295
296// Filter removes skills whose names appear in the disabled list.
297func Filter(all []*Skill, disabled []string) []*Skill {
298	if len(disabled) == 0 {
299		return all
300	}
301
302	disabledSet := make(map[string]bool, len(disabled))
303	for _, name := range disabled {
304		disabledSet[name] = true
305	}
306
307	result := make([]*Skill, 0, len(all))
308	for _, s := range all {
309		if !disabledSet[s.Name] {
310			result = append(result, s)
311		}
312	}
313	return result
314}