Files
magpie/internal/library/skill_file.go
T
yetone 2a19043afc library: a skill's files are read as Markdown and edited in the page (refeccd)
refeccd on Discord kept skills in ~/.agents/skills, handed them over to
magpie ("let magpie manage"), and then had nowhere to edit them: the
Library's skill view showed SKILL.md as raw text with no way to change
it. There never was an edit path; this adds one.

- GET /api/library/skill takes `file` and answers library.ReadSkillFile:
  the file (SKILL.md by default), its text, the skill's folder and its
  text files (UTF-8, no NUL, up to 1 MB each, 200 listed, SKILL.md first;
  links, hidden folders and what installing writes left out).
- POST /api/library/skills/save {name, file, text, was} is
  library.SaveSkillFile, through change(): it writes only a regular
  file already in the skill's library folder (no .., no absolute path,
  no link, no folder that is a link out of the skill, nothing under
  node_modules/.venv/…), refuses when the file no longer holds `was`
  (the text the page opened), keeps CRLF line ends, and writes with
  edit.WriteAtomic. The sync after it reaches every agent: a linked
  one reads the library's folder, a copy is made again. A copy edited in
  an agent before the save is older, so takeEdits sets it aside in the
  backups. A GitHub skill saved here reads as Changed here, so an update
  asks first.
- The page (viewSkill in plugins/library/client.js) draws a Markdown
  file with the Plugins page's own renderer (plugins.js exports it as
  window.mdRender, 27 bytes of core script) and its front matter as
  rows; other files as text. Edit swaps in a text box; Save or ⌘S/Ctrl+S
  sends it; Cancel asks when there are changes. Other files are the
  app's menu under the name (no native select). New code is in the
  library plugin, so the core script budget is not raised.
- SkillText is gone (its only caller was the route). One new string, in
  all five languages. docs/subsystems/library.md says all this.

Run on mote at the change rebased on 9335e23d3:
- go test -count=1 -timeout 45m ./internal/library ./internal/gui
  ./internal/cli: library ok. gui: TestCoreScriptBudget passes; the only
  red is TestMainWindowCorners/macOS_26_SDK (#3949, mote's macOS 27).
  cli: the only red is TestEveryRouteHasACommandOrIsNamed on GET
  /api/context/reply (#5026, from 0872bc2a0). Both are red on main and
  filed.
- GOOS=linux and GOOS=windows go vet -tags nogui on the three packages;
  gofmt -l clean.
- skill-edit.test.cjs: 22/22 (chromium and webkit; en, zh, zh-TW, ja,
  de; 860px and 400px). It checks the drawn Markdown and front matter,
  no sideways scroll, ⌘S posting the exact body with `was`, the status,
  the file menu, Cancel sending nothing, Save on a second file, no click
  scrolling the page, no left-border stripe or gradient. i18n-keys ok.
- Whole GUI suite (a new API call), on the Linux box (wsl-run; mote had
  two other full suites): ~4460 of its results in at the push, not
  finished. Its reds are all WebKit and none is in a file this touches.
  The ones near it, run alone at this change and at origin/main
  bc10a6198: click-scroll, found-skill-pick-remove and account-eye fail
  the same on both (#4385, #4097/#5013, #4244).

Again at the pushed head (rebased on b967b1620; its commits change
app.js and the core budget), on the Linux box: TestCoreScriptBudget ok,
go test ./internal/library ok, gofmt -l clean, skill-edit.test.cjs and
i18n-keys 26/26.

Broken by hand: without the `was` check, without the linked-folder check
and without the CRLF handling, TestSkillFileSaveRefusesAChangedFile,
TestSkillFileStaysInTheSkill and TestSkillFileKeepsLineEnds each went red.
skill-edit.test.cjs on the old assets: 0/11 in chromium (.lib-mdview
never appears).

Not tried: refeccd's own skills (the fixture is a made-up handover from
~/.agents/skills, with a copy agent and a link agent); the real app
window (the GUI tests fake the API); the TUI and CLI, which have no
editor; making, renaming or removing a file from the page; Windows.
2026-11-03 16:33:03 +08:00

222 lines
6.5 KiB
Go

package library
// A skill's files read and edited in the page (refeccd on Discord: skills
// handed over to magpie from ~/.agents/skills could no longer be edited
// there, where the user used to). What is saved goes into the library's
// folder of the skill, so every agent linked to it reads it at once, and
// the sync that follows makes each agent's copy again. A copy edited in an
// agent meanwhile loses to the newer save and is kept aside with the
// backups (takeEdits). A skill from GitHub saved here is changed here
// (editState): an update asks before it replaces the edit.
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"unicode/utf8"
"github.com/yetone/magpie/internal/edit"
)
const (
skillFileMax = 1 << 20 // a text file larger than this is not opened in the page
skillFilesMax = 200 // the files listed of one skill
)
// SkillFile is one file of a library skill as the page reads it.
type SkillFile struct {
File string `json:"file"` // its place in the skill's folder, with /
Text string `json:"text"` // what it holds
Path string `json:"path"` // the skill's folder
Files []string `json:"files"` // the skill's text files, SKILL.md first
}
// ReadSkillFile is the file of a library skill at file (SKILL.md when
// empty), with the skill's other text files listed.
func ReadSkillFile(name, file string) (*SkillFile, error) {
if err := checkName("skill", name); err != nil {
return nil, err
}
if file == "" {
file = "SKILL.md"
}
root := realDir(skillDir(name))
p, err := skillFilePath(root, file)
if err != nil {
return nil, err
}
text, err := readSkillText(p)
if err != nil {
if file == "SKILL.md" && errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("%s has no SKILL.md in the library", name)
}
return nil, err
}
return &SkillFile{File: filepath.ToSlash(filepath.Clean(file)), Text: text, Path: skillDir(name), Files: skillTextFiles(root)}, nil
}
// SaveSkillFile writes text into the file of a library skill at file, and
// gives the skill to its agents again. was is the text the page opened:
// when the file holds something else now (an agent, an update or the user
// changed it since), nothing is written, and the error says so.
func SaveSkillFile(name, file, text, was string) (*Result, error) {
if err := checkName("skill", name); err != nil {
return nil, err
}
return change(func(l *Library) error {
if l.skill(name) == nil {
return fmt.Errorf("no skill called %s", name)
}
p, err := skillFilePath(realDir(skillDir(name)), file)
if err != nil {
return err
}
cur, err := readSkillText(p)
if err != nil {
return err
}
if cur != was {
return fmt.Errorf("%s was changed since it was opened; open it again to see what it holds now", file)
}
// the line ends the file was written with: the page's text has \n
if strings.Contains(cur, "\r\n") {
text = strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\n", "\r\n")
}
if text == cur {
return nil
}
if len(text) > skillFileMax {
return fmt.Errorf("%s would be over %d KB", file, skillFileMax>>10)
}
return edit.WriteAtomic(p, []byte(text))
})
}
// skillFilePath is the file at rel in the skill's folder root: a place in
// it, not a link, and none of the folders magpie leaves aside.
func skillFilePath(root, rel string) (string, error) {
rel = filepath.FromSlash(rel)
if rel == "" || !filepath.IsLocal(rel) {
return "", fmt.Errorf("%q is not a file of the skill", rel)
}
for _, part := range strings.Split(filepath.Clean(rel), string(filepath.Separator)) {
if skipInSkill(part) || installedDirs[part] {
return "", fmt.Errorf("%q is not a file of the skill", rel)
}
}
p := filepath.Join(root, rel)
fi, err := os.Lstat(p)
if err != nil {
return "", err
}
if !fi.Mode().IsRegular() {
return "", fmt.Errorf("%s is not a file magpie opens: it is a link or a folder", filepath.ToSlash(rel))
}
// a folder in it that is a link leads out of the skill
if dir, err := filepath.EvalSymlinks(filepath.Dir(p)); err != nil {
return "", err
} else if r, err := filepath.EvalSymlinks(root); err != nil {
return "", err
} else if dir != r && !strings.HasPrefix(dir, r+string(filepath.Separator)) {
return "", fmt.Errorf("%s is outside the skill's folder", filepath.ToSlash(rel))
}
return p, nil
}
// readSkillText is the file at p as text: one too large, or not text, is
// refused rather than shown garbled or written back changed.
func readSkillText(p string) (string, error) {
f, err := os.Open(p)
if err != nil {
return "", err
}
defer f.Close()
b, err := io.ReadAll(io.LimitReader(f, skillFileMax+1))
if err != nil {
return "", err
}
if len(b) > skillFileMax {
return "", fmt.Errorf("%s is over %d KB, too large to open here", filepath.Base(p), skillFileMax>>10)
}
if !isText(b) {
return "", fmt.Errorf("%s is not a text file", filepath.Base(p))
}
return string(b), nil
}
func isText(b []byte) bool { return utf8.Valid(b) && !bytes.Contains(b, []byte{0}) }
// skillTextFiles lists the text files in the skill's folder, SKILL.md
// first, then by place; the folders installing it makes, version
// control's and links are left out.
func skillTextFiles(root string) []string {
var out []string
filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if p == root {
return nil
}
name := d.Name()
if d.IsDir() {
if skipInSkill(name) || installedDirs[name] || strings.HasPrefix(name, ".") {
return filepath.SkipDir
}
return nil
}
if len(out) >= skillFilesMax {
return filepath.SkipAll
}
if !d.Type().IsRegular() || skipInSkill(name) || fromInstall(name, false, true) {
return nil
}
fi, err := d.Info()
if err != nil || fi.Size() > skillFileMax {
return nil
}
if !headIsText(p) {
return nil
}
rel, _ := filepath.Rel(root, p)
out = append(out, filepath.ToSlash(rel))
return nil
})
slices.SortStableFunc(out, func(a, b string) int {
if (a == "SKILL.md") != (b == "SKILL.md") {
if a == "SKILL.md" {
return -1
}
return 1
}
return strings.Compare(a, b)
})
return out
}
// headIsText is whether the file's first 8 KB read as text, a rune cut at
// the end allowed.
func headIsText(p string) bool {
f, err := os.Open(p)
if err != nil {
return false
}
defer f.Close()
b := make([]byte, 8<<10)
n, _ := io.ReadFull(f, b)
b = b[:n]
if bytes.Contains(b, []byte{0}) {
return false
}
for i := 0; i < utf8.UTFMax && len(b) > 0 && !utf8.Valid(b); i++ {
b = b[:len(b)-1]
}
return utf8.Valid(b)
}