v0.1.61 0a85be3

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// The format is deliberately compact: name, one-line description,
159// and a source pointer telling the model where the full body
160// lives. Built-in skills show "builtin" since their markdown is
161// embedded in the zot binary and not on the filesystem; user
162// skills show their SKILL.md path (shortened with ~ for HOME).
163//
164// Loading still goes through the `skill` tool with just the name.
165// The pointer is there so the model can (a) mention the source
166// honestly in explanations and (b) distinguish between built-ins
167// and user-authored instruction sets when reasoning about trust.
168func SystemPromptAddendum(skills []*Skill) string {
169	if len(skills) == 0 {
170		return ""
171	}
172	home, _ := os.UserHomeDir()
173	var sb strings.Builder
174	sb.WriteString("Available skills (call the `skill` tool with a name from this list to load its full instructions):\n")
175	for _, s := range skills {
176		desc := strings.TrimSpace(s.Description)
177		if desc == "" {
178			desc = "(no description)"
179		}
180		pointer := skillSourcePointer(s, home)
181		fmt.Fprintf(&sb, "- %s [%s]: %s\n", s.Name, pointer, desc)
182	}
183	return sb.String()
184}
185
186// skillSourcePointer returns a short tag describing where a skill
187// originates. Built-ins are tagged "builtin" because their markdown
188// is embedded in the zot binary and not reachable through the
189// filesystem. User skills are tagged with their SKILL.md path,
190// collapsed to use ~ for the user home when possible.
191func skillSourcePointer(s *Skill, home string) string {
192	if s == nil {
193		return "unknown"
194	}
195	if s.Builtin {
196		return "builtin"
197	}
198	p := s.Path
199	if p == "" {
200		return "unknown"
201	}
202	if home != "" && strings.HasPrefix(p, home+string(filepath.Separator)) {
203		return "~" + p[len(home):]
204	}
205	return p
206}
207
208// FindByName returns the skill with the given name, or nil.
209func FindByName(skills []*Skill, name string) *Skill {
210	for _, s := range skills {
211		if s.Name == name {
212			return s
213		}
214	}
215	return nil
216}
217
218// ---- internals ----
219
220type location struct {
221	dir   string
222	label string
223}
224
225func searchDirs(zotHome, cwd, userHome string) []location {
226	var out []location
227	add := func(dir, label string) {
228		if dir == "" {
229			return
230		}
231		out = append(out, location{dir: dir, label: label})
232	}
233	if cwd != "" {
234		add(filepath.Join(cwd, ".zot", "skills"), "project")
235	}
236	if zotHome != "" {
237		add(filepath.Join(zotHome, "skills"), "global")
238	}
239	if cwd != "" {
240		add(filepath.Join(cwd, ".claude", "skills"), "project (claude)")
241	}
242	if userHome != "" {
243		add(filepath.Join(userHome, ".claude", "skills"), "global (claude)")
244	}
245	if cwd != "" {
246		add(filepath.Join(cwd, ".agents", "skills"), "project (agents)")
247	}
248	if userHome != "" {
249		add(filepath.Join(userHome, ".agents", "skills"), "global (agents)")
250	}
251	return out
252}
253
254func load(path, source string) (*Skill, error) {
255	raw, err := os.ReadFile(path)
256	if err != nil {
257		return nil, err
258	}
259	front, body := splitFrontmatter(string(raw))
260	s := &Skill{
261		Path:   path,
262		Source: source,
263		Body:   strings.TrimSpace(body),
264	}
265	parseFrontmatter(front, s)
266	return s, nil
267}
268
269// splitFrontmatter returns (yamlBlock, restOfDocument) for a string
270// whose first non-empty line is "---". If no frontmatter is present,
271// returns ("", entireString).
272func splitFrontmatter(raw string) (string, string) {
273	rest := strings.TrimLeft(raw, " \t\r\n")
274	if !strings.HasPrefix(rest, "---") {
275		return "", raw
276	}
277	rest = strings.TrimPrefix(rest, "---")
278	// Drop the trailing newline after the opening ---.
279	if i := strings.IndexByte(rest, '\n'); i >= 0 {
280		rest = rest[i+1:]
281	}
282	end := strings.Index(rest, "\n---")
283	if end < 0 {
284		return "", raw // malformed; treat as no frontmatter
285	}
286	front := rest[:end]
287	body := rest[end+len("\n---"):]
288	body = strings.TrimLeft(body, " \t\r\n")
289	return front, body
290}
291
292// parseFrontmatter handles the small subset of YAML zot recognizes:
293//   - simple `key: value` lines
294//   - `key: [a, b, c]` flow-style lists
295//   - `key:` followed by indented `- item` block lists
296//   - nested `key:` followed by indented `subkey: [...]` for permissions
297//
298// Anything more elaborate is ignored. We deliberately avoid a yaml
299// dependency to keep zot's binary lean.
300func parseFrontmatter(front string, s *Skill) {
301	lines := strings.Split(front, "\n")
302	i := 0
303	for i < len(lines) {
304		line := lines[i]
305		trimmed := strings.TrimSpace(line)
306		if trimmed == "" || strings.HasPrefix(trimmed, "#") {
307			i++
308			continue
309		}
310		// Top-level key: value or key:
311		if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
312			colon := strings.IndexByte(trimmed, ':')
313			if colon < 0 {
314				i++
315				continue
316			}
317			key := strings.TrimSpace(trimmed[:colon])
318			value := strings.TrimSpace(trimmed[colon+1:])
319			switch key {
320			case "name":
321				s.Name = unquote(value)
322			case "description":
323				s.Description = unquote(value)
324			case "allowed-tools", "allowed_tools":
325				if value != "" {
326					s.AllowedTools = parseInlineList(value)
327				} else {
328					items, consumed := parseBlockList(lines[i+1:])
329					s.AllowedTools = items
330					i += consumed
331				}
332			case "permissions":
333				if value != "" {
334					// Unusual layout; ignore single-line for now.
335					i++
336					continue
337				}
338				perms, consumed := parsePermissionsBlock(lines[i+1:])
339				s.Permissions = perms
340				i += consumed
341			}
342		}
343		i++
344	}
345}
346
347// unquote trims surrounding " or ' from a value.
348func unquote(v string) string {
349	if len(v) >= 2 {
350		if (v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'') {
351			return v[1 : len(v)-1]
352		}
353	}
354	return v
355}
356
357// parseInlineList parses "[a, b, c]" or "[\"a\", \"b\"]".
358func parseInlineList(v string) []string {
359	v = strings.TrimSpace(v)
360	v = strings.TrimPrefix(v, "[")
361	v = strings.TrimSuffix(v, "]")
362	if v == "" {
363		return nil
364	}
365	parts := strings.Split(v, ",")
366	out := make([]string, 0, len(parts))
367	for _, p := range parts {
368		out = append(out, unquote(strings.TrimSpace(p)))
369	}
370	return out
371}
372
373// parseBlockList consumes indented "- item" lines until a less-
374// indented line. Returns the items + how many lines to skip.
375func parseBlockList(lines []string) ([]string, int) {
376	var out []string
377	consumed := 0
378	for _, line := range lines {
379		if strings.HasPrefix(line, "  - ") || strings.HasPrefix(line, "    - ") {
380			out = append(out, unquote(strings.TrimSpace(strings.TrimPrefix(strings.TrimLeft(line, " "), "-"))))
381			consumed++
382			continue
383		}
384		if strings.TrimSpace(line) == "" {
385			consumed++
386			continue
387		}
388		break
389	}
390	return out, consumed
391}
392
393// parsePermissionsBlock parses an indented map of tool->[patterns].
394//
395//	permissions:
396//	  bash: ["git diff*", "git log*"]
397//	  read: ["./*.go"]
398func parsePermissionsBlock(lines []string) (map[string][]string, int) {
399	out := map[string][]string{}
400	consumed := 0
401	for _, line := range lines {
402		if !strings.HasPrefix(line, "  ") {
403			break
404		}
405		trimmed := strings.TrimSpace(line)
406		if trimmed == "" {
407			consumed++
408			continue
409		}
410		colon := strings.IndexByte(trimmed, ':')
411		if colon < 0 {
412			break
413		}
414		key := strings.TrimSpace(trimmed[:colon])
415		val := strings.TrimSpace(trimmed[colon+1:])
416		if val == "" {
417			break // we don't support nested-block lists for permissions
418		}
419		out[key] = parseInlineList(val)
420		consumed++
421	}
422	return out, consumed
423}

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 476

↑↓ moveenter openesc close