skills

package
v0.37.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2026 License: Apache-2.0 Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package skills implements progressive disclosure of agent instructions, following the Agent Skills format (https://agentskills.io).

The problem it solves

Reference material injected into a system prompt is paid for on every request, whether or not the turn needs it. An agent with twenty documented procedures pays twenty procedures' worth of tokens to answer "what time is it". Progressive disclosure splits that into three tiers:

  1. Catalog — each skill's name and description, roughly 50-100 tokens apiece, in the system prompt from the start. Enough for the model to decide, and nothing more.
  2. Instructions — the full SKILL.md body, delivered by a tool call only when the model activates that skill.
  3. Resources — files under the skill directory, read one at a time on demand.

Twenty skills cost twenty descriptions plus the one body actually used.

Why fs.FS

This package loads from an io/fs.FS rather than a directory path, which is what makes it usable from a library rather than only from a CLI:

skills.FromFS(ctx, os.DirFS("./skills"), skills.TrustedSource())  // disk
skills.FromFS(ctx, embeddedFS, skills.TrustedSource())            // //go:embed
skills.FromFS(ctx, tenantFS)                                      // database, S3, …

An embed.FS needs no filesystem at all, so skills ship inside the binary and work in a distroless container. A custom FS covers per-tenant content. And fs.ValidPath rejects ".." and absolute paths at the stdlib boundary, so path traversal is structurally impossible instead of guarded against.

Deliberately absent: scanning $HOME, walking up to a git root, and merging skills by directory precedence. Those belong to CLI products that own the user's filesystem. In a server, $HOME belongs to a service account and the working directory means nothing. Adopters who want that behavior can build the source list themselves and pass each directory through os.DirFS.

Trust

Trust is stated, not inferred. The caller chose which fs.FS to hand over, so the caller declares whether it is vouched content:

skills.FromFS(ctx, mine, skills.TrustedSource())  // content I control
skills.FromFS(ctx, cloned)                        // untrusted by default

Untrusted is the zero value, so forgetting the option fails closed. Untrusted skills still load; what changes is the path the model takes to reach them. The activation tools build disjoint parameter enums from NamesByTrust and put the untrusted one behind a confirmation prompt, so a human sees instructions from a repository they merely cloned before the model does.

Two things this package will not do, both permanent:

  • Honor the allowed-tools frontmatter field. It is a privilege grant authored by the content it would privilege. Skill.AllowedTools is advisory metadata; adopters may intersect it with their registry to RESTRICT a skill, never to GRANT.
  • Execute shell commands embedded in a SKILL.md. Some implementations substitute command output into the body at load time; that turns cloning a repository into arbitrary code execution. Not a gap to fill.

Bounds

The catalog sits in the prompt on every request and bodies stay resident for the process lifetime, so both are capped. See the Default* constants for the figures. MaxCatalogBytes is the one that matters most: without it, a full complement of maximum-length descriptions would render tens of thousands of prompt tokens per call. Admission happens at load time, so Catalog, Names, and Get always agree on which skills exist.

Loading tolerates a malformed skill rather than failing the process — one bad SKILL.md must not stop an agent from starting. That trade only works if rejections stay visible, so log Set.Skipped once at startup.

Wiring it up

With the YAML builder, a skills: block does everything. By hand:

set, err := skills.FromFS(ctx, os.DirFS("./skills"), skills.TrustedSource())
if err != nil {
    return err
}
for _, s := range set.Skipped() {
    log.Printf("skill skipped: %s", s)
}

prompt := builder.WithSkillCatalog(basePrompt, set)
sm := history.NewInMemSessionManager(prompt)

reg := tools.NewRegistry()
builtin.RegisterSkillTools(reg, set)
loop := agent.NewAgentLoop(sm, reg, provider)

One caveat worth knowing before it bites: a tools.Selector replaces the registry per call with its top-K matches, and the activation tool ranks poorly by design — the domain signal lives in the skill descriptions, not in the tool's own. Pin it, or activation will vanish on exactly the turns that need it:

sel, _ := tools.NewSelector(ctx, reg, embedder, 8,
    tools.WithPinned(builtin.SkillToolNames()...))

A *Set is immutable and safe to share across every session in a process. Load once at construction; never per request.

Index

Constants

View Source
const (
	// DefaultMaxSkills caps admitted skills. At the default catalog budget
	// this is rarely the binding constraint; it exists so a runaway tree
	// stops at a known count rather than at whatever fits in bytes.
	DefaultMaxSkills = 128
	// DefaultMaxSkillBytes caps one SKILL.md. The spec recommends bodies
	// under ~5k tokens; 64 KiB (~16k tokens) allows well past that while
	// still bounding a single pathological file.
	DefaultMaxSkillBytes int64 = 64 << 10
	// DefaultMaxCatalogBytes caps the rendered catalog, and is the bound
	// that matters most: the catalog is paid on EVERY request, inside the
	// prompt-cache prefix. 32 KiB is ~8k tokens worst case, ~1k typical.
	//
	// Without this bound, MaxSkills skills each carrying a maximum-length
	// name and description would render ~182 KB — roughly 45k prompt
	// tokens per call.
	DefaultMaxCatalogBytes = 32 << 10
	// DefaultMaxResourceBytes caps one Set.File read. Larger files are
	// truncated, not rejected, so a big reference is still partly useful.
	DefaultMaxResourceBytes int64 = 256 << 10
	// DefaultMaxFilesPerSkill caps captured resource paths per skill.
	DefaultMaxFilesPerSkill = 256
	// DefaultMaxDepth caps directory descent. Deep enough for skills nested
	// a few groups down, shallow enough that a generated or symlinked tree
	// cannot be walked forever.
	//
	// It applies independently to the two descents: finding skill
	// directories below the FS root, and collecting resource files below a
	// skill. The budget deliberately restarts at each skill, so a skill
	// nested near the limit still gets its references/ subtree instead of
	// silently exposing no files. Worst-case absolute depth is therefore
	// 2 x MaxDepth; MaxFilesPerSkill bounds the result either way.
	DefaultMaxDepth = 8

	// MaxNameLen and MaxDescriptionLen come from the Agent Skills spec.
	MaxNameLen        = 64
	MaxDescriptionLen = 1024
	// MaxCompatibilityLen also comes from the spec.
	MaxCompatibilityLen = 500
	// MaxMetadataKeys and MaxMetadataValueLen do not: the spec leaves
	// metadata unbounded, which is an accumulator with no ceiling. These
	// are this package's own limits.
	MaxMetadataKeys     = 32
	MaxMetadataValueLen = 256
)

Default bounds. Every one is overridable with the matching Option.

The catalog sits in the system prompt on every request, and skill bodies are held resident for the process lifetime, so both need a ceiling that holds even when the source tree is larger than anyone intended. The figures below are sized for the steady state (5-30 curated skills at ~8 KiB each) with headroom, not for the worst case being routine.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*config)

Option configures a load. Options are applied in order; the last write to a given field wins.

func MaxCatalogBytes

func MaxCatalogBytes(n int) Option

MaxCatalogBytes overrides DefaultMaxCatalogBytes, capping the rendered catalog and therefore the per-request prompt cost. Values <= 0 restore the default.

func MaxDepth

func MaxDepth(n int) Option

MaxDepth overrides DefaultMaxDepth. Values <= 0 restore the default.

func MaxFilesPerSkill

func MaxFilesPerSkill(n int) Option

MaxFilesPerSkill overrides DefaultMaxFilesPerSkill. Values <= 0 restore the default.

func MaxResourceBytes

func MaxResourceBytes(n int64) Option

MaxResourceBytes overrides DefaultMaxResourceBytes. Values <= 0 restore the default.

func MaxSkillBytes

func MaxSkillBytes(n int64) Option

MaxSkillBytes overrides DefaultMaxSkillBytes. Values <= 0 restore the default.

func MaxSkills

func MaxSkills(n int) Option

MaxSkills overrides DefaultMaxSkills. Values <= 0 restore the default.

func SkipDirs

func SkipDirs(names ...string) Option

SkipDirs replaces the default skip list. Names match a directory's base name at any depth. Passing no names disables skipping entirely.

func Strict

func Strict(on bool) Option

Strict controls whether unrecognized frontmatter keys reject a skill.

The Agent Skills spec makes unknown keys a validation error, which is the default here: an unexpected key usually means a typo in a key that was supposed to do something. Set false to interoperate with producers that ship extensions.

func TrustedSource

func TrustedSource() Option

TrustedSource marks the loaded skills as adopter-vouched, so their activation tool carries no confirmation gate. Untrusted is the default, so this is the only trust option: forgetting it fails closed.

Pass it only for content you control: a directory you ship, an embed.FS compiled into the binary, or a store you write. Content from a repository you merely cloned is not vouched content.

type Set

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

Set is the immutable result of loading skills.

Every method is safe for concurrent use with no synchronization, because nothing mutates after construction. That is the reason skill bodies are read eagerly rather than on demand: an immutable Set needs no locks, costs no syscalls when a skill is activated in forty sessions at once, and leaves no window between a trust decision and the read it guards. The memory that buys is bounded by MaxSkills times MaxSkillBytes — 8 MiB at the defaults, around 1 MiB in practice.

Resource files stay lazy: their fan-out is unbounded and most are never read. Their paths are captured eagerly, and that list is the allowlist File validates against.

A nil *Set is usable: every method reports empty. Callers can pass the result of a load that found nothing without nil-checking.

func FromFS

func FromFS(ctx context.Context, fsys fs.FS, opts ...Option) (*Set, error)

FromFS loads every skill in fsys.

A skill is a directory containing a file named exactly SKILL.md; any regular files beneath that directory become its resource files. Loading does not descend into a skill, so skills cannot nest.

Trust defaults to Untrusted — pass TrustedSource for content you control.

Taking an fs.FS rather than a directory path is what keeps this usable from a server: os.DirFS covers the on-disk case in one line, an embed.FS needs no filesystem at all, and a custom FS covers per-tenant skills read from a database. It also means fs.ValidPath rejects parent-directory and absolute paths at the stdlib boundary, so traversal is impossible rather than merely guarded against.

Per-skill problems never fail the call: one malformed SKILL.md must not break agent startup. They are recorded in Set.Skipped, which callers should log once — silently dropping them makes "my skill isn't loading" undiagnosable. An error is returned only when ctx is cancelled.

Cost is O(entries) syscalls, paid once. Call it at construction and share the resulting Set; never call it per request.

func Merge

func Merge(sets ...*Set) (*Set, error)

Merge combines Sets into one, first-wins on duplicate names. The losing skill is recorded in Skipped with SkipDuplicateName.

First-wins inverts the reference implementations, which let project-level skills override user-level ones. For a library that ordering is a one-line hijack: a skill named "deploy" in a cloned repository would silently replace the operator's own. List trusted sources first.

The merged Set adopts the most conservative resource-read limit and the catalog budget of the first Set, so merging cannot exceed the prompt cost any single source was allowed.

func New

func New(ctx context.Context, skills []Skill, opts ...Option) (*Set, error)

New builds a Set from skills already in memory — rows from a database, a response from an API, values compiled into the binary. Each is validated exactly as FromFS validates a parsed SKILL.md.

In-memory skills carry no resource files: Files is cleared, because there is no fs.FS behind them for Set.File to read. A source that does have resources should implement fs.FS and go through FromFS instead — that is the case the io/fs abstraction exists to cover.

Trust on each input Skill is ignored and replaced by the load option, so one call cannot mix vouched and unvouched content. Load them separately and combine with Merge when a source has both.

func (*Set) Body

func (s *Set) Body(name string) (string, error)

Body returns the skill's SKILL.md with frontmatter stripped — tier two.

Body does not gate on Trust. Trust is enforced where the model reaches it: the activation tools build disjoint enums from NamesByTrust and put the untrusted one behind a confirmation prompt. A caller holding a *Set already has the content in memory, so a check here would guard nothing.

The error names the valid alternatives, so a hallucinated skill name becomes a recoverable turn rather than a dead end.

func (*Set) Catalog

func (s *Set) Catalog() string

Catalog renders the block that goes into the system prompt: one entry per skill carrying only its name, description, and location.

This is tier one of progressive disclosure. It is paid on every request, so it holds no instructions — the model reads a description, decides, and spends the body's tokens only for the skill it actually uses.

The output is byte-stable across runs, which lets it sit inside a prompt-cache prefix. Returns "" for an empty Set so callers can append it unconditionally.

func (*Set) File

func (s *Set) File(ctx context.Context, name, rel string) (content string, truncated bool, err error)

File reads one of a skill's resource files — tier three, the level that keeps a large reference out of the prompt until it is asked for.

rel is checked by exact lookup against the allowlist captured at load time, not by path arithmetic. A path that was not present when the Set was built is rejected before any syscall, which closes traversal, symlink-swap, and case-folding in one rule instead of three defenses.

Content over the resource limit is truncated rather than refused, so an oversized reference is still partly useful; truncated reports it so the caller can tell the model what it is missing.

func (*Set) Get

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

Get returns the admitted skill by name.

func (*Set) HasFiles

func (s *Set) HasFiles() bool

HasFiles reports whether any admitted skill exposes resource files. Registration uses this to skip the resource-reading tool entirely when it would have nothing to serve.

func (*Set) Len

func (s *Set) Len() int

Len returns the number of admitted skills.

func (*Set) Names

func (s *Set) Names() []string

Names returns the admitted skill names, sorted. The slice is freshly allocated on each call: it becomes the activation tool's parameter enum, and a caller mutating it must not be able to poison the Set.

func (*Set) NamesByTrust

func (s *Set) NamesByTrust() (trusted, untrusted []string)

NamesByTrust returns the admitted names split by trust, each sorted.

The activation tools use this to build two disjoint parameter enums, so an untrusted skill cannot be reached through the tool that carries no confirmation gate.

func (*Set) Skipped

func (s *Set) Skipped() []Skipped

Skipped returns the rejected candidates, sorted by location. Log these once at startup: loading deliberately tolerates a malformed skill rather than failing, and that trade only works if the rejections are visible.

type Skill

type Skill struct {
	// Name is the skill identifier the model activates by. Validated to
	// 1..MaxNameLen characters of [A-Za-z0-9-], and required to equal the
	// containing directory's name so the catalog cannot advertise a skill
	// under a name that does not resolve.
	Name string
	// Description tells the model what the skill does and when to reach
	// for it. This is the only skill text in the system prompt, so it
	// carries the entire activation decision.
	Description string
	// Body is the SKILL.md content with frontmatter stripped, loaded
	// eagerly (see the Set doc for why).
	Body string
	// Location is the slash-separated path of the skill directory within
	// its source fs.FS. Rendered in the catalog so the model can refer to
	// bundled files; deliberately not an absolute host path.
	Location string
	// Files lists resource paths relative to the skill directory, sorted.
	// This doubles as the allowlist Set.File validates against — a path
	// that is not in here is rejected before any syscall.
	Files []string
	// Trust is inherited from the load option that produced this skill.
	Trust Trust
	// License and Compatibility carry the optional spec fields verbatim.
	License       string
	Compatibility string
	// Metadata is the optional free-form frontmatter map.
	Metadata map[string]string
	// AllowedTools is ADVISORY ONLY and is never consulted by this package
	// or by the activation tools.
	//
	// It is a privilege grant authored by the skill itself. Honoring it
	// would let content decide its own permissions, which is the whole
	// point of not doing so. Adopters may intersect it with their registry
	// to RESTRICT what a skill may call; never use it to GRANT.
	AllowedTools []string
	// Lenient is true when strict YAML parsing failed and the fallback
	// scanner recovered this skill from Name and Description alone. Every
	// other optional field is empty in that case — see frontmatter.go.
	Lenient bool
	// contains filtered or unexported fields
}

Skill is one validated SKILL.md and the resource files beside it. Immutable once a Set is built.

type SkipReason

type SkipReason uint8

SkipReason explains why a candidate directory did not become a Skill.

const (
	// SkipInvalidFrontmatter covers a missing fence, unparseable YAML that
	// the lenient fallback could not rescue, and failed field validation.
	SkipInvalidFrontmatter SkipReason = iota
	// SkipNameMismatch means frontmatter name != directory name.
	SkipNameMismatch
	// SkipDuplicateName means an earlier source already claimed the name.
	SkipDuplicateName
	// SkipOversize means SKILL.md exceeded MaxSkillBytes.
	SkipOversize
	// SkipBudgetExhausted means MaxSkills or MaxCatalogBytes was reached
	// before this skill could be admitted. MaxSkills short-circuits before
	// SKILL.md is opened; MaxCatalogBytes cannot, since the cost depends on
	// the name and description inside the file — but the body is discarded
	// either way, so neither bound is exceeded in memory.
	SkipBudgetExhausted
	// SkipUnreadable covers I/O errors on the directory or SKILL.md.
	SkipUnreadable
)

func (SkipReason) String

func (r SkipReason) String() string

String implements fmt.Stringer so log lines read plainly.

type Skipped

type Skipped struct {
	// Location is the candidate directory within its source fs.FS.
	Location string
	// Name is best-effort: empty when the frontmatter could not be read.
	Name string
	// Reason is the machine-readable rejection cause.
	Reason SkipReason
	// Err carries the underlying failure for I/O and parse rejections;
	// nil for duplicate-name and budget rejections, which are not errors.
	Err error
}

Skipped records a rejected candidate.

Loading never fails the whole call over one bad skill — a malformed SKILL.md must not break agent startup. That trade only works if the rejections are reportable, otherwise "my skill isn't loading" has no diagnosis. Log Set.Skipped() once at startup.

func (Skipped) String

func (s Skipped) String() string

String renders a one-line diagnostic suitable for a startup log.

type Trust

type Trust uint8

Trust records whether the adopter vouched for a skill's content.

Untrusted is the zero value so a forgotten option fails closed. Trust is not inferred from where a skill was found — the adopter chose which fs.FS to hand to FromFS and says so explicitly with the Trusted option. That is the whole reason this package takes an fs.FS instead of a directory path: provenance is the caller's knowledge, not something to guess from a path.

const (
	// Untrusted content may still be loaded, but its activation tool is
	// HITL-gated so a human sees the instructions before the model does.
	Untrusted Trust = iota
	// Trusted content activates without a confirmation prompt.
	Trusted
)

func (Trust) String

func (t Trust) String() string

String implements fmt.Stringer for log and error messages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL