diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index ee33060e3..afa16b421 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -23,7 +23,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | 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/`), 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/` (#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). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node 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 router | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP router](mcp-router.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) | | MCP market | `MarketServers` lists the featured servers that match a search, then the MCP Registry's; a search that is an address (a repository, a page, an endpoint, a package; `market_addr.go`) finds the ones at it, and `CustomAt` offers one to fill in by hand when none is. The registry lists no server by a repository's folder, so a GitHub address naming one (`#subdirectory=`, `/tree//…`, `parseRepoAt`) is read first: the folder's `pyproject.toml` names the program, and the README's `"env": {…}` examples the keys, offered as `uvx --from git+https://github.com/o/r#subdirectory=p ` (`fromRepo`, CyberCaius on Discord: volcengine/mcp-server's askecho search). A bare repository is read so only when the registry has nothing at it, and a PyPI page, or a one-word search naming mcp the registry lists nothing by, asks PyPI (`fromPyPI`, `uvx `). Of several README keys none is required, since a README often has the user pick one way to sign in (`envInputs`; `TestMarketServerInRepoFolder`). Only Python projects are read from a folder; a Node one there still gets the blank form. | [`market.go`](../../internal/library/market.go), [`market_repo.go`](../../internal/library/market_repo.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//`, `/-/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 -- ` 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//`, `/-/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 -- ` 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), [`skill_beside.go`](../../internal/library/skill_beside.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. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). 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) | @@ -80,7 +80,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - CC Switch's own skills folder is only ever read. - Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either. - A read of the page (`Read`, `Glance`) follows the links on the way to a few hundred paths, most of them many times over: each agent's skills folder for each skill, CC Switch's and the shared folder for each source. While the read holds the lock, `resolve` looks at each entry on the way once (`lookPart` in [`linkmemo.go`](../../internal/library/linkmemo.go)): one `Lstat`, and a `Readlink` for a link. Nothing is kept past the read, so a link made or moved on disk between two visits shows on the second. An entry that couldn't be looked at for another reason than its not being there is unknown and looked at again. One read had taken ~10,000 looks; on oxyuan's Windows machine that was ~1.3s a visit (#1771). -- Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, or a folder that can't be read, is left as it is and goes in `Result.Skipped` with why. The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason. +- Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, is left as it is. One from GitHub or another git repository then goes in beside it under a name of its own (mora1n on Discord: anthropics/skills' and openai/skills' `skill-creator` are two skills): the name with its source's owner added (`skill-creator-openai`), then owner and repository, the repository, then a number, at most 64 bytes (`freeSkillName` in [`skill_beside.go`](../../internal/library/skill_beside.go)). The library's copy of its `SKILL.md` gives that name too (`nameSkill`, only the front matter's top-level `name:` line), so an agent never sees two skills by one name; `Skill.Called` keeps the name its `SKILL.md` gave. Its hash is of the renamed copy, and a check or update compares what it fetches named the same way (`fetchedHash`), so it reads as unchanged and an update keeps the name. Being had is decided by source, not name (`hadSkill`): the same source under any name here, or a skill with no source (taken in from an agent's folder) by that name holding the very same files. A probe's candidate says which (`Candidate.Have`, `Candidate.As`), the page and the TUI show "in the library as …" or "adds as …", the market's had check matches by name only a skill with no repository (`haveSkill`), and the new-skills check no longer drops a skill because its name is taken. A skill already in the library keeps its name, folder and links; nothing is renamed after the fact. A folder of the user's own is linked as it is, so its `SKILL.md` can't be named apart: one by a taken name, or a folder that can't be read, goes in `Result.Skipped` with why (`TestSameNameFromAnotherSourceGoesInBeside`, `TestSameFilesByNameAreHad`, `TestInstallSetPutsAnotherByTheSameNameBeside`, `TestAddFromLibraryFolderKeepsIt`). The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason. ## Verification diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index d88c73109..483a69210 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -5110,7 +5110,11 @@ magpie.plugin("library", (ctx) => { const w = el("span", "who"); w.append(el("span", "name", x.name), el("span", "sub", x.description || x.path || "")); r.append(cb, w); - if (x.have) r.append(tag(t("in the library"), "")); + // another skill from elsewhere has its name (mora1n on Discord): + // this one is in the library, or goes in beside it, by its own + if (x.have && x.as) r.append(tag(t("In the library as {name}", { name: x.as }), "lib-as", t("In the library as {name}", { name: x.as }))); + else if (x.have) r.append(tag(t("in the library"), "")); + else if (x.as) r.append(tag(t("adds as {name}", { name: x.as }), "lib-as", t("The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.", { name: x.name, as: x.as }))); list.append(r); } }; diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index f8939345f..c7cf7dd28 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -716,6 +716,8 @@ magpie.strings({ "Nothing to show.": "暂无内容。", "Remote · sign-in": "远程 · 需登录", "In the library as {name}": "已在资源库中,名为 {name}", + "adds as {name}": "将添加为 {name}", + "The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "资源库里已有一个来自别处、同样叫 {name} 的技能。这一个会以 {as} 为名,和它并存。", "Needs {what} to add": "添加时需要 {what}", "Add…": "添加…", "About {name}": "关于 {name}", @@ -1451,6 +1453,8 @@ magpie.strings({ "Nothing to show.": "暫無內容。", "Remote · sign-in": "遠端 · 需登入", "In the library as {name}": "已在資源庫中,名為 {name}", + "adds as {name}": "將新增為 {name}", + "The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "資源庫裡已有一個來自別處、同樣叫 {name} 的技能。這一個會以 {as} 為名,和它並存。", "Needs {what} to add": "新增時需要 {what}", "Add…": "新增…", "About {name}": "關於 {name}", @@ -2185,6 +2189,8 @@ magpie.strings({ "Nothing to show.": "表示するものがありません。", "Remote · sign-in": "リモート · サインイン", "In the library as {name}": "ライブラリに {name} として登録済み", + "adds as {name}": "{name} として追加", + "The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "ライブラリには別の場所から入れた {name} という名前のスキルがすでにあります。このスキルは {as} として並べて追加されます。", "Needs {what} to add": "追加には {what} が必要です", "Add…": "追加…", "About {name}": "{name} について", @@ -2920,6 +2926,8 @@ magpie.strings({ "Nothing to show.": "Nichts anzuzeigen.", "Remote · sign-in": "Remote · Anmeldung", "In the library as {name}": "In der Bibliothek als {name}", + "adds as {name}": "wird als {name} hinzugefügt", + "The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "Die Bibliothek hat schon einen anderen Skill namens {name} aus einer anderen Quelle. Dieser kommt als {as} daneben hinzu.", "Needs {what} to add": "Zum Hinzufügen wird {what} benötigt", "Add…": "Hinzufügen…", "About {name}": "Über {name}", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 04ab3192f..0a0f73fb3 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -411,6 +411,9 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-pick .who { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } .lib-pick .name { font-size: 13px; font-weight: 500; } .lib-pick .sub { font-size: 11.5px; color: var(--muted); line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +/* "adds as skill-creator-openai": a name can be 64 letters long, so the + tag gives way to the skill's own name and is cut short, its title whole */ +.lib-pick > .lib-tag { flex: 0 1 auto; min-width: 0; max-width: 45%; display: block; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } .lib-probefoot { display: flex; align-items: center; gap: 8px; padding: 8px 4px 0; border-top: 1px solid var(--line-2); flex-wrap: wrap; } .lib-probefoot .note { font-size: 12px; color: var(--muted); } diff --git a/internal/gui/tests/skill-install-beside.test.cjs b/internal/gui/tests/skill-install-beside.test.cjs new file mode 100644 index 000000000..ac73cb35e --- /dev/null +++ b/internal/gui/tests/skill-install-beside.test.cjs @@ -0,0 +1,120 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// mora1n on Discord: anthropics/skills' skill-creator and openai/skills' are +// two skills by one name, and only the first could be added. Now the second +// goes in beside it under a name of its own, and the list of what a +// repository has says so before the click: "adds as skill-creator-openai", +// with why in its title, and one had already under such a name says that +// name. The skill stays pickable, the tag is cut short rather than pushing +// the row wider, in English and Chinese, wide and narrow. No backend: the +// API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/mora1n"; +const long = "a-skill-whose-name-is-as-long-as-the-library-lets-it-be-openai"; +const probe = { + source: "openai/skills", kind: "github", candidates: [ + { path: "skills/skill-creator", name: "skill-creator", description: "Guide for creating effective skills.", have: false, as: "skill-creator-openai" }, + { path: "skills/pdf", name: "pdf", description: "PDFs", have: true, as: "pdf-openai" }, + { path: "skills/docx", name: "docx", description: "Word files", have: false }, + { path: "skills/long", name: "a-skill-whose-name-is-as-long-as-the-library-lets-it-be", description: "Long", have: false, as: long }, + ], +}; +const lib = () => ({ + dir: `${HOME}/.config/magpie/library`, backups: `${HOME}/.config/magpie/backups`, home: HOME, + agents: [{ id: "claude", name: "Claude Code", icon: "", skills: `${HOME}/.claude/skills` }], + instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], +}); + +function server(lang, posts) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib() }); + if (url.pathname === "/api/library/skills/probe") return route.fulfill({ json: probe }); + if (url.pathname === "/api/library/skills/install") { + posts.push(req.postDataJSON().paths); + return route.fulfill({ json: { ...lib(), result: { changed: ["claude"], problems: [], installed: ["skill-creator-openai", "docx"], had: [], skipped: [] } } }); + } + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { adds: "adds as skill-creator-openai", had: "In the library as pdf-openai", why: "The library has another skill called skill-creator, from elsewhere. This one goes in beside it as skill-creator-openai." }, + zh: { adds: "将添加为 skill-creator-openai", had: "已在资源库中,名为 pdf-openai", why: "资源库里已有一个来自别处、同样叫 skill-creator 的技能。这一个会以 skill-creator-openai 为名,和它并存。" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a skill by a name the library has from elsewhere says the name it goes in by", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + const run = async (lang, width) => { + const posts = []; + const ctx = await browser.newContext({ viewport: { width, height: 800 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const src = page.locator('#view-library input[data-lib="source"]'); + await src.fill("openai/skills"); + await src.press("Enter"); + const rows = page.locator("#view-library .lib-pick"); + await rows.first().waitFor(); + const w = words[lang]; + const creator = rows.filter({ hasText: "Guide for creating" }); + const adds = creator.locator(".lib-tag"); + assert.equal((await adds.textContent()).trim(), w.adds); + assert.equal(await adds.getAttribute("title"), w.why); + assert.equal(await creator.locator("input").isDisabled(), false, "it can be picked"); + const had = rows.filter({ hasText: "PDFs" }); + assert.equal((await had.locator(".lib-tag").textContent()).trim(), w.had); + assert.equal(await had.locator("input").isDisabled(), true); + assert.equal(await rows.filter({ hasText: "Word files" }).locator(".lib-tag").count(), 0, "a name nothing has gets no tag"); + // the longest name a skill can have is cut short inside its row, + // never pushing the list wider + const fit = await rows.filter({ hasText: "Long" }).evaluate((r) => { + const tg = r.querySelector(".lib-tag"), box = r.getBoundingClientRect(), b = tg.getBoundingClientRect(); + const list = r.closest(".lib-picks"); + return { inside: b.right <= box.right + 0.5 && b.left >= box.left - 0.5, cut: tg.scrollWidth > tg.clientWidth, over: list.scrollWidth - list.clientWidth, name: r.querySelector(".name").getBoundingClientRect().width }; + }); + assert.equal(fit.inside, true, "the tag stays in its row"); + assert.equal(fit.over, 0, "the list doesn't scroll sideways"); + assert(fit.name > 60, `the skill's own name keeps room (${fit.name}px)`); + if (width < 600) assert.equal(fit.cut, true, "at this width the long tag is cut short"); + // three to add are picked for you, the one beside another among them + assert.equal(await creator.locator("input").isChecked(), true); + await page.locator("#view-library .lib-probefoot button.primary").click(); + await page.waitForTimeout(300); + assert.deepEqual(posts.map((p) => [...p].sort()), [["skills/docx", "skills/long", "skills/skill-creator"]]); + await ctx.close(); + }; + + await t.test("in English", () => run("en", 980)); + await t.test("in Chinese, narrow", () => run("zh", 440)); + + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/carry.go b/internal/library/carry.go index 549db91d3..5ab3f0024 100644 --- a/internal/library/carry.go +++ b/internal/library/carry.go @@ -43,6 +43,8 @@ type CarriedSkill struct { Files map[string][]byte `json:"files"` // by path in the folder, with / Exec []string `json:"exec,omitempty"` // the files that run Left []string `json:"left,omitempty"` // files too big to carry + // Called is the name its SKILL.md gives, when that isn't Name + Called string `json:"called,omitempty"` } // A skill's file bigger than maxCarried is left out, and so are the @@ -102,7 +104,7 @@ func Collect() (*Bundle, error) { } for i, c := range readSkills(dirs) { s := skills[i] - c.Name, c.Source, c.Agents = s.Name, s.Source, orNone(slices.Sorted(slices.Values(s.Agents))) + c.Name, c.Source, c.Agents, c.Called = s.Name, s.Source, orNone(slices.Sorted(slices.Values(s.Agents))), s.Called b.Skills = append(b.Skills, c) } subs := []*Subagent{} @@ -414,7 +416,7 @@ func Put(b *Bundle) (*Result, error) { for _, s := range b.Skills { // turned off here stays off here: that is this computer's own off := l.skill(s.Name) != nil && l.skill(s.Name).OffHere - skills = append(skills, &Skill{Name: s.Name, Source: s.Source, Agents: slices.Clone(orNone(s.Agents)), OffHere: off}) + skills = append(skills, &Skill{Name: s.Name, Source: s.Source, Agents: slices.Clone(orNone(s.Agents)), OffHere: off, Called: s.Called}) if keep[s.Name] { continue } diff --git a/internal/library/market.go b/internal/library/market.go index b5c21ca5d..d4db89e72 100644 --- a/internal/library/market.go +++ b/internal/library/market.go @@ -960,10 +960,12 @@ func (l *Library) haveSkill(source, id, name string) string { } } // one taken in from an agent's folder (npx skills puts them in - // ~/.agents/skills) has no source to match, and adding is turned away - // by name all the same (InstallMarketSkill): it's had by its name + // ~/.agents/skills) has no repository to match: it's had by its name, + // unless it is known to come from another repository. One by that name + // from another repository is another skill, added beside it + // (skill_beside.go) for _, n := range []string{id, name} { - if s := l.skill(n); s != nil { + if s := l.skill(n); s != nil && (s.Source == nil || s.Source.Kind == "folder") && (s.From == "" || strings.EqualFold(s.From, source)) { return s.Name } } diff --git a/internal/library/skill_beside.go b/internal/library/skill_beside.go new file mode 100644 index 000000000..c61d3a4a3 --- /dev/null +++ b/internal/library/skill_beside.go @@ -0,0 +1,187 @@ +package library + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" +) + +// Two skills from different places can go by one name: anthropics/skills' +// skill-creator and openai/skills' are not the same skill (mora1n on +// Discord). The library keeps each under a name of its own, since that +// name is its folder here and in every agent's skills folder: the first +// keeps the name its SKILL.md gives, and one installed after it goes in +// beside it under that name with its source's owner added +// (skill-creator-openai). Called keeps the name its SKILL.md gave. + +// hadSkill is the library's skill that is the one at from already: one +// installed from that very place, whatever its name here, or one by its +// name with no source to tell it by (taken in from an agent's folder) and +// the very same files. +func (l *Library) hadSkill(src Source, c Candidate, from string) *Skill { + for _, s := range l.Skills { + if fromSameSource(s, src, c.Path, from) { + return s + } + } + if s := l.skill(c.Name); s != nil && s.Source == nil && sameTree(skillDir(s.Name), from) { + return s + } + return nil +} + +// skillNameTaken is whether the library has a skill called name, or its +// folder has something by that name. One that can't be looked at is +// taken: what is there is unknown. +func (l *Library) skillNameTaken(name string) bool { + if l.skill(name) != nil { + return true + } + _, err := os.Lstat(skillDir(name)) + return !errors.Is(err, fs.ErrNotExist) +} + +// freeSkillName is the name a skill called name from src goes by in the +// library: name itself while nothing has it, else name with the source's +// owner, then its repository's (or folder's) name, then a number added. +func (l *Library) freeSkillName(name string, src Source) string { + if !l.skillNameTaken(name) { + return name + } + owner, repo := sourceParts(src) + var tries []string + if owner != "" { + tries = append(tries, owner, owner+"-"+repo) + } + if repo != "" { + tries = append(tries, repo) + } + for _, s := range tries { + if n := withSuffix(name, s); n != "" && n != name && !l.skillNameTaken(n) { + return n + } + } + base := owner + if base == "" { + base = repo + } + for i := 2; ; i++ { + suffix := fmt.Sprint(i) + if base != "" { + suffix = base + "-" + suffix + } + if n := withSuffix(name, suffix); n != "" && !l.skillNameTaken(n) { + return n + } + } +} + +// sourceParts is a source's owner and repository: openai and skills for +// openai/skills or https://gitlab.com/openai/skills.git, and for a folder +// the folder it is in and its own name. +func sourceParts(src Source) (owner, repo string) { + var parts []string + if src.Kind == "folder" { + d := filepath.Clean(src.Dir) + parts = []string{filepath.Base(filepath.Dir(d)), filepath.Base(d)} + } else { + r := strings.TrimSuffix(strings.TrimRight(src.Repo, "/"), ".git") + parts = strings.FieldsFunc(r, func(c rune) bool { return c == '/' || c == ':' }) + } + switch len(parts) { + case 0: + return "", "" + case 1: + return "", fitName(parts[0]) + } + return fitName(parts[len(parts)-2]), fitName(parts[len(parts)-1]) +} + +// withSuffix is name-suffix, name cut short so that the whole is a name +// the library takes (nameRe): at most 64 bytes. +func withSuffix(name, suffix string) string { + suffix = fitName(suffix) + if suffix == "" { + return "" + } + if max := 64 - len(suffix) - 1; len(name) > max { + if max < 1 { + return "" + } + name = strings.TrimRight(name[:max], "-_") + } + n := name + "-" + suffix + if !nameRe.MatchString(n) { + return "" + } + return n +} + +// nameSkill sets the name a skill's SKILL.md gives in its front matter to +// name, the folder's: an agent knows a skill by that name, and two by one +// name in an agent are one shadowing the other. Nothing else in it +// changes. A SKILL.md that gives no name already goes by its folder's, +// and one that is a link isn't written through. +func nameSkill(dir, name string) error { + p := filepath.Join(dir, "SKILL.md") + fi, err := os.Lstat(p) + if err != nil || !fi.Mode().IsRegular() { + return err + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + if out, ok := renamedMeta(string(b), name); ok { + return os.WriteFile(p, []byte(out), fi.Mode().Perm()) + } + return nil +} + +// renamedMeta is a SKILL.md with its front matter's top-level name set to +// name, its line endings kept; false when it gives no name to set. +func renamedMeta(s, name string) (string, bool) { + lines := strings.SplitAfter(s, "\n") + if len(lines) == 0 || strings.TrimRight(lines[0], "\r\n") != "---" { + return s, false + } + for i := 1; i < len(lines); i++ { + line := strings.TrimRight(lines[i], "\r\n") + if line == "---" { + break + } + if strings.HasPrefix(line, "name:") { + if strings.TrimSpace(strings.Trim(strings.TrimSpace(line[len("name:"):]), `"'`)) == name { + return s, false + } + lines[i] = "name: " + name + lines[i][len(line):] + return strings.Join(lines, ""), true + } + } + return s, false +} + +// fetchedHash is the hash a skill's files fetched at from have once in +// the library: for one kept under another name than its SKILL.md gives +// (Called), as named there. One that can't be told is "". +func (s *Skill) fetchedHash(from string) string { + if s.Called == "" { + return hashDir(from) + } + tmp, err := os.MkdirTemp("", "magpie-skill-named-") + if err != nil { + return "" + } + defer os.RemoveAll(tmp) + dir := filepath.Join(tmp, s.Name) + if err := copyDir(from, dir); err != nil { + return "" + } + if err := nameSkill(dir, s.Name); err != nil { + return "" + } + return hashDir(dir) +} diff --git a/internal/library/skill_beside_test.go b/internal/library/skill_beside_test.go new file mode 100644 index 000000000..83701b598 --- /dev/null +++ b/internal/library/skill_beside_test.go @@ -0,0 +1,231 @@ +package library + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// skillCreators serves anthropics/skills and openai/skills, each with a +// skill-creator of its own, laid out as the two repositories have them: +// anthropics' and openai's in skills/. version is what openai's says it +// is. +func skillCreators(t *testing.T, version *string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/anthropics/skills/"): + w.Write(tarball(t, map[string]string{ + "skills/skill-creator/SKILL.md": "---\nname: skill-creator\ndescription: Guide for creating effective skills (Anthropic).\nlicense: Complete terms in LICENSE.txt\n---\n\n# Skill Creator\n", + "skills/skill-creator/LICENSE.txt": "Apache", + })) + case strings.HasPrefix(r.URL.Path, "/openai/skills/"): + w.Write(tarball(t, map[string]string{ + "skills/skill-creator/SKILL.md": "---\nname: skill-creator\ndescription: Guide for creating effective skills (OpenAI " + *version + ").\nmetadata:\n short-description: Create or update a skill\n---\n\n# Skill Creator\n", + })) + case strings.HasPrefix(r.URL.Path, "/acme/skills/"): + w.Write(tarball(t, map[string]string{ + "skill-creator/SKILL.md": "---\nname: skill-creator\ndescription: Acme's own\n---\n", + })) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + old := tarballURL + tarballURL = func(repo, ref string) string { return srv.URL + "/" + repo + "/" + ref } + t.Cleanup(func() { tarballURL = old }) +} + +// mora1n on Discord: anthropics' skill-creator and openai's are two +// skills by one name, and only the first could be installed; the second +// was "left as it is". Now the second goes in beside the first under a +// name of its own, its source's owner added, and every agent gets both. +// The first keeps its name, folder and links. +func TestSameNameFromAnotherSourceGoesInBeside(t *testing.T) { + h := sandbox(t) + version := "one" + skillCreators(t, &version) + + ok(t)(InstallSkills("anthropics/skills", []string{"skills/skill-creator"}, []string{"claude"})) + anthropic := read(t, filepath.Join(skillDir("skill-creator"), "SKILL.md")) + + p, err := ProbeSkills("openai/skills") + if err != nil { + t.Fatal(err) + } + if len(p.Candidates) != 1 || p.Candidates[0].Have || p.Candidates[0].As != "skill-creator-openai" { + t.Fatalf("openai's probed as %+v", p.Candidates) + } + r := ok(t)(InstallSkills("openai/skills", []string{"skills/skill-creator"}, []string{"claude"})) + if !slices.Equal(r.Installed, []string{"skill-creator-openai"}) || len(r.Skipped) != 0 { + t.Fatalf("installed %v skipped %+v", r.Installed, r.Skipped) + } + + l, _ := load() + first, second := l.skill("skill-creator"), l.skill("skill-creator-openai") + if first == nil || first.Source.Repo != "anthropics/skills" || first.Called != "" { + t.Errorf("anthropics' is now %+v", first) + } + if second == nil || second.Source.Repo != "openai/skills" || second.Source.Path != "skills/skill-creator" || second.Called != "skill-creator" { + t.Fatalf("openai's is %+v", second) + } + if got := read(t, filepath.Join(skillDir("skill-creator"), "SKILL.md")); got != anthropic { + t.Errorf("anthropics' SKILL.md changed: %q", got) + } + // the agent knows it by its folder's name: two skill-creators in + // one agent would be one hiding the other + want := "---\nname: skill-creator-openai\ndescription: Guide for creating effective skills (OpenAI one).\nmetadata:\n short-description: Create or update a skill\n---\n\n# Skill Creator\n" + if got := read(t, filepath.Join(skillDir("skill-creator-openai"), "SKILL.md")); got != want { + t.Errorf("openai's SKILL.md is %q", got) + } + for _, n := range []string{"skill-creator", "skill-creator-openai"} { + if !ours(filepath.Join(h, ".claude/skills", n), n) { + t.Errorf("claude wasn't given %s", n) + } + } + // named so, it is what was fetched: not changed here, and a check + // finds the same files at its source + if edited, known := l.editState(second, Targets()); edited || !known { + t.Errorf("openai's reads as edited=%v known=%v", edited, known) + } + if got := second.fetchedHash(filepath.Join(p.root, "skills", "skill-creator")); got == "" || got != second.Hash { + t.Errorf("fetched hash %q, library's %q", got, second.Hash) + } + v, _ := Read(nil) + for _, s := range v.Skills { + if s.Name == "skill-creator-openai" && s.Source != "https://github.com/openai/skills/tree/HEAD/skills/skill-creator" { + t.Errorf("openai's source reads %q", s.Source) + } + } + + // installed again, it is had, by the name it has here + r = ok(t)(InstallSkills("openai/skills", []string{"skills/skill-creator"}, nil)) + if len(r.Installed) != 0 || !slices.Equal(r.Had, []string{"skill-creator-openai"}) { + t.Errorf("again: installed %v had %v", r.Installed, r.Had) + } + if p, _ := ProbeSkills("openai/skills"); !p.Candidates[0].Have || p.Candidates[0].As != "skill-creator-openai" { + t.Errorf("probed again: %+v", p.Candidates) + } + // the market sees which repository's it is + l, _ = load() + if got := l.haveSkill("openai/skills", "skill-creator", "skill-creator"); got != "skill-creator-openai" { + t.Errorf("market has openai's as %q", got) + } + if got := l.haveSkill("acme/skills", "skill-creator", "skill-creator"); got != "" { + t.Errorf("market has acme's as %q", got) + } + // a third from elsewhere gets its own owner's name + if r := ok(t)(InstallMarketSkill("acme/skills", "skill-creator", []string{"claude"})); !slices.Equal(r.Installed, []string{"skill-creator-acme"}) { + t.Errorf("acme's: installed %v skipped %+v", r.Installed, r.Skipped) + } + + // an update keeps the name it has here, in its SKILL.md too + version = "two" + ok(t)(UpdateSkill("skill-creator-openai", false)) + got := read(t, filepath.Join(skillDir("skill-creator-openai"), "SKILL.md")) + if !strings.Contains(got, "name: skill-creator-openai\n") || !strings.Contains(got, "(OpenAI two)") { + t.Errorf("after update: %q", got) + } + l, _ = load() + if edited, _ := l.editState(l.skill("skill-creator-openai"), Targets()); edited { + t.Error("the update reads as changed here") + } +} + +// A skill taken in from an agent's folder has no source to tell it by: +// the very same files by its name are had, not installed twice. +func TestSameFilesByNameAreHad(t *testing.T) { + sandbox(t) + version := "one" + skillCreators(t, &version) + p, err := ProbeSkills("acme/skills") + if err != nil { + t.Fatal(err) + } + if err := copyDir(filepath.Join(p.root, "skill-creator"), skillDir("skill-creator")); err != nil { + t.Fatal(err) + } + if _, err := change(func(l *Library) error { + l.Skills = append(l.Skills, &Skill{Name: "skill-creator", Agents: []string{}}) + return nil + }); err != nil { + t.Fatal(err) + } + r := ok(t)(InstallSkills("acme/skills", []string{"skill-creator"}, nil)) + if len(r.Installed) != 0 || !slices.Equal(r.Had, []string{"skill-creator"}) { + t.Errorf("installed %v had %v", r.Installed, r.Had) + } + // another one by that name, with no source, is another skill + r = ok(t)(InstallSkills("openai/skills", []string{"skills/skill-creator"}, nil)) + if !slices.Equal(r.Installed, []string{"skill-creator-openai"}) { + t.Errorf("openai's: installed %v had %v", r.Installed, r.Had) + } +} + +func TestFreeSkillName(t *testing.T) { + sandbox(t) + l := &Library{Skills: []*Skill{{Name: "pdf"}, {Name: "pdf-openai"}, {Name: strings.Repeat("a", 64)}}} + gh := Source{Kind: "github", Repo: "openai/skills"} + for _, c := range []struct { + name string + src Source + want string + }{ + {"docx", gh, "docx"}, + {"pdf", gh, "pdf-openai-skills"}, + {"pdf", Source{Kind: "git", Repo: "git@gitlab.example.com:team/tools.git"}, "pdf-team"}, + {"pdf", Source{Kind: "folder", Dir: "/Users/me/work/kit"}, "pdf-work"}, + {strings.Repeat("a", 64), gh, strings.Repeat("a", 64-len("-openai")) + "-openai"}, + } { + if got := l.freeSkillName(c.name, c.src); got != c.want || !nameRe.MatchString(got) { + t.Errorf("%s from %+v: %q, want %q", c.name, c.src, got, c.want) + } + } + // every other name taken: a number + l.Skills = append(l.Skills, &Skill{Name: "pdf-openai-skills"}, &Skill{Name: "pdf-skills"}) + if got := l.freeSkillName("pdf", gh); got != "pdf-openai-2" { + t.Errorf("all taken: %q", got) + } + // a folder in the library's that it doesn't list is taken too + write(t, filepath.Join(skillDir("docx"), "SKILL.md"), "mine") + if got := l.freeSkillName("docx", gh); got != "docx-openai" { + t.Errorf("unlisted folder: %q", got) + } +} + +func TestRenamedMeta(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {"---\nname: a\ndescription: d\n---\nbody name: a\n", "---\nname: b\ndescription: d\n---\nbody name: a\n"}, + {"---\r\nname: \"a\"\r\n---\r\n", "---\r\nname: b\r\n---\r\n"}, + // a nested name isn't the skill's + {"---\nmetadata:\n name: a\nname: a\n---\n", "---\nmetadata:\n name: a\nname: b\n---\n"}, + {"---\ndescription: d\n---\nname: a\n", "---\ndescription: d\n---\nname: a\n"}, + {"# no front matter\nname: a\n", "# no front matter\nname: a\n"}, + } { + got, _ := renamedMeta(c.in, "b") + if got != c.want { + t.Errorf("%q: %q, want %q", c.in, got, c.want) + } + } + // a SKILL.md that is a link isn't written through + dir := t.TempDir() + other := filepath.Join(dir, "other.md") + write(t, other, "---\nname: a\n---\n") + if err := os.MkdirAll(filepath.Join(dir, "s"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(other, filepath.Join(dir, "s", "SKILL.md")); err != nil { + t.Skip(err) + } + if err := nameSkill(filepath.Join(dir, "s"), "b"); err != nil { + t.Fatal(err) + } + if got := read(t, other); got != "---\nname: a\n---\n" { + t.Errorf("written through the link: %q", got) + } +} diff --git a/internal/library/skill_skip_test.go b/internal/library/skill_skip_test.go index da5e6262a..17fa065dd 100644 --- a/internal/library/skill_skip_test.go +++ b/internal/library/skill_skip_test.go @@ -52,13 +52,15 @@ func TestInstallSetSkipsOneInTheWay(t *testing.T) { write(t, filepath.Join(skillDir("caveman-commit"), "notes.md"), "keep me") r := ok(t)(InstallSkills("owner/caveman", []string{"skills/caveman", "skills/caveman-commit", "skills/caveman-review"}, []string{"claude"})) - if !slices.Equal(r.Installed, []string{"caveman-review"}) { + // the repository's caveman-commit goes in beside the user's, by a + // name of its own (mora1n on Discord) + if !slices.Equal(r.Installed, []string{"caveman-commit-owner", "caveman-review"}) { t.Errorf("installed %v", r.Installed) } if !slices.Equal(r.Had, []string{"caveman"}) { t.Errorf("had %v", r.Had) } - if !slices.Equal(skipped(r), []string{"caveman-commit"}) || !strings.Contains(r.Skipped[0].Error, "left as it is") { + if len(r.Skipped) != 0 { t.Errorf("skipped %+v", r.Skipped) } if got := read(t, filepath.Join(skillDir("caveman"), "SKILL.md")); got != edited { @@ -77,6 +79,9 @@ func TestInstallSetSkipsOneInTheWay(t *testing.T) { if l.skill("caveman-commit") != nil { t.Error("the user's own caveman-commit was listed as the repository's") } + if s := l.skill("caveman-commit-owner"); s == nil || s.Called != "caveman-commit" || s.Source.Path != "skills/caveman-commit" { + t.Errorf("the repository's caveman-commit is %+v", s) + } // a set whose every skill is had already is no error r = ok(t)(InstallSkills("owner/caveman", []string{"skills/caveman", "skills/caveman-review"}, []string{"claude"})) @@ -84,7 +89,7 @@ func TestInstallSetSkipsOneInTheWay(t *testing.T) { t.Errorf("again: installed %v had %v", r.Installed, r.Had) } // one skill alone that can't be installed still fails, saying why - if _, err := InstallSkills("owner/caveman", []string{"skills/caveman-commit"}, nil); err == nil || !strings.Contains(err.Error(), "left as it is") { + if _, err := InstallSkills("owner/caveman", []string{"skills/nowhere"}, nil); err == nil || !strings.Contains(err.Error(), "no skill at") { t.Errorf("alone: %v", err) } // the market's install of one the library has is had, not an error @@ -122,9 +127,10 @@ func TestInstallListsItsOwnLeftoverFolder(t *testing.T) { } } -// A skill by that name the library lists from somewhere else is the -// user's: left as it is and said, the rest installed. -func TestInstallSetSkipsAnotherByTheSameName(t *testing.T) { +// A skill by that name the library lists from somewhere else is another +// skill: it stays as it is, and the repository's goes in beside it by a +// name of its own (mora1n on Discord). +func TestInstallSetPutsAnotherByTheSameNameBeside(t *testing.T) { h := sandbox(t) cavemanRepo(t) src := filepath.Join(h, "src") @@ -132,7 +138,7 @@ func TestInstallSetSkipsAnotherByTheSameName(t *testing.T) { ok(t)(InstallSkills(src, []string{"caveman"}, []string{"claude"})) r := ok(t)(InstallSkills("owner/caveman", []string{"skills/caveman", "skills/caveman-review"}, []string{"claude"})) - if !slices.Equal(r.Installed, []string{"caveman-review"}) || !slices.Equal(skipped(r), []string{"caveman"}) { + if !slices.Equal(r.Installed, []string{"caveman-owner", "caveman-review"}) || len(r.Skipped) != 0 { t.Errorf("installed %v skipped %+v", r.Installed, r.Skipped) } l, _ := load() @@ -142,4 +148,12 @@ func TestInstallSetSkipsAnotherByTheSameName(t *testing.T) { if got := read(t, filepath.Join(skillDir("caveman"), "SKILL.md")); !strings.Contains(got, "Another caveman") { t.Errorf("caveman's SKILL.md is now %q", got) } + if got := read(t, filepath.Join(skillDir("caveman-owner"), "SKILL.md")); !strings.HasPrefix(got, "---\nname: caveman-owner\n") || !strings.Contains(got, "Talk like caveman") { + t.Errorf("caveman-owner's SKILL.md is %q", got) + } + for _, n := range []string{"caveman", "caveman-owner"} { + if !ours(filepath.Join(h, ".claude/skills", n), n) { + t.Errorf("claude wasn't given %s", n) + } + } } diff --git a/internal/library/skillcheck.go b/internal/library/skillcheck.go index f9266cef7..5c71dadd3 100644 --- a/internal/library/skillcheck.go +++ b/internal/library/skillcheck.go @@ -491,7 +491,7 @@ func checkSkill(s *Skill, f *fetcher, asked map[string]*commit, limited *atomic. if have == "" { have = hashDir(skillDir(s.Name)) // installed before magpie kept it } - if theirs := hashDir(from); theirs == "" || theirs != have { + if theirs := s.fetchedHash(from); theirs == "" || theirs != have { c.Status, c.URL = "update", history return c, "", "" } diff --git a/internal/library/skillgit.go b/internal/library/skillgit.go index 3cfdc74c2..d687103ac 100644 --- a/internal/library/skillgit.go +++ b/internal/library/skillgit.go @@ -445,7 +445,7 @@ func checkGitSkill(s *Skill, f *fetcher, asked map[string]string) (SkillCheck, s if have == "" { have = hashDir(skillDir(s.Name)) } - if theirs := hashDir(from); theirs == "" || theirs != have { + if theirs := s.fetchedHash(from); theirs == "" || theirs != have { c.Status = "update" return c, "", "" } diff --git a/internal/library/skillnew.go b/internal/library/skillnew.go index 81081f308..adb9ee915 100644 --- a/internal/library/skillnew.go +++ b/internal/library/skillnew.go @@ -6,6 +6,7 @@ import ( "fmt" "net/url" slash "path" // a repository's paths, always with / + "path/filepath" "slices" "sort" "strings" @@ -286,7 +287,10 @@ func findNew(l *Library, repo, ref string, f *fetcher, limited *atomic.Pointer[e found = []NewSkill{} from := (&Source{Kind: "github", Repo: repo, Ref: ref, Path: base}).String() 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 { + // another skill by its name, from elsewhere, doesn't make it the + // library's: it would go in beside that one (skill_beside.go) + if known[c.Path] || checkName("skill", c.Name) != nil || + l.hadSkill(Source{Kind: "github", Repo: repo, Ref: ref}, c, filepath.Join(tmp, filepath.FromSlash(c.Path))) != nil { continue } id := (&Source{Kind: "github", Repo: repo, Ref: ref, Path: c.Path}).String() @@ -303,7 +307,7 @@ func newSkills(l *Library) []NewSkill { out := []NewSkill{} for k, list := range newFound.m { for _, n := range list { - if repoKey(n.Repo, n.Ref) != k || len(l.fromRepo(n.Repo, n.Ref)) == 0 || l.skill(n.Name) != nil || + if repoKey(n.Repo, n.Ref) != k || len(l.fromRepo(n.Repo, n.Ref)) == 0 || slices.Contains(l.SeenSkills[k], n.Path) { continue } diff --git a/internal/library/skills.go b/internal/library/skills.go index 4a7593be2..2ae9b6767 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -54,6 +54,10 @@ type Skill struct { // what a sync carries and stays as the other computers have it; this // is never carried (Collect leaves it out) and a sync keeps it (Put). OffHere bool `json:"offHere,omitempty"` + // Called is the name its SKILL.md gives, when the library keeps it + // under another because a skill from elsewhere had that name first + // (skill_beside.go). Its SKILL.md is named as the library names it. + Called string `json:"called,omitempty"` } // gives reports whether the agent id gets the skill on this computer: it @@ -717,7 +721,10 @@ type Candidate struct { Path string `json:"path"` // in the repository or the folder; "" for its root Name string `json:"name"` Description string `json:"description"` - Have bool `json:"have"` // the library has a skill by that name + Have bool `json:"have"` // the library has this skill (from here, or the very same files) + // As is the name the library has it by, or would add it by, when + // that isn't Name: another skill from elsewhere has that name + As string `json:"as,omitempty"` } // Probe is what was found at a source. @@ -1168,7 +1175,21 @@ func probeSkills(input, name string) (*Probe, error) { } if l, err := load(); err == nil { for i, c := range p.Candidates { - p.Candidates[i].Have = l.skill(c.Name) != nil + from := filepath.Join(p.root, filepath.FromSlash(c.Path)) + if s := l.hadSkill(p.src, c, from); s != nil { + p.Candidates[i].Have = true + if s.Name != c.Name { + p.Candidates[i].As = s.Name + } + } else if l.skill(c.Name) != nil { + if p.src.remote() { + p.Candidates[i].As = l.freeSkillName(c.Name, p.src) + } else { + // a folder of the user's isn't added beside it + // (installFrom): shown as had by that name, as before + p.Candidates[i].Have = true + } + } } } noteFrom(p.src, p.root, p.Candidates) @@ -1285,47 +1306,66 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i from := filepath.Join(p.root, filepath.FromSlash(c.Path)) src := p.src // the same skill from the same place is had already, whatever - // the user has changed in it since; another by that name is theirs - if s := l.skill(c.Name); s != nil { - if fromSameSource(s, src, c.Path, from) { - in.had = append(in.had, c.Name) - } else { - in.skip(c.Name, fmt.Errorf("the library already has another skill called %s, left as it is", c.Name)) - } + // the user has changed in it since and whatever it is called + // here; another by that name goes in beside it, by a name of its + // own (skill_beside.go) + if s := l.hadSkill(src, c, from); s != nil { + in.had = append(in.had, s.Name) continue } - dir := skillDir(c.Name) + name := c.Name + if l.skill(name) != nil { + // the user's own folder is linked as it is, and its SKILL.md + // can't be named apart from the other: an agent would see two + // by one name + if !src.remote() { + in.skip(c.Name, fmt.Errorf("the library already has another skill called %s, left as it is: give this one another name in its SKILL.md to add it beside it", c.Name)) + continue + } + name = l.freeSkillName(c.Name, src) + } + dir := skillDir(name) // something by that name in the library's folder that the // library doesn't list is never written into: that would mix // two skills' files, and a failed copy would take it away. One // holding exactly this skill's files (an install that stopped - // before the library was saved left it) is listed where it is. + // before the library was saved left it) is listed where it is; + // another is the user's, and this one goes in beside it. + listed := false if _, err := os.Lstat(dir); err == nil { switch { case src.Kind == "folder" && linked(dir) && realDir(dir) == realDir(from): - src.Dir = from + src.Dir, listed = from, true case src.remote() && !linked(dir) && sameTree(dir, from): - src.Path = c.Path + src.Path, listed = c.Path, true case src.Kind == "folder" && realDir(from) == realDir(dir): // a folder already in the library's own (#595): linked to // itself it fails, and copied onto itself every file of it // was emptied in.skip(c.Name, fmt.Errorf("%s is in the library's folder already: bring it in from the skills found there", c.Name)) continue - default: + case !src.remote(): in.skip(c.Name, fmt.Errorf("the library's folder already has a %s that isn't this one (%s), left as it is: bring it in from the skills found there to use it", c.Name, dir)) continue + default: + name = l.freeSkillName(c.Name, src) + dir = skillDir(name) } - in.had = append(in.had, c.Name) } else if !errors.Is(err, fs.ErrNotExist) { // can't tell what is there: left alone in.skip(c.Name, err) continue - } else if src.Kind == "folder" { + } + switch { + case listed: + in.had = append(in.had, name) + case src.Kind == "folder": + // the user's folder, linked: its files stay as they are, its + // SKILL.md's name too src.Dir = from if err := dirLink(from, dir); err != nil { if errors.Is(err, fs.ErrExist) { - in.skip(c.Name, fmt.Errorf("the library's folder already has a %s in it (%s)", c.Name, dir)) + in.skip(c.Name, fmt.Errorf("the library's folder already has a %s in it (%s)", name, dir)) continue } if err := copyDir(from, dir); err != nil { @@ -1334,17 +1374,27 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i continue } } - in.added = append(in.added, c.Name) - } else { + in.added = append(in.added, name) + default: src.Path = c.Path if err := copyDir(from, dir); err != nil { os.RemoveAll(dir) in.skip(c.Name, err) continue } - in.added = append(in.added, c.Name) + if name != c.Name { + if err := nameSkill(dir, name); err != nil { + os.RemoveAll(dir) + in.skip(c.Name, err) + continue + } + } + in.added = append(in.added, name) + } + sk := &Skill{Name: name, Source: &src, Agents: slices.Clone(agents)} + if name != c.Name { + sk.Called = c.Name } - sk := &Skill{Name: c.Name, Source: &src, Agents: slices.Clone(agents)} if src.Kind == "git" { sk.Hash, sk.Own, sk.Commit = hashDir(dir), ownHash(dir), gitHeadOf(p.root) } @@ -1359,7 +1409,7 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i } } } - forgetCheck(c.Name) + forgetCheck(name) l.Skills = append(l.Skills, sk) } return nil @@ -1655,6 +1705,13 @@ func (up *skillUpdate) apply(l *Library, targets []*Target) error { os.RemoveAll(next) return err } + // one kept under another name than its SKILL.md gives stays named so + if s := l.skill(name); s != nil && s.Called != "" { + if err := nameSkill(next, name); err != nil { + os.RemoveAll(next) + return err + } + } hash, own := hashDir(next), ownHash(next) if fi, err := os.Lstat(skillDir(name)); err == nil && linkEntry(fi) { // a link to CC Switch's folder: only the link goes diff --git a/internal/tui/library.go b/internal/tui/library.go index a910ac7f0..1cec691b8 100644 --- a/internal/tui/library.go +++ b/internal/tui/library.go @@ -450,8 +450,14 @@ func (m *model) openProbe(p *library.Probe) { var items []agent.Option for _, c := range p.Candidates { note := c.Description - if c.Have { + switch { + case c.Have && c.As != "": + note = "in the library as " + c.As + " · " + note + case c.Have: note = "in the library already · " + note + case c.As != "": + // another skill from elsewhere has its name + note = "adds as " + c.As + " · " + note } v := c.Path if v == "" {