-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskill.go
More file actions
238 lines (219 loc) · 7.11 KB
/
Copy pathskill.go
File metadata and controls
238 lines (219 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package rig
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"path"
"slices"
"strings"
)
// Skill is one markdown instruction file: YAML-ish frontmatter delimited by
// "---" lines carrying single-line name and description keys, then a body.
type Skill struct {
Name string
Description string
Body string
}
const (
frontmatterDelim = "---"
skillExt = ".md"
// LoadSkillToolName is the built-in tool the advertisement tells the model
// to call. Callers append LoadSkillTool's output to their own tool list.
LoadSkillToolName = "load_skill"
advertiseHeader = "Available skills. Call the " + LoadSkillToolName +
" tool with a skill name to read its full instructions before acting on it."
)
// LoadSkills reads every *.md file directly under dir; subdirectories are not
// walked. A file with no parseable frontmatter, no name, no description, or a
// name already claimed by an earlier file is an error naming every offender --
// a broken skill file must fail loudly rather than vanish from the
// advertisement. Nothing is returned alongside such an error.
//
// A missing dir is returned wrapped; callers that treat an absent user
// directory as "no skills" check errors.Is(err, fs.ErrNotExist).
//
// The result is sorted by name so the advertisement is stable regardless of
// how the filesystem orders entries.
func LoadSkills(fsys fs.FS, dir string) ([]Skill, error) {
entries, err := fs.ReadDir(fsys, dir)
if err != nil {
return nil, fmt.Errorf("read skills dir: %w", err)
}
var (
skills []Skill
problems []string
seen = make(map[string]string)
)
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), skillExt) {
continue
}
name := path.Join(dir, entry.Name())
data, err := fs.ReadFile(fsys, name)
if err != nil {
problems = append(problems, fmt.Sprintf("%s: %v", name, err))
continue
}
skill, err := parseSkill(data)
if err != nil {
problems = append(problems, fmt.Sprintf("%s: %v", name, err))
continue
}
if first, dup := seen[skill.Name]; dup {
problems = append(problems, fmt.Sprintf("%s: duplicate skill name %q, already defined by %s", name, skill.Name, first))
continue
}
seen[skill.Name] = name
skills = append(skills, skill)
}
if len(problems) > 0 {
return nil, fmt.Errorf("load skills: %s", strings.Join(problems, "; "))
}
sortSkills(skills)
return skills, nil
}
// parseSkill reads the frontmatter block and the body. Keys other than name and
// description are ignored; values are single-line and may be wrapped in
// matching quotes, which are stripped.
func parseSkill(data []byte) (Skill, error) {
text := strings.ReplaceAll(string(data), "\r\n", "\n")
lines := strings.Split(text, "\n")
if len(lines) == 0 || strings.TrimSpace(lines[0]) != frontmatterDelim {
return Skill{}, errors.New("missing frontmatter opening delimiter")
}
var skill Skill
for i := 1; i < len(lines); i++ {
line := lines[i]
if strings.TrimSpace(line) == frontmatterDelim {
skill.Body = strings.TrimSpace(strings.Join(lines[i+1:], "\n"))
if skill.Name == "" {
return Skill{}, errors.New("frontmatter has no name")
}
if skill.Description == "" {
return Skill{}, errors.New("frontmatter has no description")
}
return skill, nil
}
key, value, ok := strings.Cut(line, ":")
if !ok {
continue
}
value = unquote(strings.TrimSpace(value))
switch strings.TrimSpace(key) {
case "name":
skill.Name = value
case "description":
skill.Description = value
}
}
return Skill{}, errors.New("missing frontmatter closing delimiter")
}
func unquote(s string) string {
if len(s) < 2 {
return s
}
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
return s[1 : len(s)-1]
}
return s
}
// MergeSkills layers overrides onto base by name -- an override replaces the
// base entry entirely, it is not merged field by field. The result is sorted by
// name and shares no backing array with either input.
func MergeSkills(base, overrides []Skill) []Skill {
byName := make(map[string]Skill, len(base)+len(overrides))
order := make([]string, 0, len(base)+len(overrides))
for _, list := range [][]Skill{base, overrides} {
for _, skill := range list {
if _, ok := byName[skill.Name]; !ok {
order = append(order, skill.Name)
}
byName[skill.Name] = skill
}
}
merged := make([]Skill, 0, len(order))
for _, name := range order {
merged = append(merged, byName[name])
}
sortSkills(merged)
return merged
}
func sortSkills(skills []Skill) {
slices.SortFunc(skills, func(a, b Skill) int { return strings.Compare(a.Name, b.Name) })
}
// Advertise renders the skill catalogue for the system prompt. Output depends
// only on the set of skills, not on their input order. An empty set renders as
// the empty string so callers can concatenate unconditionally.
func Advertise(skills []Skill) string {
if len(skills) == 0 {
return ""
}
sorted := make([]Skill, len(skills))
copy(sorted, skills)
sortSkills(sorted)
var b strings.Builder
b.WriteString(advertiseHeader)
b.WriteString("\n\n")
for i, skill := range sorted {
if i > 0 {
b.WriteString("\n")
}
fmt.Fprintf(&b, "- %s: %s", skill.Name, oneLine(skill.Description))
}
return b.String()
}
// oneLine keeps one skill to one advertisement line even when a Skill was built
// in code rather than parsed from frontmatter.
func oneLine(s string) string {
return strings.Join(strings.Fields(s), " ")
}
// LoadSkillTool returns the built-in tool that hands a skill body to the model.
// The catalogue is snapshotted, so mutating the caller's slice afterwards does
// not change what the tool serves. A miss is an error whose message lists the
// available names; the run loop feeds tool errors back to the model, so the
// model can correct itself without the loop aborting.
func LoadSkillTool(skills []Skill) Tool {
bodies := make(map[string]string, len(skills))
names := make([]string, 0, len(skills))
for _, skill := range skills {
if _, ok := bodies[skill.Name]; !ok {
names = append(names, skill.Name)
}
bodies[skill.Name] = skill.Body
}
slices.Sort(names)
available := strings.Join(names, ", ")
return Tool{
Name: LoadSkillToolName,
Description: "Load the full instructions for one of the skills listed in the system prompt. Call this before acting on a skill.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"name": map[string]any{
"type": "string",
"description": "Exact skill name as advertised in the system prompt.",
},
},
"required": []any{"name"},
"additionalProperties": false,
},
Run: func(_ context.Context, input json.RawMessage) (string, error) {
var args struct {
Name string `json:"name"`
}
if err := json.Unmarshal(input, &args); err != nil {
return "", fmt.Errorf("invalid input, expected {\"name\": string}: %w", err)
}
name := strings.TrimSpace(args.Name)
if body, ok := bodies[name]; ok {
return body, nil
}
if len(names) == 0 {
return "", errors.New("no skills are available")
}
return "", fmt.Errorf("unknown skill %q, available skills: %s", name, available)
},
}
}