Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/skill"

Package skill reads skills in the open Agent Skills format (https://agentskills.io/specification) for zelk sessions.

A skill is a directory with a SKILL.md, YAML frontmatter followed by markdown instructions, and the files bundled beside it. Sources are fs.FS trees of skill directories or skills defined in code, each with a trust level; zelk never scans the disk by itself, except that Discover gives the CLI and zelk.Run the conventional directories. Load validates skills against the specification, resolves name collisions by trust and order, and reports every skipped skill as a warning. A loaded skill is content-addressed: its manifest of file digests is what a session records, so replay and reads use what was loaded, never the current files.

The frontmatter parser handles the YAML subset skills use: scalars (plain, quoted, literal and folded), sequences and one-level mappings. Fields zelk doesn’t interpret are kept as text in Skill.Extra, whatever their shape, so skills written for other agents load unchanged.

const (
// MaxNameLen and MaxDescriptionLen are the Agent Skills
// specification's limits; MaxCompatibilityLen too.
MaxNameLen = 64
MaxDescriptionLen = 1024
MaxCompatibilityLen = 500
// MaxFiles and MaxBundleBytes bound a skill's bundle.
MaxFiles = 1000
MaxBundleBytes = 16 << 20
)

The bounds on a skill. A skill past them is skipped with a warning: its bundle is recorded whole when it loads.

const DefaultIndexBytes = 16 << 10

DefaultIndexBytes bounds the skill index in the context, the names and descriptions of the skills the model may load, when the model’s context window is unknown.

const MaxFrontmatter = frontmatter.MaxFrontmatter

MaxFrontmatter bounds the frontmatter zelk parses.

const Scheme = "skill://"

Scheme prefixes the paths Read takes for a loaded skill’s files: skill://<name>/<path>.

var ErrInvalid = errors.New("invalid skill")

ErrInvalid reports a skill that doesn’t meet the Agent Skills specification.

func Expand(body string, names []string, args string, vars map[string]string) (out string, used bool)

Expand fills a skill’s placeholders with what the user passed when invoking it, as Claude Code does, so its skills and commands work unchanged:

  • $ARGUMENTS is args as typed;
  • $ARGUMENTS[N] and its shorthand $N are the Nth argument, from 0, with shell-style quoting grouping words into one argument;
  • $name is the argument at name’s position in names, the skill’s declared arguments, or “” when there are fewer arguments;
  • ${NAME} is vars[NAME], for each name vars holds, replaced after the arguments, so in them too.

A single backslash right before an argument placeholder makes it text (\$1.00); any other backslash is left as written, and doesn’t stop a variable.

An indexed placeholder past the last argument stays as written. used reports whether a placeholder took an argument: when none did and args isn’t empty, the caller shows args separately, so the model still sees them. A named placeholder counts even when it expands to “”.

func IndexBytes(window int64) int

IndexBytes bounds the skill index for a model with a context window of window tokens: 1% of it, as Claude Code budgets its skill listing, at about four bytes a token. A window of 0, unknown, gets DefaultIndexBytes. Skills past the bound are listed by name only.

func Render(rec event.SkillLoaded, body, root, args string, opts ...RenderOption) string

Render frames a loaded skill’s instructions for the model with the authority of its source: a host skill speaks for the host; a project skill is lower-trust guidance, like project instructions. root is the workspace’s absolute path as the model sees it, for a skill whose scripts can run there; args are what the user passed when invoking it by name.

func ReplaceShell(body string, lines []ShellLine, outputs []string) string

ReplaceShell returns body with each of lines, which ShellLines found in it, replaced by outputs at the same index.

func SplitArgs(s string) []string

SplitArgs splits what the user passed a skill into its arguments as a POSIX shell splits words: at unquoted blanks, with single quotes taking everything literally, double quotes letting a backslash escape \, “, $ and `, and a backslash outside quotes escaping the next character. An unterminated quote runs to the end.

func ValidName(name string) error

ValidName reports whether name is a valid skill name: 1–64 lowercase letters, digits and hyphens, not starting or ending with a hyphen, with no two hyphens in a row.

type Loaded struct {
Skill
// Source and Trust are the source's name and trust level.
Source string
Trust Trust
// Dir is the skill's directory in the workspace, for a source given
// WithWorkspace; empty otherwise.
Dir string
// Revision is the digest of Manifest.
Revision string
// Manifest lists the bundle's files with their digests and sizes.
Manifest []event.SkillFile
}

Loaded is a skill as a session sees it: where it came from, and its content-addressed bundle.

func (l Loaded) Entry() event.SkillEntry

Entry returns the skill’s index entry. Its description is the skill’s with when_to_use after it, cut at 1,536 characters, as Claude Code lists them.

func (l Loaded) Record() event.SkillLoaded

Record returns the SkillLoaded that records the skill’s load.

type RenderOption func(*renderConfig)

RenderOption selects how a recorded skill is presented.

func WithPendingPublication() RenderOption

WithPendingPublication describes scripts awaiting durable materialization. Use it only when the session records Materializer; the harness must publish recorded bytes and report their directory before any dependent work runs.

Example

rec := event.SkillLoaded{Name: "embedded", Files: []event.SkillFile{{Path: "scripts/run"}}}
rendered := skill.Render(rec, "Run scripts/run.", "/workspace", "", skill.WithPendingPublication())
fmt.Println(strings.Contains(rendered, "wait for its recorded directory"))
// Output: true

Output:

true
type Set struct {
// contains filtered or unexported fields
}

Set is the skills of an agent, resolved from its sources. It is immutable and safe for concurrent use.

func Load(sources ...Source) (*Set, []event.Warning)

Load resolves sources into a set. Skills that fail validation are skipped, and two skills with one name keep the one from the higher-trust source, then the earlier one; each is reported as a warning, never silently.

func (s *Set) Get(name string) (Loaded, bool)

Get returns the named skill.

func (s *Set) Index(maxBytes int) ([]event.SkillEntry, []event.Warning)

Index returns the entries of the skills the model may load by itself, in source order, within maxBytes of names and descriptions. Skills past the bound, and explicit-only ones, stay loadable by name; the overflow is reported as a warning.

func (s *Set) Invocable() []Loaded

Invocable returns the skills a host offers the user to invoke by name, in source order: every skill but those whose frontmatter says user-invocable: false, which the model loads but a menu doesn’t list. Explicit-only skills are here: invoking them by name is their use.

func (s *Set) Len() int

Len returns the number of skills in the set.

func (s *Set) Unlisted(maxBytes int) []string

Unlisted returns the names of the model-invocable skills Index leaves out for lack of room, in source order, so the model can be told they exist.

type ShellLine struct {
Start, End int
Command string
}

ShellLine is a “!`command`” in a skill’s body: a shell command whose output takes its place before the skill’s message is sent, as Claude Code runs them. Start and End are its bytes in the body.

func ShellLines(body string) []ShellLine

ShellLines returns the shell commands in body, in order, as Claude Code finds them: “!`command`”, where the “!” starts a line or follows a blank and the command runs to the next backtick on the same line, and a fenced block opened by a line of “```!”, whose lines up to the closing “```” are the command. An empty command is text, as is a block never closed.

type Skill struct {
// Name is 1–64 lowercase letters, digits and single hyphens, and
// matches the skill's directory name.
Name string
// Description says what the skill does and when to use it; it is
// what the model sees in the index.
Description string
// WhenToUse adds to Description when the model should load the skill,
// as Claude Code's when_to_use does: the index shows the two together.
WhenToUse string
License string
Compatibility string
Metadata map[string]string
// AllowedTools are the frontmatter's allowed-tools entries, permission
// rules such as "Read" or "Bash(git:*)". While a host-trust skill is
// active they are allow rules, as Claude Code pre-approves a skill's
// tools; a project's skill grants nothing. Other tools are unaffected.
AllowedTools []string
// ExplicitOnly keeps the skill out of the index: it loads only when
// invoked by name (Claude's disable-model-invocation, Codex's
// allow_implicit_invocation: false).
ExplicitOnly bool
// MenuHidden keeps the skill from the user, as Claude Code's
// user-invocable: false does for reference skills the model loads by
// itself: a host doesn't offer it (Invocable), and typing its name
// doesn't run it.
MenuHidden bool
// Arguments name the positional arguments the skill takes, for
// $name placeholders in its body (Expand); ArgumentHint says what to
// pass, as "[issue] [branch]", where a host offers the skill.
Arguments []string
ArgumentHint string
// Body is the markdown after the frontmatter: the instructions.
Body string
// Extra holds frontmatter fields zelk doesn't interpret, as their
// source text. Other agents add their own; they are kept, not
// warned about.
Extra map[string]string
// Files is the bundle by path relative to the skill's directory,
// SKILL.md included. A programmatic skill without one gets a
// SKILL.md rendered from its fields.
Files map[string][]byte
// contains filtered or unexported fields
}

Skill is one skill in the Agent Skills format: a SKILL.md with YAML frontmatter and markdown instructions, and the files bundled with it.

func Parse(dir string, data []byte) (Skill, error)

Parse reads a SKILL.md found in the directory named dir and validates it against the Agent Skills specification.

func ParseCommand(name string, data []byte) (Skill, error)

ParseCommand reads a command file as the skill named name.

func (s Skill) Manifest() ([]event.SkillFile, string)

Manifest returns the skill’s bundle as recorded: each file’s path, digest and size, sorted by path, and the bundle’s revision, a digest of the manifest itself.

type Source struct {
// contains filtered or unexported fields
}

Source is where skills come from: an fs.FS of skill directories or skills given in code, with a trust level. zelk never scans the disk by itself; the host passes every source.

func Below(cwd, dir, workspace string) []Source

Below returns the project skill directories of each directory strictly below cwd down to dir, both absolute, nearest cwd first, as Claude Code finds a monorepo package’s skills once the session works with its files. Discover covers cwd and the directories above it. A dir that isn’t below cwd yields nothing. Sources are marked WithWorkspace as in Discover.

func Commands(name string, trust Trust, fsys fs.FS, opts ...SourceOption) Source

Commands returns a source of custom commands: each .md file under fsys, at any depth, is a skill of one file, as Claude Code reads .claude/commands. A file’s name without .md names it, after its directories’ names, each followed by “:”, so frontend/component.md is frontend:component. Frontmatter is optional and takes a skill’s fields but name; a command without a description is described by its body’s first line. Commands have no bundled files or scripts, so WithWorkspace changes nothing.

func Discover(home, cwd, workspace string) []Source

Discover returns the conventional skill directories as sources, for the CLI and zelk.Run only: library hosts name their sources themselves. They are, in order, home/.zelk/skills, home/.agents/skills and home/.claude/skills, then .zelk/skills, .agents/skills and .claude/skills in each directory from cwd up to the repository’s root (the first directory holding .git), or cwd alone outside a repository. Directories below cwd are found as the session reaches them (Below). The command directories (Commands) follow in the same order: home/.zelk/commands and home/.claude/commands, then .zelk/commands and .claude/commands from cwd up to the root. Coming after every skill, a command loses to a skill of its name and trust, as in Claude Code. The home directories hold the user’s own skills and have host trust, so their allowed-tools pre-approve as Claude Code’s personal skills do; the repository’s have project trust. A directory under workspace, the workspace’s absolute path, is marked WithWorkspace, so its skills’ scripts can run. Directories that don’t exist are left out. home may be empty.

func FS(name string, trust Trust, fsys fs.FS, opts ...SourceOption) Source

FS returns a source of the skills in fsys: each directory at its top holding a SKILL.md is one skill, with every regular file under it bundled. Hidden files and directories are excluded outside scripts/, where they can hold local state. Under scripts/ they are bundled so the recorded digests cover scripts with hidden names. name identifies the source in the log and in warnings.

func Programmatic(name string, trust Trust, skills ...Skill) Source

Programmatic returns a source of skills defined in code.

func (s Source) Name() string

Name returns the source’s name; Trust its trust level.

func (s Source) Trust() Trust

Trust returns the source’s trust level.

type SourceOption func(*Source)

SourceOption configures a Source.

func WithWorkspace(dir string) SourceOption

WithWorkspace says an FS source is the workspace directory dir (relative to the workspace, with forward slashes), so its skills’ scripts can run there, after a check against the recorded bundle. Skills from other sources expose instructions and files, but no runnable scripts.

type Trust string

Trust is how much authority a skill’s source has.

const (
// TrustHost skills rank with host policy.
TrustHost Trust = "host"
// TrustProject skills rank with project instructions: lower-trust
// guidance.
TrustProject Trust = "project"
)

The trust levels.