v0.0.36 961f99d

skills.go RawHistoryFolder

1// Package skills implements zot's reusable-instruction system.
2//
3// A skill is a per-folder SKILL.md file with a YAML frontmatter
4// header. Skills live in well-known directories under the project or
5// the user home; zot discovers them at startup, lists their names +
6// one-line descriptions in the system prompt, and exposes a built-in
7// "skill" tool the model uses to pull the full body on demand.
8//
9// The on-demand-load model keeps token usage cheap: only the
10// short manifest goes into every request; the body is fetched as a
11// tool result the one or two turns the model actually needs it.
12//
13// Discovery layout (priority order — first match wins per name):
14//
15//	./.zot/skills/<name>/SKILL.md            — project (native)
16//	$ZOT_HOME/skills/<name>/SKILL.md         — global (native)
17//	./.claude/skills/<name>/SKILL.md         — project (claude-compat)
18//	~/.claude/skills/<name>/SKILL.md         — global (claude-compat)
19//	./.agents/skills/<name>/SKILL.md         — project (agent-compat)
20//	~/.agents/skills/<name>/SKILL.md         — global (agent-compat)
21//
22// The compat paths are deliberate: a SKILL.md written for any of
23// the related ecosystems works in zot unchanged.
24package skills
25
26import (
27	"fmt"
28	"os"
29	"path/filepath"
30	"sort"
31	"strings"
32)
33
34// Skill is one discovered SKILL.md file.
35type Skill struct {
36	// Name is the skill identifier — what the model uses when it
37	// invokes the `skill` tool. Taken from the frontmatter `name`
38	// field; falls back to the directory basename.
39	Name string
40
41	// Description is the one-line summary shown to the model in the
42	// system-prompt manifest.
43	Description string
44
45	// Body is the markdown after the frontmatter. Returned as the
46	// tool result when the model loads this skill.
47	Body string
48
49	// Path is the absolute path to the SKILL.md file.
50	Path string
51
52	// Source is a human-friendly label describing where the skill
53	// came from ("project", "global", "project (claude)", etc.).
54	// Shown in the /skills picker.
55	Source string
56
57	// Builtin marks skills that ship inside the zot binary. They are
58	// fully active for the model (system-prompt manifest + skill
59	// tool) but hidden from user-facing surfaces like the /skills
60	// picker so users only see skills they actually installed or
61	// shipped in their project.
62	Builtin bool
63
64	// AllowedTools and Permissions are parsed for forward-
65	// compatibility but NOT enforced in this version. They appear
66	// in the skill body so the model can self-regulate.
67	AllowedTools []string
68	Permissions  map[string][]string
69}
70
71// VisibleSkills returns the subset of skills users should see in
72// pickers, /skills, and other interactive surfaces. Built-ins are
73// hidden because they're implementation detail; the model still
74// loads them through the system-prompt manifest + the skill tool.
75func VisibleSkills(in []*Skill) []*Skill {
76	out := make([]*Skill, 0, len(in))
77	for _, s := range in {
78		if s == nil || s.Builtin {
79			continue
80		}
81		out = append(out, s)
82	}
83	return out
84}
85
86// Discover returns the merged skill set. By default this is just
87// the built-in skills compiled into the zot binary; user-installed
88// SKILL.md files are NOT loaded unless includeUser is true. Users
89// opt in via the `--with-skills` flag.
90//
91// First-match-wins per name; the order matches the priority list
92// in the package doc (project-local before global before claude-
93// compat before agents-compat, all before built-ins). That means a
94// user-installed skill with the same name as a built-in shadows
95// the built-in once includeUser is true.
96//
97// Errors per skill are returned alongside the partial result so a
98// single broken file doesn't suppress the rest.
99func Discover(zotHome, cwd, userHome string, includeUser bool) ([]*Skill, []error) {
100	var errs []error
101	seen := map[string]*Skill{}
102	if includeUser {
103		errs = append(errs, scanUserSkills(zotHome, cwd, userHome, seen)...)
104	}
105	// Built-ins fill in any name the user didn't already provide
106	// (or every name, when includeUser is false).
107	for _, s := range loadBuiltins() {
108		if _, dup := seen[s.Name]; dup {
109			continue
110		}
111		seen[s.Name] = s
112	}
113	out := make([]*Skill, 0, len(seen))
114	for _, s := range seen {
115		out = append(out, s)
116	}
117	sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
118	return out, errs
119}
120
121// scanUserSkills walks the user-skill search dirs and populates
122// `seen` with first-match-wins per name. Split out so Discover's
123// includeUser=false path doesn't have to skip over a giant block.
124func scanUserSkills(zotHome, cwd, userHome string, seen map[string]*Skill) []error {
125	var errs []error
126	for _, loc := range searchDirs(zotHome, cwd, userHome) {
127		entries, err := os.ReadDir(loc.dir)
128		if err != nil {
129			continue // missing dir is fine
130		}
131		for _, e := range entries {
132			if !e.IsDir() {
133				continue
134			}
135			path := filepath.Join(loc.dir, e.Name(), "SKILL.md")
136			s, err := load(path, loc.label)
137			if err != nil {
138				if !os.IsNotExist(err) {
139					errs = append(errs, fmt.Errorf("%s: %w", path, err))
140				}
141				continue
142			}
143			if s.Name == "" {
144				s.Name = e.Name()
145			}
146			if _, dup := seen[s.Name]; dup {
147				continue // higher-priority location already won
148			}
149			seen[s.Name] = s
150		}
151	}
152	return errs
153}
154
155// SystemPromptAddendum returns the text to append to the system
156// prompt when at least one skill is loaded. Empty string if none.
157//
158// Format kept short and explicit so the model reliably calls the
159// `skill` tool with a name from the list rather than guessing.
160func SystemPromptAddendum(skills []*Skill) string {
161	if len(skills) == 0 {
162		return ""
163	}
164	var sb strings.Builder
165	sb.WriteString("Available skills (call the `skill` tool with one of these names to load full instructions):\n")
166	for _, s := range skills {
167		desc := strings.TrimSpace(s.Description)
168		if desc == "" {
169			desc = "(no description)"
170		}
171		fmt.Fprintf(&sb, "- %s — %s\n", s.Name, desc)
172	}
173	return sb.String()
174}
175
176// FindByName returns the skill with the given name, or nil.
177func FindByName(skills []*Skill, name string) *Skill {
178	for _, s := range skills {
179		if s.Name == name {
180			return s
181		}
182	}
183	return nil
184}
185
186// ---- internals ----
187
188type location struct {
189	dir   string
190	label string
191}
192
193func searchDirs(zotHome, cwd, userHome string) []location {
194	var out []location
195	add := func(dir, label string) {
196		if dir == "" {
197			return
198		}
199		out = append(out, location{dir: dir, label: label})
200	}
201	if cwd != "" {
202		add(filepath.Join(cwd, ".zot", "skills"), "project")
203	}
204	if zotHome != "" {
205		add(filepath.Join(zotHome, "skills"), "global")
206	}
207	if cwd != "" {
208		add(filepath.Join(cwd, ".claude", "skills"), "project (claude)")
209	}
210	if userHome != "" {
211		add(filepath.Join(userHome, ".claude", "skills"), "global (claude)")
212	}
213	if cwd != "" {
214		add(filepath.Join(cwd, ".agents", "skills"), "project (agents)")
215	}
216	if userHome != "" {
217		add(filepath.Join(userHome, ".agents", "skills"), "global (agents)")
218	}
219	return out
220}
221
222func load(path, source string) (*Skill, error) {
223	raw, err := os.ReadFile(path)
224	if err != nil {
225		return nil, err
226	}
227	front, body := splitFrontmatter(string(raw))
228	s := &Skill{
229		Path:   path,
230		Source: source,
231		Body:   strings.TrimSpace(body),
232	}
233	parseFrontmatter(front, s)
234	return s, nil
235}
236
237// splitFrontmatter returns (yamlBlock, restOfDocument) for a string
238// whose first non-empty line is "---". If no frontmatter is present,
239// returns ("", entireString).
240func splitFrontmatter(raw string) (string, string) {
241	rest := strings.TrimLeft(raw, " \t\r\n")
242	if !strings.HasPrefix(rest, "---") {
243		return "", raw
244	}
245	rest = strings.TrimPrefix(rest, "---")
246	// Drop the trailing newline after the opening ---.
247	if i := strings.IndexByte(rest, '\n'); i >= 0 {
248		rest = rest[i+1:]
249	}
250	end := strings.Index(rest, "\n---")
251	if end < 0 {
252		return "", raw // malformed; treat as no frontmatter
253	}
254	front := rest[:end]
255	body := rest[end+len("\n---"):]
256	body = strings.TrimLeft(body, " \t\r\n")
257	return front, body
258}
259
260// parseFrontmatter handles the small subset of YAML zot recognizes:
261//   - simple `key: value` lines
262//   - `key: [a, b, c]` flow-style lists
263//   - `key:` followed by indented `- item` block lists
264//   - nested `key:` followed by indented `subkey: [...]` for permissions
265//
266// Anything more elaborate is ignored. We deliberately avoid a yaml
267// dependency to keep zot's binary lean.
268func parseFrontmatter(front string, s *Skill) {
269	lines := strings.Split(front, "\n")
270	i := 0
271	for i < len(lines) {
272		line := lines[i]
273		trimmed := strings.TrimSpace(line)
274		if trimmed == "" || strings.HasPrefix(trimmed, "#") {
275			i++
276			continue
277		}
278		// Top-level key: value or key:
279		if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
280			colon := strings.IndexByte(trimmed, ':')
281			if colon < 0 {
282				i++
283				continue
284			}
285			key := strings.TrimSpace(trimmed[:colon])
286			value := strings.TrimSpace(trimmed[colon+1:])
287			switch key {
288			case "name":
289				s.Name = unquote(value)
290			case "description":
291				s.Description = unquote(value)
292			case "allowed-tools", "allowed_tools":
293				if value != "" {
294					s.AllowedTools = parseInlineList(value)
295				} else {
296					items, consumed := parseBlockList(lines[i+1:])
297					s.AllowedTools = items
298					i += consumed
299				}
300			case "permissions":
301				if value != "" {
302					// Unusual layout; ignore single-line for now.
303					i++
304					continue
305				}
306				perms, consumed := parsePermissionsBlock(lines[i+1:])
307				s.Permissions = perms
308				i += consumed
309			}
310		}
311		i++
312	}
313}
314
315// unquote trims surrounding " or ' from a value.
316func unquote(v string) string {
317	if len(v) >= 2 {
318		if (v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'') {
319			return v[1 : len(v)-1]
320		}
321	}
322	return v
323}
324
325// parseInlineList parses "[a, b, c]" or "[\"a\", \"b\"]".
326func parseInlineList(v string) []string {
327	v = strings.TrimSpace(v)
328	v = strings.TrimPrefix(v, "[")
329	v = strings.TrimSuffix(v, "]")
330	if v == "" {
331		return nil
332	}
333	parts := strings.Split(v, ",")
334	out := make([]string, 0, len(parts))
335	for _, p := range parts {
336		out = append(out, unquote(strings.TrimSpace(p)))
337	}
338	return out
339}
340
341// parseBlockList consumes indented "- item" lines until a less-
342// indented line. Returns the items + how many lines to skip.
343func parseBlockList(lines []string) ([]string, int) {
344	var out []string
345	consumed := 0
346	for _, line := range lines {
347		if strings.HasPrefix(line, "  - ") || strings.HasPrefix(line, "    - ") {
348			out = append(out, unquote(strings.TrimSpace(strings.TrimPrefix(strings.TrimLeft(line, " "), "-"))))
349			consumed++
350			continue
351		}
352		if strings.TrimSpace(line) == "" {
353			consumed++
354			continue
355		}
356		break
357	}
358	return out, consumed
359}
360
361// parsePermissionsBlock parses an indented map of tool->[patterns].
362//
363//	permissions:
364//	  bash: ["git diff*", "git log*"]
365//	  read: ["./*.go"]
366func parsePermissionsBlock(lines []string) (map[string][]string, int) {
367	out := map[string][]string{}
368	consumed := 0
369	for _, line := range lines {
370		if !strings.HasPrefix(line, "  ") {
371			break
372		}
373		trimmed := strings.TrimSpace(line)
374		if trimmed == "" {
375			consumed++
376			continue
377		}
378		colon := strings.IndexByte(trimmed, ':')
379		if colon < 0 {
380			break
381		}
382		key := strings.TrimSpace(trimmed[:colon])
383		val := strings.TrimSpace(trimmed[colon+1:])
384		if val == "" {
385			break // we don't support nested-block lists for permissions
386		}
387		out[key] = parseInlineList(val)
388		consumed++
389	}
390	return out, consumed
391}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 477

↑↓ moveenter openesc close