Files
magpie/internal/library/skilltree.go
T
yetone 4794de398e library: a skill installs from a repository too big to download whole, by fetching only its skills' folders (#1941, Goalonez)
What changed: fetch still downloads a repository as one codeload
tarball first. When its files pass the 200 MB limit (untar's errTooBig),
it now falls back to fetchSkillFiles: one request to GitHub's API for
the repository's file list (git/trees?recursive=1), then every file in
a folder with a SKILL.md, from raw.githubusercontent.com, each checked
against the git hash the list gives. The repository's folders are made
empty, so candidates, origin, a probe of a subfolder and an update check
read the result as they read a whole download. The 200 MB limit now
applies to what is actually fetched: skills that are themselves over it
still say so. A private repository's files come from the API's
git/blobs with the Settings token (it never goes to raw). A repository
found too big is remembered for the run, so the install after its probe,
and update checks, don't download 150 MB again before falling back.
gitTree's entries gained mode, sha and size (named gitEntry).

Why: vectorize-io/hindsight keeps its skills (a few hundred KB) beside
an app; its tarball is 188 MB gzipped, 253 MB unpacked, so any skill
in it failed with "the repository is too big to install skills from".

What was run:
- Real repo, sandbox HOME, no token: on the old code ProbeSkills
  ("https://github.com/vectorize-io/hindsight") fails with "too big"
  after 34s. With the fix it lists all 15 skills (skills/*, the
  integrations' skills; .claude/skills hidden as before) in 32s, and
  installing skills/hindsight-docs writes its 160 files, the same count
  GitHub's tree lists.
- New TestSkillsFromATooBigRepository and
  TestTooBigRepositoryChecksWhatArrives (httptest stand-ins for codeload,
  the API and raw, laid out as hindsight is, paths and tree entries
  from its real listing). With the fallback taken out both fail with
  "the repository is too big to install skills from (over 200 MB)".
  They check raw is never asked for a file outside a skill, codeload
  is asked once across two probes, a file that doesn't match its hash
  is refused, and skills over the limit themselves still error.
- go test -tags nogui ./internal/library (ok, 141s); -race -count=10
  -run TooBig (ok); gofmt -l clean; go vet, GOOS=linux and
  GOOS=windows go vet -tags nogui ./internal/library clean.
Not tried: a private repository over the limit against real GitHub
(covered only by reading: raw 404 -> git/blobs with the token).
2026-10-13 14:53:42 +08:00

233 lines
6.3 KiB
Go

package library
import (
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
slash "path" // a repository's paths, always with /
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/source"
)
// ---- fetching only a repository's skills ----------------------------------
//
// A repository that is mostly something else, an app with its skills in a
// folder beside it (vectorize-io/hindsight: 250 MB, its skills a few KB,
// #1941), is more than the whole-repository download takes. Its skills'
// folders alone are fetched instead: GitHub's API lists the files (one
// request), and each file in a folder with a SKILL.md is read from
// raw.githubusercontent.com, checked against the hash the list gives.
// maxFetch is the most a repository's files, or its skills' files, may
// come to on disk; a variable for tests.
var maxFetch int64 = 200 << 20
var errTooBig = errors.New("the repository is too big to install skills from (over 200 MB)")
// tooBig is the repositories found too big this run: fetched again (an
// install after its probe, an update check), they go straight to their
// skills' folders rather than download the whole of it again first.
var tooBig = &repoSet{m: map[string]bool{}}
type repoSet struct {
sync.Mutex
m map[string]bool
}
func (t *repoSet) key(src Source) string { return strings.ToLower(src.Repo) + "@" + src.Ref }
func (t *repoSet) has(src Source) bool {
t.Lock()
defer t.Unlock()
return t.m[t.key(src)]
}
func (t *repoSet) add(src Source) {
t.Lock()
defer t.Unlock()
t.m[t.key(src)] = true
}
// rawURL is where a file of a repository at a ref is read from; a variable
// for tests.
var rawURL = func(repo, ref, path string) string {
if ref == "" {
ref = "HEAD"
}
parts := strings.Split(path, "/")
for i, p := range parts {
parts[i] = url.PathEscape(p)
}
return "https://raw.githubusercontent.com/" + repo + "/" + url.PathEscape(ref) + "/" + strings.Join(parts, "/")
}
// fetchSkillFiles fetches, into a new folder laid out as the repository
// is, every folder of it with a SKILL.md, whatever is in it, and the
// repository's other folders empty: what candidates, origin and an update
// read of a fetched repository.
func fetchSkillFiles(src Source) (string, error) {
tree, err := repoTree(src.Repo, src.Ref)
if err != nil {
return "", err
}
if tree.Truncated {
// too many files for GitHub to list in one answer
return "", errTooBig
}
var skillDirs []string
for _, e := range tree.Tree {
if e.Type == "blob" && slash.Base(e.Path) == "SKILL.md" {
skillDirs = append(skillDirs, slash.Dir(e.Path))
}
}
inSkill := func(p string) bool {
for _, d := range skillDirs {
if d == "." || strings.HasPrefix(p, d+"/") {
return true
}
}
return false
}
type file struct {
path, sha string
exec bool
}
var files []file
total := int64(0)
for _, e := range tree.Tree {
// links and submodules are left out, as the whole download leaves
// them out
if e.Type != "blob" || e.Mode == "120000" || !inSkill(e.Path) {
continue
}
if total += e.Size; total > maxFetch {
return "", fmt.Errorf("the skills in %s are too big to install (over 200 MB)", src.Repo)
}
files = append(files, file{e.Path, e.SHA, e.Mode == "100755"})
}
tmp, err := os.MkdirTemp("", "magpie-skill-")
if err != nil {
return "", err
}
place := func(p string) (string, bool) {
dst := filepath.Join(tmp, filepath.FromSlash(p))
return dst, strings.HasPrefix(dst, tmp+string(filepath.Separator)) // never outside
}
for _, e := range tree.Tree {
if e.Type == "tree" {
if dst, ok := place(e.Path); ok {
if err := os.MkdirAll(dst, 0o755); err != nil {
os.RemoveAll(tmp)
return "", err
}
}
}
}
c := &http.Client{Timeout: time.Minute}
work := make(chan file)
errs := make(chan error, len(files))
var wg sync.WaitGroup
for range min(8, len(files)) {
wg.Add(1)
go func() {
defer wg.Done()
for f := range work {
dst, ok := place(f.path)
if !ok {
continue
}
if err := fetchBlob(c, src, f.path, f.sha, dst, f.exec); err != nil {
errs <- err
}
}
}()
}
for _, f := range files {
work <- f
}
close(work)
wg.Wait()
close(errs)
if err := <-errs; err != nil {
os.RemoveAll(tmp)
return "", err
}
return tmp, nil
}
// fetchBlob writes one file of the repository to dst: from
// raw.githubusercontent.com, or for a private repository from GitHub's API
// with the user's token. What arrives must hash to the sha GitHub's list
// gave it.
func fetchBlob(c *http.Client, src Source, path, sha, dst string, exec bool) error {
token := false
get := func(u, accept string) (*http.Response, error) {
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("User-Agent", "magpie")
if accept != "" {
req.Header.Set("Accept", accept)
}
token = withGitHubToken(req)
return source.DoOfficial(c, req)
}
resp, err := get(rawURL(src.Repo, src.Ref, path), "")
if err != nil {
return fmt.Errorf("couldn't reach GitHub: %w", err)
}
if resp.StatusCode == 404 {
if t, _ := GitHubToken(); t != "" {
resp.Body.Close()
if resp, err = get(githubAPI+"/repos/"+src.Repo+"/git/blobs/"+url.PathEscape(sha), "application/vnd.github.raw"); err != nil {
return fmt.Errorf("couldn't reach GitHub: %w", err)
}
}
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if e, ok := limitedBy(resp, body, token); ok {
return e
}
return fmt.Errorf("GitHub answered %s for %s in %s", resp.Status, path, src.Repo)
}
mode := os.FileMode(0o644)
if exec {
mode = 0o755
}
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
return err
}
// git's own hash of a file: "blob <size>\x00" and its bytes
h := sha1.New()
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFetch+1))
if err == nil {
h.Write([]byte("blob " + strconv.Itoa(len(body)) + "\x00"))
h.Write(body)
_, err = out.Write(body)
}
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
return err
}
if got := hex.EncodeToString(h.Sum(nil)); sha != "" && got != sha {
return fmt.Errorf("%s in %s changed while it was being fetched; try again", path, src.Repo)
}
return nil
}