library: one market skill from a huge repository installs alone; GitHub's file list is never cut (#2794)
Adding clean-code from sickn33/agentic-awesome-skills in the market failed with "GitHub's list of sickn33/agentic-awesome-skills's files wasn't understood: unexpected end of JSON input" (CaiusLuo; stablyai/ orca the same, ye4241). The repository's download is over 200 MB, so its skills are fetched file by file from GitHub's list of its files (#1941), and that list is 11.3 MB: apiGet cut every answer at 8 MB and dropped the read's error, so JSON was handed a cut-off body. From ye4241's patch on the issue (made on75e769a9, applied as is): apiGet takes the most its caller reads and reads one byte past it; a 200 over it is an error naming the cap, a read that breaks is a read error, a rate limit is told from the status and headers before either, and only answers up to 8 MB are kept for a 304. The file list's cap is 64 MB (maxTree), lastCommit keeps 8 MB. That alone wasn't enough for the reporter's case: the 8,589 skills of that repository come to 287 MB together, over maxFetch, so the install would then fail as "too big to install". On top of the patch: - fetchSkillFiles fetches only what the caller reads: the skills under src.Path, and for the market only the folders named as the skill it installs (InstallMarketSkill -> cachedProbeFor/probeSkills; such a probe is kept under its own key so a whole probe never takes it). When no folder has that name every skill under the path is fetched, as before. - with a path (a link to a folder, an update, a check for new skills under newBase) the list asked for is that folder's own, git's ref:path (treeUnder; a few KB instead of 11 MB, and small enough to be kept for a 304). When it can't be had (404, a ref git can't read that way, cut off) the whole list is read, which says for sure what is there, so goneFrom never trusts a 404. A rate limit is said at once. - the fetcher kept one fetch per repository and ref for every skill of it. A fetch narrowed to one skill's folder is now kept to that folder (fetcher.get): another skill of the same repository gets a fetch of its own, where it was read as removed upstream (broken by hand below). - a CC Switch skill being adopted looks in the whole repository, since its Path is only the folder's name. - a probe of a folder whose skills are all too big lists it empty and names them, as before; the whole repository's still fails. - GitHub's own truncated list is errTooBig, by path or not (TestTruncatedListIsTooBig). - apiGet's client waits 2 minutes, not 20s, for an answer over 8 MB. docs/subsystems/library.md says how far a big repository is fetched. Tests (no network; fake codeload, API and raw): - TestMarketSkillFromAHugeRepository: an 11 MB list, a download over the limit and skills over it together. The market installs one, raw is asked only for its files, and UpdateSkills of two of its skills updates both, each asking for its own folder's list. - TestRepoTreeBigList, TestApiGetWholeAnswer: ye4241's. - the fake trees in skilltree_test and skillnew_test answer git's ref:path as GitHub does (checked against api.github.com: HEAD:skills/ clean-code lists that folder, HEAD:nonexist is 404). Broken by hand, each red, then restored: - apiGet back to the 8 MB cut with the error dropped: both TestRepoTreeBigList and TestMarketSkillFromAHugeRepository fail with "unexpected end of JSON input". - no name narrowing: "the skills in vectorize-io/hindsight are too big to install". - the fetcher sharing a narrowed fetch: Gone:[hindsight-docs]. - no ref:path list: the update listed ["HEAD" "HEAD"]. Run at this tree (65ee8c65cplus this change): - gofmt -l internal: clean - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean - go test -count=1 -timeout 45m ./internal/library/: ok 131s - real: a throwaway realnet test in a sandbox HOME, no GitHub token, InstallMarketSkill("sickn33/agentic-awesome-skills", "clean-code"): installed in 15s, SKILL.md 5,202 bytes, Path skills/clean-code; UpdateSkill then took 0.6s through its folder's list. The same test at origin/main65ee8c65c: "unexpected end of JSON input". Not tried: the full ./... suite (only internal/library changed, other sessions' suites were running); Windows and Linux runs (vet only); the GUI (no GUI text changed); stablyai/orca for real. Co-authored-by: ye4241 <ye4241@users.noreply.github.com>
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1043,7 +1043,9 @@ func InstallMarketSkill(source, id string, agents []string) (*Result, error) {
|
||||
if !repoRe.MatchString(source) {
|
||||
return nil, fmt.Errorf("%s isn't a GitHub repository", source)
|
||||
}
|
||||
p, err := cachedProbe(source)
|
||||
// only this skill's folder, when the repository is too big to
|
||||
// download whole (#2794)
|
||||
p, err := cachedProbeFor(source, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ func lastCommit(src Source) (*commit, error) {
|
||||
q.Set("sha", src.Ref)
|
||||
}
|
||||
u := githubAPI + "/repos/" + src.Repo + "/commits?" + q.Encode()
|
||||
body, code, token, err := apiGet(u)
|
||||
body, code, token, err := apiGet(u, 8<<20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -154,12 +154,22 @@ func lastCommit(src Source) (*commit, error) {
|
||||
return &list[0], nil
|
||||
}
|
||||
|
||||
// cacheBody is the most of an answer kept by URL for a 304 to reuse;
|
||||
// bigger ones are read but not kept, so a huge file list isn't held for
|
||||
// the process's life.
|
||||
const cacheBody = 8 << 20
|
||||
|
||||
// errOverCap is an answer over the most its caller reads (apiGet's max).
|
||||
var errOverCap = errors.New("over the most magpie reads")
|
||||
|
||||
// apiGet asks GitHub's API for u, with the ETag of the answer it had
|
||||
// before, if any: GitHub's 304 for an unchanged one doesn't count against
|
||||
// the rate limit, and is answered as the 200 it had. It says whether the
|
||||
// request carried a GitHub token, and a rate limit used up is an
|
||||
// errLimited.
|
||||
func apiGet(u string) ([]byte, int, bool, error) {
|
||||
// errLimited. A rate limit is told from the status and headers even when
|
||||
// the answer can't be read whole. A 200 over max bytes is an error, never
|
||||
// a cut-off body handed to a caller, and no answer over cacheBody is kept.
|
||||
func apiGet(u string, max int64) ([]byte, int, bool, error) {
|
||||
req, _ := http.NewRequest("GET", u, nil)
|
||||
req.Header.Set("User-Agent", "magpie")
|
||||
req.Header.Set("Accept", "application/vnd.github+json")
|
||||
@@ -169,20 +179,31 @@ func apiGet(u string) ([]byte, int, bool, error) {
|
||||
if cached {
|
||||
req.Header.Set("If-None-Match", had.etag)
|
||||
}
|
||||
c := &http.Client{Timeout: 20 * time.Second}
|
||||
// a file list of tens of MB takes longer than 20s on a slow line
|
||||
timeout := 20 * time.Second
|
||||
if max > cacheBody {
|
||||
timeout = 2 * time.Minute
|
||||
}
|
||||
c := &http.Client{Timeout: timeout}
|
||||
resp, token, err := doGitHub(req, func(r *http.Request) (*http.Response, error) { return source.Do(c, r) })
|
||||
if err != nil {
|
||||
return nil, 0, token, fmt.Errorf("couldn't reach GitHub: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, max+1))
|
||||
if e, ok := limitedBy(resp, body, token); ok {
|
||||
return nil, resp.StatusCode, token, e
|
||||
}
|
||||
if err != nil {
|
||||
return nil, resp.StatusCode, token, fmt.Errorf("couldn't read GitHub's answer: %w", err)
|
||||
}
|
||||
if resp.StatusCode == 304 && cached {
|
||||
return had.body, 200, token, nil
|
||||
}
|
||||
if et := resp.Header.Get("ETag"); resp.StatusCode == 200 && et != "" {
|
||||
if resp.StatusCode == 200 && int64(len(body)) > max {
|
||||
return nil, resp.StatusCode, token, fmt.Errorf("GitHub's answer was over %s: %w", mb(max), errOverCap)
|
||||
}
|
||||
if et := resp.Header.Get("ETag"); resp.StatusCode == 200 && et != "" && int64(len(body)) <= cacheBody {
|
||||
etags.Lock()
|
||||
etags.m[u] = etagged{etag: et, body: body}
|
||||
etags.Unlock()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -182,3 +183,70 @@ func check(t *testing.T) map[string]SkillCheck {
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// An answer over the cap is an error that says so, never a cut body for a
|
||||
// JSON parse to trip on; a cut-off answer is a read error; a rate limit is
|
||||
// told from the status and headers even then; and an answer the cap lets
|
||||
// through but cacheBody doesn't isn't kept for a 304 to answer with.
|
||||
func TestApiGetWholeAnswer(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var ifNone []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
ifNone = append(ifNone, r.Header.Get("If-None-Match"))
|
||||
mu.Unlock()
|
||||
w.Header().Set("ETag", `"v1"`)
|
||||
fmt.Fprint(w, strings.Repeat(`{"path":"a","type":"blob"},`, 1<<20)) // ~27 MB
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
if _, _, _, err := apiGet(srv.URL, 8<<20); err == nil || !strings.Contains(err.Error(), "over 8 MB") {
|
||||
t.Fatalf("over the cap: %v", err)
|
||||
}
|
||||
for range 2 {
|
||||
if _, _, _, err := apiGet(srv.URL, 64<<20); err != nil {
|
||||
t.Fatalf("whole answer under the cap: %v", err)
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(ifNone) != 3 || slices.Contains(ifNone, `"v1"`) {
|
||||
t.Errorf("an over-cacheBody answer was kept for a 304: %q", ifNone)
|
||||
}
|
||||
|
||||
// a connection that drops mid-body is a read error, not a part body
|
||||
drop := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "100")
|
||||
fmt.Fprint(w, `{"sha":`)
|
||||
}))
|
||||
defer drop.Close()
|
||||
if _, _, _, err := apiGet(drop.URL, 8<<20); err == nil || !strings.Contains(err.Error(), "couldn't read GitHub's answer") {
|
||||
t.Fatalf("dropped connection: %v", err)
|
||||
}
|
||||
|
||||
// so is a cut-off rate limit, but it's told from the status and
|
||||
// headers: CheckSkills stops asking once GitHub limits it
|
||||
limited := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-RateLimit-Remaining", "0")
|
||||
w.Header().Set("X-RateLimit-Reset", "2000000000")
|
||||
w.Header().Set("Content-Length", "100")
|
||||
w.WriteHeader(403)
|
||||
fmt.Fprint(w, `{"message":`)
|
||||
}))
|
||||
defer limited.Close()
|
||||
_, _, _, err := apiGet(limited.URL, 8<<20)
|
||||
var el errLimited
|
||||
if !errors.As(err, &el) {
|
||||
t.Fatalf("cut-off rate limit: %v", err)
|
||||
}
|
||||
|
||||
// a non-200's size never masks the status the caller reports
|
||||
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(502)
|
||||
fmt.Fprint(w, strings.Repeat("bad gateway ", 1<<20)) // ~12 MB
|
||||
}))
|
||||
defer bad.Close()
|
||||
if _, code, _, err := apiGet(bad.URL, 8<<20); err != nil || code != 502 {
|
||||
t.Fatalf("502 over the cap: code %d, err %v", code, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,11 @@ func newBase(skills []*Skill) string {
|
||||
return base
|
||||
}
|
||||
|
||||
// maxTree is the most of a repository's file list magpie reads; a list can
|
||||
// be tens of MB for a big app (stablyai/orca's is ~10 MB, and GitHub
|
||||
// answers one whole under its own 100,000-entry cap).
|
||||
const maxTree = 64 << 20
|
||||
|
||||
// gitTree is a repository's files as GitHub's API lists them.
|
||||
type gitTree struct {
|
||||
Truncated bool `json:"truncated"`
|
||||
@@ -169,10 +174,24 @@ func hiddenThroughSkills(parts []string) bool {
|
||||
|
||||
// repoTree is a repository's files at a ref, from GitHub's API.
|
||||
func repoTree(repo, ref string) (*gitTree, error) {
|
||||
return listTree(repo, ref, "")
|
||||
}
|
||||
|
||||
// listTree is GitHub's list of the files at a ref under path (the whole
|
||||
// repository's for ""), with paths from that folder. A list over maxTree,
|
||||
// or one cut off, is an error that says so, never a list read in part.
|
||||
func listTree(repo, ref, path string) (*gitTree, error) {
|
||||
if ref == "" {
|
||||
ref = "HEAD"
|
||||
}
|
||||
body, code, _, err := apiGet(githubAPI + "/repos/" + repo + "/git/trees/" + url.PathEscape(ref) + "?recursive=1")
|
||||
ish := ref
|
||||
if path != "" {
|
||||
ish += ":" + path // git's ref:path, a folder's own tree
|
||||
}
|
||||
body, code, _, err := apiGet(githubAPI+"/repos/"+repo+"/git/trees/"+url.PathEscape(ish)+"?recursive=1", maxTree)
|
||||
if errors.Is(err, errOverCap) {
|
||||
return nil, fmt.Errorf("GitHub's list of %s's files is over %s", repo, mb(maxTree))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -186,6 +205,31 @@ func repoTree(repo, ref string) (*gitTree, error) {
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// treeUnder is a repository's files at a ref under path, with their paths
|
||||
// from its root. With a path it asks for that folder's list alone: one
|
||||
// skill's folder is a few KB where the whole repository's list is over
|
||||
// 11 MB for sickn33/agentic-awesome-skills (#2794). When that can't be
|
||||
// had (no such folder, a ref git's ref:path doesn't read, a list cut
|
||||
// off) the whole repository's is read, which says for sure what is there.
|
||||
// A rate limit is said at once.
|
||||
func treeUnder(repo, ref, path string) (*gitTree, error) {
|
||||
if path != "" {
|
||||
t, err := listTree(repo, ref, path)
|
||||
var e errLimited
|
||||
if errors.As(err, &e) {
|
||||
return nil, err
|
||||
}
|
||||
if err == nil && !t.Truncated {
|
||||
for i := range t.Tree {
|
||||
t.Tree[i].Path = path + "/" + t.Tree[i].Path
|
||||
}
|
||||
t.Tree = append([]gitEntry{{Path: path, Type: "tree", Mode: "040000"}}, t.Tree...)
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return repoTree(repo, ref)
|
||||
}
|
||||
|
||||
// findNew looks in one repository at one ref for skills beside the
|
||||
// library's from there that it doesn't have and hasn't offered: GitHub's
|
||||
// list of the repository's files first, and only when that has one, the
|
||||
@@ -210,7 +254,7 @@ func findNew(l *Library, repo, ref string, f *fetcher, limited *atomic.Pointer[e
|
||||
known[s.Source.Path] = true
|
||||
}
|
||||
}
|
||||
tree, err := repoTree(repo, ref)
|
||||
tree, err := treeUnder(repo, ref, base)
|
||||
if err != nil {
|
||||
var e errLimited
|
||||
if errors.As(err, &e) {
|
||||
@@ -221,7 +265,9 @@ func findNew(l *Library, repo, ref string, f *fetcher, limited *atomic.Pointer[e
|
||||
if !tree.Truncated && !slices.ContainsFunc(skillDirsIn(tree, base), func(d string) bool { return !known[d] }) {
|
||||
return []NewSkill{}, true
|
||||
}
|
||||
src := Source{Kind: "github", Repo: repo, Ref: ref}
|
||||
// only base's folder: candidates looks nowhere else, and a
|
||||
// repository too big to download whole is then fetched only there
|
||||
src := Source{Kind: "github", Repo: repo, Ref: ref, Path: base}
|
||||
tmp, err := f.fetch(src)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -31,10 +32,21 @@ func fakeSkillRepo(t *testing.T, files map[string]string) (asked map[string]int,
|
||||
if r.URL.Query().Get("recursive") != "1" {
|
||||
t.Errorf("tree asked without recursive: %s", r.URL)
|
||||
}
|
||||
// git's ref:path is that folder's own list, as GitHub
|
||||
// answers it; no such folder is a 404
|
||||
_, under, _ := strings.Cut(r.URL.Path[strings.Index(r.URL.Path, "/git/trees/")+len("/git/trees/"):], ":")
|
||||
var tree gitTree
|
||||
paths := []string{}
|
||||
for p := range files {
|
||||
paths = append(paths, p)
|
||||
if under == "" {
|
||||
paths = append(paths, p)
|
||||
} else if rest, in := strings.CutPrefix(p, under+"/"); in {
|
||||
paths = append(paths, rest)
|
||||
}
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
sort.Strings(paths)
|
||||
for _, p := range paths {
|
||||
@@ -365,3 +377,43 @@ func TestRepoWithAPluginCopyListsEachSkillOnce(t *testing.T) {
|
||||
t.Errorf("skills in the tree %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// stablyai/orca's file list answers 200 with ~10 MB of JSON, over the 8 MB
|
||||
// apiGet once read; the cut-off body then failed to parse as "unexpected
|
||||
// end of JSON input". A list that size is read and understood.
|
||||
func TestRepoTreeBigList(t *testing.T) {
|
||||
// ~10 MB of entries, the shape GitHub answers for orca
|
||||
tree := &gitTree{}
|
||||
for i := 0; i < 60_000; i++ {
|
||||
tree.Tree = append(tree.Tree, gitEntry{
|
||||
Path: fmt.Sprintf("apps/desktop/src/renderer/components/panels/sidebar/file%05d.ts", i),
|
||||
Type: "blob", Mode: "100644", SHA: "e488653ba64c6cfc3551ec46454b965421d50176", Size: 321,
|
||||
})
|
||||
}
|
||||
tree.Tree = append(tree.Tree, gitEntry{Path: "skills/orca/SKILL.md", Type: "blob", Mode: "100644", SHA: "a438021d7b90192e2c0c4802e6cff1b0df8bb203"})
|
||||
b, err := json.Marshal(tree)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(b) <= 8<<20 {
|
||||
t.Fatalf("fixture is %d bytes, not over the old cap", len(b))
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(b)
|
||||
}))
|
||||
defer srv.Close()
|
||||
oldA := githubAPI
|
||||
githubAPI = srv.URL
|
||||
defer func() { githubAPI = oldA }()
|
||||
|
||||
got, err := repoTree("stablyai/orca", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Tree) != len(tree.Tree) {
|
||||
t.Fatalf("read %d of %d entries", len(got.Tree), len(tree.Tree))
|
||||
}
|
||||
if dirs := skillDirsIn(got, "skills"); !slices.Equal(dirs, []string{"skills/orca"}) {
|
||||
t.Errorf("skills in it: %v", dirs)
|
||||
}
|
||||
}
|
||||
|
||||
+83
-21
@@ -765,10 +765,24 @@ func (s *Source) remote() bool { return s != nil && (s.Kind == "github" || s.Kin
|
||||
// asked of GitHub's API with the user's GitHub token (37FlowAI on X): the
|
||||
// API redirects to codeload, and the token, sent to the API's host alone,
|
||||
// isn't carried over to it.
|
||||
//
|
||||
// A repository too big to download whole is fetched only as far as src.Path
|
||||
// and name narrow it (fetchSkillFiles); part says it was.
|
||||
func fetch(src Source) (string, error) {
|
||||
dir, _, err := fetchPart(src, "")
|
||||
return dir, err
|
||||
}
|
||||
|
||||
func fetchPart(src Source, name string) (dir string, part bool, err error) {
|
||||
if src.Kind == "git" {
|
||||
return fetchGit(src)
|
||||
dir, err = fetchGit(src)
|
||||
return dir, false, err
|
||||
}
|
||||
dir, err = fetchWhole(src, name)
|
||||
return dir, tooBig.has(src) && (src.Path != "" || name != ""), err
|
||||
}
|
||||
|
||||
func fetchWhole(src Source, name string) (string, error) {
|
||||
c := &http.Client{Timeout: 2 * time.Minute}
|
||||
get := func(u string) (*http.Response, bool, error) {
|
||||
req, _ := http.NewRequest("GET", u, nil)
|
||||
@@ -776,7 +790,7 @@ func fetch(src Source) (string, error) {
|
||||
return doGitHub(req, func(r *http.Request) (*http.Response, error) { return source.DoOfficial(c, r) })
|
||||
}
|
||||
if tooBig.has(src) {
|
||||
return fetchSkillFiles(src)
|
||||
return fetchSkillFiles(src, name)
|
||||
}
|
||||
resp, _, err := get(tarballURL(src.Repo, src.Ref))
|
||||
if err != nil {
|
||||
@@ -827,7 +841,7 @@ func fetch(src Source) (string, error) {
|
||||
// skills beside it, #1941): only the skills' folders
|
||||
resp.Body.Close()
|
||||
tooBig.add(src)
|
||||
return fetchSkillFiles(src)
|
||||
return fetchSkillFiles(src, name)
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
@@ -1011,7 +1025,13 @@ func skillsCommand(input string) string {
|
||||
// (or a folder in one), any other git repository (GitLab, one on a
|
||||
// company's own server; fetched with the user's git), a folder on this
|
||||
// machine, or a skills CLI command for one of them.
|
||||
func ProbeSkills(input string) (*Probe, error) {
|
||||
func ProbeSkills(input string) (*Probe, error) { return probeSkills(input, "") }
|
||||
|
||||
// probeSkills is ProbeSkills for the skill called name, when one is
|
||||
// wanted: a repository too big to download whole is then fetched only for
|
||||
// the skills by that name (fetchSkillFiles), and the probe is kept apart
|
||||
// from a whole one (probeKey).
|
||||
func probeSkills(input, name string) (*Probe, error) {
|
||||
input = strings.TrimSpace(skillsCommand(input))
|
||||
if input == "" {
|
||||
return nil, fmt.Errorf("paste a GitHub or git repository's link or a folder's path")
|
||||
@@ -1033,7 +1053,7 @@ func ProbeSkills(input string) (*Probe, error) {
|
||||
if !ok {
|
||||
src, _, _ = gitSource(input)
|
||||
}
|
||||
tmp, err := fetch(src)
|
||||
tmp, part, err := fetchPart(src, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1044,7 +1064,11 @@ func ProbeSkills(input string) (*Probe, error) {
|
||||
}
|
||||
p.Candidates = candidates(tmp, src.Path)
|
||||
p.Left = tookLeftOut(tmp, src.Path)
|
||||
keepProbe(input, p, tmp)
|
||||
key := input
|
||||
if part && name != "" {
|
||||
key = probeKey(input, name)
|
||||
}
|
||||
keepProbe(key, p, tmp)
|
||||
} else if _, ok, err := gitSource(input); ok && err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
@@ -1062,16 +1086,30 @@ func ProbeSkills(input string) (*Probe, error) {
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func cachedProbe(input string) (*Probe, error) {
|
||||
func cachedProbe(input string) (*Probe, error) { return cachedProbeFor(input, "") }
|
||||
|
||||
// probeKey is where a probe fetched only for the skill called name is
|
||||
// kept: a later probe of the whole source never takes it for one.
|
||||
func probeKey(input, name string) string { return input + "\x00" + name }
|
||||
|
||||
// cachedProbeFor is the probe kept for input, a whole one or one made for
|
||||
// the skill called name, or a new one for name.
|
||||
func cachedProbeFor(input, name string) (*Probe, error) {
|
||||
key := strings.TrimSpace(skillsCommand(input))
|
||||
probes.Lock()
|
||||
e := probes.m[strings.TrimSpace(skillsCommand(input))]
|
||||
es := []*probeEntry{probes.m[key]}
|
||||
if name != "" {
|
||||
es = append(es, probes.m[probeKey(key, name)])
|
||||
}
|
||||
probes.Unlock()
|
||||
if e != nil {
|
||||
if _, err := os.Stat(e.tmp); err == nil {
|
||||
return e.p, nil
|
||||
for _, e := range es {
|
||||
if e != nil {
|
||||
if _, err := os.Stat(e.tmp); err == nil {
|
||||
return e.p, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return ProbeSkills(input)
|
||||
return probeSkills(input, name)
|
||||
}
|
||||
|
||||
// InstallSkills adds the skills at those paths of the source to the library
|
||||
@@ -1391,7 +1429,10 @@ func updatable(s *Skill) bool {
|
||||
}
|
||||
|
||||
// fetcher downloads each repository at each ref once, however many of
|
||||
// its skills are updated.
|
||||
// its skills are updated. A repository too big to download whole is
|
||||
// fetched only under the folder asked for (fetchPart), so a skill
|
||||
// elsewhere in it is fetched on its own: read from the first folder, it
|
||||
// would look removed there (goneFrom).
|
||||
type fetcher struct {
|
||||
mu sync.Mutex
|
||||
got map[string]*fetched
|
||||
@@ -1399,17 +1440,28 @@ type fetcher struct {
|
||||
}
|
||||
|
||||
type fetched struct {
|
||||
once sync.Once
|
||||
dir string
|
||||
err error
|
||||
once sync.Once
|
||||
dir string
|
||||
err error
|
||||
part bool // only under
|
||||
under string // the folder fetched, when part
|
||||
}
|
||||
|
||||
func (f *fetcher) fetch(src Source) (string, error) {
|
||||
key := src.Repo + "@" + src.Ref
|
||||
g := f.get(key, src)
|
||||
if g.part && !inRepoDir(src.Path, g.under) {
|
||||
g = f.get(key+"@"+src.Path, src)
|
||||
}
|
||||
return g.dir, g.err
|
||||
}
|
||||
|
||||
// get is the fetch kept under key, made from src the first time.
|
||||
func (f *fetcher) get(key string, src Source) *fetched {
|
||||
f.mu.Lock()
|
||||
if f.got == nil {
|
||||
f.got = map[string]*fetched{}
|
||||
}
|
||||
key := src.Repo + "@" + src.Ref
|
||||
g := f.got[key]
|
||||
if g == nil {
|
||||
g = &fetched{}
|
||||
@@ -1417,14 +1469,15 @@ func (f *fetcher) fetch(src Source) (string, error) {
|
||||
}
|
||||
f.mu.Unlock()
|
||||
g.once.Do(func() {
|
||||
g.dir, g.err = fetch(src)
|
||||
g.dir, g.part, g.err = fetchPart(src, "")
|
||||
g.under = src.Path
|
||||
if g.err == nil {
|
||||
f.mu.Lock()
|
||||
f.dirs = append(f.dirs, g.dir)
|
||||
f.mu.Unlock()
|
||||
}
|
||||
})
|
||||
return g.dir, g.err
|
||||
return g
|
||||
}
|
||||
|
||||
func (f *fetcher) clean() {
|
||||
@@ -1457,10 +1510,19 @@ func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) {
|
||||
c := *src
|
||||
src = &c
|
||||
}
|
||||
tmp, err := f.fetch(*src)
|
||||
// CC Switch's Path is only the folder's name (origin): the whole
|
||||
// repository is looked in
|
||||
at := func() Source {
|
||||
w := *src
|
||||
if adopt {
|
||||
w.Path = ""
|
||||
}
|
||||
return w
|
||||
}
|
||||
tmp, err := f.fetch(at())
|
||||
if err != nil && adopt && src.Ref != "" {
|
||||
src.Ref = "" // the branch CC Switch recorded is gone: the default one
|
||||
tmp, err = f.fetch(*src)
|
||||
tmp, err = f.fetch(at())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -72,11 +72,15 @@ var rawURL = func(repo, ref, path string) string {
|
||||
}
|
||||
|
||||
// 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)
|
||||
// is, every folder of it with a SKILL.md under src.Path, whatever is in
|
||||
// it, and the other folders there empty: what candidates, origin and an
|
||||
// update read of a fetched repository. With name, only the skills whose
|
||||
// folder is called that are fetched, if any is: the market installs one
|
||||
// skill by its name, and sickn33/agentic-awesome-skills' 8,589 skills
|
||||
// come to 287 MB, over maxFetch (#2794). A skill's folder is its name
|
||||
// (agentskills.io's SKILL.md spec).
|
||||
func fetchSkillFiles(src Source, name string) (string, error) {
|
||||
tree, err := treeUnder(src.Repo, src.Ref, src.Path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -84,12 +88,20 @@ func fetchSkillFiles(src Source) (string, error) {
|
||||
// too many files for GitHub to list in one answer
|
||||
return "", errTooBig
|
||||
}
|
||||
var skillDirs []string
|
||||
var skillDirs, named []string
|
||||
for _, e := range tree.Tree {
|
||||
if e.Type == "blob" && slash.Base(e.Path) == "SKILL.md" {
|
||||
skillDirs = append(skillDirs, slash.Dir(e.Path))
|
||||
if d := slash.Dir(e.Path); inRepoDir(d, src.Path) {
|
||||
skillDirs = append(skillDirs, d)
|
||||
if name != "" && slash.Base(d) == name {
|
||||
named = append(named, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(named) > 0 {
|
||||
skillDirs = named
|
||||
}
|
||||
inSkill := func(p string) bool {
|
||||
for _, d := range skillDirs {
|
||||
if d == "." || strings.HasPrefix(p, d+"/") {
|
||||
@@ -134,7 +146,9 @@ func fetchSkillFiles(src Source) (string, error) {
|
||||
left = append(left, LeftOut{Path: p, Size: size[d]})
|
||||
}
|
||||
}
|
||||
if len(left) == len(skillDirs) && len(left) > 0 {
|
||||
// a folder asked for whose skills are all too big is listed empty,
|
||||
// naming them, as the whole repository's list would
|
||||
if len(left) == len(skillDirs) && len(left) > 0 && src.Path == "" {
|
||||
return "", fmt.Errorf("the skills in %s are too big to install (over %s)", src.Repo, mb(maxFetch))
|
||||
}
|
||||
var files []file
|
||||
@@ -157,7 +171,9 @@ func fetchSkillFiles(src Source) (string, error) {
|
||||
return dst, strings.HasPrefix(dst, tmp+string(filepath.Separator)) // never outside
|
||||
}
|
||||
for _, e := range tree.Tree {
|
||||
if e.Type == "tree" {
|
||||
// only the named skills' folders when narrowed to them: the rest
|
||||
// of a big repository is thousands of empty folders
|
||||
if e.Type == "tree" && inRepoDir(e.Path, src.Path) && (len(named) == 0 || inSkill(e.Path)) {
|
||||
if dst, ok := place(e.Path); ok {
|
||||
if err := os.MkdirAll(dst, 0o755); err != nil {
|
||||
os.RemoveAll(tmp)
|
||||
@@ -208,6 +224,12 @@ func fetchSkillFiles(src Source) (string, error) {
|
||||
return tmp, nil
|
||||
}
|
||||
|
||||
// inRepoDir is whether a repository's path p is under the folder dir, or
|
||||
// is it; everything is under "". A skill at the repository's root is ".".
|
||||
func inRepoDir(p, dir string) bool {
|
||||
return dir == "" || p == dir || strings.HasPrefix(p, dir+"/")
|
||||
}
|
||||
|
||||
// LeftOut is a skill of a repository too big to install on its own
|
||||
// (fetchSkillFiles): where it is, and what its files come to.
|
||||
type LeftOut struct {
|
||||
|
||||
@@ -4,12 +4,14 @@ import (
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
slash "path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -27,6 +29,8 @@ type fakeBigRepo struct {
|
||||
tarballs int
|
||||
files map[string]string
|
||||
serve map[string]string // what raw hands out, where it differs
|
||||
trees []string // the tree-ish each file list was asked at
|
||||
pad int // files of the app's own, in the whole list only
|
||||
}
|
||||
|
||||
func gitSHA(body string) string {
|
||||
@@ -57,10 +61,18 @@ func newFakeBigRepo(t *testing.T) *fakeBigRepo {
|
||||
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/") {
|
||||
ish, found := strings.CutPrefix(r.URL.Path, "/repos/vectorize-io/hindsight/git/trees/")
|
||||
if !found {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.trees = append(g.trees, ish)
|
||||
pad := g.pad
|
||||
g.mu.Unlock()
|
||||
// git's ref:path is that folder's own list, its paths from there,
|
||||
// as GitHub answers it; no such folder is a 404
|
||||
_, under, _ := strings.Cut(ish, ":")
|
||||
// GitHub's answer, as it lists hindsight: folders, then files with
|
||||
// their mode, git hash and size
|
||||
var tree []map[string]any
|
||||
@@ -76,16 +88,32 @@ func newFakeBigRepo(t *testing.T) *fakeBigRepo {
|
||||
paths = append(paths, d)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
if under != "" && !dirs[under] {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
for _, p := range paths {
|
||||
at := p
|
||||
if under != "" {
|
||||
var in bool
|
||||
if at, in = strings.CutPrefix(p, under+"/"); !in {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if dirs[p] {
|
||||
tree = append(tree, map[string]any{"mode": "040000", "path": p, "sha": "e488653ba64c6cfc3551ec46454b965421d50176", "type": "tree"})
|
||||
tree = append(tree, map[string]any{"mode": "040000", "path": at, "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"})
|
||||
tree = append(tree, map[string]any{"mode": mode, "path": at, "sha": gitSHA(g.files[p]), "size": len(g.files[p]), "type": "blob"})
|
||||
}
|
||||
for i := 0; under == "" && i < pad; i++ {
|
||||
tree = append(tree, map[string]any{"mode": "100644", "path": fmt.Sprintf("hindsight-app/src/renderer/components/panels/sidebar/file%05d.ts", i),
|
||||
"sha": "e488653ba64c6cfc3551ec46454b965421d50176", "size": 321, "type": "blob",
|
||||
"url": "https://api.github.com/repos/vectorize-io/hindsight/git/blobs/e488653ba64c6cfc3551ec46454b965421d50176"})
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"sha": "52ef60fad332184c3b8a1f9fff4756247fc07146", "tree": tree, "truncated": false})
|
||||
}))
|
||||
@@ -241,3 +269,68 @@ func TestOneSkillTooBigLeavesTheOthers(t *testing.T) {
|
||||
t.Fatalf("the big skill's folder: %+v, %v", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
// #2794 (CaiusLuo): the market installs clean-code from
|
||||
// sickn33/agentic-awesome-skills, whose whole download is too big, whose
|
||||
// file list is 11 MB (over the 8 MB GitHub's answers were cut at, so it
|
||||
// failed as "unexpected end of JSON input"), and whose 8,589 skills come
|
||||
// to 287 MB, over the limit together. The list is read whole, only the
|
||||
// skill by that name is fetched, and an update asks for its folder's list
|
||||
// alone. Two skills of it updated together are each fetched, neither
|
||||
// taken for removed.
|
||||
func TestMarketSkillFromAHugeRepository(t *testing.T) {
|
||||
sandbox(t)
|
||||
t.Setenv("GITHUB_TOKEN", "")
|
||||
t.Setenv("GH_TOKEN", "")
|
||||
g := newFakeBigRepo(t)
|
||||
g.pad = 60_000 // ~11 MB of list, as sickn33/agentic-awesome-skills'
|
||||
// each under the limit, together over it
|
||||
g.files["skills/hindsight-local/references/big.md"] = strings.Repeat("local ", 10<<10)
|
||||
g.files["hindsight-integrations/cursor/skills/hindsight-recall/references/big.md"] = strings.Repeat("recall ", 10<<10)
|
||||
|
||||
ok(t)(InstallMarketSkill("vectorize-io/hindsight", "hindsight-docs", []string{"claude"}))
|
||||
if b, err := os.ReadFile(filepath.Join(skillDir("hindsight-docs"), "references/changelog/index.md")); err != nil || string(b) != "# Changelog\n" {
|
||||
t.Fatalf("hindsight-docs: %q, %v", b, err)
|
||||
}
|
||||
g.mu.Lock()
|
||||
for _, r := range g.raw {
|
||||
if !strings.HasPrefix(r, "skills/hindsight-docs/") {
|
||||
t.Errorf("raw was asked for %s, outside the one skill the market installs", r)
|
||||
}
|
||||
}
|
||||
g.raw, g.trees = nil, nil
|
||||
g.mu.Unlock()
|
||||
|
||||
ok(t)(InstallMarketSkill("vectorize-io/hindsight", "hindsight-recall", []string{"claude"}))
|
||||
g.mu.Lock()
|
||||
g.trees = nil
|
||||
g.mu.Unlock()
|
||||
r, err := UpdateSkills()
|
||||
if err != nil || len(r.Gone) > 0 || len(r.Unupdated) > 0 || len(r.Updated) != 2 {
|
||||
t.Fatalf("update: %+v, %v", r, err)
|
||||
}
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
sort.Strings(g.trees)
|
||||
if want := []string{"HEAD:hindsight-integrations/cursor/skills/hindsight-recall", "HEAD:skills/hindsight-docs"}; !slices.Equal(g.trees, want) {
|
||||
t.Errorf("an update listed %q, want each skill's own folder %q", g.trees, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A list GitHub cut off itself (over 100,000 files) says the repository
|
||||
// is too big; it is never read as the whole of it.
|
||||
func TestTruncatedListIsTooBig(t *testing.T) {
|
||||
sandbox(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"sha":"x","tree":[{"path":"skills/a/SKILL.md","type":"blob","mode":"100644","sha":"y","size":3}],"truncated":true}`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
oldA := githubAPI
|
||||
githubAPI = srv.URL
|
||||
defer func() { githubAPI = oldA }()
|
||||
for _, path := range []string{"", "skills/a"} {
|
||||
if _, err := fetchSkillFiles(Source{Kind: "github", Repo: "o/r", Path: path}, ""); !errors.Is(err, errTooBig) {
|
||||
t.Errorf("path %q: %v", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user