Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

library: every skill named in another script is listed, under its folder's name

yetone033b17bafe0e
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md
index 34f7acc54..619faa731 100644
--- a/docs/subsystems/library.md
+++ b/docs/subsystems/library.md
@@ -21,7 +21,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
| 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`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `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. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`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. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `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). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). 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/<name>`), 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 refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and the row says "signed in in Claude Code (Ubuntu)" instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#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:<port>/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). A server run as `npx -y <package> args` (a registry package, no other npx flag) is given to an agent on this machine as `node <the package's bin> args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) |
| MCP hub | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/<agent>`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP hub](mcp-hub.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) |
-| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree/<ref>/<path>`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- <url> <ref>` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). 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`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). 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), [`skillgit.go`](../../internal/library/skillgit.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 goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree/<ref>/<path>`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- <url> <ref>` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). 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`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). 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), [`skillgit.go`](../../internal/library/skillgit.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`), in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills), go first, marked official: `magpie-setup` has an agent set magpie up as the user asks through its commands (providers, accounts, agents, routing groups and rules, gateway keys and limits, models, the library), and `magpie-quota` lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Their commands live in magpie's CLI, so a change to a command either uses gets the skill updated in that repository. 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/ccswitch.go b/internal/library/ccswitch.go
index 1536a8640..e3e2235a7 100644
--- a/internal/library/ccswitch.go
+++ b/internal/library/ccswitch.go
@@ -37,7 +37,7 @@ func ccSwitchOrigin(s *Skill) (Source, bool) {
// origin finds the skill in the repository fetched for it: the folder
// named as CC Switch named it, or the skill of that name.
func origin(root string, src Source, name string) (string, bool) {
- for _, c := range candidates(root, "") {
+ for _, c := range candidates(root, "", srcFolder(src)) {
if lastPart(c.Path) == src.Path || c.Name == name {
return c.Path, true
}
diff --git a/internal/library/skill_from.go b/internal/library/skill_from.go
index 83d82c023..a7abd76c5 100644
--- a/internal/library/skill_from.go
+++ b/internal/library/skill_from.go
@@ -378,7 +378,7 @@ func RegroupSkills() (int, error) {
continue
}
fetched++
- noted += noteFrom(src, root, candidates(root, ""))
+ noted += noteFrom(src, root, candidates(root, "", srcFolder(src)))
os.RemoveAll(root)
}
if fetched == 0 && first != nil {
diff --git a/internal/library/skill_names_test.go b/internal/library/skill_names_test.go
new file mode 100644
index 000000000..ce568882d
--- /dev/null
+++ b/internal/library/skill_names_test.go
@@ -0,0 +1,151 @@
+package library
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+)
+
+// tnt1223 on Discord: asdfgh1445/ctf-super-hub has 35 skills, one folder
+// each at the top, and the page listed 16. Each SKILL.md names its skill in
+// Chinese after a "CTF•" or "Strix•", and made fit for a file name the
+// names fell to "CTF" (11 of them), "Strix" (10) and "" (头脑风暴), which
+// were listed once each. The folders and names are the repository's own,
+// at 7715719, quotes as written.
+var ctfSuperHub = []struct{ dir, name string }{
+ {"brainstorming", `"头脑风暴"`},
+ {"ctf-ai-ml", `"CTF•AI/ML 攻防"`},
+ {"ctf-beginner-hub", `"CTF•新手入口"`},
+ {"ctf-crypto", `"CTF•密码学"`},
+ {"ctf-forensics", `"CTF•数字取证"`},
+ {"ctf-malware", `"CTF•恶意软件分析"`},
+ {"ctf-misc", `"CTF•杂项"`},
+ {"ctf-osint", `"CTF•开源情报"`},
+ {"ctf-pwn", `"CTF•二进制利用"`},
+ {"ctf-reverse", `"CTF•逆向工程"`},
+ {"ctf-super-hub", `"CTF•超级总控"`},
+ {"ctf-web", `"CTF•Web 漏洞"`},
+ {"ctf-writeup", `"CTF•题解写作"`},
+ {"solve-challenge", `"CTF•挑战调度器"`},
+ {"strix-authentication-jwt", `Strix•JWT 身份认证测试`},
+ {"strix-beginner-hub", `Strix•新手入口`},
+ {"strix-broken-function-level-authorization", `Strix•功能级授权缺陷`},
+ {"strix-business-logic", `Strix•业务逻辑漏洞`},
+ {"strix-csrf", `Strix•CSRF 测试`},
+ {"strix-ffuf", `Strix•ffuf 用法`},
+ {"strix-httpx", `Strix•httpx 用法`},
+ {"strix-idor", `Strix•IDOR 测试`},
+ {"strix-information-disclosure", `Strix•信息泄露测试`},
+ {"strix-insecure-file-uploads", `Strix•不安全文件上传`},
+ {"strix-katana", `Strix•Katana 用法`},
+ {"strix-nuclei", `Strix•Nuclei 用法`},
+ {"strix-open-redirect", `Strix•开放重定向`},
+ {"strix-path-traversal-lfi-rfi", `Strix•路径穿越与文件包含`},
+ {"strix-quick", `Strix•快速扫描`},
+ {"strix-rce", `Strix•远程代码执行`},
+ {"strix-sql-injection", `Strix•SQL 注入`},
+ {"strix-sqlmap", `Strix•sqlmap 用法`},
+ {"strix-ssrf", `Strix•SSRF 测试`},
+ {"strix-standard", `Strix•标准扫描`},
+ {"strix-xss", `Strix•XSS 测试`},
+}
+
+func TestSkillsNamedInAnotherScriptAllListed(t *testing.T) {
+ sandbox(t)
+ files := map[string]string{
+ "README.md": "# CTF Super Hub\n",
+ "SKILL-INDEX.md": "| skill |\n",
+ "docs/guide.md": "guide\n",
+ "evals/README.md": "evals\n",
+ "scripts/install.sh": "#!/bin/sh\n",
+ ".github/workflows/validate.yml": "on: push\n",
+ }
+ var want []string
+ for _, s := range ctfSuperHub {
+ files[s.dir+"/SKILL.md"] = "---\nname: " + s.name + "\ndescription: \"用于 " + s.dir + ";触发名:" + s.dir + "\"\n---\n\n# " + s.dir + "\n"
+ files[s.dir+"/references/notes.md"] = "notes\n"
+ want = append(want, s.dir)
+ }
+ fakeSkillRepo(t, files)
+
+ p, err := ProbeSkills("https://github.com/asdfgh1445/ctf-super-hub")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var paths, names []string
+ for _, c := range p.Candidates {
+ paths, names = append(paths, c.Path), append(names, c.Name)
+ if !nameRe.MatchString(c.Name) {
+ t.Errorf("%s goes by %q, which the library can't hold", c.Path, c.Name)
+ }
+ }
+ slices.Sort(paths)
+ if !slices.Equal(paths, want) {
+ t.Errorf("listed %d skills %v, want all %d", len(paths), paths, len(want))
+ }
+ if !slices.Equal(names, want) { // sorted by name, each its folder's
+ t.Errorf("names %v, want %v", names, want)
+ }
+
+ r, err := InstallSkills("https://github.com/asdfgh1445/ctf-super-hub", []string{"ctf-crypto", "strix-rce", "brainstorming"}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := slices.Sorted(slices.Values(r.Installed)); !slices.Equal(got, []string{"brainstorming", "ctf-crypto", "strix-rce"}) {
+ t.Errorf("installed %v", r.Installed)
+ }
+ if _, err := os.Stat(filepath.Join(skillDir("ctf-crypto"), "references", "notes.md")); err != nil {
+ t.Errorf("ctf-crypto's files: %v", err)
+ }
+}
+
+// A name in ASCII goes as it did, its spaces and marks made dashes, so a
+// skill installed from it before is still the one the library has. A name
+// in another script with no folder name to fall back on keeps what is left
+// of it. A skill at the top of a repository goes by the repository's name,
+// not the temporary folder it was downloaded to.
+func TestSkillNameFallsBackToFolderOnlyWhenLettersAreLost(t *testing.T) {
+ for _, c := range []struct{ folder, name, want string }{
+ {"my-skill", "My Skill", "My-Skill"},
+ {"pdf", "pdf", "pdf"},
+ {"x", "", "x"},
+ {"ctf-crypto", "CTF•密码学", "ctf-crypto"},
+ {"brainstorming", "头脑风暴", "brainstorming"},
+ {"cafe-notes", "Café notes", "cafe-notes"},
+ {"技能", "头脑风暴", ""},
+ {"技能", "CTF•密码学", "CTF"},
+ } {
+ if got := nameFor(c.folder, meta{Name: c.name}); got != c.want {
+ t.Errorf("nameFor(%s, %q) = %q, want %q", c.folder, c.name, got, c.want)
+ }
+ }
+ for _, c := range []struct {
+ src Source
+ want string
+ }{
+ {Source{Kind: "github", Repo: "asdfgh1445/ctf-super-hub"}, "ctf-super-hub"},
+ {Source{Kind: "git", Repo: "https://gitlab.example.com/group/skills.git"}, "skills"},
+ {Source{Kind: "git", Repo: "[email protected]:group/skills.git"}, "skills"},
+ {Source{Kind: "git", Repo: "git@host:skills"}, "skills"},
+ {Source{Kind: "folder", Dir: filepath.FromSlash("/home/me/my-skill")}, "my-skill"},
+ } {
+ if got := srcFolder(c.src); got != c.want {
+ t.Errorf("srcFolder(%+v) = %q, want %q", c.src, got, c.want)
+ }
+ }
+}
+
+// A repository that is one skill at its top, named in another script, is
+// listed under the repository's name.
+func TestSkillAtTheTopNamedInAnotherScript(t *testing.T) {
+ sandbox(t)
+ fakeSkillRepo(t, map[string]string{"SKILL.md": "---\nname: \"头脑风暴\"\ndescription: d\n---\n"})
+ p, err := ProbeSkills("asdfgh1445/brainstorming")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(p.Candidates) != 1 || p.Candidates[0].Name != "brainstorming" || p.Candidates[0].Path != "" {
+ t.Errorf("candidates %+v, want brainstorming at the top", p.Candidates)
+ }
+}
diff --git a/internal/library/skillnew.go b/internal/library/skillnew.go
index cbad1451d..81081f308 100644
--- a/internal/library/skillnew.go
+++ b/internal/library/skillnew.go
@@ -285,7 +285,7 @@ func findNew(l *Library, repo, ref string, f *fetcher, limited *atomic.Pointer[e
sort.Strings(agents)
found = []NewSkill{}
from := (&Source{Kind: "github", Repo: repo, Ref: ref, Path: base}).String()
- for _, c := range candidates(tmp, base) {
+ for _, c := range candidates(tmp, base, srcFolder(Source{Kind: "github", Repo: repo})) {
if known[c.Path] || l.skill(c.Name) != nil || checkName("skill", c.Name) != nil {
continue
}
diff --git a/internal/library/skills.go b/internal/library/skills.go
index d4d9ce0ad..bfc509b1d 100644
--- a/internal/library/skills.go
+++ b/internal/library/skills.go
@@ -20,6 +20,7 @@ import (
"strings"
"sync"
"time"
+ "unicode"
"github.com/yetone/magpie/internal/source"
"gopkg.in/yaml.v3"
@@ -139,13 +140,37 @@ func parseMeta(b []byte) meta {
var unsafe = regexp.MustCompile(`[^A-Za-z0-9_-]+`)
-// nameFor is the name a skill found at dir goes by: what its SKILL.md
-// says, else its folder's, made fit for a file name.
-func nameFor(dir string, m meta) string {
- n := m.Name
- if n == "" {
- n = filepath.Base(dir)
+// nameFor is the name a skill in the folder named folder goes by: what its
+// SKILL.md says, made fit for a file name. A name in another script doesn't
+// survive that: asdfgh1445/ctf-super-hub's "CTF•密码学" and ten more were
+// all "CTF", "Strix•RCE 测试" and ten more "Strix", and "头脑风暴" nothing,
+// so 35 skills were listed as 16 (tnt1223 on Discord). Such a name, or
+// none, goes by its folder's name instead, which a repository keeps apart;
+// only a folder whose name is no name either leaves the name as it came
+// out.
+func nameFor(folder string, m meta) string {
+ if n := fitName(m.Name); n != "" && !dropsLetters(m.Name) {
+ return n
}
+ if n := fitName(folder); n != "" {
+ return n
+ }
+ return fitName(m.Name)
+}
+
+// srcFolder is the name of the folder a source's top is: a repository's
+// own name, not the temporary folder it was downloaded to.
+func srcFolder(src Source) string {
+ if src.Kind == "folder" {
+ return filepath.Base(src.Dir)
+ }
+ r := strings.TrimSuffix(strings.TrimRight(src.Repo, "/"), ".git")
+ return r[strings.LastIndexAny(r, "/:")+1:]
+}
+
+// fitName is a name made fit for a file name: anything but ASCII letters,
+// digits, _ and - is a -, and it is at most 64 bytes.
+func fitName(n string) string {
n = strings.Trim(unsafe.ReplaceAllString(n, "-"), "-_")
if len(n) > 64 {
n = n[:64]
@@ -153,6 +178,14 @@ func nameFor(dir string, m meta) string {
return n
}
+// dropsLetters is whether making n fit for a file name loses a letter or
+// digit of it, not only a space or a mark between words.
+func dropsLetters(n string) bool {
+ return strings.ContainsFunc(n, func(r rune) bool {
+ return r > unicode.MaxASCII && (unicode.IsLetter(r) || unicode.IsDigit(r))
+ })
+}
+
// ---- linking into agents --------------------------------------------------
// marker is left in a copy magpie makes where it can't link (Windows
@@ -931,17 +964,18 @@ func untar(r io.Reader, dst string) error {
// skills folder: some repositories keep their skill only in
// .claude/skills (#1964, UFO404). A skill the repository holds twice, in a
// hidden folder or a plugin's, is listed once (unhiddenFirst).
-func candidates(root, sub string) []Candidate {
+func candidates(root, sub, top string) []Candidate {
base := filepath.Join(root, filepath.FromSlash(sub))
var out []Candidate
var walk func(dir string, depth int)
walk = func(dir string, depth int) {
if m, ok := readMeta(dir); ok {
rel, _ := filepath.Rel(root, dir)
+ folder := filepath.Base(dir)
if rel == "." {
- rel = ""
+ rel, folder = "", top
}
- out = append(out, Candidate{Path: filepath.ToSlash(rel), Name: nameFor(dir, m), Description: m.Description})
+ out = append(out, Candidate{Path: filepath.ToSlash(rel), Name: nameFor(folder, m), Description: m.Description})
return
}
if depth == 0 {
@@ -1072,7 +1106,7 @@ func probeSkills(input, name string) (*Probe, error) {
return nil, fmt.Errorf("%s isn't a folder", input)
}
p.Kind, p.root, p.src = "folder", dir, Source{Kind: "folder", Dir: dir}
- p.Candidates = candidates(dir, "")
+ p.Candidates = candidates(dir, "", filepath.Base(dir))
} else if src, ok := githubSource(input); ok || isGit(input) {
if !ok {
src, _, _ = gitSource(input)
@@ -1086,7 +1120,7 @@ func probeSkills(input, name string) (*Probe, error) {
os.RemoveAll(tmp)
return nil, fmt.Errorf("%s has no folder %s", src.Repo, src.Path)
}
- p.Candidates = candidates(tmp, src.Path)
+ p.Candidates = candidates(tmp, src.Path, srcFolder(src))
p.Left = tookLeftOut(tmp, src.Path)
key := input
if part && name != "" {