skill

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package skill implements support for Anthropic Agent Skills (an open standard, December 2025): single-directory capabilities that a running agent can discover by name+description and load in full when relevant.

A skill is a directory containing a SKILL.md file with YAML frontmatter:

---
name: my-skill-name
description: What this skill does and when to use it
---

# Body
Free-form markdown the agent reads when it triggers the skill.

Squad implements the spec's three-level progressive disclosure:

  • Level 1 (always): name + description injected into the agent's system prompt at boot, so the agent knows the skill exists.
  • Level 2 (on demand): full SKILL.md body returned by the Skill tool when the agent decides it matches the task.
  • Level 3 (on demand): bundled files under references/, scripts/, assets/ accessed by the agent via the existing Read and Bash tools.

Phase 1 covers manifest parsing, validation, and multi-scope discovery. The runtime hooks (system prompt injection, Skill tool, skill stack) land in later phases.

Index

Constants

View Source
const FileName = "SKILL.md"

FileName is the standard skill manifest filename, per spec.

View Source
const MaxBodyBytes = 64 * 1024

MaxBodyBytes caps the on-disk size of a SKILL.md body. The spec targets <5k tokens for L2 content. Empirically the largest first-party skill Anthropic ships (skill-creator) is ~32 KiB, so the hard cap sits at 64 KiB — generous enough for legitimate large skills, still tight enough to prevent runaway context consumption.

View Source
const MaxCompatibilityLen = 500

MaxCompatibilityLen is the per-spec upper bound on the compatibility field (Reference B of the Skills guide: 1–500 characters).

View Source
const MaxDescriptionLen = 1024

MaxDescriptionLen is the per-spec upper bound on a skill description.

View Source
const MaxNameLen = 64

MaxNameLen is the per-spec upper bound on a skill name.

View Source
const PromptBlockHeader = "## Available skills"

PromptBlockHeader is the markdown heading the system-prompt section opens with. Exported so tests and callers that want to detect the block can grep for it without hardcoding the exact wording.

View Source
const WarnBodyBytes = 24 * 1024

WarnBodyBytes is the soft cap surfaced by Validate as a warning. Skills past this size still load but the author is told to consider splitting. The guide's "<5,000 word" target maps to roughly 25 KiB by char count; 24 KiB rounds to that without being so tight that every real-world procedural skill (~7–16 KiB) trips a warning on every validate run.

Variables

This section is empty.

Functions

func FindRepoRoot

func FindRepoRoot(start string) string

FindRepoRoot walks up from start looking for the nearest ancestor that contains a .git entry and returns it, so repo-scoped skills under <root>/.squad/skills are discoverable when squad is run from a subdirectory. When start is not inside a git repository (or cannot be resolved), start is returned unchanged so discovery still works in non-repo working dirs.

func GlobalSkillsDir

func GlobalSkillsDir() (string, error)

GlobalSkillsDir returns the user-level skills directory. The parent (`$XDG_CONFIG_HOME/squad/`) is created on demand by the config package; we do not create the `skills/` directory itself so that an absent directory remains a clean "no global skills" signal during discovery.

func HasReservedSubstring

func HasReservedSubstring(s string) (string, bool)

HasReservedSubstring reports whether s contains a spec-reserved substring. Exported so the validator (and tests) can surface it as a warning.

func IsSkillDir

func IsSkillDir(dir string) bool

IsSkillDir reports whether dir contains a readable SKILL.md. It does not validate the manifest; the caller should LoadManifest after.

func RenderPromptBlock

func RenderPromptBlock(entries []Entry) string

RenderPromptBlock builds the Level-1 system-prompt section listing every visible skill the agent should know about. The block is intentionally prose — the model selects skills by reading the descriptions, not by pattern-matching structured fields.

Returns the empty string when entries is empty so callers can append unconditionally:

if block := RenderPromptBlock(catalog); block != "" {
    sys.WriteString(block)
}

The output is sorted by name so the block is stable across runs.

func RepoSkillsDir

func RepoSkillsDir(repoRoot string) string

RepoSkillsDir returns the per-repo skills directory under repoRoot. It does not create the directory.

func ValidateCompatibility

func ValidateCompatibility(c string) error

ValidateCompatibility reports whether c satisfies the per-spec 1–500 character bound. Empty is allowed (the field itself is optional).

func ValidateDescription

func ValidateDescription(d string) error

ValidateDescription reports whether d satisfies the spec constraints: non-empty, ≤1024 chars, no XML-tag characters.

func ValidateName

func ValidateName(s string) error

ValidateName reports whether s is a syntactically valid skill name per the open Skills spec. The reserved-substring rule ("anthropic"/"claude") is enforced as a warning in Validate rather than here, because Anthropic's own first-party skills violate it (e.g. `claude-api`).

Types

type AllowedTools

type AllowedTools []string

AllowedTools is the list of tool names a skill is permitted to invoke. In YAML it may appear as a space-separated string (the form shown in the Skills guide example: `"Bash(python:*) Bash(npm:*) WebFetch"`) or as a sequence of scalars. squad enforces tool-name matching only — the Claude Code permission-pattern syntax (`Bash(python:*)`) is normalized to the bare tool name preceding the parenthesis. Authors who need finer-grained constraints should bundle a script rather than rely on the field.

func (AllowedTools) Allows

func (a AllowedTools) Allows(toolName string) bool

Allows reports whether toolName is permitted. An empty/unset allow-list imposes no restriction.

func (*AllowedTools) UnmarshalYAML

func (a *AllowedTools) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML accepts either a scalar (space-separated tool names) or a sequence of scalars. Anything else is a parse error.

type Catalog

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

Catalog is the set of skills discovered across one or more scopes. The zero value is unusable; construct via Discover.

func Discover

func Discover(repoRoot string, catalogDirs ...string) (*Catalog, error)

Discover scans the configured scopes for skill manifests. repoRoot, when non-empty, enables repo-scope discovery under <repoRoot>/.squad/skills/. catalogDirs are additional roots whose immediate subdirectories are scanned as catalog-scope skills (lowest precedence). A missing directory at any scope is not an error.

Returns the catalog and (separately) the slice of non-fatal load errors. The catalog's All() method also exposes these via LoadErrors().

func (*Catalog) All

func (c *Catalog) All() []Entry

All returns every discovered entry including shadowed ones. Used by `squad skill list` to surface conflicts.

func (*Catalog) Filter

func (c *Catalog) Filter(opts FilterOptions) []Entry

Filter applies FilterOptions to the visible entries and returns the resulting list. Visible-only is intentional: filtering should not bring shadowed skills back to life.

Precedence (per PLAN.md): allow > deny > scopes. When Allow is non-empty it is an exclusive allowlist — Deny and Scopes are ignored and only the listed names appear. When Allow is empty, the result is the entries matching Scopes minus the entries listed in Deny.

func (*Catalog) Find

func (c *Catalog) Find(name string) (Entry, bool)

Find returns the visible entry with the given name. Shadowed entries are not returned — by definition the lookup should yield the active skill.

func (*Catalog) LoadErrors

func (c *Catalog) LoadErrors() []LoadError

LoadErrors returns the list of skills that could not be loaded.

func (*Catalog) Visible

func (c *Catalog) Visible() []Entry

Visible returns the unshadowed entries — the set an agent should be told about via the system prompt.

type Entry

type Entry struct {
	Manifest     *Manifest
	Scope        Scope
	Dir          string
	ManifestPath string
	// Origin is a human-readable label for `squad skill list` ("global" or the
	// repo root path).
	Origin string
	// Shadowed is true when another entry with the same name lives in a
	// higher-precedence scope. Shadowed entries are kept in the catalog so the
	// CLI can surface them, but they are excluded from Visible().
	Shadowed bool
}

Entry is a fully resolved skill in the catalog. ManifestPath points at the SKILL.md; Dir is the parent directory containing references/, scripts/, etc.

func (Entry) Name

func (e Entry) Name() string

Name returns the skill name from the manifest. Convenience accessor for callers that don't want to dereference twice.

type FilterOptions

type FilterOptions struct {
	// Scopes restricts to this set of scopes (empty = all).
	Scopes []Scope
	// Allow, when non-empty, restricts to skills whose name is listed.
	Allow []string
	// Deny removes skills whose name is listed, after Allow is applied.
	Deny []string
}

FilterOptions controls which visible entries an agent actually sees. Empty fields are treated as "no constraint".

type Finding

type Finding struct {
	Severity Severity
	// Path is the file the finding applies to, relative to the skill dir
	// when known (e.g. "SKILL.md", "scripts/foo.py") or absolute otherwise.
	Path    string
	Message string
}

Finding is a single spec-conformance issue found by Validate.

type LoadError

type LoadError struct {
	Path string
	Err  error
}

LoadError describes a single skill that could not be added to the catalog.

func (LoadError) Error

func (e LoadError) Error() string

Error implements the error interface.

func (LoadError) Unwrap

func (e LoadError) Unwrap() error

Unwrap allows errors.Is / errors.As to reach the underlying parse error.

type Manifest

type Manifest struct {
	// Name is the skill's stable identifier. Required.
	Name string `yaml:"name"`
	// Description is the prose summary used at Level 1 to decide whether the
	// skill matches a task. Required.
	Description string `yaml:"description"`
	// License is the optional SPDX-style license identifier (e.g. "MIT") for
	// open-source skills. Spec: free-form string.
	License string `yaml:"license,omitempty"`
	// Compatibility describes environment requirements — intended platform,
	// system packages, network access. Optional, 1–500 chars.
	Compatibility string `yaml:"compatibility,omitempty"`
	// AllowedTools restricts which tools the agent may call while this skill
	// is on the stack. Empty means no restriction. See AllowedTools for the
	// accepted YAML shapes and the matching semantics squad implements.
	AllowedTools AllowedTools `yaml:"allowed-tools,omitempty"`
	// Metadata holds the spec's free-form key/value bag (author, version,
	// mcp-server, tags, etc.). Preserved verbatim for callers that want to
	// surface it via `squad skill list` without re-reading the file.
	Metadata map[string]any `yaml:"metadata,omitempty"`
	// Body is the markdown content after the frontmatter block, with leading
	// and trailing whitespace trimmed. Returned by the Skill tool at L2.
	Body string `yaml:"-"`
}

Manifest is a parsed SKILL.md. Frontmatter fields are typed; the body is retained verbatim (without the leading frontmatter block) for L2 delivery.

func LoadManifest

func LoadManifest(path string) (*Manifest, error)

LoadManifest reads SKILL.md from path and returns the parsed manifest. path must be the full path to the SKILL.md file (callers in catalog.go already know the skill dir; they join FileName themselves).

func ParseManifest

func ParseManifest(data []byte) (*Manifest, error)

ParseManifest reads a SKILL.md byte buffer and returns the parsed manifest. The buffer is split on the YAML frontmatter fences; the remainder is the body. Anything other than the leading `---` … `---\n` shape is an error because the spec requires frontmatter.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate runs every spec-required check on the manifest's frontmatter and body. It does not touch the filesystem; callers that load from disk should use LoadManifest, which calls Validate after parsing.

type Scope

type Scope int

Scope identifies where a skill manifest lives. Scope ordering is meaningful: when two skills share a name, the lower-numbered scope wins.

const (
	// ScopeRepo is a skill checked into the project at <repo>/.squad/skills/<name>/SKILL.md.
	ScopeRepo Scope = iota
	// ScopeGlobal is a user-level skill at $XDG_CONFIG_HOME/squad/skills/<name>/SKILL.md.
	ScopeGlobal
	// ScopeCatalog is a skill from a shared catalog — a git repo cloned under
	// the skills cache dir or a directory the user has registered via
	// skills.local_paths. Lowest precedence so local edits always win.
	ScopeCatalog
)

func ParseScope

func ParseScope(s string) (Scope, error)

ParseScope converts a CLI-supplied string to a Scope value.

func (Scope) String

func (s Scope) String() string

String returns the lowercase scope name used in CLI output and config.

type Severity

type Severity int

Severity classifies a validation finding. Errors block successful validation; warnings are surfaced but do not fail.

const (
	// SeverityError is a fatal validation finding.
	SeverityError Severity = iota
	// SeverityWarning is a non-fatal finding the author should address.
	SeverityWarning
)

func (Severity) String

func (s Severity) String() string

String renders the severity for CLI output.

type Stack

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

Stack is the per-run set of skill directories that have been activated via the Skill tool. While a skill is on the stack, the runner permits Read and Bash to operate on files inside that directory in addition to the working directory.

A stack rather than a single value because a skill is allowed (rarely) to invoke another skill mid-execution. Popping is not exposed — once activated a skill remains visible for the rest of the run, matching the spec expectation that "loaded" instructions remain in context.

All methods are safe for concurrent use; the stack is touched from the tool-dispatch goroutine and may be observed from background task workers.

func NewStack

func NewStack() *Stack

NewStack returns an empty stack.

func (*Stack) Contains

func (s *Stack) Contains(abs string) bool

Contains reports whether abs sits at or beneath any stacked skill dir. abs must already be cleaned and absolute.

func (*Stack) Entries

func (s *Stack) Entries() []Entry

Entries returns a snapshot of every entry on the stack, oldest first.

func (*Stack) Len

func (s *Stack) Len() int

Len reports the number of entries on the stack.

func (*Stack) Push

func (s *Stack) Push(e Entry) bool

Push adds an entry to the stack and reports whether it is now on the stack. Idempotent: re-pushing a skill already on the stack returns true without adding a duplicate. Returns false only when the entry is invalid (nil receiver or empty Dir) — Dir anchors the Read/Bash scope expansion, so an entry without one would be unusable. Callers that don't care about the result can discard it; tests should assert it to catch silent drops.

func (*Stack) Resolve

func (s *Stack) Resolve(input string) (string, bool)

Resolve interprets input the way the file tools do — absolute paths are taken as-is, relative paths are joined against the top-of-stack skill dir — and reports success only if the result is inside an active skill dir.

Returns ("", false) when the stack is empty or the path escapes every active skill dir. Callers fall back to the working-dir anchor in that case.

func (*Stack) Top

func (s *Stack) Top() (Entry, bool)

Top returns the most recently pushed entry. ok is false when the stack is empty.

func (*Stack) VerifyNoSymlinkEscape

func (s *Stack) VerifyNoSymlinkEscape(abs string) error

VerifyNoSymlinkEscape defends the relaxed read path against a skill dir that contains a symlink pointing outside itself. Resolve does a purely lexical containment check (it must, since callers resolve paths to files that may not exist yet); this method closes the gap for paths that DO exist by resolving symlinks on both the target and every active skill dir and re-checking containment on the real paths.

A path that does not exist is allowed through unchanged — lexical containment already held and the caller's file operation surfaces its own not-found error. An existing path that resolves outside every skill dir is rejected.

type ValidationReport

type ValidationReport struct {
	SkillDir string
	Findings []Finding
}

ValidationReport collects findings from validating a single skill dir. HasErrors reports whether any finding is a fatal error.

func Validate

func Validate(path string) (*ValidationReport, error)

Validate runs every spec-conformance check on the skill directory at path. It returns the report even when checks fail — callers render the report regardless. An error is returned only when path itself cannot be read.

func (ValidationReport) Errors

func (r ValidationReport) Errors() []Finding

Errors returns only the error-severity findings.

func (ValidationReport) HasErrors

func (r ValidationReport) HasErrors() bool

HasErrors reports whether the report contains at least one error-severity finding.

func (ValidationReport) Warnings

func (r ValidationReport) Warnings() []Finding

Warnings returns only the warning-severity findings.

Jump to

Keyboard shortcuts

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