diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index f73d68bb8..fa1f8d1a2 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -28,7 +28,7 @@ Pi's extensions and packages. | MCP server on/off | `ServerOn` (`POST /api/library/servers/on` with `name` and `on`, `magpie library mcp off|on `) turns a server off for everyone without removing it (swang20201 on X, Docker gateway mode, where a server ticked for no agent is still given to every app at the MCP router's address). Off, it is `Hidden` with its agents kept in `Paused` and `Agents` empty, as a plugin's server hidden from agents is (`PluginServerOn`, [Plugin tools](plugin-tools.md)): no agent's file has it, no project's (`syncProjectMCP` skips it, keeping the project's own agents for it), no subagent names it (`renderSubagent`), the router lists and calls it for nobody, and a process the router held for it ends, since `Hidden` and `Paused` are part of its `hubKey`. Its command, URL, env, headers, sign-in, `DisabledTools` and note stay in library.json. On, the agents in `Paused` get it back (none when it had none, so the router gives it to other apps again), as before it was turned off; giving it agents (`ServerAgents`, the CLI's `mcp agents`) turns it on with those (`save`), while Turn all on (`EveryServerAgents` with every agent) leaves it off. The row's switch sits after its agent chips (`serverSwitch` in plugins/library/client.js); off, the row is dimmed, its chips take no click, and it is health-checked only on a click (`TestServerOnKeepsAndRestores`, `TestLibraryMCPOffOn`, `library-mcp-on.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.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. A registry package is started the way its entry says (`launchLine`): its `runtimeArguments` are the runner's options (`uvx -p 3.13`, `npx --package`, docker's mounts) and the program's own words (Serena's `start-mcp-server`), then its `packageArguments`; an executable not named after the package is reached with `uvx --from ` or `npx --package `. The shipped crawl keeps each package's executables (`bins`, from npm's `bin` and the wheel's console scripts); a package with none, several with none standing out (`pickBin`), or a required option magpie can't fill isn't offered. A server installed from the market before, still on the line magpie gave it then, is given the new one on load (`healMarketLines`; fwxkogaia on X, `TestRegistryLaunchLines`, `TestInstalledMarketLineHealed`). | [`market.go`](../../internal/library/market.go), [`market_launch.go`](../../internal/library/market_launch.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`). A front matter setting `disable-model-invocation: true` marks it "Manual only" in the page, in the library and in the agents' own (`meta.Manual`, `SkillView.Manual`, `FoundSkill.Manual`; sunset3279 on Discord): Claude Code runs such a skill only on the user's `/name`. A front matter that doesn't parse, or a value that isn't a bool, is not known to be, and gets no mark (`TestSkillManualFromFrontMatter`, `skill-manual.test.cjs`). 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 gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). 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 | 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`). A front matter setting `disable-model-invocation: true` marks it "Manual only" in the page, in the library and in the agents' own (`meta.Manual`, `SkillView.Manual`, `FoundSkill.Manual`; sunset3279 on Discord): Claude Code runs such a skill only on the user's `/name`. A front matter that doesn't parse, or a value that isn't a bool, is not known to be, and gets no mark (`TestSkillManualFromFrontMatter`, `skill-manual.test.cjs`). 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 gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). 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 of the user's own is made with `CreateSkill` (`POST /api/library/skills/create`, Skills > New skill; josephBenchap on X): a name (`checkName`, and not one the library or an agent has, compared without case, nor a folder in the way) and a one-line description of at most 1024 characters make `skills//SKILL.md` with `name` and `description` front matter, listed with no source and given to the agents picked; the page then opens it in the reader (`TestCreateSkill`, `library-new-skill.test.cjs`). 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 or folder 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}`). A git repository on another host has no such list: when `git ls-remote` gives its ref a head, `findNewGit` reads the fetch the check shares (`fetcher`), once per head while its finds are kept (`gitLooked`), and offers the skills under `newBase` with the address as the library has it, `.git` and all, so an Add keeps the same `repo@ref`. A folder the user added linked skills from is kept as `folder:` in `SeenSkills` (`offered`, at install), which is also how the library knows which folder to look in again: `findNewFolder` reads it as Add from folder does and offers a skill folder there the library doesn't link, hasn't offered, and has no skill by that name of; a folder that can't be read keeps what was found. `View.CheckFolders` (`addedFromFolders`, which reads no folder) puts Check for updates on the page with only linked skills, and makes `checkDue` true. A check never adds or writes a skill: each is offered, and one the user removed or set aside isn't offered again. A folder added before this kept no `folder:` key and is looked in only once the user adds from it again (refeccd on Discord; `TestCheckSkillsFindsNewInGitRepo`, `TestCheckSkillsFindsNewInFolder`, `skill-new-in-repo.test.cjs`). | [`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) | diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 2c9b87b36..c56df6802 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -6680,6 +6680,53 @@ magpie.plugin("library", (ctx) => { }; } + // A skill of the user's own: a name and a description make its SKILL.md + // in the library's folder (josephBenchap on X); it opens in the reader, + // whose path opens it in their editor. + function newSkill() { + const all = skillAgents(); + const d = { name: "", description: "", agents: all.map((a) => a.id) }; + const ed = el("div", "editor lib-editor lib-newskill"); + const head = el("div", "ehead"); + head.append(glyph(GLYPH.skill), el("b", "", t("New skill"))); + ed.append(head); + const err = el("div", "editor-error"); + const name = field2("", t("e.g. my-skill"), (v) => { d.name = v.trim(); }); + name.classList.add("mono"); + ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it"))); + const desc = el("textarea", "lib-text small lib-newskilldesc"); + desc.placeholder = t("e.g. Writes release notes. Use when asked for a changelog."); + desc.spellcheck = false; + desc.rows = 2; + desc.maxLength = 1024; + desc.oninput = () => { d.description = desc.value; }; + desc.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter") { e.preventDefault(); modal?.save?.(); } }; + ed.append(...field(t("Description"), desc, t("What it does and when to use it: the agent reads this to decide when to load it"))); + const agentsBox = el("div"); + ed.append(...field(t("Agents"), agentsBox)); + ed.append(err); + const drawAgents = () => agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, all: true })); + drawAgents(); + const bar = el("div", "bar"); + bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal)); + const save = async () => { + err.textContent = ""; + try { + take(await api("library/skills/create", { name: d.name, description: d.description, agents: d.agents })); + report(lib.result, t("{name} is in the library now", { name: d.name })); + render(); + const made = lib.skills.find((x) => x.name === d.name); + if (made) viewSkill(made); else closeLibModal(true); + } catch (e) { err.textContent = e.message; } + }; + bar.append(button(t("Create"), "primary", save)); + ed.append(bar); + const original = JSON.stringify(d); + modal = { save, dirty: () => JSON.stringify(d) !== original }; + openLib(ed); + requestAnimationFrame(() => name.focus()); + } + function installCard() { const card = el("div", "list lib-card lib-install"); const line = el("div", "lib-find"); @@ -6695,7 +6742,9 @@ magpie.plugin("library", (ctx) => { if (probing) go.classList.add("busy"); inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") find(); else if (e.key === "Escape" && probe) { probe = null; render(); } }; const g = glyph(GLYPH.search, "lib-mini"); - line.append(g, inp, go); + const mk = button(t("New skill"), "", () => newSkill()); + mk.dataset.lib = "new-skill"; + line.append(g, inp, go, mk); card.append(line); async function find() { const src = inp.value.trim(); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 3fd2963bb..5867fcbd7 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,10 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "New skill": "新建技能", + "e.g. my-skill": "例如 my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "例如:撰写发布说明。需要更新日志时使用。", + "What it does and when to use it: the agent reads this to decide when to load it": "它做什么、何时使用:Agent 据此决定何时加载它", "This computer follows the server: what you change here is replaced by the next sync.": "这台电脑跟随服务器:你在这里的改动会被下一次同步替换。", "Sync settings": "同步设置", "Stop picking memories": "不再选择记忆", @@ -975,6 +979,10 @@ magpie.strings({ "{name} read again from its source": "已重新从来源读取 {name}", }, "zh-TW": { + "New skill": "新增技能", + "e.g. my-skill": "例如 my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "例如:撰寫發佈說明。需要更新日誌時使用。", + "What it does and when to use it: the agent reads this to decide when to load it": "它做什麼、何時使用:Agent 據此決定何時載入它", "This computer follows the server: what you change here is replaced by the next sync.": "這台電腦跟隨伺服器:你在這裡的變更會被下一次同步取代。", "Sync settings": "同步設定", "Stop picking memories": "不再選擇記憶", @@ -1948,6 +1956,10 @@ magpie.strings({ "{name} read again from its source": "已重新從來源讀取 {name}", }, ja: { + "New skill": "新しいスキル", + "e.g. my-skill": "例: my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "例: リリースノートを書く。変更履歴を求められたときに使う。", + "What it does and when to use it: the agent reads this to decide when to load it": "何をするか、いつ使うか。エージェントはこれを読んで読み込むかを決めます", "This computer follows the server: what you change here is replaced by the next sync.": "このコンピュータはサーバーに従います。ここでの変更は次の同期で置き換えられます。", "Sync settings": "同期の設定", "Stop picking memories": "メモリの選択を終える", @@ -2921,6 +2933,10 @@ magpie.strings({ "{name} read again from its source": "{name} をソースから読み直しました", }, de: { + "New skill": "Neuer Skill", + "e.g. my-skill": "z. B. my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "z. B. Schreibt Release Notes. Zu verwenden, wenn ein Changelog verlangt wird.", + "What it does and when to use it: the agent reads this to decide when to load it": "Was er tut und wann er gebraucht wird: Der Agent entscheidet danach, ob er ihn lädt", "This computer follows the server: what you change here is replaced by the next sync.": "Dieser Computer folgt dem Server: Änderungen hier werden bei der nächsten Synchronisierung ersetzt.", "Sync settings": "Sync-Einstellungen", "Stop picking memories": "Keine Erinnerungen mehr auswählen", diff --git a/internal/gui/library.go b/internal/gui/library.go index 90de5dcc0..8e19d6c63 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -604,11 +604,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { // Agents is named as the page sends it, so that it is this // and not the instructions' own Agents that "agents" fills Agents []string `json:"agents"` - Source string - Paths []string - Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents - Server library.Server - Hook library.Hook // a hook saved (#1790) + // Description is a new skill's (skills/create) + Description string `json:"description"` + Source string + Paths []string + Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents + Server library.Server + Hook library.Hook // a hook saved (#1790) // a subagent saved (#2283) Subagent library.Subagent Agent string // the agent whose own skill is in the library's way @@ -715,6 +717,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.RemoveSubagents([]string{in.Name}) case "skills/install": res, err = library.InstallSkills(in.Source, in.Paths, in.Agents) + case "skills/create": + res, err = library.CreateSkill(in.Name, in.Description, in.Agents) case "skills/update": res, err = library.UpdateSkill(in.Name, in.Replace) var gone *library.GoneError diff --git a/internal/gui/tests/library-new-skill.test.cjs b/internal/gui/tests/library-new-skill.test.cjs new file mode 100644 index 000000000..83a78e43f --- /dev/null +++ b/internal/gui/tests/library-new-skill.test.cjs @@ -0,0 +1,93 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A skill made in the Library (josephBenchap on X): Skills > New skill takes +// a name and a description and the agents, posts library/skills/create, and +// opens the new skill in the reader. A refusal is said in the dialog and the +// dialog stays. No native select, no sideways scroll. English and Chinese, +// Chromium and WebKit, 1100 and 420px. The API is faked. +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/emo"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const lib = (skills) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("codex", "Codex"), agent("claude", "Claude Code")], + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills, servers: [], +}); + +function server(lang, posts, state) { + 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/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib(state.skills) }); + if (url.pathname === "/api/library/skills/create") { + const b = req.postDataJSON(); + posts.push(b); + if (b.name === "taken") return route.fulfill({ status: 400, body: "there is a skill called taken already" }); + state.skills = [{ name: b.name, description: b.description, agents: b.agents }]; + return route.fulfill({ json: { ...lib(state.skills), result: { changed: b.agents, problems: [] } } }); + } + if (url.pathname === "/api/library/skill") return route.fulfill({ json: { text: `---\nname: ${url.searchParams.get("name")}\n---\n`, path: `${HOME}/.magpie/library/skills/${url.searchParams.get("name")}/SKILL.md` } }); + if (url.pathname === "/api/library/rtk") return route.fulfill({ json: {} }); + if (url.pathname === "/api/davsync") return route.fulfill({ json: { on: false } }); + 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 }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": Library makes a skill of the user's own", async (t) => { + 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(); }); + for (const lang of ["en", "zh"]) { + for (const width of [1100, 420]) { + await t.test(`${lang} ${width}`, async () => { + 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)); + const posts = [], state = { skills: [] }; + await page.route("**/*", server(lang, posts, state)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + await v.locator("[data-lib=new-skill]").click(); + const dlg = page.locator(".lib-newskill"); + await dlg.waitFor(); + assert.equal(await dlg.locator("select").count(), 0, "native select"); + const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(sideways <= 0, `page scrolls sideways by ${sideways}px`); + // a refusal stays in the dialog + await dlg.locator("input").first().fill("taken"); + await dlg.locator("textarea").fill("Does a thing"); + await dlg.locator("button.primary").click(); + await dlg.locator(".editor-error").filter({ hasText: "taken" }).waitFor(); + assert.equal(posts.length, 1); + // one agent unticked, then created + await dlg.locator("input").first().fill("my-skill"); + await dlg.locator(".lib-ag[data-agent=claude]").click(); + await dlg.locator("button.primary").click(); + await page.locator(".lib-reader").waitFor(); + assert.deepEqual(posts[1], { name: "my-skill", description: "Does a thing", agents: ["codex"] }); + await page.locator(".lib-reader .lib-md").filter({ hasText: "my-skill" }).waitFor(); + await ctx.close(); + }); + } + } + }); +} diff --git a/internal/library/create_skill_test.go b/internal/library/create_skill_test.go new file mode 100644 index 000000000..1e04565d9 --- /dev/null +++ b/internal/library/create_skill_test.go @@ -0,0 +1,44 @@ +package library + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// A skill made in the Library (josephBenchap on X): SKILL.md with valid +// front matter in the library's folder, given to the agents picked, and a +// name that clashes or isn't folder-safe is refused. +func TestCreateSkill(t *testing.T) { + h := sandbox(t) + ok(t)(CreateSkill("my-skill", "Does: a thing\nacross lines", []string{"claude", "codex"})) + b, err := os.ReadFile(filepath.Join(skillDir("my-skill"), "SKILL.md")) + if err != nil { + t.Fatal(err) + } + m := parseMeta(b) + if m.Name != "my-skill" || m.Description != "Does: a thing across lines" { + t.Errorf("front matter: %+v\\n%s", m, b) + } + for _, d := range []string{".claude/skills/my-skill", ".codex/skills/my-skill"} { + if _, err := os.Stat(filepath.Join(h, d, "SKILL.md")); err != nil { + t.Errorf("not given to %s: %v", d, err) + } + } + v, _ := Read(nil) + if len(v.Skills) != 1 || v.Skills[0].Name != "my-skill" { + t.Errorf("listed: %+v", v.Skills) + } + skill(t, filepath.Join(h, ".claude/skills/theirs"), "theirs", "An agent's own") + for _, c := range [][2]string{ + {"My-Skill", "d"}, {"theirs", "d"}, {"../x", "d"}, {"a/b", "d"}, {"", "d"}, {"fine", " "}, {"fine", strings.Repeat("x", 1025)}, + } { + if _, err := CreateSkill(c[0], c[1], nil); err == nil { + t.Errorf("%q / %.10q was taken", c[0], c[1]) + } + } + if _, err := os.Lstat(skillDir("fine")); err == nil { + t.Error("a refused skill left a folder") + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index dd882ae69..de352a178 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -1731,6 +1731,53 @@ func (l *Library) offered(p *Probe, path string, shown bool) { } } +// CreateSkill makes a skill of the user's own in the library's folder: a +// SKILL.md with a name and description in its front matter, listed with no +// source and given to the agents like any other. The name can't be one the +// library has, one an agent has of its own, or a folder in the way. +func CreateSkill(name, description string, agents []string) (*Result, error) { + name = strings.TrimSpace(name) + if err := checkName("skill", name); err != nil { + return nil, err + } + description = strings.Join(strings.Fields(description), " ") + if description == "" { + return nil, errors.New("a skill needs a description: it is how an agent knows when to load it") + } + if len([]rune(description)) > 1024 { + return nil, errors.New("the description is over 1024 characters") + } + return change(func(l *Library) error { + same := func(n string) bool { return strings.EqualFold(n, name) } + if slices.ContainsFunc(l.Skills, func(s *Skill) bool { return same(s.Name) }) || + slices.ContainsFunc(foundSkills(l), func(f FoundSkill) bool { return same(f.Name) }) { + return fmt.Errorf("there is a skill called %s already", name) + } + dir := skillDir(name) + if _, err := os.Lstat(dir); err == nil { + return fmt.Errorf("the library's folder already has a %s in it (%s)", name, dir) + } else if !errors.Is(err, fs.ErrNotExist) { + return err + } + head, err := yaml.Marshal(meta{Name: name, Description: description}) + if err != nil { + return err + } + text := "---\n" + string(head) + "---\n\n# " + name + "\n\nWrite what the agent should do when this skill is used.\n" + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(text), 0o644); err != nil { + os.RemoveAll(dir) + return err + } + ag := slices.Clone(agents) + slices.Sort(ag) + l.Skills = append(l.Skills, &Skill{Name: name, Agents: slices.Compact(ag)}) + return nil + }) +} + // UpdateSkill fetches a skill from GitHub again, in place: the agents' // links go on pointing at it. One changed here since it was fetched is // an *EditedError unless replace is set, and then the changed version is