diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 2f4a56128..71182333d 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -34,6 +34,7 @@ Pi's extensions and packages. | Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository are found from its fetch (`findNewGit`, above); Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) | | Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | | Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`.agent.md`); a TOML role (`name`, `description`, `model` when set, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. A subagent's optional `Model` (a model or routing group of Codex's list, `subagentModels` in `/api/library`) is written only into Codex's role (luckymanjc on Discord): the role file is a config layer, and Codex lays its `model` over the one its lead names in spawn_agent (`apply_spawn_agent_role` after `apply_requested_spawn_agent_model_overrides` in codex-rs `core/src/agent/child_config.rs`), so the subagent's requests carry it and the gateway routes them as any other. Codex's subagent model on the Agents page (`CodexSubagentModel`), when set, still rewrites every subagent's request, and the editor says so. Without one, a Codex subagent runs on the model its lead names, else the lead's own. The page lists, per agent, whether it binds skills, servers and a model (`SubagentAgentView`), names the agents that run a subagent on their own pick, and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) | +| Claude plugins | A `Plugin` (FakeshadowzZ on X) is a Claude Code plugin kept as one item: `.claude-plugin/plugin.json`, `skills//SKILL.md`, `agents/*.md`, `hooks/hooks.json` and `.mcp.json`, from a folder, a git address or a marketplace.json (`ProbePlugins`, `InstallPlugins`; a marketplace entry with a relative path, or a github/url/git source, is fetched when installed). Its files are copied to `/plugins/`; `${CLAUDE_PLUGIN_ROOT}` is that folder and `${CLAUDE_PLUGIN_DATA}` is `/plugin-data/`, which an update keeps. Its parts are ordinary library skills, MCP servers, hooks and subagents, each tagged `Bundle: `, so every agent gets them through the code of its kind and the old tabs go on working; the plugin holds the names, its agents and `Off`. `PluginAgents` sets every part's agents, `PluginOn` clears them (kept in `Agents` for turning it on again) or gives them back, `RemovePlugin` removes the parts, and `UpdatePlugin` reads the source again. A hook whose Claude event and matcher have a portable event becomes it (Stop turn-end, PostToolUse after-tool, PreToolUse before-tool, UserPromptSubmit prompt, SessionStart session-start; Bash is shell, Edit/Write/MultiEdit is edit); any other event is `claude:`, for Claude Code only. Subagents go to the agents in `SubagentAgents`. A part whose name the library has gets the prefix `-`: the user's own item is never written over or removed. Slash commands, LSP servers and hooks that aren't a command are listed in `Left` and shown, not carried. A backup file carries the parts but not the plugin record or its folder, so on another computer they are ordinary items whose `${CLAUDE_PLUGIN_ROOT}` paths don't exist (`TestPluginImportCarryOnOffRemove`, `TestPluginNameClashKeepsTheUsersOwn`, `TestPluginMarketplaceAndUpdate`, `TestPluginRefusesWhatIsNone`, `library-plugins.test.cjs`). | [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) | | RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. Factory's Droid (lml0664 on Discord) gets rtk's own `rtk init -g --agent droid`, given Droid's folder as `FACTORY_HOME_OVERRIDE`; rtk puts its `Execute` group (`rtk hook droid`) in the root `hooks.json`, or in `settings.json`'s `hooks.PreToolUse` where Droid's hooks already are, so `droidHookFiles` reads and switches off all three places rtk 1.1.0 may use (`hooks.json`, `hooks/hooks.json`, `settings.json`), leaving the user's own hooks. rtk before 0.44 has no Droid agent, so it is `blocked` (`droidBlocked`). A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off; Qoder and Qoder CN: rtk 1.1.0 has no Qoder agent; Cline and Kimi Code: `rtk init --agent cline|kimi` writes only one project's `.clinerules` or `AGENTS.md`, instructions with no hook, and Kimi's refuses `-g`). RTK 1.1.0's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent. The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136, Qoder and Qoder CN #1327, Cline #3841), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) | | RTK in WSL | An agent in a WSL distro (`claude@wsl:Ubuntu`) is listed by its kind (`rtkKind`), and its hook runs in the distro, where Windows' rtk.exe is no command, so it gets the distro's own rtk (lex on Discord). `rtkDistroOf` asks the distro with `wsl.exe -d -e sh -lc` where rtk is (a login or interactive shell's PATH; else `~/.local/bin` or `~/.cargo/bin`, `offPath`), kept 15s; `ReadRTK` lists one `RTKDistro` for each distro its agents are in. Install RTK in WSL `` (`InstallRTKIn`, `POST /api/library/rtk/install` with `distro`, `magpie library rtk install `) runs RTK's own Linux installer in the distro (`curl -fsSL …/install.sh \| sh`, wget where there's no curl). Switching an agent on runs the distro's rtk there (`rtkInstallWSL`: `rtk init -g …` with its folder on PATH, Claude Code pointed at a folder of its own for the OpenCode and Cursor installers), and reads and edits its files under the distro's home as magpie opens it (`rtkClaudeDir`, `rtkCodexDir`, `rtkHome`). A distro that isn't running is never started (#3896): `rtkWSLLive` and `rtkDistroOf` check `agent.WSLRunning` first, its agents are listed `asleep` with the switch off, and switching or installing says to start it (`TestRTKWSLAsleep`). The page gives each distro a card (`rtkDistroCard` in plugins/library/client.js; library-rtk-wsl.test.cjs). | [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) | @@ -105,7 +106,7 @@ Pi's extensions and packages. ## Verification ```sh -go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead' +go test -tags nogui ./internal/library -run 'TestPlugin|TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead' go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal' go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks' go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills' @@ -121,7 +122,7 @@ node --test internal/gui/tests/library-pi-extensions.test.cjs internal/gui/tests node --test internal/gui/tests/library-rtk-wsl.test.cjs node --test internal/gui/tests/library-wsl-asleep.test.cjs node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/skill-handover.test.cjs -node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs +node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-gone.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-plugins.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs ``` The package's `TestMain` runs in a home of its own (`testenv`), never the diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 2b745ad9d..537434561 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -702,7 +702,7 @@ magpie.plugin("library", (ctx) => { ul.append(li); } if (ul.childElementCount) card.append(ul); - const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents") }; + const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents"), plugins: t("Claude plugins") }; const others = Object.keys(away).filter((k) => k in tabNames); if (others.length) { const more = el("div", "lib-problems-away"); @@ -738,7 +738,7 @@ magpie.plugin("library", (ctx) => { } // the tab a problem is about; "" is one shown on every tab function problemTab(what) { - return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents" }[what.split(":")[0]] || ""; + return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || ""; } function problemWhat(what) { const [kind, ...rest] = what.split(":"); @@ -851,6 +851,7 @@ magpie.plugin("library", (ctx) => { ["skills", t("Skills") + n("skills")], ["hooks", t("Hooks") + n("hooks")], ["subagents", t("Subagents") + n("subagents")], + ["plugins", t("Claude plugins") + n("plugins")], ["rtk", "RTK"], ["bili", "billion-context"], ...(hasPi() ? [["pi", t("Pi packages")]] : []), @@ -909,7 +910,7 @@ magpie.plugin("library", (ctx) => { if (agentless()) tab = "mcp"; // Pi's tab only while a Pi is here; the pick is kept for when one is else if (tab === "pi" && !hasPi()) tab = "instructions"; - const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length }); + const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length }); page.append(head); head.classList.toggle("stuck", top > 0); // what changed in a tab is drawn in place: only another tab (or the @@ -926,6 +927,7 @@ magpie.plugin("library", (ctx) => { else if (tab === "pi") renderPi(body); else if (tab === "hooks") renderHooks(body); else if (tab === "subagents") renderSubagents(body); + else if (tab === "plugins") renderPlugins(body); else renderSkills(body); page.append(body); for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent; @@ -4382,6 +4384,160 @@ magpie.plugin("library", (ctx) => { if (!s) requestAnimationFrame(() => name.focus()); } + // ---------- Claude plugins ---------- + + // A Claude Code plugin kept as one item (FakeshadowzZ on X): its skills, + // MCP servers, hooks and subagents are ordinary library items marked with + // the plugin, so each agent gets them through the code that writes that + // kind, and the other tabs go on listing them. The plugin's switch, its + // agents and Remove act on every part at once (library/plugin.go). + let plProbe = null; // plugins found at an address: { source, found, pick:Set, agents } + let plProbing = false; + const pluginParts = (p) => [ + p.skills?.length ? t("Skills: {names}", { names: p.skills.join(", ") }) : "", + p.mcp?.length ? t("MCP servers: {names}", { names: p.mcp.join(", ") }) : "", + p.hooks?.length ? t("Hooks: {names}", { names: p.hooks.join(", ") }) : "", + p.subagents?.length ? t("Subagents: {names}", { names: p.subagents.join(", ") }) : "", + ].filter(Boolean).join(" · "); + + function renderPlugins(body) { + body.append(intro(t("A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs."))); + body.append(pluginFind()); + const all = shownAgents(); + const plugins = lib.plugins || []; + if (!plugins.length) { + body.append(empty(t("No Claude plugins in the library yet"), t("Install one from a folder, a git address or a marketplace.json."))); + return; + } + const list = el("div", "list lib-list"); + list.append(...[...plugins].sort((a, b) => a.name.localeCompare(b.name)).map((p) => pluginRow(p, all))); + body.append(list); + } + + function pluginFind() { + const card = el("div", "list lib-card lib-install lib-plfind"); + const line = el("div", "lib-find"); + const inp = el("input"); + inp.type = "text"; + inp.dataset.lib = "plsource"; + inp.placeholder = t("owner/repo, a git address, or a folder with a plugin or a marketplace.json"); + inp.spellcheck = false; + inp.autocomplete = "off"; + inp.value = plProbe?.source || ""; + const go = button(plProbing ? t("Looking…") : t("Find plugins"), "action", () => find()); + go.disabled = plProbing; + if (plProbing) go.classList.add("busy"); + inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") find(); else if (e.key === "Escape" && plProbe) { plProbe = null; render(); } }; + line.append(glyph(GLYPH.search, "lib-mini"), inp, go); + card.append(line); + async function find() { + const src = inp.value.trim(); + if (!src || plProbing) return; + plProbing = true; + plProbe = { source: src }; + render(); + try { + const f = await api("library/plugins/probe", { source: src }); + const fresh = f.candidates.filter((c) => !c.have); + plProbe = { source: src, found: f, pick: new Set((fresh.length === 1 ? fresh : []).map((c) => c.name)), agents: shownAgents().map((a) => a.id) }; + if (!f.candidates.length) status(t("No Claude plugin found there"), "warn"); + } catch (e) { + plProbe = { source: src, error: e.message }; + } + plProbing = false; + render(); + } + if (plProbe?.error) card.append(el("div", "lib-err", plProbe.error)); + if (plProbe?.found?.candidates.length) card.append(pluginPicks(plProbe)); + return card; + } + + function pluginPicks(p) { + const box = el("div", "lib-probe"); + const list = el("div", "lib-picks"); + for (const x of p.found.candidates) { + const r = el("label", "lib-pick lib-plpick" + (x.have ? " dim" : "")); + const cb = el("input"); + cb.type = "checkbox"; + cb.checked = p.pick.has(x.name); + cb.onchange = () => { if (cb.checked) p.pick.add(x.name); else p.pick.delete(x.name); syncGo(); }; + const w = el("span", "who"); + w.append(el("span", "name", x.name), el("span", "sub", x.description || "")); + const count = (n) => (n ? [String(n)] : []); + const parts = x.remote ? t("Fetched from its own repository when installed") + : pluginParts({ skills: count(x.skills), mcp: count(x.mcp), hooks: count(x.hooks), subagents: count(x.subagents) }); + if (parts) w.append(el("span", "sub lib-plparts", parts)); + r.append(cb, w); + if (x.have) r.append(tag(t("in the library"), "")); + list.append(r); + } + box.append(list); + const foot = el("div", "lib-probefoot"); + const agentsBox = el("div"); + const drawAgents = () => agentsBox.replaceChildren(agentChips(shownAgents(), p.agents, (n) => { p.agents = n; drawAgents(); }, { names: false, all: true })); + drawAgents(); + foot.append(el("span", "note", t("for")), agentsBox, el("span", "grow")); + foot.append(button(t("Cancel"), "", () => { plProbe = null; render(); })); + const go = button("", "primary", async () => { + go.disabled = true; + go.textContent = t("Installing…"); + const n = p.pick.size; + if (await change("plugins/install", { source: p.source, names: [...p.pick], agents: p.agents }, n === 1 ? t("1 plugin installed") : t("{n} plugins installed", { n }))) { plProbe = null; render(); } + else { go.disabled = false; syncGo(); } + }); + const syncGo = () => { const n = p.pick.size; go.textContent = n === 1 ? t("Install 1 plugin") : t("Install {n} plugins", { n }); go.disabled = !n; }; + syncGo(); + foot.append(go); + box.append(foot); + return box; + } + + function pluginRow(p, all) { + const row = el("div", "row lib-row click lib-plugin" + (p.off ? " off" : "")); + const who = el("div", "who"); + who.append(el("div", "name mono", p.name + (p.version ? " " + p.version : ""))); + if (p.description) who.append(el("div", "lib-subagentdesc", p.description)); + const line = pluginParts(p); + if (line) who.append(el("div", "sub lib-plparts", line)); + row.append(glyph(GLYPH.folder), who, + agentChips(all, p.agents, chipsChange("plugins/agents", p.name, "plugins", (x) => pluginRow(x, all)), { all: true }), + toggle(!p.off, t("Turn {name} on or off", { name: p.name }), (v) => change("plugins/on", { name: p.name, on: v }, + v ? t("{name} is on again", { name: p.name }) : t("{name} is off for every agent", { name: p.name })))); + row.onclick = () => pluginDetail(p); + row.title = t("Open the plugin {name}", { name: p.name }); + return row; + } + + function pluginDetail(p) { + const ed = el("div", "editor lib-editor lib-pldetail"); + const head = el("div", "ehead"); + head.append(glyph(GLYPH.folder), el("b", "", p.name)); + ed.append(head); + if (p.description) ed.append(el("p", "lib-subagentdesc", p.description)); + const rows = [[t("Skills"), p.skills], [t("MCP servers"), p.mcp], [t("Hooks"), p.hooks], [t("Subagents"), p.subagents]].filter(([, v]) => v?.length); + for (const [label, names] of rows) ed.append(...field(label, el("div", "mono lib-plnames", names.join(", ")))); + if (p.missing?.length) ed.append(el("div", "hint lib-plmissing", t("Taken out by hand: {names}", { names: p.missing.join(", ") }))); + if (p.left?.length) { + const left = el("div", "lib-plleft"); + for (const x of p.left) left.append(el("div", "hint", x.what + " — " + x.why)); + ed.append(...field(t("Not carried"), left)); + } + if (p.source) ed.append(el("div", "hint lib-plsource mono", p.source + (p.pick ? " · " + p.pick : ""))); + const bar = el("div", "bar"); + bar.append(button(t("Remove from the library"), "danger", async () => { + if (!await confirmRemoval(p.name, "It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.")) return; + if (await change("plugins/remove", { name: p.name }, t("{name} is out of the library and the agents it was given to", { name: p.name }))) closeLibModal(true); + })); + bar.append(el("span", "grow")); + if (p.source) bar.append(button(t("Update"), "", async () => { + if (await change("plugins/update", { name: p.name }, t("{name} read again from its source", { name: p.name }))) closeLibModal(true); + })); + bar.append(button(t("Cancel"), "", closeLibModal)); + ed.append(bar); + modal = { dirty: () => false }; + openLib(ed); + } + // ---------- skills ---------- function renderSkills(body) { diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 0a02ee0af..efcc67cba 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -937,6 +937,25 @@ magpie.strings({ "Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "已经过 {requests},还没有折叠:会话接近模型窗口时 billion-context 才会折叠。", "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "这是 billion-context 自己的统计,已扣除折叠后的重建和摘要的开销(扣除前 {gross}):包括这台电脑上它运行过的所有会话,不分 Agent。", "As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 现在没有运行。", + "Claude plugins": "Claude 插件", + "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code 插件把技能、MCP 服务器、hooks 和子代理装成一个包。装一次,magpie 就把每一部分交给你选的智能体;插件可以整体开启、关闭或移除。它的各部分也会出现在各自的标签页里。", + "No Claude plugins in the library yet": "资源库里还没有 Claude 插件", + "Install one from a folder, a git address or a marketplace.json.": "从文件夹、git 地址或 marketplace.json 安装。", + "owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo、git 地址,或含插件或 marketplace.json 的文件夹", + "Find plugins": "查找插件", + "No Claude plugin found there": "那里没有找到 Claude 插件", + "Fetched from its own repository when installed": "安装时从它自己的仓库获取", + "1 plugin installed": "已安装 1 个插件", + "{n} plugins installed": "已安装 {n} 个插件", + "Install 1 plugin": "安装 1 个插件", + "Install {n} plugins": "安装 {n} 个插件", + "Hooks: {names}": "Hooks:{names}", + "Subagents: {names}": "子代理:{names}", + "Taken out by hand: {names}": "已手动取出:{names}", + "Not carried": "未带上的部分", + "It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "它会连同技能、MCP 服务器、hooks 和子代理一起从资源库移除,也会从它们所在的智能体中取出。", + "Open the plugin {name}": "打开插件 {name}", + "{name} read again from its source": "已重新从来源读取 {name}", }, "zh-TW": { "Stop picking memories": "不再選擇記憶", @@ -1874,6 +1893,25 @@ magpie.strings({ "Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "已經過 {requests},還沒有摺疊:工作階段接近模型視窗時 billion-context 才會摺疊。", "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "這是 billion-context 自己的統計,已扣除摺疊後的重建和摘要的開銷(扣除前 {gross}):包括這台電腦上它執行過的所有工作階段,不分 Agent。", "As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 現在沒有執行。", + "Claude plugins": "Claude 外掛", + "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code 外掛把技能、MCP 伺服器、hooks 和子代理裝成一個包。裝一次,magpie 就把每一部分交給你選的代理;外掛可以整體開啟、關閉或移除。它的各部分也會出現在各自的分頁裡。", + "No Claude plugins in the library yet": "資源庫裡還沒有 Claude 外掛", + "Install one from a folder, a git address or a marketplace.json.": "從資料夾、git 位址或 marketplace.json 安裝。", + "owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo、git 位址,或含外掛或 marketplace.json 的資料夾", + "Find plugins": "查詢外掛", + "No Claude plugin found there": "那裡沒有找到 Claude 外掛", + "Fetched from its own repository when installed": "安裝時從它自己的儲存庫取得", + "1 plugin installed": "已安裝 1 個外掛", + "{n} plugins installed": "已安裝 {n} 個外掛", + "Install 1 plugin": "安裝 1 個外掛", + "Install {n} plugins": "安裝 {n} 個外掛", + "Hooks: {names}": "Hooks:{names}", + "Subagents: {names}": "子代理:{names}", + "Taken out by hand: {names}": "已手動取出:{names}", + "Not carried": "未帶上的部分", + "It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "它會連同技能、MCP 伺服器、hooks 和子代理一起從資源庫移除,也會從它們所在的代理中取出。", + "Open the plugin {name}": "開啟外掛 {name}", + "{name} read again from its source": "已重新從來源讀取 {name}", }, ja: { "Stop picking memories": "メモリの選択を終える", @@ -2811,6 +2849,25 @@ magpie.strings({ "Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "{requests}を処理しましたが、まだ折りたたんでいません。billion-context はセッションがモデルのウィンドウに近づくと折りたたみます。", "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "billion-context 自身の集計で、折りたたみ後の再構築と要約のコストを差し引いた値です(差し引く前は {gross})。このコンピューターで動いたすべてのセッションが対象で、エージェントは問いません。", "As of {time}: billion-context isn't running now.": "{time} 時点:billion-context は現在動いていません。", + "Claude plugins": "Claude プラグイン", + "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Claude Code プラグインは、スキル、MCP サーバー、フック、サブエージェントを 1 つにまとめたパッケージです。一度インストールすると、magpie が選んだエージェントに各パーツを渡し、プラグイン全体をオン、オフ、削除できます。各パーツはそれぞれのタブにも表示されます。", + "No Claude plugins in the library yet": "ライブラリにはまだ Claude プラグインがありません", + "Install one from a folder, a git address or a marketplace.json.": "フォルダ、git アドレス、marketplace.json からインストールします。", + "owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo、git アドレス、またはプラグインか marketplace.json があるフォルダ", + "Find plugins": "プラグインを探す", + "No Claude plugin found there": "そこに Claude プラグインは見つかりませんでした", + "Fetched from its own repository when installed": "インストール時に専用リポジトリから取得します", + "1 plugin installed": "プラグインを 1 件インストールしました", + "{n} plugins installed": "プラグインを {n} 件インストールしました", + "Install 1 plugin": "プラグインを 1 件インストール", + "Install {n} plugins": "プラグインを {n} 件インストール", + "Hooks: {names}": "フック: {names}", + "Subagents: {names}": "サブエージェント: {names}", + "Taken out by hand: {names}": "手動で外したもの: {names}", + "Not carried": "引き継がれない部分", + "It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "スキル、MCP サーバー、フック、サブエージェントごとライブラリから削除され、渡されていたエージェントからも外されます。", + "Open the plugin {name}": "プラグイン {name} を開く", + "{name} read again from its source": "{name} をソースから読み直しました", }, de: { "Stop picking memories": "Keine Erinnerungen mehr auswählen", @@ -3748,5 +3805,24 @@ magpie.strings({ "Nothing folded yet over {requests}: billion-context folds a session once it nears the model's window.": "Noch nichts gefaltet nach {requests}: billion-context faltet eine Sitzung, wenn sie sich dem Fenster des Modells nähert.", "billion-context's own count, after the rebuilds a fold causes and the summaries' cost ({gross} before them): every session it ran on this computer, from any agent.": "Die eigene Zählung von billion-context, abzüglich der Neuaufbauten nach einer Faltung und der Kosten der Zusammenfassungen ({gross} davor): jede Sitzung, in der es auf diesem Computer lief, von jedem Agenten.", "As of {time}: billion-context isn't running now.": "Stand {time}: billion-context läuft gerade nicht.", + "Claude plugins": "Claude-Plugins", + "A Claude Code plugin is skills, MCP servers, hooks and subagents in one package. Install it once: magpie gives each part to the agents you pick, and you turn the plugin on, off or remove it as a whole. Its parts also show under their own tabs.": "Ein Claude-Code-Plugin bündelt Skills, MCP-Server, Hooks und Subagenten in einem Paket. Einmal installieren: magpie gibt jeden Teil den gewählten Agenten, und das Plugin lässt sich als Ganzes ein-, ausschalten oder entfernen. Die Teile erscheinen auch in ihren eigenen Tabs.", + "No Claude plugins in the library yet": "Noch keine Claude-Plugins in der Bibliothek", + "Install one from a folder, a git address or a marketplace.json.": "Aus einem Ordner, einer Git-Adresse oder einer marketplace.json installieren.", + "owner/repo, a git address, or a folder with a plugin or a marketplace.json": "owner/repo, eine Git-Adresse oder ein Ordner mit einem Plugin oder einer marketplace.json", + "Find plugins": "Plugins suchen", + "No Claude plugin found there": "Dort wurde kein Claude-Plugin gefunden", + "Fetched from its own repository when installed": "Wird bei der Installation aus dem eigenen Repository geladen", + "1 plugin installed": "1 Plugin installiert", + "{n} plugins installed": "{n} Plugins installiert", + "Install 1 plugin": "1 Plugin installieren", + "Install {n} plugins": "{n} Plugins installieren", + "Hooks: {names}": "Hooks: {names}", + "Subagents: {names}": "Subagenten: {names}", + "Taken out by hand: {names}": "Von Hand entfernt: {names}", + "Not carried": "Nicht übernommen", + "It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "Es wird samt Skills, MCP-Servern, Hooks und Subagenten aus der Bibliothek und aus den Agenten entfernt, denen sie gegeben wurden.", + "Open the plugin {name}": "Plugin {name} öffnen", + "{name} read again from its source": "{name} wurde erneut aus der Quelle gelesen", }, }); diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index f0f6b20e3..3466623b3 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -789,6 +789,10 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-subagent > .who { flex-basis: 240px; } .lib-subagent .lib-subagentdesc { font-size: 12px; line-height: 1.45; color: var(--fg); white-space: normal; overflow-wrap: anywhere; margin-top: 1px; } .lib-subagent .lib-subagentuses { white-space: normal; overflow-wrap: anywhere; } +.lib-plugin > .who { flex-basis: 240px; } +.lib-plugin.off .name, .lib-plugin.off .lib-subagentdesc { opacity: .55; } +.lib-plugin .lib-plparts, .lib-plpick .lib-plparts { white-space: normal; overflow-wrap: anywhere; } +.lib-pldetail .lib-plnames, .lib-pldetail .lib-plsource { white-space: normal; overflow-wrap: anywhere; } .lib-subagentedit .lib-menu { max-width: 100%; height: 28px; color: var(--fg); } .lib-subagentedit .lib-menu > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .lib-subagentedit .lib-subagentdescin, .lib-subagentedit .lib-subagentprompt { width: 100%; box-sizing: border-box; resize: none; font: inherit; font-size: 12.5px; line-height: 1.45; } diff --git a/internal/gui/library.go b/internal/gui/library.go index 7ff0647a9..f7956c81c 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -248,6 +248,21 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { } writeJSON(rw, p) }) + // the Claude Code plugins at an address: a folder, a repository, a + // marketplace.json (plugin.go); nothing is written + mux.HandleFunc("POST /api/library/plugins/probe", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Source string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + p, err := library.ProbePlugins(in.Source) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, p) + }) // which skills GitHub has changed: the page as it is, each skill from // there carrying what the check found of it mux.HandleFunc("POST /api/library/skills/check", func(rw http.ResponseWriter, r *http.Request) { @@ -681,6 +696,16 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.RemoveHooks([]string{in.Name}) case "hooks/remove-all": res, err = library.RemoveHooks(in.Names) + case "plugins/install": + res, err = library.InstallPlugins(in.Source, in.Names, in.Agents) + case "plugins/agents": + res, err = library.PluginAgents(in.Name, in.Agents) + case "plugins/on": + res, err = library.PluginOn(in.Name, in.On) + case "plugins/update": + res, err = library.UpdatePlugin(in.Name) + case "plugins/remove": + res, err = library.RemovePlugin(in.Name) case "subagents/save": res, err = library.SaveSubagent(in.Old, in.Subagent) case "subagents/agents": diff --git a/internal/gui/tests/library-hooks.test.cjs b/internal/gui/tests/library-hooks.test.cjs index 0447e899b..dc502323b 100644 --- a/internal/gui/tests/library-hooks.test.cjs +++ b/internal/gui/tests/library-hooks.test.cjs @@ -152,7 +152,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the tab, with its count, between Skills and Subagents const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim()); - assert.deepEqual(tabs.slice(3, 7), [w("Skills"), w("Hooks") + " · 2", w("Subagents"), "RTK"]); + assert.deepEqual(tabs.slice(3, 8), [w("Skills"), w("Hooks") + " · 2", w("Subagents"), w("Claude plugins"), "RTK"]); // each hook says when it runs, in words, and what it runs assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits")); assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends")); diff --git a/internal/gui/tests/library-plugins.test.cjs b/internal/gui/tests/library-plugins.test.cjs new file mode 100644 index 000000000..0d6e067da --- /dev/null +++ b/internal/gui/tests/library-plugins.test.cjs @@ -0,0 +1,210 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// FakeshadowzZ on X: the Library's Claude plugins tab. A Claude Code plugin +// is one row: its parts (skills, MCP servers, hooks, subagents), the agents +// it is given to, a switch that turns it on or off as a whole, and a dialog +// with what it holds, what magpie doesn't carry, Update and Remove (which +// asks first). Find plugins posts plugins/probe and lists what it found +// with an Install that posts plugins/install; a chip posts plugins/agents, +// the switch plugins/on. No native "); + + // the switch turns every part off at once + await press(page, row("code-kit").locator(".lib-switch")); + await page.waitForFunction(() => document.querySelector("#view-library .lib-plugin.off")); + assert.deepEqual(posts.shift(), { what: "plugins/on", body: { name: "code-kit", on: false } }); + await press(page, row("code-kit").locator(".lib-switch")); + await page.waitForFunction(() => !document.querySelector("#view-library .lib-plugin.off")); + assert.deepEqual(posts.shift(), { what: "plugins/on", body: { name: "code-kit", on: true } }); + + // a chip changes its agents + await press(page, row("code-kit").locator('.lib-ag[data-agent="codex"]')); + await page.waitForTimeout(250); + assert.deepEqual(posts.shift(), { what: "plugins/agents", body: { name: "code-kit", agents: ["claude"] } }); + + // find: probe, pick the new one, install + await v.locator('input[data-lib="plsource"]').fill("/Users/chuan/market"); + await v.locator(".lib-plfind .lib-find button").click(); + await v.locator(".lib-plpick").first().waitFor(); + assert.deepEqual(posts.shift(), { what: "plugins/probe", body: { source: "/Users/chuan/market" } }); + assert.equal(await v.locator(".lib-plpick input:checked").count(), 1); + assert.equal(await v.locator(".lib-plpick input:disabled").count(), 0); + assert.deepEqual(await sideways(page), [], "sideways scroll with the finds at 420"); + await v.locator(".lib-plfind .lib-probefoot button.primary", { hasText: w("Install 1 plugin") }).click(); + await row("fresh-kit").waitFor(); + const inst = posts.shift(); + assert.equal(inst.what, "plugins/install"); + assert.deepEqual(inst.body.names, ["fresh-kit"]); + assert.equal(inst.body.source, "/Users/chuan/market"); + + // the dialog: parts, what isn't carried; Remove asks first + await press(page, row("code-kit")); + const d = page.locator("#modal .lib-pldetail"); + await d.waitFor(); + await settled(page); + assert.equal((await d.locator(".lib-plleft").textContent()).trim(), "commands/ship.md — slash commands aren't carried"); + await d.locator(".bar button.danger").click(); + const sheet = page.locator("dialog.action-confirm"); + await sheet.waitFor(); + await sheet.locator("button", { hasText: w("Cancel") }).click(); + await sheet.waitFor({ state: "detached" }); + await page.waitForTimeout(150); + assert.deepEqual(posts, [], "Cancel posts nothing"); + await d.locator(".bar button.danger").click(); + await sheet.waitFor(); + await sheet.locator("button.danger-fill").click(); + await d.waitFor({ state: "detached" }); + assert.deepEqual(posts.shift(), { what: "plugins/remove", body: { name: "code-kit" } }); + assert.equal(await row("code-kit").count(), 0); + + assert.deepEqual(posts, []); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/gui/tests/library-subagents.test.cjs b/internal/gui/tests/library-subagents.test.cjs index a67869b7c..e2ac9f435 100644 --- a/internal/gui/tests/library-subagents.test.cjs +++ b/internal/gui/tests/library-subagents.test.cjs @@ -172,7 +172,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // the tab, with its count, between Hooks and RTK const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim()); - assert.deepEqual(tabs.slice(4, 7), [w("Hooks"), w("Subagents") + " · 1", "RTK"]); + assert.deepEqual(tabs.slice(4, 8), [w("Hooks"), w("Subagents") + " · 1", w("Claude plugins"), "RTK"]); // the row: what it is for, and what it binds assert.equal((await row("reviewer").locator(".lib-subagentdesc").textContent()).trim(), LONG); assert.equal((await row("reviewer").locator(".lib-subagentuses").textContent()).trim(), w("Skills: {names}", { names: "tdd" }) + " · " + w("MCP servers: {names}", { names: "github" })); diff --git a/internal/library/hooks.go b/internal/library/hooks.go index 4ff60add1..7e3efe826 100644 --- a/internal/library/hooks.go +++ b/internal/library/hooks.go @@ -40,7 +40,8 @@ import ( // Hook is a command the agents ticked for it run at Event. type Hook struct { - Name string `json:"name"` + Name string `json:"name"` + Bundle string `json:"bundle,omitempty"` // the plugin it came with (plugin.go) // Description says what the hook is for, in any language (#2011): // the name is letters, digits, - and _, which says little to someone // who reads Chinese. Only the library keeps it; no agent is given it. diff --git a/internal/library/library.go b/internal/library/library.go index 2d65ac021..69075707d 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -32,6 +32,10 @@ type Library struct { // Subagents are agents of their own the agents ticked for each can // hand a task to (subagents.go, #2283) Subagents []*Subagent `json:"subagents,omitempty"` + // Plugins are the Claude Code plugins kept as one item each: its + // skills, servers, hooks and subagents are the items above marked + // with its name (plugin.go) + Plugins []*Plugin `json:"plugins,omitempty"` // Applied is what magpie wrote into each agent, so that what it takes // away is only ever its own. Applied map[string]*Applied `json:"applied,omitempty"` diff --git a/internal/library/mcp.go b/internal/library/mcp.go index 955cb4fd0..b61558ab0 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -33,7 +33,8 @@ import ( // Server is one MCP server: a command magpie's agents start, or a URL they // reach. type Server struct { - Name string `json:"name"` + Name string `json:"name"` + Bundle string `json:"bundle,omitempty"` // the Claude Code plugin it came with (plugin.go) // Transport is stdio for a command, http (streamable) or sse for a URL. Transport string `json:"transport"` Command string `json:"command,omitempty"` diff --git a/internal/library/plugin.go b/internal/library/plugin.go new file mode 100644 index 000000000..bdd06f92a --- /dev/null +++ b/internal/library/plugin.go @@ -0,0 +1,1279 @@ +package library + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +// A bundle is a Claude Code plugin kept in the library as one item +// (@FakeshadowzZ on X: manage a plugin's subagents, MCP servers, skills +// and hooks together). Its files are copied to /plugins/: +// +// .claude-plugin/plugin.json name, version, description, and paths for the parts below +// skills//SKILL.md skills +// agents/.md subagents (front matter name, description; the prompt below) +// hooks/hooks.json hooks, {"hooks": {"PostToolUse": [{"matcher", "hooks": [{"type": "command", "command"}]}]}} +// .mcp.json MCP servers, {"mcpServers": {...}} +// +// A plugin's parts become ordinary library skills, servers, hooks and +// subagents, each marked with its Bundle, so every agent gets them through +// the code that already writes each kind in that agent's own format, and +// the skills, MCP servers, Hooks and Subagents tabs go on working. The +// bundle records which items are its own and which agents it is given to: +// turning it off takes every part from every agent, turning it on gives +// them back, and removing it takes the parts out of the library. Parts no +// agent here can take (slash commands, LSP servers, hooks that aren't a +// command) are listed in Left, never silently dropped. +// +// ${CLAUDE_PLUGIN_ROOT} in a command, argument, header or value is the +// bundle's folder; ${CLAUDE_PLUGIN_DATA} a folder of its own that stays +// across updates. + +// Plugin is a plugin the library keeps. +type Plugin struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Version string `json:"version,omitempty"` + // Source is what the user gave to install it (a folder, a repository, + // a marketplace.json's folder), and Pick the plugin's name in it when + // that is a marketplace: an update fetches it again from there + Source string `json:"source,omitempty"` + Pick string `json:"pick,omitempty"` + // Agents are the agents it is given to when it is on + Agents []string `json:"agents"` + // Off is set while it is turned off: none of its parts is given to any + // agent, and Agents are kept for turning it on again + Off bool `json:"off,omitempty"` + // the items it made, by name + Skills []string `json:"skills,omitempty"` + MCP []string `json:"mcp,omitempty"` + Hooks []string `json:"hooks,omitempty"` + Subagents []string `json:"subagents,omitempty"` + // Left are the parts of the plugin magpie doesn't carry, and why + Left []PluginLeft `json:"left,omitempty"` + // Installed is when it was installed or last updated + Installed string `json:"installed,omitempty"` +} + +// PluginLeft is a part of a plugin that wasn't carried. +type PluginLeft struct { + What string `json:"what"` + Why string `json:"why"` +} + +func (l *Library) plugin(name string) *Plugin { + for _, b := range l.Plugins { + if b.Name == name { + return b + } + } + return nil +} + +func pluginsDir() string { return filepath.Join(Dir(), "plugins") } + +func pluginDir(name string) string { return filepath.Join(pluginsDir(), name) } + +// pluginData is a folder a plugin keeps its own files in, which an update +// of the plugin leaves as it is. +func pluginData(name string) string { return filepath.Join(Dir(), "plugin-data", name) } + +// ---- reading a plugin -------------------------------------------------------- + +// plSkill is a skill found in a plugin's folder. +type plSkill struct { + name, dir string +} + +// plLoaded is a plugin as read from its folder. +type plLoaded struct { + name, description, version string + skills []plSkill + servers []*Server + hooks []*Hook + agents []*Subagent + left []PluginLeft +} + +func (p *plLoaded) parts() int { + return len(p.skills) + len(p.servers) + len(p.hooks) + len(p.agents) +} + +func readJSONFile(p string) (map[string]any, error) { + b, err := os.ReadFile(p) + if err != nil { + return nil, err + } + var m map[string]any + if err := json.Unmarshal(stripBOM(b), &m); err != nil { + return nil, fmt.Errorf("%s doesn't parse: %w", filepath.Base(p), err) + } + return m, nil +} + +func stripBOM(b []byte) []byte { return []byte(strings.TrimPrefix(string(b), "\ufeff")) } + +func plStr(v any) string { + s, _ := v.(string) + return strings.TrimSpace(s) +} + +// pathsOf is a manifest value naming one path or a list of them. +func pathsOf(v any) []string { + switch x := v.(type) { + case string: + return []string{x} + case []any: + var out []string + for _, e := range x { + if s, ok := e.(string); ok { + out = append(out, s) + } + } + return out + } + return nil +} + +// inside resolves a path a manifest names against the plugin's folder: one +// that leaves it is refused. +func inside(dir, p string) (string, bool) { + p = filepath.Join(dir, filepath.FromSlash(strings.TrimPrefix(p, "./"))) + rel, err := filepath.Rel(dir, p) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false + } + return p, true +} + +var pluginName = regexp.MustCompile(`[^A-Za-z0-9_-]+`) + +func pluginSlug(s string) string { + s = strings.Trim(pluginName.ReplaceAllString(strings.TrimSpace(s), "-"), "-_") + if len(s) > 40 { + s = strings.Trim(s[:40], "-_") + } + return s +} + +// isPlugin is whether dir looks like a plugin's folder. +func isPlugin(dir string) bool { + for _, p := range []string{".claude-plugin/plugin.json", "skills", "agents", "commands", "hooks/hooks.json", ".mcp.json"} { + if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(p))); err == nil { + return true + } + } + return false +} + +// readPlugin reads the plugin in dir. over are the fields a marketplace's +// entry gives for it, which a plugin.json overrides; hint is the name the +// marketplace calls it by. +func readPlugin(dir, hint string, over map[string]any) (*plLoaded, error) { + man := map[string]any{} + if m, err := readJSONFile(filepath.Join(dir, ".claude-plugin", "plugin.json")); err == nil { + man = m + } else if !errors.Is(err, fs.ErrNotExist) { + return nil, err + } + for k, v := range over { + if _, ok := man[k]; !ok { + man[k] = v + } + } + if !isPlugin(dir) && len(man) == 0 { + return nil, fmt.Errorf("no Claude Code plugin in %s: it has no .claude-plugin/plugin.json, skills, agents, hooks or .mcp.json", dir) + } + name := pluginSlug(plStr(man["name"])) + if name == "" { + name = pluginSlug(hint) + } + if name == "" { + name = pluginSlug(filepath.Base(dir)) + } + if name == "" { + return nil, errors.New("the plugin has no name") + } + p := &plLoaded{name: name, description: strings.Join(strings.Fields(plStr(man["description"])), " "), version: plStr(man["version"])} + root, data := pluginDir(name), pluginData(name) + sub := func(s string) string { + return strings.NewReplacer("${CLAUDE_PLUGIN_ROOT}", root, "$CLAUDE_PLUGIN_ROOT", root, + "${CLAUDE_PLUGIN_DATA}", data, "$CLAUDE_PLUGIN_DATA", data).Replace(s) + } + leave := func(what, why string) { p.left = append(p.left, PluginLeft{What: what, Why: why}) } + + // skills + seen := map[string]bool{} + for _, rel := range append([]string{"skills"}, pathsOf(man["skills"])...) { + d, ok := inside(dir, rel) + if !ok { + leave("skills "+rel, "the path leaves the plugin's folder") + continue + } + var dirs []string + if _, ok := readMeta(d); ok { + dirs = []string{d} + } else if es, err := os.ReadDir(d); err == nil { + for _, e := range es { + if c := filepath.Join(d, e.Name()); e.IsDir() || isDirLink(c) { + if _, ok := readMeta(c); ok { + dirs = append(dirs, c) + } + } + } + } + for _, sd := range dirs { + m, _ := readMeta(sd) + n := nameFor(filepath.Base(sd), m) + if n == "" || seen[sd] { + continue + } + seen[sd] = true + if err := checkName("skill", n); err != nil { + leave("skill "+n, err.Error()) + continue + } + p.skills = append(p.skills, plSkill{name: n, dir: sd}) + } + } + sort.Slice(p.skills, func(i, j int) bool { return p.skills[i].name < p.skills[j].name }) + + // subagents + var agentFiles []string + for _, rel := range append([]string{"agents"}, pathsOf(man["agents"])...) { + d, ok := inside(dir, rel) + if !ok { + leave("agents "+rel, "the path leaves the plugin's folder") + continue + } + if fi, err := os.Stat(d); err == nil && !fi.IsDir() { + agentFiles = append(agentFiles, d) + } else if es, err := os.ReadDir(d); err == nil { + for _, e := range es { + if !e.IsDir() && strings.HasSuffix(strings.ToLower(e.Name()), ".md") { + agentFiles = append(agentFiles, filepath.Join(d, e.Name())) + } + } + } + } + slices.Sort(agentFiles) + agentFiles = slices.Compact(agentFiles) + for _, f := range agentFiles { + s, err := readSubagentFile(f, p) + if err != nil { + leave("agent "+strings.TrimSuffix(filepath.Base(f), filepath.Ext(f)), err.Error()) + continue + } + p.agents = append(p.agents, s) + } + + // MCP servers + var mcpDocs []map[string]any + if m, err := readJSONFile(filepath.Join(dir, ".mcp.json")); err == nil { + mcpDocs = append(mcpDocs, m) + } else if !errors.Is(err, fs.ErrNotExist) { + leave(".mcp.json", err.Error()) + } + for _, v := range manifestList(man["mcpServers"]) { + switch x := v.(type) { + case string: + if d, ok := inside(dir, x); ok { + if m, err := readJSONFile(d); err == nil { + mcpDocs = append(mcpDocs, m) + } else { + leave(x, err.Error()) + } + } + case map[string]any: + mcpDocs = append(mcpDocs, x) + } + } + for _, doc := range mcpDocs { + servers, left := serversOf(doc, sub) + p.servers = append(p.servers, servers...) + p.left = append(p.left, left...) + } + + // hooks + var hookDocs []map[string]any + if m, err := readJSONFile(filepath.Join(dir, "hooks", "hooks.json")); err == nil { + hookDocs = append(hookDocs, m) + } else if !errors.Is(err, fs.ErrNotExist) { + leave("hooks/hooks.json", err.Error()) + } + for _, v := range manifestList(man["hooks"]) { + switch x := v.(type) { + case string: + if d, ok := inside(dir, x); ok { + if m, err := readJSONFile(d); err == nil { + hookDocs = append(hookDocs, m) + } else if !errors.Is(err, fs.ErrNotExist) { + leave(x, err.Error()) + } + } + case map[string]any: + hookDocs = append(hookDocs, x) + } + } + n := 0 + for _, doc := range hookDocs { + hooks, left := plHooksOf(doc, name, root, sub, &n) + p.hooks = append(p.hooks, hooks...) + p.left = append(p.left, left...) + } + + // what no agent here takes + if es, err := os.ReadDir(filepath.Join(dir, "commands")); err == nil { + c := 0 + for _, e := range es { + if strings.HasSuffix(strings.ToLower(e.Name()), ".md") { + c++ + } + } + if c > 0 { + leave(fmt.Sprintf("%d slash commands", c), "slash commands are Claude Code's own: magpie carries a plugin's skills, MCP servers, hooks and subagents") + } + } + for _, k := range []string{"lspServers", "outputStyles", "themes", "monitors"} { + if man[k] != nil { + leave(k, "no agent magpie writes to reads it") + } + } + return p, nil +} + +// manifestList is a manifest value that is one thing or a list of them. +func manifestList(v any) []any { + switch x := v.(type) { + case nil: + return nil + case []any: + return x + } + return []any{v} +} + +func isDirLink(p string) bool { + fi, err := os.Stat(p) + return err == nil && fi.IsDir() +} + +// subagentName is the name a subagent goes by in every agent: lowercase +// letters, digits and -. +func subagentName(s string) string { + s = strings.ToLower(strings.TrimSpace(s)) + s = strings.Trim(regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(s, "-"), "-") + if len(s) > 50 { + s = strings.Trim(s[:50], "-") + } + return s +} + +// splitFront is a Markdown file's YAML front matter and what follows it. +func splitFront(b []byte) (map[string]any, string) { + s := strings.ReplaceAll(strings.TrimPrefix(string(b), "\ufeff"), "\r\n", "\n") + rest, ok := strings.CutPrefix(s, "---\n") + if !ok { + return nil, s + } + front, body, ok := strings.Cut(rest, "\n---") + if !ok { + return nil, s + } + body = strings.TrimPrefix(body, "\n") + var m map[string]any + if yaml.Unmarshal([]byte(front), &m) != nil { + return nil, s + } + return m, body +} + +func readSubagentFile(f string, p *plLoaded) (*Subagent, error) { + b, err := os.ReadFile(f) + if err != nil { + return nil, err + } + front, body := splitFront(b) + name := subagentName(plStr(front["name"])) + if name == "" { + name = subagentName(strings.TrimSuffix(filepath.Base(f), filepath.Ext(f))) + } + s := &Subagent{ + Name: name, + Description: strings.Join(strings.Fields(plStr(front["description"])), " "), + Prompt: strings.TrimRight(strings.ReplaceAll(body, "\r\n", "\n"), " \n\t"), + Agents: []string{}, + } + // the skills it names that this plugin brought + var named []string + switch x := front["skills"].(type) { + case string: + named = strings.Split(x, ",") + case []any: + for _, e := range x { + named = append(named, plStr(e)) + } + } + for _, n := range named { + n = strings.TrimSpace(n) + if i := strings.LastIndex(n, ":"); i >= 0 { + n = n[i+1:] + } + if slices.ContainsFunc(p.skills, func(k plSkill) bool { return k.name == n }) { + s.Skills = append(s.Skills, n) + } + } + if err := s.check(); err != nil { + return nil, err + } + return s, nil +} + +// serversOf reads a .mcp.json: {"mcpServers": {...}} or the map itself. +func serversOf(doc map[string]any, sub func(string) string) ([]*Server, []PluginLeft) { + m, _ := doc["mcpServers"].(map[string]any) + if m == nil { + m = doc + } + names := make([]string, 0, len(m)) + for k := range m { + names = append(names, k) + } + sort.Strings(names) + var out []*Server + var left []PluginLeft + for _, k := range names { + e, ok := m[k].(map[string]any) + if !ok { + continue + } + s := &Server{Name: pluginSlug(k), Agents: []string{}} + switch typ := plStr(e["type"]); { + case typ == "sse": + s.Transport = "sse" + case typ == "http" || typ == "streamable-http" || (typ == "" && plStr(e["url"]) != ""): + s.Transport = "http" + case typ == "" || typ == "stdio": + s.Transport = "stdio" + default: + left = append(left, PluginLeft{What: "MCP server " + k, Why: "a server of type " + typ + " isn't one agents take"}) + continue + } + s.Command, s.URL = sub(plStr(e["command"])), sub(plStr(e["url"])) + if a, ok := e["args"].([]any); ok { + for _, x := range a { + s.Args = append(s.Args, sub(fmt.Sprint(x))) + } + } + strMap := func(v any) map[string]string { + mm, _ := v.(map[string]any) + if len(mm) == 0 { + return nil + } + out := map[string]string{} + for k, x := range mm { + out[k] = sub(fmt.Sprint(x)) + } + return out + } + s.Env, s.Headers = strMap(e["env"]), strMap(e["headers"]) + if err := s.check(); err != nil { + left = append(left, PluginLeft{What: "MCP server " + k, Why: err.Error()}) + continue + } + out = append(out, s) + } + return out, left +} + +// claudeEvents are Claude Code's hook events that a portable event of +// the library's stands for. +var claudeEvents = map[string]string{"Stop": "turn-end", "PostToolUse": "after-tool", "PreToolUse": "before-tool", + "UserPromptSubmit": "prompt", "SessionStart": "session-start"} + +// toolKind is a Claude Code tool matcher as a portable kind of tool, or +// "" when it names others. +func toolKind(m string) (string, bool) { + if m == "" || m == "*" { + return "", true + } + set := map[string]bool{} + for _, x := range strings.Split(m, "|") { + set[strings.TrimSpace(x)] = true + } + switch { + case len(set) == 1 && set["Bash"]: + return "shell", true + case (len(set) == 2 && set["Edit"] && set["Write"]) || (len(set) == 3 && set["Edit"] && set["Write"] && set["MultiEdit"]): + return "edit", true + } + return "", false +} + +// plHooksOf reads a hooks.json: {"hooks": {Event: [...]}} or the map itself. +// A hook whose event and matcher are another agent's the same moment too +// is the portable one; any other is given to Claude Code alone, as +// written. +func plHooksOf(doc map[string]any, bundle, root string, sub func(string) string, n *int) ([]*Hook, []PluginLeft) { + m, _ := doc["hooks"].(map[string]any) + if m == nil { + m = doc + } + events := make([]string, 0, len(m)) + for k := range m { + events = append(events, k) + } + sort.Strings(events) + var out []*Hook + var left []PluginLeft + for _, ev := range events { + groups, _ := m[ev].([]any) + for _, g := range groups { + gm, _ := g.(map[string]any) + if gm == nil { + continue + } + matcher := plStr(gm["matcher"]) + hs, _ := gm["hooks"].([]any) + for _, h := range hs { + hm, _ := h.(map[string]any) + if hm == nil { + continue + } + if t := plStr(hm["type"]); t != "" && t != "command" { + left = append(left, PluginLeft{What: ev + " hook", Why: "a hook of type " + t + " isn't a command: agents take commands only"}) + continue + } + cmd := sub(quoteRoot(plStr(hm["command"]), root)) + if cmd == "" { + continue + } + *n++ + x := &Hook{Name: hookName(bundle, *n), Description: "From plugin " + bundle, Command: cmd, Agents: []string{}} + if t, ok := hm["timeout"].(float64); ok && t > 0 && t <= 86400 { + x.Timeout = int(t) + } + if portable, ok := claudeEvents[ev]; ok { + k, tools := toolKind(matcher) + if slices.Contains(toolEvents, portable) && tools { + x.Event, x.Matcher = portable, k + } else if !slices.Contains(toolEvents, portable) && matcher == "" { + x.Event = portable + } + } + if x.Event == "" { + if !slices.Contains(claudeHookEvents, ev) { + left = append(left, PluginLeft{What: ev + " hook", Why: "Claude Code has no event called " + ev}) + *n-- + continue + } + x.Event, x.Matcher = "claude:"+ev, matcher + } + if err := x.check(); err != nil { + left = append(left, PluginLeft{What: ev + " hook", Why: err.Error()}) + *n-- + continue + } + out = append(out, x) + } + } + } + return out, left +} + +// quoteRoot quotes the plugin's folder where a command names it bare and +// the folder has a space in it, as a plugin's own scripts assume it has +// none. +func quoteRoot(cmd, root string) string { + if !strings.ContainsAny(root, " \t") { + return cmd + } + re := regexp.MustCompile(`(["']?)(\$\{CLAUDE_PLUGIN_ROOT\}|\$CLAUDE_PLUGIN_ROOT)([^\s"']*)`) + return re.ReplaceAllStringFunc(cmd, func(s string) string { + if s[0] == '"' || s[0] == '\'' { + return s + } + return `"` + s + `"` + }) +} + +func hookName(bundle string, n int) string { + b := bundle + if len(b) > 40 { + b = b[:40] + } + return fmt.Sprintf("%s-%d", b, n) +} + +// ---- finding plugins --------------------------------------------------------- + +// PluginCandidate is a plugin found at what the user gave. +type PluginCandidate struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Version string `json:"version,omitempty"` + Skills int `json:"skills"` + MCP int `json:"mcp"` + Hooks int `json:"hooks"` + Subagents int `json:"subagents"` + // Remote: it is fetched from another repository when installed, so + // its parts aren't counted + Remote bool `json:"remote,omitempty"` + // Have: the library has it already + Have bool `json:"have,omitempty"` + Left []PluginLeft `json:"left,omitempty"` + // where it is, in the probe's folder + dir string + over map[string]any + src *Source // another repository, for a marketplace's entry that names one + path string // its folder in that repository +} + +// PluginProbe is what was found at an address. +type PluginProbe struct { + Source string `json:"source"` + Marketplace string `json:"marketplace,omitempty"` // its name, when there are several + Candidates []PluginCandidate `json:"candidates"` + root string +} + +// resolvePluginRoot is the folder a plugin or a marketplace is in, for +// what the user gave: a folder, a plugin.json or marketplace.json in one, +// or a git repository. tmp is a download that is the caller's to remove. +func resolvePluginRoot(input string) (root, tmp string, err error) { + input = strings.TrimSpace(input) + if input == "" { + return "", "", errors.New("paste a plugin's folder, or a GitHub or git repository's link") + } + if strings.HasPrefix(input, "-") { + return "", "", errors.New("an address can't start with -") + } + if dir := expand(input); filepath.IsAbs(dir) { + fi, err := os.Stat(dir) + if err != nil { + return "", "", fmt.Errorf("%s isn't a folder", input) + } + if !fi.IsDir() { + // .claude-plugin/marketplace.json or plugin.json + dir = filepath.Dir(dir) + if filepath.Base(dir) == ".claude-plugin" { + dir = filepath.Dir(dir) + } + } + return dir, "", nil + } + sweepStaleDownloads() + src, ok := githubSource(input) + if !ok { + var err error + if src, ok, err = gitSource(input); err != nil { + return "", "", err + } else if !ok { + return "", "", errors.New("that's neither a git repository's link (GitHub, GitLab or another host) nor a folder's full path") + } + } + path := src.Path + src.Path = "" + tmp, err = fetch(src) + if err != nil { + return "", "", err + } + if path == "" { + return tmp, tmp, nil + } + sub, ok := inside(tmp, path) + if fi, err := os.Stat(sub); !ok || err != nil || !fi.IsDir() { + os.RemoveAll(tmp) + return "", "", fmt.Errorf("%s has no folder %s", src.Repo, path) + } + return sub, tmp, nil +} + +// findPlugins reads the plugins at root: a marketplace's entries, or the +// one plugin there. +func findPlugins(root string) (*PluginProbe, error) { + p := &PluginProbe{root: root, Candidates: []PluginCandidate{}} + mk, err := readJSONFile(filepath.Join(root, ".claude-plugin", "marketplace.json")) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, err + } + if mk == nil { + pl, err := readPlugin(root, filepath.Base(root), nil) + if err != nil { + return nil, err + } + p.Candidates = append(p.Candidates, candidateOf(pl, root, nil)) + return p, nil + } + p.Marketplace = plStr(mk["name"]) + pluginRoot := "" + if md, ok := mk["metadata"].(map[string]any); ok { + pluginRoot = plStr(md["pluginRoot"]) + } + entries, _ := mk["plugins"].([]any) + for _, e := range entries { + em, _ := e.(map[string]any) + if em == nil || pluginSlug(plStr(em["name"])) == "" { + continue + } + over := map[string]any{} + for _, k := range []string{"description", "version", "skills", "agents", "hooks", "mcpServers"} { + if v, ok := em[k]; ok { + over[k] = v + } + } + c := PluginCandidate{Name: pluginSlug(plStr(em["name"])), Description: strings.Join(strings.Fields(plStr(em["description"])), " "), Version: plStr(em["version"]), over: over} + switch s := em["source"].(type) { + case string: + d, ok := inside(root, filepath.Join(pluginRoot, s)) + if !ok { + c.Left = []PluginLeft{{What: c.Name, Why: "its source leaves the marketplace's folder"}} + break + } + if pl, err := readPlugin(d, c.Name, over); err == nil { + c2 := candidateOf(pl, d, over) + c2.Name = c.Name + c = c2 + } else { + c.Left = []PluginLeft{{What: c.Name, Why: err.Error()}} + } + c.dir = d + case map[string]any: + src, why := marketSource(s) + if why != "" { + c.Left = []PluginLeft{{What: c.Name, Why: why}} + break + } + c.Remote, c.src, c.path = true, &src, plStr(s["path"]) + default: + c.Left = []PluginLeft{{What: c.Name, Why: "it has no source"}} + } + c.over = over + p.Candidates = append(p.Candidates, c) + } + if len(p.Candidates) == 0 { + return nil, errors.New("the marketplace lists no plugins") + } + return p, nil +} + +// marketSource is where a marketplace entry's plugin is fetched from. +func marketSource(s map[string]any) (Source, string) { + ref := plStr(s["ref"]) + switch plStr(s["source"]) { + case "github": + repo := plStr(s["repo"]) + if src, ok := githubSource(repo); ok { + src.Ref = ref + return src, "" + } + return Source{}, "its GitHub repository " + repo + " isn't owner/repo" + case "url", "git", "git-subdir": + u := plStr(s["url"]) + if src, ok := githubSource(u); ok { + src.Ref = ref + return src, "" + } + if src, ok, err := gitSource(u); ok && err == nil { + src.Ref = ref + return src, "" + } + return Source{}, "its address " + u + " isn't a git repository's" + } + return Source{}, "its source of kind " + plStr(s["source"]) + " isn't one magpie fetches" +} + +func candidateOf(pl *plLoaded, dir string, over map[string]any) PluginCandidate { + return PluginCandidate{Name: pl.name, Description: pl.description, Version: pl.version, + Skills: len(pl.skills), MCP: len(pl.servers), Hooks: len(pl.hooks), Subagents: len(pl.agents), + Left: pl.left, dir: dir, over: over} +} + +var pluginProbes = struct { + m map[string]*PluginProbe +}{m: map[string]*PluginProbe{}} + +// ProbePlugins looks for plugins at what the user typed: a plugin's +// folder, a marketplace's (its .claude-plugin/marketplace.json), or a +// repository with either. +func ProbePlugins(input string) (*PluginProbe, error) { + root, tmp, err := resolvePluginRoot(input) + if err != nil { + return nil, err + } + p, err := findPlugins(root) + if err != nil { + if tmp != "" { + os.RemoveAll(tmp) + } + return nil, err + } + p.Source = strings.TrimSpace(input) + if l, err := load(); err == nil { + for i := range p.Candidates { + p.Candidates[i].Have = l.plugin(p.Candidates[i].Name) != nil + } + } + if tmp != "" { + // the install that follows uses this download; it is removed + // with the probe's life, as a skill's is + keepProbe("plugin:"+p.Source, &Probe{Source: p.Source, root: root}, tmp) + } + return p, nil +} + +// ---- installing ---------------------------------------------------------------- + +// InstallPlugins installs the plugins named (all of them, of one plugin) +// from what the user gave, and gives them to the agents. One the library +// has is replaced by this one, keeping the agents it was given to and +// whether it is on. +func InstallPlugins(input string, names, agents []string) (*Result, error) { + input = strings.TrimSpace(input) + p, cleanup, err := pluginProbeFor(input) + if err != nil { + return nil, err + } + defer cleanup() + return installPlugins(p, input, names, agents) +} + +// pluginProbeFor is the probe of input, from the one the page just made when it +// is still kept; cleanup removes a download made here. +func pluginProbeFor(input string) (*PluginProbe, func(), error) { + if dir := expand(input); !filepath.IsAbs(dir) { + probes.Lock() + e := probes.m["plugin:"+input] + probes.Unlock() + if e != nil { + if _, err := os.Stat(e.tmp); err == nil { + if p, err := findPlugins(e.p.root); err == nil { + p.Source = input + return p, func() {}, nil + } + } + } + } + root, tmp, err := resolvePluginRoot(input) + if err != nil { + return nil, nil, err + } + p, err := findPlugins(root) + if err != nil { + if tmp != "" { + os.RemoveAll(tmp) + } + return nil, nil, err + } + p.Source = input + return p, func() { + if tmp != "" { + os.RemoveAll(tmp) + } + }, nil +} + +func installPlugins(p *PluginProbe, input string, names, agents []string) (*Result, error) { + var picked []PluginCandidate + switch { + case len(names) == 0 && len(p.Candidates) == 1: + picked = p.Candidates + case len(names) == 0: + return nil, fmt.Errorf("%s lists %d plugins: pick the ones to install", p.Marketplace, len(p.Candidates)) + default: + for _, n := range names { + i := slices.IndexFunc(p.Candidates, func(c PluginCandidate) bool { return c.Name == n }) + if i < 0 { + return nil, fmt.Errorf("no plugin called %s there", n) + } + picked = append(picked, p.Candidates[i]) + } + } + // read each before anything changes: one that can't be read stops the + // install with nothing written + type one struct { + c PluginCandidate + pl *plLoaded + d string + } + var ones []one + var cleanups []func() + defer func() { + for _, f := range cleanups { + f() + } + }() + for _, c := range picked { + d := c.dir + if c.Remote { + tmp, err := fetch(*c.src) + if err != nil { + return nil, fmt.Errorf("%s: %w", c.Name, err) + } + cleanups = append(cleanups, func() { os.RemoveAll(tmp) }) + var ok bool + if d, ok = inside(tmp, c.path); !ok { + return nil, fmt.Errorf("%s: its folder %s leaves its repository", c.Name, c.path) + } + } + pl, err := readPlugin(d, c.Name, c.over) + if err != nil { + return nil, fmt.Errorf("%s: %w", c.Name, err) + } + if len(p.Candidates) > 1 || c.Remote { + pl.name = c.Name // a marketplace's name for it + } + if pl.parts() == 0 { + return nil, fmt.Errorf("%s has no skills, MCP servers, hooks or subagents magpie can give an agent", pl.name) + } + ones = append(ones, one{c, pl, d}) + } + var done []string + var skipped []Problem + res, err := change(func(l *Library) error { + done, skipped = nil, nil + for _, o := range ones { + pick := "" + if len(p.Candidates) > 1 { + pick = o.pl.name + } + sk, err := installPlugin(l, o.pl, o.d, input, pick, agents) + if err != nil { + return fmt.Errorf("%s: %w", o.pl.name, err) + } + skipped = append(skipped, sk...) + done = append(done, o.pl.name) + } + return nil + }) + if res != nil { + res.Installed, res.Skipped = done, skipped + } + return res, err +} + +// installPlugin puts one plugin in l: its files in the library's folder, +// its parts among the library's items. +func installPlugin(l *Library, pl *plLoaded, dir, input, pick string, agents []string) ([]Problem, error) { + old := l.plugin(pl.name) + b := &Plugin{Name: pl.name, Description: pl.description, Version: pl.version, Source: input, Pick: pick, + Agents: orNone(slices.Compact(slices.Sorted(slices.Values(agents)))), Installed: time.Now().Format(time.RFC3339)} + if old != nil { + b.Agents, b.Off = old.Agents, old.Off + if len(agents) > 0 { + b.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents)))) + } + } + // the files first, beside the old ones, and swapped in once copied + if err := os.MkdirAll(pluginsDir(), 0o755); err != nil { + return nil, err + } + if err := os.MkdirAll(pluginData(pl.name), 0o755); err != nil { + return nil, err + } + stage := pluginDir(pl.name) + ".new" + os.RemoveAll(stage) + if err := copyDir(dir, stage); err != nil { + os.RemoveAll(stage) + return nil, err + } + // what the old version made goes, to be made again + if old != nil { + removePluginParts(l, old) + } + os.RemoveAll(pluginDir(pl.name)) + if err := os.Rename(stage, pluginDir(pl.name)); err != nil { + os.RemoveAll(stage) + return nil, err + } + root := pluginDir(pl.name) + // skills are read again from the copy + rel := func(p string) string { r, _ := filepath.Rel(dir, p); return filepath.Join(root, r) } + + var skipped []Problem + skip := func(what, why string) { + b.Left = append(b.Left, PluginLeft{What: what, Why: why}) + skipped = append(skipped, Problem{What: "plugin:" + pl.name, Error: what + ": " + why}) + } + b.Left = append(b.Left, pl.left...) + for _, k := range pl.left { + skipped = append(skipped, Problem{What: "plugin:" + pl.name, Error: k.What + ": " + k.Why}) + } + // a name another item has is given this plugin's name before it + free := func(name string, taken func(string) bool, ok func(string) bool) (string, bool) { + for _, n := range []string{name, pluginSlug(pl.name) + "-" + name} { + if ok(n) && !taken(n) { + return n, true + } + } + return "", false + } + skillNames := map[string]string{} + for _, s := range pl.skills { + n, ok := free(s.name, func(n string) bool { + if l.skill(n) != nil { + return true + } + _, err := os.Lstat(skillDir(n)) + return err == nil + }, func(n string) bool { return checkName("skill", n) == nil }) + if !ok { + skip("skill "+s.name, "the library already has one by that name") + continue + } + if err := os.MkdirAll(skillsDir(), 0o755); err != nil { + return nil, err + } + if err := copyDir(rel(s.dir), skillDir(n)); err != nil { + os.RemoveAll(skillDir(n)) + skip("skill "+s.name, err.Error()) + continue + } + l.Skills = append(l.Skills, &Skill{Name: n, Agents: []string{}, Bundle: pl.name}) + b.Skills = append(b.Skills, n) + skillNames[s.name] = n + } + for _, s := range pl.servers { + n, ok := free(s.Name, func(n string) bool { return l.server(n) != nil }, func(n string) bool { return checkName("server", n) == nil }) + if !ok { + skip("MCP server "+s.Name, "the library already has one by that name") + continue + } + s.Name, s.Bundle = n, pl.name + l.MCP = append(l.MCP, s) + b.MCP = append(b.MCP, n) + } + for _, h := range pl.hooks { + n, ok := free(h.Name, func(n string) bool { return l.hook(n) != nil }, func(n string) bool { return checkName("hook", n) == nil }) + if !ok { + skip("hook "+h.Name, "the library already has one by that name") + continue + } + h.Name, h.Bundle = n, pl.name + l.Hooks = append(l.Hooks, h) + b.Hooks = append(b.Hooks, n) + } + for _, s := range pl.agents { + n, ok := free(s.Name, func(n string) bool { return l.subagent(n) != nil }, func(n string) bool { return subagentNameRe.MatchString(n) }) + if !ok { + skip("subagent "+s.Name, "the library already has one by that name") + continue + } + s.Name, s.Bundle = n, pl.name + for i, k := range s.Skills { + if m := skillNames[k]; m != "" { + s.Skills[i] = m + } + } + l.Subagents = append(l.Subagents, s) + b.Subagents = append(b.Subagents, n) + } + if len(b.Skills)+len(b.MCP)+len(b.Hooks)+len(b.Subagents) == 0 { + os.RemoveAll(pluginDir(pl.name)) + return nil, errors.New("every part of it clashes with the library's own: " + skipped[len(skipped)-1].Error) + } + if old != nil { + l.Plugins = slices.DeleteFunc(l.Plugins, func(x *Plugin) bool { return x.Name == old.Name }) + } + l.Plugins = append(l.Plugins, b) + sort.Slice(l.Plugins, func(i, j int) bool { return l.Plugins[i].Name < l.Plugins[j].Name }) + l.givePlugin(b) + return skipped, nil +} + +// givePlugin sets each part's agents from the bundle's: its Agents when +// on, none when off. A part an agent can't take is left out for that +// agent, not given and then refused. +func (l *Library) givePlugin(b *Plugin) { + agents := b.Agents + if b.Off { + agents = nil + } + for _, n := range b.Skills { + if s := l.skill(n); s != nil { + s.Agents = orNone(slices.Clone(agents)) + } + } + for _, n := range b.MCP { + if s := l.server(n); s != nil { + s.Agents = orNone(slices.Clone(agents)) + } + } + for _, n := range b.Hooks { + if h := l.hook(n); h != nil { + h.Agents = orNone(slices.DeleteFunc(slices.Clone(agents), func(a string) bool { return !hookTakes(h, a) })) + } + } + for _, n := range b.Subagents { + if s := l.subagent(n); s != nil { + s.Agents = orNone(slices.DeleteFunc(slices.Clone(agents), func(a string) bool { + base, _, _ := strings.Cut(a, "@wsl:") + return !slices.Contains(SubagentAgents, base) + })) + } + } +} + +// removePluginParts takes out of l every item the bundle made. +func removePluginParts(l *Library, b *Plugin) { + stamp := time.Now().Format("2006-01-02_15-04-05.000") + for _, n := range b.Skills { + if s := l.skill(n); s != nil && s.Bundle == b.Name { + _ = removeSkill(l, n, stamp) + } + } + for _, n := range b.MCP { + if s := l.server(n); s != nil && s.Bundle == b.Name { + _ = removeServer(l, n) + } + } + l.Hooks = slices.DeleteFunc(l.Hooks, func(h *Hook) bool { return h.Bundle == b.Name && slices.Contains(b.Hooks, h.Name) }) + l.Subagents = slices.DeleteFunc(l.Subagents, func(s *Subagent) bool { return s.Bundle == b.Name && slices.Contains(b.Subagents, s.Name) }) +} + +// ---- changes ------------------------------------------------------------------- + +// PluginAgents sets which agents get a plugin's parts. Each part goes only +// to the agents that can take it. +func PluginAgents(name string, agents []string) (*Result, error) { + for _, a := range agents { + if err := checkAgent(a); err != nil { + return nil, err + } + } + return change(func(l *Library) error { + b := l.plugin(name) + if b == nil { + return fmt.Errorf("no plugin called %s", name) + } + b.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents)))) + l.givePlugin(b) + return nil + }) +} + +// PluginOn turns a plugin on or off: off takes all its parts from every +// agent and keeps them in the library. +func PluginOn(name string, on bool) (*Result, error) { + return change(func(l *Library) error { + b := l.plugin(name) + if b == nil { + return fmt.Errorf("no plugin called %s", name) + } + b.Off = !on + l.givePlugin(b) + return nil + }) +} + +// RemovePlugin takes a plugin out of the library, every part of it out of +// every agent and its folder out of the library's. +func RemovePlugin(name string) (*Result, error) { + res, err := change(func(l *Library) error { + b := l.plugin(name) + if b == nil { + return fmt.Errorf("no plugin called %s", name) + } + removePluginParts(l, b) + l.Plugins = slices.DeleteFunc(l.Plugins, func(x *Plugin) bool { return x.Name == name }) + return nil + }) + if err == nil { + os.RemoveAll(pluginDir(name)) + } + return res, err +} + +// UpdatePlugin fetches a plugin again from where it came from and +// replaces its parts, keeping the agents it is given to and whether it is +// on. +func UpdatePlugin(name string) (*Result, error) { + mu.Lock() + l, err := load() + mu.Unlock() + if err != nil { + return nil, err + } + b := l.plugin(name) + if b == nil { + return nil, fmt.Errorf("no plugin called %s", name) + } + if b.Source == "" { + return nil, fmt.Errorf("%s has no source to fetch again", name) + } + var names []string + if b.Pick != "" { + names = []string{b.Pick} + } + p, cleanup, err := pluginProbeFor(b.Source) + if err != nil { + return nil, err + } + defer cleanup() + return installPlugins(p, b.Source, names, nil) +} + +// ---- the page -------------------------------------------------------------- + +// PluginView is a plugin as the page shows it. +type PluginView struct { + *Plugin + // Missing are parts the user took out one by one since + Missing []string `json:"missing,omitempty"` + Dir string `json:"dir"` +} + +func (l *Library) pluginsView() []PluginView { + out := []PluginView{} + for _, b := range l.Plugins { + v := PluginView{Plugin: b, Dir: pluginDir(b.Name)} + // the parts the user took out one by one aren't listed as its + c := *b + c.Skills = slices.DeleteFunc(slices.Clone(b.Skills), func(n string) bool { + s := l.skill(n) + gone := s == nil || s.Bundle != b.Name + if gone { + v.Missing = append(v.Missing, "skill "+n) + } + return gone + }) + c.MCP = slices.DeleteFunc(slices.Clone(b.MCP), func(n string) bool { + s := l.server(n) + gone := s == nil || s.Bundle != b.Name + if gone { + v.Missing = append(v.Missing, "MCP server "+n) + } + return gone + }) + c.Hooks = slices.DeleteFunc(slices.Clone(b.Hooks), func(n string) bool { + h := l.hook(n) + gone := h == nil || h.Bundle != b.Name + if gone { + v.Missing = append(v.Missing, "hook "+n) + } + return gone + }) + c.Subagents = slices.DeleteFunc(slices.Clone(b.Subagents), func(n string) bool { + s := l.subagent(n) + gone := s == nil || s.Bundle != b.Name + if gone { + v.Missing = append(v.Missing, "subagent "+n) + } + return gone + }) + v.Plugin = &c + out = append(out, v) + } + return out +} diff --git a/internal/library/plugin_test.go b/internal/library/plugin_test.go new file mode 100644 index 000000000..32d8aa931 --- /dev/null +++ b/internal/library/plugin_test.go @@ -0,0 +1,238 @@ +package library + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// writePlugin writes a Claude Code plugin's folder: a skill, a subagent +// that names it, a hook on shell tools, a Stop hook, an MCP server, a +// slash command and a hook that isn't a command. +func writePlugin(t *testing.T, dir string) { + t.Helper() + write(t, filepath.Join(dir, ".claude-plugin/plugin.json"), `{"name":"acme-kit","version":"1.2.0","description":"Acme's review kit"}`) + write(t, filepath.Join(dir, "skills/tdd/SKILL.md"), "---\nname: tdd\ndescription: Test first\n---\nWrite the test first.\n") + write(t, filepath.Join(dir, "agents/reviewer.md"), "---\nname: reviewer\ndescription: Reviews a diff\nskills: tdd\n---\nYou review code.\n") + write(t, filepath.Join(dir, "commands/ship.md"), "Ship it\n") + write(t, filepath.Join(dir, "hooks/hooks.json"), `{"hooks":{ + "PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"${CLAUDE_PLUGIN_ROOT}/scripts/lint.sh","timeout":20}]}], + "Stop":[{"hooks":[{"type":"command","command":"echo done"}]}], + "PreCompact":[{"hooks":[{"type":"command","command":"echo compacting"},{"type":"prompt","prompt":"x"}]}]}}`) + write(t, filepath.Join(dir, ".mcp.json"), `{"mcpServers":{"acme-db":{"command":"${CLAUDE_PLUGIN_ROOT}/bin/db","args":["--data","${CLAUDE_PLUGIN_DATA}"],"env":{"K":"v"}}}}`) +} + +func pluginAgents(t *testing.T, h string) { + t.Helper() + write(t, filepath.Join(h, ".claude/settings.json"), "{}\n") + write(t, filepath.Join(h, ".codex/config.toml"), "") + write(t, filepath.Join(h, ".config/opencode/opencode.json"), "{}\n") +} + +func TestPluginImportCarryOnOffRemove(t *testing.T) { + h := sandbox(t) + pluginAgents(t, h) + src := filepath.Join(t.TempDir(), "acme") + writePlugin(t, src) + + p, err := ProbePlugins(src) + if err != nil || len(p.Candidates) != 1 { + t.Fatalf("probe: %v %+v", err, p) + } + c := p.Candidates[0] + if c.Name != "acme-kit" || c.Skills != 1 || c.MCP != 1 || c.Hooks != 3 || c.Subagents != 1 || len(c.Left) != 2 { + t.Fatalf("candidate: %+v", c) + } + + res := ok(t)(InstallPlugins(src, nil, []string{"claude", "codex"})) + if len(res.Installed) != 1 || res.Installed[0] != "acme-kit" { + t.Fatalf("installed: %+v", res.Installed) + } + root := filepath.Join(Dir(), "plugins", "acme-kit") + data := filepath.Join(Dir(), "plugin-data", "acme-kit") + + // every part is an ordinary item of its page, marked with the plugin + v := View0(t) + if len(v.Plugins) != 1 || v.Plugins[0].Name != "acme-kit" || v.Plugins[0].Version != "1.2.0" { + t.Fatalf("plugins: %+v", v.Plugins) + } + if len(v.Skills) != 1 || v.Skills[0].Bundle != "acme-kit" { + t.Fatalf("skills: %+v", v.Skills) + } + + // carried, each part to the agents that take it + if got := read(t, filepath.Join(h, ".claude/agents/reviewer.md")); !strings.Contains(got, "You review code.") || !strings.Contains(got, `skills: ["tdd"]`) { + t.Errorf("claude subagent:\n%s", got) + } + if _, err := os.Stat(filepath.Join(h, ".codex/agents/reviewer.toml")); err != nil { + t.Errorf("codex subagent: %v", err) + } + if _, err := os.Lstat(filepath.Join(h, ".claude/skills/tdd")); err != nil { + t.Errorf("claude skill: %v", err) + } + settings := read(t, filepath.Join(h, ".claude/settings.json")) + for _, want := range []string{filepath.Join(root, "scripts/lint.sh"), "Bash", "echo done"} { + if !strings.Contains(settings, want) { + t.Errorf("claude settings lack %q:\n%s", want, settings) + } + } + if strings.Contains(settings, "compacting") == false { + t.Errorf("claude's own PreCompact hook missing:\n%s", settings) + } + if codexHooks := read(t, filepath.Join(h, ".codex/hooks.json")); strings.Contains(codexHooks, "compacting") { + t.Errorf("codex was given claude's own event:\n%s", codexHooks) + } + cj := read(t, filepath.Join(h, ".claude.json")) + if !strings.Contains(cj, filepath.Join(root, "bin/db")) || !strings.Contains(cj, data) { + t.Errorf("claude's server lacks the plugin's folders:\n%s", cj) + } + if !strings.Contains(read(t, filepath.Join(h, ".codex/config.toml")), "acme-db") { + t.Errorf("codex lacks the server") + } + if _, err := os.Stat(data); err != nil { + t.Errorf("data folder: %v", err) + } + + // off: every part leaves every agent, and stays in the library + ok(t)(PluginOn("acme-kit", false)) + for _, f := range []string{".claude/agents/reviewer.md", ".claude/skills/tdd", ".codex/agents/reviewer.toml"} { + if _, err := os.Lstat(filepath.Join(h, f)); err == nil { + t.Errorf("%s stays while the plugin is off", f) + } + } + if s := read(t, filepath.Join(h, ".claude/settings.json")); strings.Contains(s, "echo done") || strings.Contains(s, "compacting") { + t.Errorf("hooks stay while off:\n%s", s) + } + if s := read(t, filepath.Join(h, ".claude.json")); strings.Contains(s, "acme-db") { + t.Errorf("server stays while off:\n%s", s) + } + if v := View0(t); len(v.Skills) != 1 || len(v.Servers) != 1 || len(v.Subagents) != 1 || !v.Plugins[0].Off { + t.Fatalf("off keeps the parts in the library: %+v", v) + } + + // on again, and for one agent only + ok(t)(PluginAgents("acme-kit", []string{"codex"})) + ok(t)(PluginOn("acme-kit", true)) + if _, err := os.Stat(filepath.Join(h, ".claude/agents/reviewer.md")); err == nil { + t.Errorf("claude got the subagent it wasn't ticked for") + } + if _, err := os.Stat(filepath.Join(h, ".codex/agents/reviewer.toml")); err != nil { + t.Errorf("codex: %v", err) + } + + // removed: nothing of it is left, in an agent or the library + ok(t)(RemovePlugin("acme-kit")) + v = View0(t) + if len(v.Plugins)+len(v.Skills)+len(v.Servers)+len(v.Hooks)+len(v.Subagents) != 0 { + t.Errorf("left after remove: %+v", v) + } + if _, err := os.Stat(root); err == nil { + t.Errorf("its folder stays") + } + if _, err := os.Stat(filepath.Join(h, ".codex/agents/reviewer.toml")); err == nil { + t.Errorf("codex's subagent stays") + } +} + +// The user's own items by the same names are never written over, and a +// plugin never takes them for its own. +func TestPluginNameClashKeepsTheUsersOwn(t *testing.T) { + h := sandbox(t) + pluginAgents(t, h) + ok(t)(SaveServer("", Server{Name: "acme-db", Transport: "stdio", Command: "mine", Agents: []string{"claude"}})) + src := filepath.Join(t.TempDir(), "acme") + writePlugin(t, src) + res := ok(t)(InstallPlugins(src, nil, []string{"claude"})) + if len(res.Skipped) == 0 { + t.Fatalf("nothing said about the clash") + } + v := View0(t) + var own, theirs int + for _, s := range v.Servers { + if s.Name == "acme-db" && s.Bundle == "" && s.Command == "mine" { + own++ + } + if s.Name == "acme-kit-acme-db" && s.Bundle == "acme-kit" { + theirs++ + } + } + if own != 1 || theirs != 1 { + t.Fatalf("servers: %+v", v.Servers) + } + ok(t)(RemovePlugin("acme-kit")) + if v := View0(t); len(v.Servers) != 1 || v.Servers[0].Command != "mine" { + t.Errorf("remove took the user's own: %+v", v.Servers) + } + _ = h +} + +// A marketplace lists several plugins, each a folder in it; one picked is +// installed, and an update reads it again from the same place keeping +// where it was given. +func TestPluginMarketplaceAndUpdate(t *testing.T) { + h := sandbox(t) + pluginAgents(t, h) + mk := filepath.Join(t.TempDir(), "market") + write(t, filepath.Join(mk, ".claude-plugin/marketplace.json"), `{"name":"m","plugins":[ + {"name":"one","source":"./plugins/one","description":"First"}, + {"name":"two","source":"./plugins/two"}, + {"name":"far","source":{"source":"github","repo":"o/r"}}, + {"name":"out","source":"../../etc"}]}`) + write(t, filepath.Join(mk, "plugins/one/skills/a/SKILL.md"), "---\nname: a\ndescription: A\n---\nA\n") + write(t, filepath.Join(mk, "plugins/two/.mcp.json"), `{"two-srv":{"url":"https://example.com/mcp"}}`) + + p, err := ProbePlugins(mk) + if err != nil || len(p.Candidates) != 4 || p.Marketplace != "m" { + t.Fatalf("probe: %v %+v", err, p) + } + if !p.Candidates[2].Remote || len(p.Candidates[3].Left) == 0 { + t.Fatalf("candidates: %+v", p.Candidates) + } + if _, err := InstallPlugins(mk, nil, nil); err == nil { + t.Fatalf("a marketplace with no pick installs nothing") + } + ok(t)(InstallPlugins(mk, []string{"one", "two"}, []string{"claude"})) + v := View0(t) + if len(v.Plugins) != 2 || v.Plugins[0].Description != "First" || len(v.Skills) != 1 || len(v.Servers) != 1 || v.Servers[0].Transport != "http" { + t.Fatalf("%+v", v) + } + ok(t)(PluginOn("one", false)) + write(t, filepath.Join(mk, "plugins/one/skills/b/SKILL.md"), "---\nname: b\ndescription: B\n---\nB\n") + ok(t)(UpdatePlugin("one")) + v = View0(t) + if len(v.Skills) != 2 || !v.Plugins[0].Off || len(v.Plugins[0].Agents) != 1 { + t.Fatalf("update keeps off and agents: %+v", v.Plugins[0]) + } + for _, s := range v.Skills { + if len(s.Agents) != 0 { + t.Errorf("%s was given to %v while off", s.Name, s.Agents) + } + } +} + +func TestPluginRefusesWhatIsNone(t *testing.T) { + sandbox(t) + empty := t.TempDir() + if _, err := ProbePlugins(empty); err == nil { + t.Errorf("an empty folder is no plugin") + } + if _, err := ProbePlugins("-oProxyCommand=x"); err == nil { + t.Errorf("an option isn't an address") + } + cmds := t.TempDir() + write(t, filepath.Join(cmds, "commands/x.md"), "x") + if _, err := InstallPlugins(cmds, nil, nil); err == nil { + t.Errorf("a plugin of slash commands only has nothing to carry") + } +} + +// View0 is the page's view of the library. +func View0(t *testing.T) *View { + t.Helper() + v, err := Read(nil) + if err != nil { + t.Fatal(err) + } + return v +} diff --git a/internal/library/skills.go b/internal/library/skills.go index 85858c9ca..29ddfa48b 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -33,6 +33,7 @@ import ( // the agents that get it. type Skill struct { Name string `json:"name"` + Bundle string `json:"bundle,omitempty"` // the plugin it came with (plugin.go) Source *Source `json:"source,omitempty"` Agents []string `json:"agents"` // Hash is of the skill's files as last fetched from GitHub, and Commit diff --git a/internal/library/subagents.go b/internal/library/subagents.go index 99444e259..e249471b2 100644 --- a/internal/library/subagents.go +++ b/internal/library/subagents.go @@ -53,6 +53,7 @@ import ( // Subagent is one the agents ticked for it are given. type Subagent struct { Name string `json:"name"` + Bundle string `json:"bundle,omitempty"` // the plugin it came with (plugin.go) Description string `json:"description"` Prompt string `json:"prompt"` // Model is the model or routing group the subagent runs on, as the diff --git a/internal/library/sync.go b/internal/library/sync.go index 9532d3dae..83408c686 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -458,6 +458,7 @@ type ServerView struct { // SkillView is a library skill as the page shows it. type SkillView struct { Name string `json:"name"` + Bundle string `json:"bundle,omitempty"` // the plugin it came with Description string `json:"description"` Source string `json:"source,omitempty"` Kind string `json:"kind"` // github, git, folder, or "" for one kept in the library @@ -511,8 +512,10 @@ type View struct { Subagents []SubagentView `json:"subagents"` SubagentAgents []SubagentAgentView `json:"subagentAgents"` FoundServers []Found `json:"foundServers"` - Skills []SkillView `json:"skills"` - FoundSkills []FoundSkill `json:"foundSkills"` + // Plugins are the plugins kept as one item each (plugin.go) + Plugins []PluginView `json:"plugins"` + Skills []SkillView `json:"skills"` + FoundSkills []FoundSkill `json:"foundSkills"` // NewSkills are skills a check found its skills' repositories, or // the folders they were added from, to have beside them since, to // add or set aside @@ -704,9 +707,10 @@ func readView(problems []Problem, glance bool) (*View, error) { } v.Hooks, v.HookAgents = l.hooksView(append(slices.Clone(targets), gone...), asleep, of) v.Subagents, v.SubagentAgents = l.subagentsView(targets, asleep, of) + v.Plugins = l.pluginsView() tr := &tracer{} for _, s := range l.Skills { - sv := SkillView{Name: s.Name, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note, Router: s.Router} + sv := SkillView{Name: s.Name, Bundle: s.Bundle, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note, Router: s.Router} if s.Source != nil { sv.Source, sv.Kind = s.Source.String(), s.Source.Kind }