diff --git a/internal/library/skillnew.go b/internal/library/skillnew.go index 5774c3518..c0a4fd96b 100644 --- a/internal/library/skillnew.go +++ b/internal/library/skillnew.go @@ -100,11 +100,17 @@ func newBase(skills []*Skill) string { // gitTree is a repository's files as GitHub's API lists them. type gitTree struct { - Truncated bool `json:"truncated"` - Tree []struct { - Path string `json:"path"` - Type string `json:"type"` - } `json:"tree"` + Truncated bool `json:"truncated"` + Tree []gitEntry `json:"tree"` +} + +// gitEntry is one file or folder in a gitTree. +type gitEntry struct { + Path string `json:"path"` + Type string `json:"type"` + Mode string `json:"mode"` + SHA string `json:"sha"` + Size int64 `json:"size"` } // skillDirsIn are the folders with a SKILL.md under base in a repository's diff --git a/internal/library/skillnew_test.go b/internal/library/skillnew_test.go index eec973012..f85d2680e 100644 --- a/internal/library/skillnew_test.go +++ b/internal/library/skillnew_test.go @@ -38,10 +38,7 @@ func fakeSkillRepo(t *testing.T, files map[string]string) (asked map[string]int, } sort.Strings(paths) for _, p := range paths { - tree.Tree = append(tree.Tree, struct { - Path string `json:"path"` - Type string `json:"type"` - }{p, "blob"}) + tree.Tree = append(tree.Tree, gitEntry{Path: p, Type: "blob"}) } b, _ := json.Marshal(tree) etag := `"` + hashOf(b) + `"` @@ -209,10 +206,7 @@ func TestNewBase(t *testing.T) { } tree := &gitTree{} for _, p := range []string{"SKILL.md.bak", "skills/a/SKILL.md", "skills/a/b/SKILL.md", "skills/node_modules/x/SKILL.md", "skills/.x/SKILL.md", "skills/c/d/e/f/SKILL.md", "skills/c/d/e/f/g/SKILL.md", "other/z/SKILL.md"} { - tree.Tree = append(tree.Tree, struct { - Path string `json:"path"` - Type string `json:"type"` - }{p, "blob"}) + tree.Tree = append(tree.Tree, gitEntry{Path: p, Type: "blob"}) } if got := skillDirsIn(tree, "skills"); !slices.Equal(got, []string{"skills/a", "skills/c/d/e/f"}) { t.Errorf("skills in the tree: %v", got) diff --git a/internal/library/skills.go b/internal/library/skills.go index 6171ebd72..d822b48c3 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -687,6 +687,9 @@ func fetch(src Source) (string, error) { resp, err := source.DoOfficial(c, req) return resp, token, err } + if tooBig.has(src) { + return fetchSkillFiles(src) + } resp, _, err := get(tarballURL(src.Repo, src.Ref)) if err != nil { return "", fmt.Errorf("couldn't reach GitHub: %w", err) @@ -731,6 +734,13 @@ func fetch(src Source) (string, error) { } if err := untar(resp.Body, tmp); err != nil { os.RemoveAll(tmp) + if errors.Is(err, errTooBig) { + // a repository that is mostly something else (an app with its + // skills beside it, #1941): only the skills' folders + resp.Body.Close() + tooBig.add(src) + return fetchSkillFiles(src) + } return "", err } return tmp, nil @@ -766,8 +776,8 @@ func untar(r io.Reader, dst string) error { return err } case tar.TypeReg: - if total += h.Size; total > 200<<20 { - return fmt.Errorf("the repository is too big to install skills from (over 200 MB)") + if total += h.Size; total > maxFetch { + return errTooBig } if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { return err diff --git a/internal/library/skilltree.go b/internal/library/skilltree.go new file mode 100644 index 000000000..27b83730e --- /dev/null +++ b/internal/library/skilltree.go @@ -0,0 +1,232 @@ +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 \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 +} diff --git a/internal/library/skilltree_test.go b/internal/library/skilltree_test.go new file mode 100644 index 000000000..6c2a55c51 --- /dev/null +++ b/internal/library/skilltree_test.go @@ -0,0 +1,191 @@ +package library + +import ( + "crypto/sha1" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + slash "path" + "path/filepath" + "sort" + "strings" + "sync" + "testing" +) + +// fakeBigRepo stands in for codeload, GitHub's API and +// raw.githubusercontent.com for a repository laid out as +// vectorize-io/hindsight is (#1941): an app whose whole download is over +// the limit, with its skills in a few small folders beside it. It notes +// the paths raw was asked for and how often codeload was. +type fakeBigRepo struct { + mu sync.Mutex + raw []string + tarballs int + files map[string]string + serve map[string]string // what raw hands out, where it differs +} + +func gitSHA(body string) string { + h := sha1.New() + fmt.Fprintf(h, "blob %d\x00%s", len(body), body) + return hex.EncodeToString(h.Sum(nil)) +} + +func newFakeBigRepo(t *testing.T) *fakeBigRepo { + t.Helper() + big := strings.Repeat("PK\x03\x04 jar ", 20<<10) // 240 KB, past the test's limit + g := &fakeBigRepo{serve: map[string]string{}, files: map[string]string{ + "README.md": "# Hindsight", + "hindsight-clients/go/openapi-generator-cli.jar": big, + "hindsight-clients/go/openapi-generator-config.yaml": "packageName: hindsight\n", + "skills/hindsight-docs/SKILL.md": "---\nname: hindsight-docs\ndescription: Hindsight's docs\n---\n# Docs\n", + "skills/hindsight-docs/references/best-practices.md": "# Best practices\n", + "skills/hindsight-docs/references/changelog/index.md": "# Changelog\n", + "skills/hindsight-local/SKILL.md": "---\nname: hindsight-local\ndescription: Run Hindsight locally\n---\n", + "skills/hindsight-local/scripts/start.sh": "#!/bin/sh\necho start\n", + ".claude/skills/ship-it/SKILL.md": "---\nname: ship-it\n---\n", + "hindsight-integrations/cursor/skills/hindsight-recall/SKILL.md": "---\nname: hindsight-recall\ndescription: Recall\n---\n", + }} + codeload := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + g.mu.Lock() + g.tarballs++ + g.mu.Unlock() + w.Write(tarball(t, g.files)) + })) + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.URL.Path, "/repos/vectorize-io/hindsight/git/trees/") { + http.NotFound(w, r) + return + } + // GitHub's answer, as it lists hindsight: folders, then files with + // their mode, git hash and size + var tree []map[string]any + dirs := map[string]bool{} + paths := []string{} + for p := range g.files { + paths = append(paths, p) + for d := slash.Dir(p); d != "."; d = slash.Dir(d) { + dirs[d] = true + } + } + for d := range dirs { + paths = append(paths, d) + } + sort.Strings(paths) + for _, p := range paths { + if dirs[p] { + tree = append(tree, map[string]any{"mode": "040000", "path": p, "sha": "e488653ba64c6cfc3551ec46454b965421d50176", "type": "tree"}) + continue + } + mode := "100644" + if strings.HasSuffix(p, ".sh") { + mode = "100755" + } + tree = append(tree, map[string]any{"mode": mode, "path": p, "sha": gitSHA(g.files[p]), "size": len(g.files[p]), "type": "blob"}) + } + json.NewEncoder(w).Encode(map[string]any{"sha": "52ef60fad332184c3b8a1f9fff4756247fc07146", "tree": tree, "truncated": false}) + })) + raw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p, _ := strings.CutPrefix(r.URL.Path, "/vectorize-io/hindsight/HEAD/") + g.mu.Lock() + g.raw = append(g.raw, p) + body, ok := g.serve[p] + g.mu.Unlock() + if !ok { + if body, ok = g.files[p]; !ok { + http.NotFound(w, r) + return + } + } + fmt.Fprint(w, body) + })) + oldT, oldA, oldR, oldM := tarballURL, githubAPI, rawURL, maxFetch + tarballURL = func(repo, ref string) string { return codeload.URL + "/tar/" + repo } + githubAPI = api.URL + rawURL = func(repo, ref, path string) string { + if ref == "" { + ref = "HEAD" + } + return raw.URL + "/" + repo + "/" + ref + "/" + path + } + maxFetch = 100 << 10 + t.Cleanup(func() { + tarballURL, githubAPI, rawURL, maxFetch = oldT, oldA, oldR, oldM + codeload.Close() + api.Close() + raw.Close() + tooBig.Lock() + clear(tooBig.m) + tooBig.Unlock() + }) + return g +} + +// #1941 (Goalonez): a repository too big to download whole, its skills in +// small folders beside an app, installs them: only the skills' folders are +// fetched, every file of them, and a second fetch goes straight to them. +func TestSkillsFromATooBigRepository(t *testing.T) { + sandbox(t) + t.Setenv("GITHUB_TOKEN", "") + t.Setenv("GH_TOKEN", "") + g := newFakeBigRepo(t) + + p, err := ProbeSkills("https://github.com/vectorize-io/hindsight") + if err != nil { + t.Fatalf("probe: %v", err) + } + var names []string + for _, c := range p.Candidates { + names = append(names, c.Path) + } + if want := []string{"skills/hindsight-docs", "skills/hindsight-local", "hindsight-integrations/cursor/skills/hindsight-recall"}; strings.Join(names, " ") != strings.Join(want, " ") { + t.Fatalf("candidates %v, want %v", names, want) + } + ok(t)(InstallSkills("https://github.com/vectorize-io/hindsight", []string{"skills/hindsight-docs", "skills/hindsight-local"}, []string{"claude"})) + for _, f := range []string{"hindsight-docs/SKILL.md", "hindsight-docs/references/changelog/index.md", "hindsight-local/scripts/start.sh"} { + b, err := os.ReadFile(filepath.Join(skillDir("."), f)) + if err != nil || string(b) != g.files["skills/"+f] { + t.Errorf("%s: %q, %v", f, b, err) + } + } + g.mu.Lock() + for _, p := range g.raw { + if strings.HasPrefix(p, "hindsight-clients/") || p == "README.md" { + t.Errorf("raw was asked for %s, which no skill has", p) + } + } + g.mu.Unlock() + + // a subfolder deep in the repository, as a link to it gives + p, err = ProbeSkills("https://github.com/vectorize-io/hindsight/tree/HEAD/hindsight-integrations/cursor") + if err != nil || len(p.Candidates) != 1 || p.Candidates[0].Name != "hindsight-recall" { + t.Fatalf("subfolder probe: %+v, %v", p, err) + } + g.mu.Lock() + defer g.mu.Unlock() + if g.tarballs != 1 { + t.Errorf("codeload was asked %d times; once found too big, the repository's skills are fetched alone", g.tarballs) + } +} + +// What raw hands out must be the file GitHub's list names; skills too big +// themselves still say so. +func TestTooBigRepositoryChecksWhatArrives(t *testing.T) { + sandbox(t) + t.Setenv("GITHUB_TOKEN", "") + t.Setenv("GH_TOKEN", "") + g := newFakeBigRepo(t) + g.serve["skills/hindsight-docs/references/best-practices.md"] = "something else" + if _, err := ProbeSkills("vectorize-io/hindsight"); err == nil || !strings.Contains(err.Error(), "changed while it was being fetched") { + t.Fatalf("a file that isn't the listed one: %v", err) + } + delete(g.serve, "skills/hindsight-docs/references/best-practices.md") + g.files["skills/hindsight-local/model.bin"] = strings.Repeat("x", 200<<10) + if _, err := ProbeSkills("vectorize-io/hindsight"); err == nil || !strings.Contains(err.Error(), "skills in vectorize-io/hindsight are too big") { + t.Fatalf("skills too big themselves: %v", err) + } +}