Files
coder/coderd/x/chatd/chattool/skill_test.go
T
Michael Suchacz 0a71846385 refactor(coderd/x/chatd/chattool): drop the read_skill alias fallback (#31123)
When `ReadSkillOptions.ResolveAlias` is nil, `read_skill` and
`read_skill_file` build a workspace skill from `GetSkills` and serve it.
Only tests leave the resolver nil. The one production caller,
`skillOpts` in `turn_environment.go`, always sets it to
`skillspkg.Lookup` over the merged personal, organization, project, and
workspace skills.

This PR deletes `resolveSkillAlias` and that fallback. Without a
resolver, both tools now return `skill alias resolver is not
configured`, as they already do for the other unset options. The tests
resolve names with the real `skillspkg.MergeSkills` and
`skillspkg.Lookup` instead of hand-written fakes. `read_skill_file`
still serves a workspace skill hidden from the model (#31147): it checks
for a nil resolver before `resolveSkillFileTarget`, which now calls
`ResolveAlias` directly. The PR adds 89 lines and removes 160.

## Why it is safe

- `git grep 'ReadSkillOptions{'` finds one non-test caller, and it sets
`ResolveAlias`. Behavior with a resolver does not change.
- `GetSkills` and `findSkill` stay. They still supply the pinned body,
the directory, and the supporting files of a resolved workspace skill.
- `TestReadSkillTool/ModelHiddenSkill` is deleted. It checked that the
fallback hid a skill that disables model invocation. With the real
resolver, `TestModelHiddenWorkspaceSkillsLeftOutOfModelSkills` checks
that, and it fails when the model-invocable filter in
`workspaceSkillsForResolution` is removed.
`ListedSkillServesFileThatDisablesModelInvocation` now sets a resolver.

Mutants of `skill.go` (`go test -overlay`, `-run TestReadSkill`), on
`main` at 27db7ace68 and on this branch:

| Mutant | Fails on `main` | Fails on this branch |
|---|---|---|
| Fallback restored (`skill.go` from `main`) | n/a |
`TestReadSkillToolsRequireAliasResolver` |
| No nil check in `ReadSkill`, or in `ReadSkillFile` | n/a |
`TestReadSkillToolsRequireAliasResolver` (nil function call) |
| Response `name` is `resolved.Alias` | nothing |
`PersonalQualifiedAliasPreservesAlias`, `WorkspaceQualifiedAlias` |
| Pinned body empty | `PinnedBodyFromMeta`,
`PinnedBodyServedWhenWorkspaceUnreachable`, `WorkspaceQualifiedAlias` |
the same, and `CollisionAliasRoundTrip` |
| 10 others: no `dir`, no supporting files, empty file content,
ambiguity reported as not found, resolver or loader error text returned,
deleted stored skill reported as a load failure, file read allowed for a
personal skill, hidden skill not matched, hidden skill meta file served
| at least one test each | the same tests |

A copy of `skill.go` with a syntax error fails to build in both runs, so
the overlay applies.

## Review focus

- The qualified alias tests are stronger. The fakes returned the alias
they got, so on `main` a tool that echoed `resolved.Alias` passed. The
real lookup resolves `personal/my-skill` to the bare alias `my-skill`,
so the tests now check that the tool returns the requested name.
- `CollisionAliasRoundTrip` no longer calls the resolver itself. It
checks each response body instead. The fake said that a bare `deploy`
was not found; the real lookup says it is ambiguous, which
`AmbiguousLookupSurfacesAliases` covers.
- `ResolveAliasErrorIsSanitized` keeps a fake, because the real lookup
returns only not-found and ambiguous errors.
- #29323 (plugin skills) replaces `ResolveAlias` and rewrites
`resolveSkillAlias`, so it conflicts with this PR. Whichever merges
second must reconcile.

## Validation

- `go test ./coderd/x/chatd/chattool/ -count=1`: pass.
- `go test ./coderd/x/chatd/chattool/ -race -count=3 -run Skill`: pass.
- `go test ./coderd/x/chatd/ -run Skill`: pass.
- `go vet ./coderd/x/chatd/chattool/ ./coderd/x/chatd/`: no issues.
- Mutants: each fails as listed.
- `make pre-commit` with `CODER_HOOK_RUN_ALL=1` passed.

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-30 21:52:43 +01:00

1064 lines
33 KiB
Go

package chattool_test
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"unicode/utf8"
"charm.land/fantasy"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/x/chatd/chattool"
skillspkg "github.com/coder/coder/v2/coderd/x/skills"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/codersdk/workspacesdk/agentconnmock"
)
// validSkillMD returns a valid SKILL.md with the given name and
// description.
func validSkillMD(name, description string) string {
return "---\nname: " + name + "\ndescription: " + description + "\n---\n\n# Instructions\n\nDo the thing.\n"
}
func responseName(t *testing.T, resp fantasy.ToolResponse) string {
t.Helper()
var payload struct {
Name string `json:"name"`
}
require.NoError(t, json.Unmarshal([]byte(resp.Content), &payload))
return payload.Name
}
// responseDir extracts the "dir" field from a read_skill response. It is
// empty when the field is absent, as it is for personal skills.
func responseDir(t *testing.T, resp fantasy.ToolResponse) string {
t.Helper()
var payload struct {
Dir string `json:"dir"`
}
require.NoError(t, json.Unmarshal([]byte(resp.Content), &payload))
return payload.Dir
}
// lookupSkills resolves aliases the way chatd does: it merges the sources and
// looks the alias up in the merged list.
func lookupSkills(sources ...skillspkg.SourceSkills) func(string) (skillspkg.ResolvedSkill, error) {
resolved := skillspkg.MergeSkills(sources...)
return func(alias string) (skillspkg.ResolvedSkill, error) {
return skillspkg.Lookup(resolved, alias)
}
}
func skillSource(source skillspkg.Source, name string) skillspkg.SourceSkills {
return skillspkg.SourceSkills{Source: source, Skills: []skillspkg.Skill{{Name: name}}}
}
func TestFormatResolvedSkillIndex(t *testing.T) {
t.Parallel()
t.Run("Empty", func(t *testing.T) {
t.Parallel()
assert.Empty(t, chattool.FormatResolvedSkillIndex(nil))
})
t.Run("PersonalOnly", func(t *testing.T) {
t.Parallel()
idx := chattool.FormatResolvedSkillIndex([]skillspkg.ResolvedSkill{{
Skill: skillspkg.Skill{
Name: "personal-review",
Description: "Personal review process",
Source: skillspkg.SourcePersonal,
},
Alias: "personal-review",
}})
assert.Contains(t, idx, "- personal-review: Personal review process")
assert.NotContains(t, idx, "read_skill_file")
assert.NotContains(t, idx, "qualified alias")
})
t.Run("WorkspaceOnlyMatchesLegacy", func(t *testing.T) {
t.Parallel()
resolved := []skillspkg.ResolvedSkill{{
Skill: skillspkg.Skill{
Name: "deep-review",
Description: "Review",
Source: skillspkg.SourceWorkspace,
},
Alias: "deep-review",
}}
assert.Equal(t,
"<available-skills>\n"+
"Use read_skill to load a skill's full instructions before following them.\n"+
"Use read_skill_file to read supporting files referenced by a workspace skill.\n"+
"\n"+
"- deep-review: Review\n"+
"</available-skills>",
chattool.FormatResolvedSkillIndex(resolved),
)
})
t.Run("MixedNonColliding", func(t *testing.T) {
t.Parallel()
idx := chattool.FormatResolvedSkillIndex([]skillspkg.ResolvedSkill{
{
Skill: skillspkg.Skill{
Name: "personal-review",
Description: "Personal review process",
Source: skillspkg.SourcePersonal,
},
Alias: "personal-review",
},
{
Skill: skillspkg.Skill{
Name: "deep-review",
Description: "Workspace review process",
Source: skillspkg.SourceWorkspace,
},
Alias: "deep-review",
},
})
assert.Contains(t, idx, "- personal-review: Personal review process")
assert.Contains(t, idx, "- deep-review: Workspace review process")
assert.Contains(t, idx, "read_skill_file")
assert.NotContains(t, idx, "personal/personal-review")
assert.NotContains(t, idx, "workspace/deep-review")
})
t.Run("CollidingNames", func(t *testing.T) {
t.Parallel()
resolved := skillspkg.MergeSkills(
skillspkg.SourceSkills{Source: skillspkg.SourcePersonal, Skills: []skillspkg.Skill{{Name: "review", Description: "Personal"}}},
skillspkg.SourceSkills{Source: skillspkg.SourceOrganization, Skills: []skillspkg.Skill{{Name: "review", Description: "Organization"}}},
skillspkg.SourceSkills{Source: skillspkg.SourceWorkspace, Skills: []skillspkg.Skill{{Name: "review", Description: "Workspace"}}},
)
idx := chattool.FormatResolvedSkillIndex(resolved)
assert.Contains(t, idx, "- personal/review: Personal\n- org/review: Organization\n- workspace/review: Workspace\n")
assert.Contains(t, idx, "\nWhen a skill is listed with a source prefix, such as personal/name, pass that qualified alias to read_skill.\n")
})
t.Run("TruncatesLongDescriptionsOnRuneBoundary", func(t *testing.T) {
t.Parallel()
// A 3-byte rune makes a byte-based cut at 1,024 split a rune.
atLimit := strings.Repeat("界", 1024)
idx := chattool.FormatResolvedSkillIndex(skillspkg.MergeSkills(
skillspkg.SourceSkills{Source: skillspkg.SourcePersonal, Skills: []skillspkg.Skill{
{Name: "at-limit", Description: atLimit},
{Name: "over-limit", Description: atLimit + "界tail"},
{Name: "short", Description: "Short description"},
}},
))
assert.True(t, utf8.ValidString(idx))
assert.Contains(t, idx, "- at-limit: "+atLimit+"\n")
assert.Contains(t, idx, "- over-limit: "+strings.Repeat("界", 1023)+"…\n")
assert.Contains(t, idx, "- short: Short description\n")
assert.NotContains(t, idx, "tail")
})
}
func TestLoadSkillFile(t *testing.T) {
t.Parallel()
t.Run("ValidFile", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill",
"roles/reviewer.md",
int64(0),
int64(512*1024+1),
).Return(
io.NopCloser(strings.NewReader("review instructions")),
"text/markdown",
nil,
)
content, err := chattool.LoadSkillFile(
context.Background(), conn, skill, "roles/reviewer.md",
)
require.NoError(t, err)
assert.Equal(t, "review instructions", content)
})
t.Run("PathTraversalRejected", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
_, err := chattool.LoadSkillFile(
context.Background(), conn, skill, "../../etc/passwd",
)
require.Error(t, err)
assert.Contains(t, err.Error(), "traversal")
})
t.Run("AbsolutePathRejected", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
_, err := chattool.LoadSkillFile(
context.Background(), conn, skill, "/etc/passwd",
)
require.Error(t, err)
assert.Contains(t, err.Error(), "absolute")
})
t.Run("HiddenFileRejected", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
_, err := chattool.LoadSkillFile(
context.Background(), conn, skill, ".git/config",
)
require.Error(t, err)
assert.Contains(t, err.Error(), "hidden")
})
t.Run("EmptyPathRejected", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
_, err := chattool.LoadSkillFile(
context.Background(), conn, skill, "",
)
require.Error(t, err)
assert.Contains(t, err.Error(), "required")
})
t.Run("OversizedFileTruncated", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
// Build a file that exceeds maxSkillFileBytes (512KB).
bigContent := strings.Repeat("x", 512*1024+100)
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill",
"large.txt",
int64(0),
int64(512*1024+1),
).Return(
io.NopCloser(strings.NewReader(bigContent)),
"text/plain",
nil,
)
content, err := chattool.LoadSkillFile(
context.Background(), conn, skill, "large.txt",
)
require.NoError(t, err)
assert.Equal(t, 512*1024, len(content),
"content should be truncated to maxSkillFileBytes")
})
}
func TestReadSkillTool(t *testing.T) {
t.Parallel()
t.Run("PinnedBodyFromMeta", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
// Meta carries the pushed SKILL.md, so the body is served from the
// pin: the conn must never be asked to ReadFile the SKILL.md. The
// supporting-file list is still a live, best-effort LS.
skills := []chattool.SkillMeta{{
Name: "my-skill",
Description: "test",
Dir: "/work/.agents/skills/my-skill",
Meta: []byte(validSkillMD("my-skill", "test")),
}}
conn.EXPECT().LS(gomock.Any(), "", gomock.Any()).Return(
workspacesdk.LSResponse{
Contents: []workspacesdk.LSFile{
{Name: "SKILL.md"},
{Name: "helper.md"},
},
}, nil,
)
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"my-skill"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError)
assert.Contains(t, resp.Content, "Do the thing.")
assert.Contains(t, resp.Content, "helper.md")
// Workspace skills expose the absolute skill directory so the
// model can reach supporting files with read_file/execute.
assert.Equal(t, "/work/.agents/skills/my-skill", responseDir(t, resp))
})
t.Run("PinnedBodyServedWhenWorkspaceUnreachable", func(t *testing.T) {
t.Parallel()
// With the body pinned, an unreachable workspace must not block
// read_skill: the body is returned and the file list degrades to empty.
skills := []chattool.SkillMeta{{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
Meta: []byte(validSkillMD("my-skill", "test")),
}}
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return nil, xerrors.New("workspace is stopped")
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"my-skill"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError)
assert.Contains(t, resp.Content, "Do the thing.")
assert.Contains(t, resp.Content, `"files":[]`)
// The dir comes from the pinned SkillMeta, so it is still
// returned even when the workspace is unreachable and the file
// list degrades to empty.
assert.Equal(t, "/work/.agents/skills/my-skill", responseDir(t, resp))
})
t.Run("PersonalSkill", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(skillSource(skillspkg.SourcePersonal, "my-skill")),
LoadStoredSkillBody: func(context.Context, skillspkg.Skill) (skillspkg.ParsedSkill, error) {
return skillspkg.ParsedSkill{
Skill: skillspkg.Skill{
Name: "my-skill",
Description: "test",
Source: skillspkg.SourcePersonal,
},
Body: "Personal instructions.",
}, nil
},
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"my-skill"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError)
assert.Contains(t, resp.Content, "Personal instructions.")
assert.Contains(t, resp.Content, `"files":[]`)
// Personal skills are database-backed and have no directory.
assert.Empty(t, responseDir(t, resp))
assert.NotContains(t, resp.Content, `"dir"`)
})
t.Run("PersonalQualifiedAliasPreservesAlias", func(t *testing.T) {
t.Parallel()
var loadedName string
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(skillSource(skillspkg.SourcePersonal, "my-skill")),
LoadStoredSkillBody: func(_ context.Context, skill skillspkg.Skill) (skillspkg.ParsedSkill, error) {
loadedName = skill.Name
return skillspkg.ParsedSkill{
Skill: skillspkg.Skill{
Name: "my-skill",
Description: "test",
Source: skillspkg.SourcePersonal,
},
Body: "Personal instructions.",
}, nil
},
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"personal/my-skill"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError)
assert.Equal(t, "personal/my-skill", responseName(t, resp))
assert.Equal(t, "my-skill", loadedName)
})
t.Run("WorkspaceQualifiedAlias", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skills := []chattool.SkillMeta{{
Name: "my-skill",
Description: "test",
Dir: "/work/.agents/skills/my-skill",
Meta: []byte(validSkillMD("my-skill", "test")),
}}
conn.EXPECT().LS(gomock.Any(), "", gomock.Any()).Return(
workspacesdk.LSResponse{}, nil,
)
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"workspace/my-skill"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError)
assert.Equal(t, "workspace/my-skill", responseName(t, resp))
assert.Contains(t, resp.Content, "Do the thing.")
assert.Equal(t, "/work/.agents/skills/my-skill", responseDir(t, resp))
})
t.Run("CollisionAliasRoundTrip", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
workspaceSkills := []chattool.SkillMeta{{
Name: "deploy",
Description: "workspace deploy",
Dir: "/work/.agents/skills/deploy",
Meta: []byte(validSkillMD("deploy", "workspace deploy")),
}}
conn.EXPECT().LS(gomock.Any(), "", gomock.Any()).Return(
workspacesdk.LSResponse{}, nil,
)
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return workspaceSkills },
ResolveAlias: lookupSkills(
skillSource(skillspkg.SourcePersonal, "deploy"),
skillSource(skillspkg.SourceWorkspace, "deploy"),
),
LoadStoredSkillBody: func(_ context.Context, skill skillspkg.Skill) (skillspkg.ParsedSkill, error) {
require.Equal(t, "deploy", skill.Name)
return skillspkg.ParsedSkill{
Skill: skillspkg.Skill{
Name: "deploy",
Description: "personal deploy",
Source: skillspkg.SourcePersonal,
},
Body: "Personal deploy instructions.",
}, nil
},
})
workspaceResp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"workspace/deploy"}`,
})
require.NoError(t, err)
assert.False(t, workspaceResp.IsError)
assert.Equal(t, "workspace/deploy", responseName(t, workspaceResp))
assert.Equal(t, "/work/.agents/skills/deploy", responseDir(t, workspaceResp))
assert.Contains(t, workspaceResp.Content, "Do the thing.")
personalResp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-2",
Name: "read_skill",
Input: `{"name":"personal/deploy"}`,
})
require.NoError(t, err)
assert.False(t, personalResp.IsError)
assert.Equal(t, "personal/deploy", responseName(t, personalResp))
assert.Contains(t, personalResp.Content, "Personal deploy instructions.")
})
t.Run("MissingPersonalSkill", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(skillSource(skillspkg.SourcePersonal, "missing-skill")),
LoadStoredSkillBody: func(context.Context, skillspkg.Skill) (skillspkg.ParsedSkill, error) {
return skillspkg.ParsedSkill{}, skillspkg.ErrSkillNotFound
},
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"missing-skill"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, `skill "missing-skill" not found`)
})
t.Run("PersonalSkillLoaderErrorIsSanitized", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(skillSource(skillspkg.SourcePersonal, "my-skill")),
LoadStoredSkillBody: func(context.Context, skillspkg.Skill) (skillspkg.ParsedSkill, error) {
return skillspkg.ParsedSkill{}, xerrors.New("synthetic private storage failure")
},
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"my-skill"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, `failed to load personal skill "my-skill"`)
assert.NotContains(t, resp.Content, "synthetic private storage failure")
})
t.Run("ResolveAliasErrorIsSanitized", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
ResolveAlias: func(string) (skillspkg.ResolvedSkill, error) {
return skillspkg.ResolvedSkill{}, xerrors.New("synthetic private resolver failure")
},
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"my-skill"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, `failed to resolve skill "my-skill"`)
assert.NotContains(t, resp.Content, "synthetic private resolver failure")
})
t.Run("AmbiguousLookupSurfacesAliases", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(
skillSource(skillspkg.SourcePersonal, "deploy"),
skillSource(skillspkg.SourceWorkspace, "deploy"),
),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"deploy"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "skill lookup is ambiguous")
assert.Contains(t, resp.Content, "personal/deploy")
assert.Contains(t, resp.Content, "workspace/deploy")
})
t.Run("UnknownSkill", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
t.Fatal("unexpected call to GetWorkspaceConn")
return nil, xerrors.New("unreachable")
},
ResolveAlias: lookupSkills(),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":"nonexistent"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "not found")
})
t.Run("EmptyName", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkill(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
t.Fatal("unexpected call to GetWorkspaceConn")
return nil, xerrors.New("unreachable")
},
GetSkills: func() []chattool.SkillMeta { return nil },
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill",
Input: `{"name":""}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "required")
})
}
func TestReadSkillFileTool(t *testing.T) {
t.Parallel()
t.Run("ValidFile", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skills := []chattool.SkillMeta{{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}}
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill",
"roles/reviewer.md",
int64(0),
int64(512*1024+1),
).Return(
io.NopCloser(strings.NewReader("reviewer guide")),
"text/markdown",
nil,
)
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"my-skill","path":"roles/reviewer.md"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError)
assert.Contains(t, resp.Content, "reviewer guide")
})
t.Run("PersonalSkillUnsupported", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(skillSource(skillspkg.SourcePersonal, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"my-skill","path":"helper.md"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "not supported for personal skills")
})
t.Run("AmbiguousLookupSurfacesAliases", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
ResolveAlias: lookupSkills(
skillSource(skillspkg.SourcePersonal, "deploy"),
skillSource(skillspkg.SourceWorkspace, "deploy"),
),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"deploy","path":"helper.md"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "skill lookup is ambiguous")
assert.Contains(t, resp.Content, "personal/deploy")
assert.Contains(t, resp.Content, "workspace/deploy")
})
// The model cannot resolve a skill hidden from it, but a person who
// invoked the skill needs the supporting files its body references.
modelHiddenSkills := []chattool.SkillMeta{{
Name: "manual",
Dir: "/work/.agents/skills/manual",
Meta: []byte("---\nname: manual\ndescription: Manual only\ndisable-model-invocation: true\n---\nRun scripts/run.sh.\n"),
}}
resolveNoModelSkills := func(alias string) (skillspkg.ResolvedSkill, error) {
return skillspkg.ResolvedSkill{}, xerrors.Errorf("%q: %w", alias, skillspkg.ErrSkillNotFound)
}
t.Run("ModelHiddenSkillServesSupportingFiles", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/manual",
"scripts/run.sh",
int64(0),
int64(512*1024+1),
).DoAndReturn(func(context.Context, string, string, int64, int64) (io.ReadCloser, string, error) {
return io.NopCloser(strings.NewReader("echo manual")), "text/plain", nil
}).Times(2)
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return modelHiddenSkills },
ResolveAlias: resolveNoModelSkills,
})
for _, name := range []string{"manual", "workspace/manual"} {
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-" + name,
Name: "read_skill_file",
Input: `{"name":"` + name + `","path":"scripts/run.sh"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError, resp.Content)
assert.Contains(t, resp.Content, "echo manual")
}
})
t.Run("ModelHiddenSkillRefusesMetaFile", func(t *testing.T) {
t.Parallel()
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
t.Fatal("unexpected call to GetWorkspaceConn")
return nil, xerrors.New("unreachable")
},
GetSkills: func() []chattool.SkillMeta { return modelHiddenSkills },
ResolveAlias: resolveNoModelSkills,
})
for _, path := range []string{"SKILL.md", "skill.md", "SKILL.md/"} {
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-" + path,
Name: "read_skill_file",
Input: `{"name":"workspace/manual","path":"` + path + `"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "cannot be read with read_skill_file")
}
})
t.Run("ListedSkillServesFileThatDisablesModelInvocation", func(t *testing.T) {
t.Parallel()
const content = "---\nname: example\ndescription: example\ndisable-model-invocation: true\n---\nCodeword.\n"
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/auto-helper",
"example-skill.md",
int64(0),
int64(512*1024+1),
).Return(io.NopCloser(strings.NewReader(content)), "text/markdown", nil)
skills := []chattool.SkillMeta{{
Name: "auto-helper",
Dir: "/work/.agents/skills/auto-helper",
Meta: []byte("---\nname: auto-helper\ndescription: Listed\n---\nHelp.\n"),
}}
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "auto-helper")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"auto-helper","path":"example-skill.md"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError, resp.Content)
assert.Contains(t, resp.Content, "Codeword.")
})
t.Run("ModelHiddenSkillBareNameSharedWithStoredSkill", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/manual",
"scripts/run.sh",
int64(0),
int64(512*1024+1),
).DoAndReturn(func(context.Context, string, string, int64, int64) (io.ReadCloser, string, error) {
return io.NopCloser(strings.NewReader("echo manual")), "text/plain", nil
})
// The model sees only the stored skills, so the bare name is
// ambiguous among them.
listed := skillspkg.MergeSkills(skillspkg.SourceSkills{
Source: skillspkg.SourcePersonal,
Skills: []skillspkg.Skill{{Name: "manual", Source: skillspkg.SourcePersonal}},
}, skillspkg.SourceSkills{
Source: skillspkg.SourceOrganization,
Skills: []skillspkg.Skill{{Name: "manual", Source: skillspkg.SourceOrganization}},
})
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return modelHiddenSkills },
ResolveAlias: func(alias string) (skillspkg.ResolvedSkill, error) {
return skillspkg.Lookup(listed, alias)
},
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-bare",
Name: "read_skill_file",
Input: `{"name":"manual","path":"scripts/run.sh"}`,
})
require.NoError(t, err)
assert.False(t, resp.IsError, resp.Content)
assert.Contains(t, resp.Content, "echo manual")
resp, err = tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-qualified",
Name: "read_skill_file",
Input: `{"name":"personal/manual","path":"scripts/run.sh"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "not supported for personal skills")
})
t.Run("AgentRefusalIsToolError", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill",
"refs.md",
int64(0),
int64(512*1024+1),
).Return(nil, "", xerrors.New("openat refs.md: path escapes from parent"))
skills := []chattool.SkillMeta{{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}}
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
return conn, nil
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"my-skill","path":"refs.md"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "path escapes from parent")
})
t.Run("AgentErrorsAreRewrittenForModel", func(t *testing.T) {
t.Parallel()
escape := codersdk.NewTestError(http.StatusBadRequest, http.MethodGet, "http://agent/api/v0/read-file?root=%2Fsecret")
escape.Message = "openat refs.md: path escapes from parent"
outdated := codersdk.NewTestError(http.StatusBadRequest, http.MethodGet, "http://agent/api/v0/read-file?root=%2Fsecret")
outdated.Message = "Query parameters have invalid values."
outdated.Validations = []codersdk.ValidationError{{Field: "root", Detail: `"root" is not a valid query param`}}
for _, tc := range []struct {
name string
err error
want string
}{
{name: "Refusal", err: escape, want: "read skill file: openat refs.md: path escapes from parent"},
{name: "OutdatedAgent", err: outdated, want: "read skill file: the workspace agent is outdated; restart the workspace to read skill files"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ReadFileInRoot(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
Return(nil, "", tc.err)
skills := []chattool.SkillMeta{{Name: "my-skill", Dir: "/work/.agents/skills/my-skill"}}
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) { return conn, nil },
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"my-skill","path":"refs.md"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Equal(t, tc.want, resp.Content)
})
}
})
t.Run("TraversalRejected", func(t *testing.T) {
t.Parallel()
skills := []chattool.SkillMeta{{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}}
tool := chattool.ReadSkillFile(chattool.ReadSkillOptions{
GetWorkspaceConn: func(context.Context) (workspacesdk.AgentConn, error) {
t.Fatal("unexpected call to GetWorkspaceConn")
return nil, xerrors.New("unreachable")
},
GetSkills: func() []chattool.SkillMeta { return skills },
ResolveAlias: lookupSkills(skillSource(skillspkg.SourceWorkspace, "my-skill")),
})
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: "read_skill_file",
Input: `{"name":"my-skill","path":"../../etc/passwd"}`,
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "traversal")
})
}
func TestReadSkillToolsRequireAliasResolver(t *testing.T) {
t.Parallel()
// GetSkills lists a readable workspace skill, but without a resolver the
// tools must not guess that the name refers to it.
options := chattool.ReadSkillOptions{
GetSkills: func() []chattool.SkillMeta {
return []chattool.SkillMeta{{
Name: "my-skill",
Meta: []byte(validSkillMD("my-skill", "test")),
}}
},
}
for _, tool := range []fantasy.AgentTool{
chattool.ReadSkill(options),
chattool.ReadSkillFile(options),
} {
name := tool.Info().Name
resp, err := tool.Run(context.Background(), fantasy.ToolCall{
ID: "call-1",
Name: name,
Input: `{"name":"my-skill","path":"helper.md"}`,
})
require.NoError(t, err, name)
assert.True(t, resp.IsError, name)
assert.Contains(t, resp.Content, "skill alias resolver is not configured", name)
}
}