Stages: optional skills block loading pinned library skills per visit
A model stage may declare a skills block (name or name@N per line). Drafts and publications are validated against the server skill library; human/ntfy stages reject the block. Each run resolves unpinned names to the latest version at admission and records name@N per stage (run stage_skills, step skills); retry reuses the recorded versions. Every visit gets a private read-only copy of exactly those bundles under the run's artifact tree, and the harness loads only them: Claude via a session plugin (--plugin-dir, Skill tool with per-skill allow rules, bundled skills off, ambient loads fail the visit), Pi via --skill under --no-skills, and OpenCode via per-session instruction entries (V2 only). The app shows the block in the stage definition and the resolved versions on each visit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -217,6 +217,12 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
|
||||
if c.Policy.Shell != nil {
|
||||
prompt += "\nPermitted shell commands: " + strings.Join(c.Policy.Shell, "; ")
|
||||
}
|
||||
if resume == "" {
|
||||
// Owned but not yet prompted: the deferred cleanup stops the session.
|
||||
if err = c.attachSkills(ctx, c.SessionID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
ctx, watch, err = c.watchBudget(ctx, config.Budget, c.SessionID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
||||
@@ -50,9 +50,12 @@ type ClaudeStageClient struct {
|
||||
Tools []string
|
||||
WritePaths []string
|
||||
ArtifactsDir string
|
||||
Policy ToolPolicy
|
||||
OnOwnership func(string, string, bool) error
|
||||
WorkStarted bool
|
||||
// Skills are the visit's configured skills, loaded as a session-only
|
||||
// plugin; nil keeps every skill and slash command disabled.
|
||||
Skills *SkillSet
|
||||
Policy ToolPolicy
|
||||
OnOwnership func(string, string, bool) error
|
||||
WorkStarted bool
|
||||
|
||||
budget *Budget
|
||||
// Session totals across the visit's invocations (the prompt and one
|
||||
@@ -145,20 +148,44 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
|
||||
return rules
|
||||
}
|
||||
|
||||
// claudeSkillSettings is the flag-settings layer of a Claude stage with
|
||||
// configured skills. --disable-slash-commands would also disable the plugin
|
||||
// skills, so ambient skills are turned off individually instead: user, project
|
||||
// and local settings (and their skills directories) are already not loaded,
|
||||
// disableBundledSkills turns off the skills that ship with Claude Code, and
|
||||
// the builtin plugin that contributes a model-invocable skill is disabled. The
|
||||
// stream guard (claudeSkillGuard) fails the visit if any other skill is
|
||||
// still invoked.
|
||||
const claudeSkillSettings = `{"disableBundledSkills":true,"enabledPlugins":{"cc-plugin-plugin-authoring@builtin":false}}`
|
||||
|
||||
func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort string, resume bool) []string {
|
||||
skilled := !c.Skills.Empty()
|
||||
// Permission rules come from the declared tools only: a bare Skill rule
|
||||
// would approve every skill, so each configured skill is approved by name.
|
||||
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir)
|
||||
if skilled {
|
||||
tools = append(append([]string(nil), tools...), "Skill")
|
||||
}
|
||||
args := []string{"-p", "--output-format", "stream-json", "--verbose",
|
||||
"--model", config.Model,
|
||||
"--permission-mode", "dontAsk",
|
||||
"--setting-sources", "",
|
||||
"--disable-slash-commands",
|
||||
"--tools", strings.Join(tools, ",")}
|
||||
"--setting-sources", ""}
|
||||
mcpRules, _ := claudeMCPAllowRules(c.Tools)
|
||||
if len(mcpRules) == 0 {
|
||||
tail := append([]string(nil), args[10:]...)
|
||||
args = append(append(append([]string(nil), args[:10]...), "--strict-mcp-config"), tail...)
|
||||
args = append(args, "--strict-mcp-config")
|
||||
}
|
||||
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir)
|
||||
if skilled {
|
||||
args = append(args, "--settings", claudeSkillSettings, "--plugin-dir", c.Skills.Root)
|
||||
} else {
|
||||
args = append(args, "--disable-slash-commands")
|
||||
}
|
||||
args = append(args, "--tools", strings.Join(tools, ","))
|
||||
rules = append(rules, mcpRules...)
|
||||
if skilled {
|
||||
for _, bundle := range c.Skills.Bundles {
|
||||
rules = append(rules, "Skill("+ClaudeSkillPlugin+":"+bundle.Name+")")
|
||||
}
|
||||
}
|
||||
if len(rules) > 0 {
|
||||
args = append(args, "--allowedTools")
|
||||
args = append(args, rules...)
|
||||
@@ -338,11 +365,55 @@ type claudeStreamRecord struct {
|
||||
} `json:"rate_limit_info"`
|
||||
Message *struct {
|
||||
Error string `json:"error"`
|
||||
// Content stays raw: a string content must not make the record
|
||||
// undecodable (it would drop the line from the evidence stream).
|
||||
Content json.RawMessage `json:"content"`
|
||||
} `json:"message"`
|
||||
}
|
||||
|
||||
// run executes one CLI invocation and returns its final result text. The
|
||||
// process group is always gone when it returns; otherwise ErrStageCleanup.
|
||||
// claudeContent is the part of a message content item the skill guard reads.
|
||||
type claudeContent struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ToolUseID string `json:"tool_use_id"`
|
||||
IsError bool `json:"is_error"`
|
||||
Input struct {
|
||||
Skill string `json:"skill"`
|
||||
} `json:"input"`
|
||||
}
|
||||
|
||||
// claudeSkillGuard tracks Skill tool calls for skills the visit did not
|
||||
// configure. A call Claude Code refuses (an unknown or disabled skill) is
|
||||
// harmless; one whose tool result succeeded loaded an ambient skill, which
|
||||
// fails the visit.
|
||||
type claudeSkillGuard struct {
|
||||
configured *SkillSet
|
||||
pending map[string]bool
|
||||
violated bool
|
||||
}
|
||||
|
||||
func (g *claudeSkillGuard) observe(record claudeStreamRecord) {
|
||||
if record.Message == nil || len(record.Message.Content) == 0 || record.Message.Content[0] != '[' {
|
||||
return
|
||||
}
|
||||
var items []claudeContent
|
||||
if json.Unmarshal(record.Message.Content, &items) != nil {
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
switch {
|
||||
case record.Type == "assistant" && item.Type == "tool_use" && item.Name == "Skill" && !g.configured.claudeAllowed(item.Input.Skill):
|
||||
if g.pending == nil {
|
||||
g.pending = map[string]bool{}
|
||||
}
|
||||
g.pending[item.ID] = true
|
||||
case record.Type == "user" && item.Type == "tool_result" && g.pending[item.ToolUseID] && !item.IsError:
|
||||
g.violated = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) {
|
||||
cmd := exec.Command(c.Executable, args...)
|
||||
cmd.Dir = c.Directory
|
||||
@@ -379,6 +450,7 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
|
||||
var refusal, limited bool
|
||||
var resetsAt int64
|
||||
var authFailed, sessionMismatch, modelMismatch bool
|
||||
skills := &claudeSkillGuard{configured: c.Skills}
|
||||
scanned := make(chan error, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(out)
|
||||
@@ -406,7 +478,10 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
|
||||
limited = true
|
||||
resetsAt = record.RateLimit.ResetsAt
|
||||
}
|
||||
case "user":
|
||||
skills.observe(record)
|
||||
case "assistant":
|
||||
skills.observe(record)
|
||||
if record.Message != nil {
|
||||
switch record.Message.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
@@ -480,6 +555,8 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
|
||||
return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan"))
|
||||
}
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota)
|
||||
case skills.violated:
|
||||
return "", fmt.Errorf("Claude Code invoked a skill that is not configured for this stage; only the stage's skills block may be used")
|
||||
case sessionMismatch || modelMismatch:
|
||||
return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport)
|
||||
case final == nil:
|
||||
|
||||
@@ -84,6 +84,16 @@ case "$FAKE_CLAUDE_CASE" in
|
||||
init "$session" "$model"
|
||||
echo '{"type":"result","subtype":"error_max_turns","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
skill|ambientskill|refusedskill)
|
||||
init "$session" "$model"
|
||||
name=pipelines-stage:hello; failed=false
|
||||
if [ "$FAKE_CLAUDE_CASE" != skill ]; then name=dataviz; fi
|
||||
if [ "$FAKE_CLAUDE_CASE" = refusedskill ]; then failed=true; fi
|
||||
echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":"a plain string content"}}'
|
||||
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Skill","input":{"skill":"'"$name"'"}}]}}'
|
||||
echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"Launching skill: '"$name"'","is_error":'"$failed"'}]}}'
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
othermodel)
|
||||
init "$session" "some-other-model"
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
|
||||
|
||||
@@ -24,6 +24,8 @@ func (HumanStage) Validate(def Definition) error {
|
||||
for name := range def.Blocks {
|
||||
switch name {
|
||||
case "configs", "edges", "output", "prompt":
|
||||
case "skills":
|
||||
return errSkillsModelOnly("human")
|
||||
default:
|
||||
return fmt.Errorf("unexpected block %q for human stage", name)
|
||||
}
|
||||
|
||||
+11
-2
@@ -3,6 +3,7 @@ package stage
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -58,7 +59,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
|
||||
}
|
||||
for block := range def.Blocks {
|
||||
switch block {
|
||||
case "output", "prompt", "edges", "configs", "tools", "permissions", "checks", "verification":
|
||||
case "output", "prompt", "edges", "configs", "tools", "permissions", "checks", "verification", "skills":
|
||||
default:
|
||||
return ModelSpec{}, fmt.Errorf("unexpected block %q for model stage", block)
|
||||
}
|
||||
@@ -69,6 +70,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
|
||||
if _, err := StagePermissions(def); err != nil {
|
||||
return ModelSpec{}, err
|
||||
}
|
||||
skillRefs, err := SkillRefs(def)
|
||||
if err != nil {
|
||||
return ModelSpec{}, err
|
||||
}
|
||||
if _, err := VerificationTargetFor(def); err != nil {
|
||||
return ModelSpec{}, err
|
||||
}
|
||||
@@ -113,10 +118,14 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
|
||||
return ModelSpec{}, err
|
||||
}
|
||||
if backend == "pi" {
|
||||
tools, _, _ := ToolNames(def)
|
||||
tools, explicit, _ := ToolNames(def)
|
||||
if _, err := piTools(tools); err != nil {
|
||||
return ModelSpec{}, err
|
||||
}
|
||||
if len(skillRefs) > 0 && explicit && !slices.Contains(tools, "read") {
|
||||
// Pi advertises a skill by path and the model reads its SKILL.md.
|
||||
return ModelSpec{}, fmt.Errorf("the pi harness loads skills with its read tool; add read to the tools block or remove the skills block")
|
||||
}
|
||||
}
|
||||
if backend != ClaudeBackend {
|
||||
tools, _, _ := ToolNames(def)
|
||||
|
||||
@@ -37,6 +37,8 @@ func (NtfyStage) Validate(def Definition) error {
|
||||
for name := range def.Blocks {
|
||||
switch name {
|
||||
case "configs", "edges", "output":
|
||||
case "skills":
|
||||
return errSkillsModelOnly("ntfy")
|
||||
default:
|
||||
return fmt.Errorf("unexpected block %q for ntfy stage", name)
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ type OpenCodeClient struct {
|
||||
ArtifactsDir string
|
||||
Operations *OperationLog
|
||||
OnGenerationSession func(id, backend, reference string, active bool) error
|
||||
// Skills are attached to each new session as instruction entries (see
|
||||
// attachSkills); nil attaches none.
|
||||
Skills *SkillSet
|
||||
connection *opencode.Connection
|
||||
command func(context.Context, string, ...string) ([]byte, error)
|
||||
sessionPollInterval time.Duration // test seam; defaults to defaultSessionPollInterval
|
||||
@@ -413,6 +416,11 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if resume == "" {
|
||||
if err = c.attachSkills(ctx, session.Data.ID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
ctx, watch, err = c.watchBudget(ctx, config.Budget, session.Data.ID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// OpenCode discovers skills per service location (config `skills` paths and
|
||||
// the standard skills directories), and a stage shares one long-lived service,
|
||||
// so a session cannot be given private skills through skill discovery. The
|
||||
// stage session's deny-all permission rules already keep OpenCode's own skill
|
||||
// tool, and with it every ambient skill, unavailable. The configured skills are
|
||||
// attached instead as durable per-session instruction entries (the V2
|
||||
// experimental session instructions API), one entry per skill carrying its
|
||||
// SKILL.md and the private directory holding its bundled files.
|
||||
|
||||
// openCodeSkillEntryKey is the instruction entry key for one skill.
|
||||
func openCodeSkillEntryKey(name string) string { return "pipelines-skill-" + name }
|
||||
|
||||
// openCodeSkillEntry is the instruction text for one materialised skill.
|
||||
func openCodeSkillEntry(bundle SkillBundle) (string, error) {
|
||||
data, err := os.ReadFile(filepath.Join(bundle.Dir, "SKILL.md"))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("skill %s@%d: read SKILL.md: %w", bundle.Name, bundle.Version, err)
|
||||
}
|
||||
return "Pipelines stage skill " + bundle.Name + " (version " + strconv.Itoa(bundle.Version) + ") is configured for this stage. " +
|
||||
"Follow its instructions below when the task calls for them. Its bundled files (references/, scripts/, assets/) are in " + bundle.Dir +
|
||||
" and are read-only.\n\n" + string(data), nil
|
||||
}
|
||||
|
||||
// attachSkills gives a freshly created, not yet prompted session the visit's
|
||||
// configured skills. A V1 service has no per-session instructions API, so a
|
||||
// configured skill fails the visit there rather than being silently dropped.
|
||||
func (c *OpenCodeClient) attachSkills(ctx context.Context, sessionID string) error {
|
||||
if c.Skills.Empty() {
|
||||
return nil
|
||||
}
|
||||
if c.Backend != "v2" {
|
||||
return fmt.Errorf("skills need the OpenCode V2 service (per-session instruction entries); this stage's OpenCode backend is %q", c.Backend)
|
||||
}
|
||||
if !sessionIDPattern.MatchString(sessionID) {
|
||||
return fmt.Errorf("OpenCode returned an invalid session ID")
|
||||
}
|
||||
for _, bundle := range c.Skills.Bundles {
|
||||
value, err := openCodeSkillEntry(bundle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.call(ctx, "put", "/api/experimental/session/"+sessionID+"/instructions/entries/"+openCodeSkillEntryKey(bundle.Name), map[string]string{"value": value}); err != nil {
|
||||
return fmt.Errorf("attach skill %s@%d to the OpenCode session: %w", bundle.Name, bundle.Version, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+24
-1
@@ -31,6 +31,9 @@ type PiClient struct {
|
||||
// PIPELINES_ARTIFACTS_DIR so its tools can write stage artifacts.
|
||||
ArtifactsDir string
|
||||
ArtifactAccess ArtifactAccess
|
||||
// Skills are loaded with --skill while --no-skills keeps every discovered
|
||||
// and configured skill out; nil loads none.
|
||||
Skills *SkillSet
|
||||
Policy ToolPolicy
|
||||
OnSession func(string, bool) error
|
||||
OnOwnership func(string, string, bool) error
|
||||
@@ -71,6 +74,11 @@ func piPolicyMap(c *PiClient, tools []string) map[string]any {
|
||||
if paths == nil {
|
||||
paths = []string{}
|
||||
}
|
||||
read := c.ArtifactAccess.Read
|
||||
if !c.Skills.Empty() {
|
||||
// The model reads each skill's SKILL.md and bundled files by path.
|
||||
read = append(append([]string(nil), read...), c.Skills.Root)
|
||||
}
|
||||
return map[string]any{
|
||||
"directory": c.Directory,
|
||||
"tools": tools,
|
||||
@@ -79,7 +87,7 @@ func piPolicyMap(c *PiClient, tools []string) map[string]any {
|
||||
"shell": c.Policy.Shell,
|
||||
"artifact_write": c.ArtifactAccess.Write,
|
||||
"artifact_write_shared": c.ArtifactAccess.WriteShared,
|
||||
"artifact_read": c.ArtifactAccess.Read,
|
||||
"artifact_read": read,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,6 +167,7 @@ func (c *PiClient) Generate(ctx context.Context, config ModelConfig, prompt stri
|
||||
if thinking != "" {
|
||||
args = append(args, "--thinking", thinking)
|
||||
}
|
||||
args = append(args, piSkillArgs(c.Skills)...)
|
||||
if len(tools) == 0 {
|
||||
args = append(args, "--no-tools")
|
||||
} else {
|
||||
@@ -652,3 +661,17 @@ func PiEvidence(reference string) (string, error) {
|
||||
data, err = io.ReadAll(io.LimitReader(file, 8<<20))
|
||||
return RedactEvidence(string(data)), err
|
||||
}
|
||||
|
||||
// piSkillArgs loads exactly the visit's configured skills. Pi documents that
|
||||
// explicit --skill paths still load under --no-skills, which keeps disabling
|
||||
// every discovered (user, project) and settings-configured skill.
|
||||
func piSkillArgs(set *SkillSet) []string {
|
||||
if set.Empty() {
|
||||
return nil
|
||||
}
|
||||
args := make([]string, 0, 2*len(set.Bundles))
|
||||
for _, bundle := range set.Bundles {
|
||||
args = append(args, "--skill", bundle.Dir)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/skills"
|
||||
)
|
||||
|
||||
// SkillRef is one entry of a model stage's `skills` block: a server skill
|
||||
// library name, pinned to Version when it is positive and otherwise resolved to
|
||||
// the library's latest version when the run starts.
|
||||
type SkillRef struct {
|
||||
Name string
|
||||
Version int
|
||||
}
|
||||
|
||||
// String renders the entry as written in a definition: name or name@N.
|
||||
func (r SkillRef) String() string {
|
||||
if r.Version > 0 {
|
||||
return r.Name + "@" + strconv.Itoa(r.Version)
|
||||
}
|
||||
return r.Name
|
||||
}
|
||||
|
||||
// ParseSkillRef parses one `name` or `name@N` entry. N must be a positive
|
||||
// integer without sign or leading zeros.
|
||||
func ParseSkillRef(text string) (SkillRef, error) {
|
||||
text = strings.TrimSpace(text)
|
||||
name, version, pinned := strings.Cut(text, "@")
|
||||
if err := skills.ValidateName(name); err != nil {
|
||||
return SkillRef{}, fmt.Errorf("invalid skill %q: %w", text, err)
|
||||
}
|
||||
ref := SkillRef{Name: name}
|
||||
if pinned {
|
||||
n, err := strconv.Atoi(version)
|
||||
if err != nil || n <= 0 || strconv.Itoa(n) != version {
|
||||
return SkillRef{}, fmt.Errorf("invalid skill %q: the version after @ must be a positive integer", text)
|
||||
}
|
||||
ref.Version = n
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
// SkillRefs parses a model stage's optional `skills` block, one entry per
|
||||
// line. An absent or empty block configures no skills. A skill may appear
|
||||
// only once, pinned or not.
|
||||
func SkillRefs(def Definition) ([]SkillRef, error) {
|
||||
text, present := def.Blocks["skills"]
|
||||
if !present {
|
||||
return nil, nil
|
||||
}
|
||||
var refs []SkillRef
|
||||
seen := map[string]bool{}
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
ref, err := ParseSkillRef(line)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if seen[ref.Name] {
|
||||
return nil, fmt.Errorf("duplicate skill %s", ref.Name)
|
||||
}
|
||||
seen[ref.Name] = true
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
// errSkillsModelOnly is the clear diagnostic for a skills block on a stage that
|
||||
// has no model session to load skills into.
|
||||
func errSkillsModelOnly(kind string) error {
|
||||
return fmt.Errorf("skills blocks are supported only on model stages, not %s stages", kind)
|
||||
}
|
||||
|
||||
// ClaudeSkillPlugin is the name of the per-visit plugin a Claude stage's
|
||||
// configured skills are loaded from; Claude Code names its skills
|
||||
// ClaudeSkillPlugin:<skill>.
|
||||
const ClaudeSkillPlugin = "pipelines-stage"
|
||||
|
||||
// SkillBundle is one resolved skill copied for a single stage visit. Dir holds
|
||||
// the bundle (SKILL.md and its references/, scripts/ and assets/).
|
||||
type SkillBundle struct {
|
||||
Name string
|
||||
Version int
|
||||
Dir string
|
||||
}
|
||||
|
||||
// SkillSet is the runtime-provided skill material for one model visit. Root is
|
||||
// the visit's private skills directory: it is also a Claude Code plugin root
|
||||
// (.claude-plugin/plugin.json) whose skills/<name>/ entries are the bundles.
|
||||
// A nil or empty set means the stage configured no skills.
|
||||
type SkillSet struct {
|
||||
Root string
|
||||
Bundles []SkillBundle
|
||||
}
|
||||
|
||||
// Empty reports whether the set configures no skills.
|
||||
func (s *SkillSet) Empty() bool { return s == nil || len(s.Bundles) == 0 }
|
||||
|
||||
// Names lists name@version for every bundle, in definition order.
|
||||
func (s *SkillSet) Names() []string {
|
||||
if s.Empty() {
|
||||
return nil
|
||||
}
|
||||
names := make([]string, 0, len(s.Bundles))
|
||||
for _, b := range s.Bundles {
|
||||
names = append(names, b.Name+"@"+strconv.Itoa(b.Version))
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// claudeAllowed reports whether a Claude Code Skill tool call names one of the
|
||||
// configured skills. Only the plugin-qualified name counts: a bare name could
|
||||
// be an ambient skill of the same name.
|
||||
func (s *SkillSet) claudeAllowed(name string) bool {
|
||||
if s.Empty() {
|
||||
return false
|
||||
}
|
||||
name = strings.TrimPrefix(strings.TrimSpace(name), "/")
|
||||
for _, b := range s.Bundles {
|
||||
if name == ClaudeSkillPlugin+":"+b.Name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSkillRefsParsePinsAndRejectMistakes(t *testing.T) {
|
||||
def := Definition{Blocks: map[string]string{"skills": "\n review-checklist \nrelease-notes@3\n\n"}}
|
||||
refs, err := SkillRefs(def)
|
||||
if err != nil || !slices.Equal(refs, []SkillRef{{Name: "review-checklist"}, {Name: "release-notes", Version: 3}}) {
|
||||
t.Fatal(refs, err)
|
||||
}
|
||||
if refs[0].String() != "review-checklist" || refs[1].String() != "release-notes@3" {
|
||||
t.Fatal(refs)
|
||||
}
|
||||
for _, text := range []string{"", "\n \n"} {
|
||||
if refs, err := SkillRefs(Definition{Blocks: map[string]string{"skills": text}}); err != nil || refs != nil {
|
||||
t.Fatalf("empty block %q: %v %v", text, refs, err)
|
||||
}
|
||||
}
|
||||
if refs, err := SkillRefs(Definition{}); err != nil || refs != nil {
|
||||
t.Fatal("absent block", refs, err)
|
||||
}
|
||||
for text, want := range map[string]string{
|
||||
"Bad_Name": "lowercase slug",
|
||||
"a@0": "positive integer",
|
||||
"a@-1": "positive integer",
|
||||
"a@01": "positive integer",
|
||||
"a@x": "positive integer",
|
||||
"a@": "positive integer",
|
||||
"a@1\nb\na@2": "duplicate skill a",
|
||||
"a\na": "duplicate skill a",
|
||||
"a b": "lowercase slug",
|
||||
"../etc@1": "lowercase slug",
|
||||
"review@1@2": "positive integer",
|
||||
"name@1 # note": "positive integer",
|
||||
} {
|
||||
if _, err := SkillRefs(Definition{Blocks: map[string]string{"skills": text}}); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%q: got %v, want %q", text, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillsBlockValidationByStageTypeAndHarness(t *testing.T) {
|
||||
model := modelDefinition()
|
||||
model.Blocks["skills"] = "review@2"
|
||||
if err := (ModelStage{}).Validate(model); err != nil {
|
||||
t.Fatal("opencode model stage:", err)
|
||||
}
|
||||
model.Blocks["skills"] = "review@0"
|
||||
if err := (ModelStage{}).Validate(model); err == nil {
|
||||
t.Fatal("a bad version must be rejected")
|
||||
}
|
||||
pi := modelDefinition()
|
||||
pi.Configs["harness"] = "pi"
|
||||
pi.Blocks["skills"] = "review"
|
||||
pi.Blocks["tools"] = "grep"
|
||||
if err := (ModelStage{}).Validate(pi); err == nil || !strings.Contains(err.Error(), "read tool") {
|
||||
t.Fatal("pi without read:", err)
|
||||
}
|
||||
pi.Blocks["tools"] = "read\ngrep"
|
||||
if err := (ModelStage{}).Validate(pi); err != nil {
|
||||
t.Fatal("pi with read:", err)
|
||||
}
|
||||
delete(pi.Blocks, "tools") // the legacy bundle includes read
|
||||
if err := (ModelStage{}).Validate(pi); err != nil {
|
||||
t.Fatal("pi legacy tools:", err)
|
||||
}
|
||||
human := Definition{Key: "ask", Type: HumanType, Blocks: map[string]string{"prompt": "Pick", "skills": "review"}, Edges: map[string]string{"yes": "#success", "error": "#failure"}}
|
||||
if err := (HumanStage{}).Validate(human); err == nil || !strings.Contains(err.Error(), "only on model stages") {
|
||||
t.Fatal("human:", err)
|
||||
}
|
||||
ntfy := Definition{Key: "tell", Type: NtfyType, Blocks: map[string]string{"skills": "review"}, Configs: map[string]string{"destination": "phone"}, Edges: map[string]string{"success": "#success", "error": "#failure"}}
|
||||
if err := (NtfyStage{}).Validate(ntfy); err == nil || !strings.Contains(err.Error(), "only on model stages") {
|
||||
t.Fatal("ntfy:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func testSkillSet(t *testing.T) *SkillSet {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
dir := filepath.Join(root, "skills", "hello")
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: hello\ndescription: Says hello.\n---\nSay hello.\n"), 0o400); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &SkillSet{Root: root, Bundles: []SkillBundle{{Name: "hello", Version: 2, Dir: dir}}}
|
||||
}
|
||||
|
||||
func TestClaudeStageSkillsLoadAsSessionPlugin(t *testing.T) {
|
||||
client, root, _ := fakeClaudeClient(t, "skill")
|
||||
client.Skills = testSkillSet(t)
|
||||
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := fakeClaudeArgs(t, root)
|
||||
want := []string{"-p", "--output-format", "stream-json", "--verbose", "--model", "claude-haiku-5-5",
|
||||
"--permission-mode", "dontAsk", "--setting-sources", "", "--strict-mcp-config",
|
||||
"--settings", claudeSkillSettings, "--plugin-dir", client.Skills.Root,
|
||||
"--tools", "Read,Skill", "--allowedTools", "Read", "Skill(pipelines-stage:hello)", "--session-id", client.SessionID}
|
||||
if len(calls) != 1 || !slices.Equal(calls[0], want) {
|
||||
t.Fatalf("args\n got %q\nwant %q", calls, want)
|
||||
}
|
||||
var settings map[string]any
|
||||
if err := json.Unmarshal([]byte(claudeSkillSettings), &settings); err != nil || settings["disableBundledSkills"] != true {
|
||||
t.Fatal("settings", settings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeStageAmbientSkillFailsTheVisit(t *testing.T) {
|
||||
client, _, _ := fakeClaudeClient(t, "ambientskill")
|
||||
client.Skills = testSkillSet(t)
|
||||
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err == nil || !strings.Contains(err.Error(), "not configured for this stage") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Without configured skills any loaded skill is a violation too.
|
||||
client, _, _ = fakeClaudeClient(t, "skill")
|
||||
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err == nil {
|
||||
t.Fatal("a skill call without configured skills must fail")
|
||||
}
|
||||
// A call Claude Code refused (unknown or disabled skill) loaded nothing.
|
||||
client, _, _ = fakeClaudeClient(t, "refusedskill")
|
||||
client.Skills = testSkillSet(t)
|
||||
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
|
||||
t.Fatal("a refused ambient skill call must not fail the visit:", err)
|
||||
}
|
||||
// String message content stays in the evidence stream.
|
||||
if !strings.Contains(client.Transcript, "a plain string content") {
|
||||
t.Fatal("string-content record dropped from the transcript")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPiSkillArgsAndReadScope(t *testing.T) {
|
||||
if args := piSkillArgs(nil); args != nil {
|
||||
t.Fatal(args)
|
||||
}
|
||||
set := testSkillSet(t)
|
||||
if args := piSkillArgs(set); !slices.Equal(args, []string{"--skill", set.Bundles[0].Dir}) {
|
||||
t.Fatal(args)
|
||||
}
|
||||
client := &PiClient{Directory: "/work", ArtifactAccess: ArtifactAccess{Read: []string{"/runs/1/stages/01-a"}}}
|
||||
if read := piPolicyMap(client, nil)["artifact_read"].([]string); len(read) != 1 {
|
||||
t.Fatal("no skills widened reads", read)
|
||||
}
|
||||
client.Skills = set
|
||||
if read := piPolicyMap(client, nil)["artifact_read"].([]string); !slices.Equal(read, []string{"/runs/1/stages/01-a", set.Root}) {
|
||||
t.Fatal(read)
|
||||
}
|
||||
if len(client.ArtifactAccess.Read) != 1 {
|
||||
t.Fatal("caller's read list mutated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPiLaunchesWithExplicitSkillsOnly(t *testing.T) {
|
||||
for _, skilled := range []bool{false, true} {
|
||||
root := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", root)
|
||||
t.Setenv("HOME", root)
|
||||
t.Setenv("PIPELINES_PI_FIXTURE", "1")
|
||||
t.Setenv("PI_FIXTURE_CASE", "success")
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wrapper := filepath.Join(root, "pi")
|
||||
script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > '" + filepath.Join(root, "args") + "'\nexec '" + executable + "' -test.run=^TestPiRPCFixture$\n"
|
||||
if err := os.WriteFile(wrapper, []byte(script), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &PiClient{Executable: wrapper, Directory: root, Tools: []string{"read"}}
|
||||
if skilled {
|
||||
client.Skills = testSkillSet(t)
|
||||
}
|
||||
if _, err := client.Generate(context.Background(), ModelConfig{Provider: "fixture", Model: "model", Budget: NewBudget(0, 100)}, "task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(root, "args"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := strings.Split(strings.TrimSpace(string(data)), "\n")
|
||||
if !slices.Contains(args, "--no-skills") {
|
||||
t.Fatal("--no-skills must stay", args)
|
||||
}
|
||||
index := slices.Index(args, "--skill")
|
||||
if skilled != (index >= 0) || (skilled && args[index+1] != client.Skills.Bundles[0].Dir) {
|
||||
t.Fatalf("skilled=%v args %q", skilled, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenCodeSkillsAttachAsSessionInstructionEntries(t *testing.T) {
|
||||
set := testSkillSet(t)
|
||||
var calls [][]string
|
||||
client := &OpenCodeClient{Backend: "v2", Skills: set, command: func(_ context.Context, _ string, args ...string) ([]byte, error) {
|
||||
calls = append(calls, args)
|
||||
return nil, nil
|
||||
}}
|
||||
if err := client.attachSkills(context.Background(), "ses_one"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(calls) != 1 || calls[0][1] != "put" || calls[0][2] != "/api/experimental/session/ses_one/instructions/entries/pipelines-skill-hello" {
|
||||
t.Fatal(calls)
|
||||
}
|
||||
var body map[string]string
|
||||
if err := json.Unmarshal([]byte(calls[0][4]), &body); err != nil || !strings.Contains(body["value"], "Say hello.") || !strings.Contains(body["value"], set.Bundles[0].Dir) || !strings.Contains(body["value"], "version 2") {
|
||||
t.Fatal(body, err)
|
||||
}
|
||||
calls = nil
|
||||
client.Skills = nil
|
||||
if err := client.attachSkills(context.Background(), "ses_one"); err != nil || calls != nil {
|
||||
t.Fatal("no skills must make no calls", calls, err)
|
||||
}
|
||||
client.Skills, client.Backend = set, "v1"
|
||||
if err := client.attachSkills(context.Background(), "ses_one"); err == nil || !strings.Contains(err.Error(), "V2") || calls != nil {
|
||||
t.Fatal("v1 must refuse configured skills", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenCodeAgentSkillsAttachBeforePromptAndGrantReads(t *testing.T) {
|
||||
client := &AgentClient{Tools: []string{"read"}}
|
||||
client.Directory = "/work"
|
||||
client.Backend = "v2"
|
||||
client.Skills = testSkillSet(t)
|
||||
allowed := false
|
||||
for _, rule := range client.permissionRules() {
|
||||
if rule["action"] == "external_directory" && rule["effect"] == "allow" && rule["resource"] == filepath.ToSlash(filepath.Join(client.Skills.Root, "*")) {
|
||||
allowed = true
|
||||
}
|
||||
if rule["action"] == "skill" && rule["effect"] == "allow" {
|
||||
t.Fatal("OpenCode's own skill tool must stay denied")
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
t.Fatal("configured skills must be readable")
|
||||
}
|
||||
var order []string
|
||||
client.command = func(_ context.Context, _ string, args ...string) ([]byte, error) {
|
||||
order = append(order, args[1]+" "+args[2])
|
||||
switch {
|
||||
case args[2] == "/api/session":
|
||||
return []byte(`{"data":{"id":"ses_owned"}}`), nil
|
||||
case strings.HasSuffix(args[2], "/prompt"):
|
||||
return nil, os.ErrDeadlineExceeded
|
||||
}
|
||||
return []byte(`{"data":[]}`), nil
|
||||
}
|
||||
_, _ = client.Generate(context.Background(), ModelConfig{}, "task")
|
||||
entry := slices.Index(order, "put /api/experimental/session/ses_owned/instructions/entries/pipelines-skill-hello")
|
||||
prompt := slices.Index(order, "post /api/session/ses_owned/prompt")
|
||||
if entry < 0 || prompt < 0 || entry > prompt {
|
||||
t.Fatal(order)
|
||||
}
|
||||
// Without read tools, no read grant is added for the skills directory.
|
||||
client.Tools = []string{}
|
||||
for _, rule := range client.permissionRules() {
|
||||
if rule["action"] == "external_directory" && rule["effect"] == "allow" {
|
||||
t.Fatal("text-only stages get no directory grants", rule)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,12 @@ type Definition struct {
|
||||
// visit; empty when the runner did not provide one (for example in tests).
|
||||
ArtifactsDir string
|
||||
Turn TurnPaths
|
||||
Blocks map[string]string
|
||||
Configs map[string]string
|
||||
Edges map[string]string
|
||||
// Skills is the visit's materialised skills block (runtime-provided, like
|
||||
// ArtifactsDir); nil when the stage configures none or in tests.
|
||||
Skills *SkillSet
|
||||
Blocks map[string]string
|
||||
Configs map[string]string
|
||||
Edges map[string]string
|
||||
}
|
||||
|
||||
// Result selects one declared outcome. The future graph runner owns resolving
|
||||
|
||||
@@ -293,7 +293,12 @@ func (c *AgentClient) permissionRules() []map[string]string {
|
||||
writeArtifacts = writeArtifacts || tool == "edit"
|
||||
}
|
||||
if readArtifacts {
|
||||
for _, directory := range c.ArtifactAccess.Read {
|
||||
read := c.ArtifactAccess.Read
|
||||
if !c.Skills.Empty() {
|
||||
// The configured skills' bundled references/, scripts/ and assets/.
|
||||
read = append(append([]string(nil), read...), c.Skills.Root)
|
||||
}
|
||||
for _, directory := range read {
|
||||
if artifactDirectory(directory) {
|
||||
allow("external_directory", filepath.ToSlash(filepath.Join(directory, "*")))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user