diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 652ab759a..607cad4e3 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -19,7 +19,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid and Cline. A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. | [`instructions.go`](../../internal/library/instructions.go) | | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | -| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), and a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) | +| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), and a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) | | Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) | | Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | diff --git a/internal/library/main_test.go b/internal/library/main_test.go index 55d0aad51..68b79049c 100644 --- a/internal/library/main_test.go +++ b/internal/library/main_test.go @@ -1,10 +1,56 @@ package library import ( + "fmt" + "os" + "path/filepath" + "strings" "testing" "github.com/yetone/magpie/internal/testenv" ) -// The tests run in a home of their own, never the user's real files. -func TestMain(m *testing.M) { testenv.Main(m) } +// The tests run in a home of their own, never the user's real files, with +// a temp dir of their own: what they leave in it is theirs, and a skill's +// download left there fails the run (#2321). +func TestMain(m *testing.M) { + if os.Getenv(testenv.Marker) != "" { + testenv.Main(m) // started again by a test: in its temp dir already + } + tmp, err := os.MkdirTemp("", "magpie-library-test-") + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + for _, k := range []string{"TMPDIR", "TMP", "TEMP"} { // TMP, TEMP: Windows' + os.Setenv(k, tmp) + } + code := testenv.Run(m) + forgetProbes() + if left := leftDownloads(tmp); len(left) > 0 && code == 0 { + fmt.Fprintf(os.Stderr, "library: the tests left %d skill downloads in the temp dir: %s\n", len(left), strings.Join(left, ", ")) + code = 1 + } + os.RemoveAll(tmp) + os.Exit(code) +} + +// forgetProbes ends every cached probe, as its expiry would. +func forgetProbes() { + probes.Lock() + m := probes.m + probes.m = map[string]*probeEntry{} + probes.Unlock() + for _, e := range m { + e.timer.Stop() + os.RemoveAll(e.tmp) + } +} + +func leftDownloads(dir string) []string { + got, _ := filepath.Glob(filepath.Join(dir, skillTemp+"*")) + for i, p := range got { + got[i] = filepath.Base(p) + } + return got +} diff --git a/internal/library/probe_life_test.go b/internal/library/probe_life_test.go new file mode 100644 index 000000000..8f76ddcee --- /dev/null +++ b/internal/library/probe_life_test.go @@ -0,0 +1,78 @@ +package library + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +// #2321: a probe's download goes when it is replaced or expires, not only +// at the next probe, which may never come. +func TestProbeDownloadEndsWithIt(t *testing.T) { + t.Cleanup(forgetProbes) + defer func(l time.Duration) { probeLife = l }(probeLife) + probeLife = time.Hour + first, second := t.TempDir(), t.TempDir() + keepProbe("owner/repo", &Probe{}, first) + keepProbe("owner/repo", &Probe{}, second) + if _, err := os.Stat(first); !os.IsNotExist(err) { + t.Fatalf("the replaced probe's download is still there: %v", err) + } + if _, err := os.Stat(second); err != nil { + t.Fatalf("the probe kept lost its download: %v", err) + } + + probeLife = 20 * time.Millisecond + third := t.TempDir() + keepProbe("owner/other", &Probe{}, third) + deadline := time.Now().Add(time.Minute) + for { + probes.Lock() + _, cached := probes.m["owner/other"] + probes.Unlock() + _, err := os.Stat(third) + if !cached && os.IsNotExist(err) { + break + } + if time.Now().After(deadline) { + t.Fatalf("an expired probe is kept: cached %v, download %v", cached, err) + } + time.Sleep(10 * time.Millisecond) + } +} + +// #2321: a download a magpie that quit left behind goes at the next probe; +// one that may be in use, and what isn't ours, stays. +func TestStaleDownloadsSwept(t *testing.T) { + dir := t.TempDir() + for _, k := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(k, dir) + } + if os.TempDir() != dir { + t.Fatalf("the temp dir is %s, not %s", os.TempDir(), dir) + } + old := filepath.Join(dir, skillTemp+"1") + fresh := filepath.Join(dir, skillTemp+"2") + other := filepath.Join(dir, "someone-else-1") + for _, d := range []string{old, fresh, other} { + if err := os.MkdirAll(filepath.Join(d, "skills"), 0o755); err != nil { + t.Fatal(err) + } + } + long := time.Now().Add(-2 * time.Hour) + for _, d := range []string{old, other} { + if err := os.Chtimes(d, long, long); err != nil { + t.Fatal(err) + } + } + sweepStaleDownloads() + if _, err := os.Stat(old); !os.IsNotExist(err) { + t.Errorf("a download two hours old is still there: %v", err) + } + for _, d := range []string{fresh, other} { + if _, err := os.Stat(d); err != nil { + t.Errorf("%s was swept: %v", filepath.Base(d), err) + } + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index 466b38d65..a978f25e1 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -634,9 +634,57 @@ var probes = struct { }{m: map[string]*probeEntry{}} type probeEntry struct { - p *Probe - tmp string - at time.Time + p *Probe + tmp string + timer *time.Timer // removes it when probeLife is up +} + +// probeLife is how long a probe's download is kept for an install from it. +var probeLife = 15 * time.Minute + +// skillTemp starts the name of a download's folder in the temp dir. +const skillTemp = "magpie-skill-" + +// keepProbe caches p's download under input for probeLife, in place of +// one before it; the folder is removed when it is replaced or expires, not +// only at the next probe, which may never come (#2321). +func keepProbe(input string, p *Probe, tmp string) { + e := &probeEntry{p: p, tmp: tmp} + probes.Lock() + old := probes.m[input] + probes.m[input] = e + e.timer = time.AfterFunc(probeLife, func() { + probes.Lock() + if probes.m[input] == e { + delete(probes.m, input) + } + probes.Unlock() + os.RemoveAll(tmp) + }) + probes.Unlock() + if old != nil { + old.timer.Stop() + os.RemoveAll(old.tmp) + } +} + +// sweepStaleDownloads removes the downloads a magpie that quit left in the +// temp dir (#2321): a folder of ours over an hour old, longer than a probe +// is kept or a fetch takes, so none in use. +func sweepStaleDownloads() { + dir := os.TempDir() + ents, err := os.ReadDir(dir) + if err != nil { + return + } + for _, e := range ents { + if !e.IsDir() || !strings.HasPrefix(e.Name(), skillTemp) { + continue + } + if fi, err := e.Info(); err == nil && time.Since(fi.ModTime()) > time.Hour { + os.RemoveAll(filepath.Join(dir, e.Name())) + } + } } // githubSource reads a repository out of what the user typed: owner/repo, @@ -746,7 +794,7 @@ func fetch(src Source) (string, error) { case resp.StatusCode != 200: return "", fmt.Errorf("GitHub answered %s", resp.Status) } - tmp, err := os.MkdirTemp("", "magpie-skill-") + tmp, err := os.MkdirTemp("", skillTemp) if err != nil { return "", err } @@ -892,14 +940,7 @@ func ProbeSkills(input string) (*Probe, error) { if input == "" { return nil, fmt.Errorf("paste a GitHub link or a folder's path") } - probes.Lock() - for k, e := range probes.m { - if time.Since(e.at) > 15*time.Minute { - os.RemoveAll(e.tmp) - delete(probes.m, k) - } - } - probes.Unlock() + sweepStaleDownloads() p := &Probe{Source: input} if dir := expand(input); filepath.IsAbs(dir) { @@ -921,12 +962,7 @@ func ProbeSkills(input string) (*Probe, error) { } p.Candidates = candidates(tmp, src.Path) p.Left = tookLeftOut(tmp, src.Path) - probes.Lock() - if old := probes.m[input]; old != nil { - os.RemoveAll(old.tmp) - } - probes.m[input] = &probeEntry{p: p, tmp: tmp, at: time.Now()} - probes.Unlock() + keepProbe(input, p, tmp) } else { return nil, fmt.Errorf("that's neither a GitHub repository nor a folder's full path") } diff --git a/internal/library/skilltree.go b/internal/library/skilltree.go index 4202074e4..06baa0acc 100644 --- a/internal/library/skilltree.go +++ b/internal/library/skilltree.go @@ -148,7 +148,7 @@ func fetchSkillFiles(src Source) (string, error) { } files = append(files, file{e.Path, e.SHA, e.Mode == "100755"}) } - tmp, err := os.MkdirTemp("", "magpie-skill-") + tmp, err := os.MkdirTemp("", skillTemp) if err != nil { return "", err }