diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 813860155..b47dba766 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -23,7 +23,7 @@ Pi's extensions and packages. | Targets | `Targets` lists the detected agents (`agent.Detected`), a folder an agent shares with its vendor's other app when only that app is here (`agent.SharedHere`: the Cursor editor's `~/.cursor`, whose `mcp.json` and skills it reads, listed as Cursor; `TestCursorEditorAloneKeepsItsLibraryRow`; and `~/.copilot` or `$COPILOT_HOME`, listed as GitHub Copilot, whose `copilot-instructions.md` Copilot CLI, VS Code and GitHub Copilot's JetBrains plugin all read as the user's own instructions, kept with VS Code, VS Code Insiders or the plugin alone here even before the folder is (`agent.SharedRead`, `sharedApp`; @codealc on X, `TestCopilotVSCodeAloneGetsInstructions`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent whose CLI is gone (`CLIMissing`: an uninstall that left the folder behind, #2177, #2254) is no target: it is given nothing it can't read. One whose vendor's other app still reads the folder (`SharedRead`: VS Code for `~/.copilot`) stays one (`TestCopilotCLIGoneVSCodeKeepsTheRow`). One that isn't a target but still has skills, servers or hooks magpie gave it (in `Applied`: a tick a synced library brought for an agent this computer never gave anything is no reason to list it, `TestGoneAgentWithOnlySyncedTicksIsNotListed`; izhidigua on X) is held (`held`, a `Target` with `Gone`): a sync takes edits from its copies and then only takes out of it (`syncSkills`, `syncMCP` and `syncHooks` give a gone target nothing new), and `Read` lists it with `gone: true` while it has any. On a row, an agent's profiles (`hermes#name`, `omp#name`, `claude#name`, `qwenpaw#id`, WSL ones included) are one chip with a count, when an agent has more than one (`profileChip` in plugins/library/client.js, Yanzhongixuy on X: about twenty identical Hermes glyphs on every skill row); a click opens the app menu to pick profiles singly, and All still means every profile (`library-profile-chip.test.cjs`). A repository's, part's or pick's heading folds them the same way (`groupChips` sets `change.rows`; its chip is half lit when a profile has some of the skills), and the profiles chip takes part in the row's fan like any other (`[data-members]` in library.css), so the hand stays in line (Yanzhongixuy on X, 0.1.3926; `library-profile-group.test.cjs`). How far the chips close up with many agents (#936) is set in whole pixels from each row's width by one ResizeObserver (`handGap` in plugins/library/client.js), never in container units, which made every chip's style be worked out again on each step of a window resize: about 0.5s a step at 196 skills of 24 agents (lexrus on X; `skill-name-many-agents.test.cjs`). The page shows a gone agent's chip only on the rows of what it has, lit, so a click takes it out (`withGone` in plugins/library/client.js), leaves it out of All, the per-agent How sheet and every picker, and lists it in By agent as Not installed here with Turn all on off (@jiahao_jayden on X: an uninstalled WorkBuddy was on every skill's row; `TestGoneAgentListedToTakeOut`, `library-gone-agents.test.cjs`). On a Mac WorkBuddy and WorkBuddy AI are detected by their apps' bundle ids (`com.tencent.workbuddy.mac`, `com.workbuddy.workbuddy-ai`, `macBundle`), not by `~/.workbuddy`, which an uninstall leaves and magpie itself writes into (`TestWorkBuddyOnMacIsItsApp`); off a Mac the folder still counts. `everyTarget` keeps it for the guards that refuse an agent's own places: a project folder whose skills folder or MCP file is the agent's, and an instruction set kept in its instructions file. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi, OmO, Gemini CLI, Antigravity CLI, Crush, Cline, CodeBuddy Code, Kimi Code and Goose each by its own rule, never reading this machine's variables (Kimi Code's and Goose's shared `~/.agents/skills` there isn't given), Pi's MCP file chosen by `piMCP` as on this machine from the version the distro's `pi --version` gave its probe (`InstalledVersion`) and the distro's npm folders (`wslPiRoots`; leokon on Discord: only the Windows Pi was offered MCP servers, `TestWSLPiMCP`, `TestWSLMCPSiblings`), and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. A place below a folder the distro has as a link is opened where the link leads (`wslOpen`, agent-wiring's WSL folders that are links, #4502); a link the distro couldn't resolve gives that agent one `wsl` problem and nothing is written to it (`TestWSLFolderIsALinkToC`, `TestWSLFolderLinkUnresolved`). An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. Every built-in agent is a target or is in `noLibrary` with why: OpenBot was added with neither and was in no picker (SSNQT on X), so `TestEveryAgentInLibrary` fails a new agent until it gets one (34 were in no picker when it landed, listed there under #5897). | [`targets.go`](../../internal/library/targets.go) | | Stopped WSL distro | A stopped distro's agents are no targets: opening their files would start the distro, or the read fails (#3896). While a distro runs, `keepShape` keeps each agent's places and what its MCP file takes in `wsl.json` (`agent.WSLKeep`, key `library:`). While it is stopped, `Read` lists its agents from that (`asleepView`, `asleep: `), ticks as library.json has them; one magpie never saw there is listed only on the rows that name it, as `unseen`, its ticks not shown (cybercaius on Discord: the MCP page knew a distro's agents only once WSL had started). A tick on a stopped agent is kept in library.json as any is (`Takes` accepts one with a known shape; `serversAgents` judges it by `shape.reaches`), nothing is written and nothing in the distro runs; `Woken`, from `KeepLinked`'s loop (and the app's start-up sync), syncs when a distro the library names is seen go from stopped to running (`wsl.exe -l --running`, which starts nothing). The page greys a stopped agent's chip, says so in its tooltip and in one line per distro (`.lib-asleep`); an unseen chip is `aria-disabled` and kept by every click on its row (`keptOf`). The CLI says the same on stderr (`AsleepIn`). Queued, not a start button: a start costs the memory #3896 is about, and All or a bulk tick would start every distro. The Instructions page lists them too (`asleepInstructions`, #4182), at the instructions file the shape keeps, switched on as library.json has them, with what each gets besides (magpie's own folder) and nothing read from the file: its own lines and edits aren't counted then, and its path is plain text, not a reveal, which would open the distro. One switched on whose file magpie never saw is listed as `unseen`, its switch greyed out and kept by every other switch; before, a switch on the page sent the agents without the stopped distro's and took them off. A switch on one is written by `Woken`, which watches a distro named in `Instructions.Agents`, or whose agent still has magpie's part (`Applied.Instructions`), so one switched off has it taken out. The Hooks page lists the stopped agents with a shape as it does while the distro runs (`hooksView`, #4237): greyed, since magpie gives no agent in WSL hooks yet (`wslNoHooks`), and a hook given one says so; there is nothing for `Woken` to write. So does the Subagents page for the kinds it lists (`subagentsView`, `wslNoSubagents`, #4238). | [`wsl_asleep.go`](../../internal/library/wsl_asleep.go), [`targets.go`](../../internal/library/targets.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first (`sweepShared`, then `syncShared` for the Put skills in setting), so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) | -| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). A project also takes the library's subagents (jinpwng on X; `Subagents`, `AgentFiles`, [`project_subagents.go`](../../internal/library/project_subagents.go)): one file per subagent in the folder the agent reads a project's subagents from (`projectSubagentDirs`, cited per agent in its comment): `.claude/agents` for Claude Code, `.codex/agents`, `.opencode/agents`, `.gemini/agents`, `.qwen/agents`, `.factory/droids` for Droid, `.cursor/agents` and `.github/agents` for Copilot, in that agent's own format. A file is recorded with its hash (`SubagentFile`) and rewritten or removed only while it is exactly as magpie wrote it, so a same-name file of the user's is never touched (`TestProjectSubagentsLeaveTheUsersFiles`); a subagent renamed in the library is renamed in each project (`TestProjectSubagentsFollowTheLibrary`); the files are kept out of git by the same `info/exclude` block and follow the project's worktrees. `POST /api/library/projects/subagents` with `dir`, `name`/`names`, `agents`; the Subagents tab lists the projects as Skills and MCP do (`project-subagents.test.cjs`). It has no CLI yet, like project servers. A project also has instructions of its own (VictorHong1022 on X; `Instr`, `InstrAgents`, `InstrFiles`, [`project_instructions.go`](../../internal/library/project_instructions.go)), so the user-wide ones keep only what holds everywhere: one text, written into the file each picked agent reads in the project (`projectInstrNames`, cited per agent in its comment): `CLAUDE.md` (or `.claude/CLAUDE.md` when only that is there) for Claude Code, `AGENTS.override.md` over `AGENTS.md` for Codex and Pi, `GEMINI.md`/`QWEN.md` or the name their settings' `context.fileName` gives, `CODEBUDDY.md`, and `AGENTS.md` for the rest; a file several agents read is written once. Only the part between the user-wide part's two marker lines (`blockBegin`, `blockEnd`) is magpie's, the rest of the file is the user's and keeps its CRLF (`TestProjectInstructionsEachAgentsFile`, `KeepCRLF`); a part edited in the file stays until the project's text changes, and one taken out is written again (`TestProjectInstructionsLeaveTheUsersEdits`). Turned off, the part comes out and a file magpie made goes once nothing else is in it; a made file is kept out of git by the `info/exclude` block; a project file that is an agent's user-wide instructions file (a link, or a project at the home folder) is left alone with a problem (`TestProjectInstructionsNeverAnAgentsOwnFile`); worktrees follow (`TestProjectInstructionsFollowWorktrees`). `POST /api/library/projects/instructions` with `dir` and `instr` and/or `agents`; the Instructions tab lists the projects under the shared set, the page's Save saving a project's text too, first to the agents the shared set is on for (`project-instructions.test.cjs`); `magpie library project instructions [text …|--file f|-|agents a,b|none]` is its CLI. Cursor and Copilot read `CLAUDE.md` as well as `AGENTS.md`, so with Claude Code picked too they may read the text twice. Hooks and Claude plugins have no project scope yet. `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go), [`project_instructions.go`](../../internal/library/project_instructions.go) | +| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). A project also takes the library's subagents (jinpwng on X; `Subagents`, `AgentFiles`, [`project_subagents.go`](../../internal/library/project_subagents.go)): one file per subagent in the folder the agent reads a project's subagents from (`projectSubagentDirs`, cited per agent in its comment): `.claude/agents` for Claude Code, `.codex/agents`, `.opencode/agents`, `.gemini/agents`, `.qwen/agents`, `.factory/droids` for Droid, `.cursor/agents` and `.github/agents` for Copilot, in that agent's own format. A file is recorded with its hash (`SubagentFile`) and rewritten or removed only while it is exactly as magpie wrote it, so a same-name file of the user's is never touched (`TestProjectSubagentsLeaveTheUsersFiles`); a subagent renamed in the library is renamed in each project (`TestProjectSubagentsFollowTheLibrary`); the files are kept out of git by the same `info/exclude` block and follow the project's worktrees. `POST /api/library/projects/subagents` with `dir`, `name`/`names`, `agents`; the Subagents tab lists the projects as Skills and MCP do (`project-subagents.test.cjs`). It has no CLI yet, like project servers. A project also has instructions of its own (VictorHong1022 on X; `Instr`, `InstrAgents`, `InstrFiles`, [`project_instructions.go`](../../internal/library/project_instructions.go)), so the user-wide ones keep only what holds everywhere: one text, written into the file each picked agent reads in the project (`projectInstrNames`, cited per agent in its comment): `CLAUDE.md` (or `.claude/CLAUDE.md` when only that is there) for Claude Code, `AGENTS.override.md` over `AGENTS.md` for Codex and Pi, `GEMINI.md`/`QWEN.md` or the name their settings' `context.fileName` gives, `CODEBUDDY.md`, and `AGENTS.md` for the rest; a file several agents read is written once. Only the part between the user-wide part's two marker lines (`blockBegin`, `blockEnd`) is magpie's, the rest of the file is the user's and keeps its CRLF (`TestProjectInstructionsEachAgentsFile`, `KeepCRLF`); a part edited in the file stays until the project's text changes, and one taken out is written again (`TestProjectInstructionsLeaveTheUsersEdits`). Turned off, the part comes out and a file magpie made goes once nothing else is in it; a made file is kept out of git by the `info/exclude` block; a project file that is an agent's user-wide instructions file (a link, or a project at the home folder) is left alone with a problem (`TestProjectInstructionsNeverAnAgentsOwnFile`); worktrees follow (`TestProjectInstructionsFollowWorktrees`). `POST /api/library/projects/instructions` with `dir` and `instr` and/or `agents`; the Instructions tab lists the projects under the shared set, the page's Save saving a project's text too, first to the agents the shared set is on for (`project-instructions.test.cjs`); `magpie library project instructions [text …|--file f|-|agents a,b|none]` is its CLI. Cursor and Copilot read `CLAUDE.md` as well as `AGENTS.md`, so with Claude Code picked too they may read the text twice. A project also takes whole Claude plugins (jinpwng on X; `Plugins`, `HookRecs`, [`project_plugins.go`](../../internal/library/project_plugins.go)): `ProjectPlugin` sets which agents get a library plugin in the project, and for a sync `syncProject` adds the plugin's skills, servers and subagents to the project's own sets (`withPlugins`, put back as they were after), so each part goes where the project's own do, for the picked agents that take it there, and a part the project also has of its own stays when the plugin goes. Its hooks are written entry by entry into the project's hooks file (`projectHookFiles`): `.claude/settings.local.json` for Claude Code and `.codex/hooks.json` for Codex, through the same `hookWrite` as the user-wide ones, so an entry the user changed is theirs and stays, and taking out one of the plugin's before one of the user's moves the user's Codex trust (`[hooks.state]` in the user-wide config) with it. Codex runs a project's hooks only in a project the user trusts, once reviewed in `/hooks`; the card says so. Pi gets skills and servers; no other agent has a project hooks file magpie knows. A plugin turned off gives the project nothing while off; removing it from the library takes it out of every project (`dropProjectPlugin`). Taking it out is only deleting its `Plugins` entry: what magpie placed or wrote for it comes out by the records each part keeps, and a file magpie made goes once empty (`TestProjectPluginEachPartInTheProject`, `TestProjectPluginWithdrawLeavesTheUsers`, `TestProjectPluginFollowsTheLibrary`, `TestProjectPluginCodexTrustFollows`). `POST /api/library/projects/plugin` with `dir`, `name`, `agents` (none takes it out); the Claude plugins tab lists the projects as the other tabs do (`project-plugins.test.cjs`). It has no CLI yet. Pi packages and Codex's `.codex-plugin` folders aren't read as plugins. `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go), [`project_instructions.go`](../../internal/library/project_instructions.go), [`project_plugins.go`](../../internal/library/project_plugins.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). MiniMax Code reads `AGENTS.md` in its data folder (`$MINIMAX_DATA_DIR`, else `~/.minimax`) before every conversation, so its target is that file (`TestMiniMaxCodeInstructions`). WorkBuddy and WorkBuddy AI keep theirs as a string in a JSON file: `personalization.customPrompt` in `app/app-config.json` of their folder, the Custom Instructions of the app's Personalization settings (`Target.Field`, `instr_field.go`). magpie's part goes into that string between the same marker lines, after the user's own prompt, and a `Field` write goes through `edit.SetJSON`, so every other key, its order and its indentation stay as the app wrote them; taking the part back leaves the file as it was, the field (and a `personalization` object nothing else is in) going out when it holds nothing. A file that is not JSON, or a field that holds something other than text, is unknown: it is reported and written over by nothing (`TestWorkBuddyInstructionsAreAJSONField`, `TestWorkBuddyInstructionsFromNothing`, `TestWorkBuddyInstructionsUnreadFileIsLeftAlone`, `TestWorkBuddyInstructionsImport`). The app's config service loads the file as it starts and writes it whole on a save (`AppConfigService`, 5.5.6's app.asar), so a change made while it runs may need a restart of the app, and may be lost to its next save of any setting; this has not been tried against a running app. A file several agents read (agy and Antigravity's app both read `~/.gemini/config/GEMINI.md`) is written for the one of them switched on (`instrOwner`): the one switched off neither empties it nor shows it as edited (vizmoe42 on X, `TestAntigravitySharedInstructionsFile`). | [`instructions.go`](../../internal/library/instructions.go) | | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). The editor's command is a box that wraps, so a long line is read whole, and Enter still saves it (hema_17384 on Discord). Its Form | JSON switch shows the server as JSON in Claude Code's `.mcp.json` shape, the one Copy config… gives for it (`jsonOf` in plugins/library/client.js), with `${NAME}` references as written. An edit there is read as a paste is (`serversIn`) and becomes the form's at once. JSON that isn't one server's keeps the dialog from saving or going back to the form, and counts as unsaved. The note, the agents and sync stay in the form (`library-mcp-json.test.cjs`). A server's and a skill's `Note` (youyo.p_10001 on Discord) is the user's own word on what it is for: one line of at most `maxNote` (200) characters, whitespace run together (`checkNote`), as a hook's description is. The row shows it in place of the command or description, and its tooltip still gives that line. The skills' filter reads it too. A sync carries it (a server whole, a skill as `CarriedSkill.Note`), and no agent is given it, through the MCP router or not (`TestNoteNeverGiven`, `TestNoteCarried`). A skill's is set by itself (`SkillNote`, `skills/note`) from the skill's reader. Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). A remote server holds several accounts (Elorynth on X), one in use that every agent is given: sets of headers are `Server.Accounts` with `Server.Account` the one in use ("" is the server's own `Headers`), laid over `Headers` by `live` in `through`, `remoteHeaders` and `hubKey`, so a switch rewrites each agent's file (`TestServerAccountsSwitchEveryAgent`); a save from the editor, which doesn't send them, keeps them, and a backup carries no account's key (`TestServerAccountKeysAreSecrets`). magpie's OAuth sign-ins are `mcpauth` records, the one in use at `m[name]` and the others in `Spare` (`Use`, `RemoveAccount`, `StartAccount`), which the gateway's `/mcp/` sends from its next request on; an agent's existing upstream `Mcp-Session-Id` isn't reset by a switch. API `/api/library/mcp-account`; GUI `headerAccounts` and `acctList` (`mcp-accounts.test.cjs`). Agents that read one file (Antigravity and agy: `~/.gemini/config/mcp_config.json`) are written in turn, and the `magpie` entry one wrote there is magpie's for the other too (`sharerWrote`, `TestAntigravitySharedMCPFile`; izhidigua on X: it was taken for a server of the user's own and kept the servers direct). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | | MCP server on/off | `ServerOn` (`POST /api/library/servers/on` with `name` and `on`, `magpie library mcp off|on `) turns a server off for everyone without removing it (swang20201 on X, Docker gateway mode, where a server ticked for no agent is still given to every app at the MCP router's address). Off, it is `Hidden` with its agents kept in `Paused` and `Agents` empty, as a plugin's server hidden from agents is (`PluginServerOn`, [Plugin tools](plugin-tools.md)): no agent's file has it, no project's (`syncProjectMCP` skips it, keeping the project's own agents for it), no subagent names it (`renderSubagent`), the router lists and calls it for nobody, and a process the router held for it ends, since `Hidden` and `Paused` are part of its `hubKey`. Its command, URL, env, headers, sign-in, `DisabledTools` and note stay in library.json. On, the agents in `Paused` get it back (none when it had none, so the router gives it to other apps again), as before it was turned off; giving it agents (`ServerAgents`, the CLI's `mcp agents`) turns it on with those (`save`), while Turn all on (`EveryServerAgents` with every agent) leaves it off. The row's switch sits after its agent chips (`serverSwitch` in plugins/library/client.js); off, the row is dimmed, its chips take no click, and it is health-checked only on a click (`TestServerOnKeepsAndRestores`, `TestLibraryMCPOffOn`, `library-mcp-on.test.cjs`). The servers off are listed apart, below the ones on, under a Servers turned off (N) fold drawn as Providers' Turned off one (`.fold` in an `.off-head`), folded at first and remembered in localStorage (`magpie.offServersOpen`); while picking (Select) it is held open, so every server picked is in sight (hzlxb on X, `library-mcp-off-fold.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.go) | @@ -43,7 +43,7 @@ Pi's extensions and packages. | Slash commands | A `Command` (miantiao_me on X) is a name (lowercase letters, digits, - and _), a one-line description and a prompt, given to the agents ticked for it, and typed as /name there. The prompt says `$ARGUMENTS` for every word typed after the name and `$1`, `$2`… for the first, second… of them. `syncCommands` writes it as a file of its own in each agent's user-level folder, in that agent's shape (`commandSpecOf`): `/commands/.md` (front matter `description`; `$n` becomes Claude Code's `$ARGUMENTS[n-1]`, counted from 0), OpenCode's `commands/.md` beside its config and Pi's `/prompts/.md` (`$ARGUMENTS` and `$n` as magpie's), `~/.gemini/commands/.toml` (`description`, `prompt`, `$ARGUMENTS` as `{{args}}`), Qwen Code's `commands/.md` (`{{args}}`) and `~/.factory/commands/.md` (`$ARGUMENTS`). Gemini CLI, Qwen Code and Droid take no words by place, so a command that uses `$1`… isn't written for them: the agent gets a problem, the editor names them under the prompt while it uses one, and the tab says so under the list. Codex is listed but greyed: Codex 0.165 has no loader of `~/.codex/prompts` any more, its skills took their place. An agent in a WSL distro gets none. The page lists, per agent, its folder and whether it takes `$1`… (`CommandAgentView`). There is no CLI for them yet. | [`commands.go`](../../internal/library/commands.go), `TestCommandsEachAgentsFile`, `TestCommandsWordsByPlace` | | Slash commands from the agents | The Slash commands tab's "Find in agents" (miantiao_me on X: "can the ones I defined in Pi be imported?") lists the commands the user already made in each agent here (`ProbeCommands`), read where that agent reads them, at the folder's top only: Pi's `prompts/*.md`, Claude Code's `commands/*.md`, OpenCode's `commands/*.md` and `command/*.md`, Gemini CLI's `commands/*.toml`, Qwen Code's `commands/*.md` and `*.toml` (its FileCommandLoader reads both) and Droid's `commands/*.md`. The file's name is the command's; the description is the front matter's (a TOML's `description`), the prompt the body (a TOML's `prompt`), and each agent's way of saying the words typed in reads back as magpie's: Claude Code's `$ARGUMENTS[n]` and `$n`, counted from 0, as `$n+1` (the `\$0` magpie writes as `$0`), Pi's `$@` and Gemini's and Qwen's `{{args}}` as `$ARGUMENTS`; Pi's `${@:N}` is left as written. A name magpie can't take, a file over 1 MB or one with no prompt is listed as left out, with why. A file magpie wrote, still as it wrote it (`Applied.Commands`), isn't listed. One name saying the same in several agents is one candidate for all of them; saying different things, each is listed, tagged, and only one can be picked. A name the library has saying the same is tagged and joins (the import ticks these agents too); one the library has for another command can't be picked, and the user's file stays as it is. `ImportCommands` takes the paths picked, reads them again, and ticks the agents each was found in. Each command keeps the files it came from (`Command.Taken`, per agent: path, bytes, and a hash of what they said): while the command says the same, `syncCommands` writes those bytes at that path, so `syncOwnFiles` takes the user's own file as magpie's byte for byte, and nothing is doubled or written over (OpenCode's `command/` file stays there). After an edit here, the command is written in the agent's shape at the same path when its extension is the one magpie writes, else at magpie's own path. A rename drops `Taken`. Unticking or removing an imported command takes its file away, into the backups, as with any file of magpie's. `Taken` is this computer's: never in `Bundle.Commands` or the page's view, and a bundle put here keeps it for a command of the same name. | [`command_import.go`](../../internal/library/command_import.go), `TestCommandImportPiPrompts` (Pi's own `.pi/prompts` files in `testdata/pi-prompts`), `TestCommandImportArgs`, `TestCommandImportByName`, `TestCommandImportNotCarried`, `library-commands-import.test.cjs` | | Rules | A `Rule` (JonahFu on X) is a name (as a slash command's), a Markdown body and, if wanted, `Paths`: globs, one a line in the editor, that keep it to the files they match. `syncRules` writes it as `.md` in each ticked agent's own folder of rules (`ruleSpecOf`), through the shared `syncOwnFiles`: Claude Code's `/rules` (front matter `paths`, the only key it reads; checked against the memory docs and v2.1.327, which reads every .md under the folder, loads one without `paths` at launch and one with them when Read/Write/Edit touches a match), Cline's `/rules` (CLINE_DIR, else ~/.cline; Cline 3.0.70 reads every rule always and has no paths key, so a rule with paths isn't written for it: the agent gets a problem (`noPaths`), and the editor names it under the paths) and Kiro CLI's steering folder beside its AGENTS.md (`inclusion: fileMatch` and `fileMatchPattern` for paths, else always; a rule called `agents` is refused there, as it would be AGENTS.md on a disk that ignores case). A body starting with `---` gets an empty front matter first, so it isn't read as one. Cursor (user rules live in its settings, `.cursor/rules` is per project), Codex (its rules are execpolicy) and Droid (command permissions) read no such folder and aren't listed; nor are Gemini CLI, Qwen Code and OpenCode, which read only their instructions file. An agent in a WSL distro gets none. The editor lists each agent's file as a path to show (`revealable`). Bundles carry them as slash commands; there is no CLI yet. | [`rules.go`](../../internal/library/rules.go), `TestRulesEachAgentsFile`, `TestRulesKeptToTheirPaths`, `TestRulesLeaveTheUsersFiles`, `TestRulesCarried`, `library-rules.test.cjs` | -| 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. No agent sets either variable outside Claude Code's plugin runtime, so every reference is resolved before a part is written out ([`plugin_env.go`](../../internal/library/plugin_env.go)): `${NAME}`/`$NAME` in a hook command, a server's command, args and env, a subagent's prompt and a copied SKILL.md become the folder; a hook program's own read (`process.env.NAME`, `Bun.env`, `Deno.env.get`, Python's `os.environ`/`os.getenv`, Ruby's `ENV`) becomes a quoted string literal of the folder with forward slashes, and PowerShell's `$env:NAME` and cmd's `%NAME%` the folder (ponytail's hooks threw at every start without it, @AXmake110 on X); a command server is given both variables in its env, as Claude Code gives them. Parts a magpie before this wrote with the variables in them are resolved at load (`healPluginRefs`) and written out again at the next sync; a SKILL.md copied before is fixed by Update or a reinstall. Exec-form hooks (`args`) and `CLAUDE_PLUGIN_OPTION_` are not carried yet (#6682). 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 plugin goes to another computer whole, by sync or a backup file (#6685, JJasonsun on Discord; [`plugin_carry.go`](../../internal/library/plugin_carry.go)): `Bundle.Plugins` carries each record (name, version, source, pick, agents, `Off`, and the parts taken out by hand), never its parts, which name this computer's folder. A plugin from a GitHub or git link goes as that source, and the other computer installs it from there as `UpdatePlugin` does, outside the library's lock; one it can't fetch yet is kept with `Pending`, its old parts if any, and a problem, the row says so, and Update or the next sync tries again. A plugin from a folder, or a link holding a sign-in (whose link isn't carried), goes with its files, on the skills' budget, and is installed from them. Either way that computer reads the parts again, so every hook, server and skill names its own `/plugins/`, Windows' too. A plugin the bundle no longer has is removed with its folder. A bundle from a magpie before this has no `plugins`, and this computer's plugins keep their parts over the same-named items it carries. A marketplace entry's own fields (`strict: false`) aren't carried, so a local marketplace plugin is read from its files alone there. A plugin installed from a marketplace under a name other than its manifest's names that folder in its parts too (`TestPluginCarriedWhole`, `TestPluginCarriedBySource`, `TestPluginOldBundleKeepsPlugins`, `TestPluginMarketplaceNameIsItsFolder`, davsync's `TestSyncLibraryPlugins`, `TestPluginImportCarryOnOffRemove`, `TestPluginHookReadsRootFromItsProgram`, `TestPluginHookWrittenBeforeIsResolved`, `TestPluginPartsGetItsFolders`, `TestPluginNameClashKeepsTheUsersOwn`, `TestPluginMarketplaceAndUpdate`, `TestPluginRefusesWhatIsNone`, `library-plugins.test.cjs`). | [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | +| 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. No agent sets either variable outside Claude Code's plugin runtime, so every reference is resolved before a part is written out ([`plugin_env.go`](../../internal/library/plugin_env.go)): `${NAME}`/`$NAME` in a hook command, a server's command, args and env, a subagent's prompt and a copied SKILL.md become the folder; a hook program's own read (`process.env.NAME`, `Bun.env`, `Deno.env.get`, Python's `os.environ`/`os.getenv`, Ruby's `ENV`) becomes a quoted string literal of the folder with forward slashes, and PowerShell's `$env:NAME` and cmd's `%NAME%` the folder (ponytail's hooks threw at every start without it, @AXmake110 on X); a command server is given both variables in its env, as Claude Code gives them. Parts a magpie before this wrote with the variables in them are resolved at load (`healPluginRefs`) and written out again at the next sync; a SKILL.md copied before is fixed by Update or a reinstall. Exec-form hooks (`args`) and `CLAUDE_PLUGIN_OPTION_` are not carried yet (#6682). 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 takes the plugin out of every project), `ProjectPlugin` gives it to a project (see Projects), 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 plugin goes to another computer whole, by sync or a backup file (#6685, JJasonsun on Discord; [`plugin_carry.go`](../../internal/library/plugin_carry.go)): `Bundle.Plugins` carries each record (name, version, source, pick, agents, `Off`, and the parts taken out by hand), never its parts, which name this computer's folder. A plugin from a GitHub or git link goes as that source, and the other computer installs it from there as `UpdatePlugin` does, outside the library's lock; one it can't fetch yet is kept with `Pending`, its old parts if any, and a problem, the row says so, and Update or the next sync tries again. A plugin from a folder, or a link holding a sign-in (whose link isn't carried), goes with its files, on the skills' budget, and is installed from them. Either way that computer reads the parts again, so every hook, server and skill names its own `/plugins/`, Windows' too. A plugin the bundle no longer has is removed with its folder. A bundle from a magpie before this has no `plugins`, and this computer's plugins keep their parts over the same-named items it carries. A marketplace entry's own fields (`strict: false`) aren't carried, so a local marketplace plugin is read from its files alone there. A plugin installed from a marketplace under a name other than its manifest's names that folder in its parts too (`TestPluginCarriedWhole`, `TestPluginCarriedBySource`, `TestPluginOldBundleKeepsPlugins`, `TestPluginMarketplaceNameIsItsFolder`, davsync's `TestSyncLibraryPlugins`, `TestPluginImportCarryOnOffRemove`, `TestPluginHookReadsRootFromItsProgram`, `TestPluginHookWrittenBeforeIsResolved`, `TestPluginPartsGetItsFolders`, `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. An rtk.exe in one of winget's folders that winget has no record of (`winget list` says so, or its records name another folder; netube99 on X, 0x8A150014) is upgraded from rtk's own Windows release over the file a `WinGet\Links` link points to, not by `winget upgrade`. `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) | @@ -131,6 +131,8 @@ go test -tags nogui ./internal/library -run 'TestCommand' go test -tags nogui ./internal/library -run 'TestRule' go test -tags nogui ./internal/library -run 'TestSubagentFile|TestSubagentOwnFile' node --test internal/gui/tests/library-rules.test.cjs +go test -tags nogui ./internal/library -run 'TestProjectPlugin|TestHook' +node --test internal/gui/tests/project-plugins.test.cjs go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal|TestServerHere' go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks' go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills' diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 77d98694c..de0002c0d 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -5646,6 +5646,7 @@ magpie.plugin("library", (ctx) => { 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); + if (!agentless()) renderProjects(body, "plugins"); } function pluginFind() { @@ -6989,7 +6990,7 @@ magpie.plugin("library", (ctx) => { function renderProjects(body, kind) { const rh = el("div", "row-head"); - rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : kind === "instructions" ? t("Project instructions") : t("Project servers")), el("span", "grow")); + rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : kind === "plugins" ? t("Project plugins") : kind === "instructions" ? t("Project instructions") : t("Project servers")), el("span", "grow")); if (!addingProject) rh.append(button(t("Add a project"), "action lib-updall", () => { addingProject = { dir: "" }; render(); })); body.append(rh); if (addingProject) body.append(addProjectCard(kind)); @@ -6998,6 +6999,8 @@ magpie.plugin("library", (ctx) => { ? t("Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.") : kind === "subagents" ? t("Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.") + : kind === "plugins" + ? t("Give a project a whole plugin: magpie writes each part where its agents read the project's own, and taking the plugin out takes out only what it wrote.") : kind === "mcp" ? t("Give a project's agents some of these servers as the project's own: magpie writes them into its {files}, leaving the rest of each file as it is.", { files: projectFiles() }) : t("Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git."))); @@ -7045,7 +7048,7 @@ magpie.plugin("library", (ctx) => { addingProject = null; const p = lib.projects.find((x) => !was.has(x.dir)); if (p) openProjects.add(p.dir); - status(kind === "instructions" ? t("{name} added — write its instructions", { name: p?.name || dir }) : kind === "subagents" ? t("{name} added — pick the subagents it gets", { name: p?.name || dir }) : kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok"); + status(kind === "instructions" ? t("{name} added — write its instructions", { name: p?.name || dir }) : kind === "plugins" ? t("{name} added — pick the plugins it gets", { name: p?.name || dir }) : kind === "subagents" ? t("{name} added — pick the subagents it gets", { name: p?.name || dir }) : kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok"); } catch (e) { a.busy = false; a.error = e.message; @@ -7056,19 +7059,19 @@ magpie.plugin("library", (ctx) => { } function projectCard(p, kind) { - const mcp = kind === "mcp", sub = kind === "subagents", ins = kind === "instructions"; + const mcp = kind === "mcp", sub = kind === "subagents", ins = kind === "instructions", plg = kind === "plugins"; const card = el("div", "list lib-card lib-project" + (p.missing ? " missing" : "")); const isOpen = openProjects.has(p.dir); const head = el("div", "row lib-row click lib-projhead" + (isOpen ? " open" : "")); const who = el("div", "who"); const nm = el("div", "name", p.name); if (p.missing) nm.append(tag(t("Folder is gone"), "warn")); - else if (p.copy && !mcp && !sub && !ins) nm.append(tag(t("Copies"), "")); + else if (p.copy && !mcp && !sub && !ins && !plg) nm.append(tag(t("Copies"), "")); who.append(nm); const src = el("div", "lib-src"); src.append(pathLink(p.dir)); who.append(src); - const names = Object.keys((sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort(); + const names = Object.keys((plg ? p.plugins : sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort(); const pills = el("div", "lib-tags"); if (!isOpen && ins) { const first = (projTexts[p.dir] ?? p.instr ?? "").split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "") || ""; @@ -7081,7 +7084,7 @@ magpie.plugin("library", (ctx) => { } else if (!isOpen) { for (const n of names.slice(0, 4)) pills.append(tag(n, "lib-dot")); if (names.length > 4) pills.append(tag("+" + (names.length - 4), "")); - if (!names.length) pills.append(tag(sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked")); + if (!names.length) pills.append(tag(plg ? t("No Claude plugins yet") : sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked")); } const acts = el("div", "lib-rowacts"); const rm = button("", "lib-icon danger", () => confirmRemoveProject(p)); @@ -7092,12 +7095,13 @@ magpie.plugin("library", (ctx) => { chev.append(svg(CHEV_R, 11, 1.7)); head.append(glyph(GLYPH.folder), who, pills, acts, chev); head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); projectShown.delete(p.dir); render(); }; - head.title = ins ? (isOpen ? t("Hide its instructions") : t("Write its instructions")) : sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets"); + head.title = ins ? (isOpen ? t("Hide its instructions") : t("Write its instructions")) : plg ? (isOpen ? t("Hide its plugins") : t("Pick the plugins it gets")) : sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets"); card.append(head); if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""])); if (!isOpen) return card; if (mcp) return projectServers(p, card); if (sub) return projectSubagents(p, card); + if (plg) return projectPlugins(p, card); if (ins) return projectInstructions(p, card); const opts = el("div", "lib-projopts"); @@ -7324,6 +7328,40 @@ magpie.plugin("library", (ctx) => { return card; } + // The project's card, open on the Claude plugins tab: each library + // plugin with the chips of the agents that take some part of it in a + // project. A chip gives the agent every part it can take there; none + // takes the plugin out, and only what magpie wrote for it (jinpwng on X). + function projectPlugins(p, card) { + const all = shownAgents().filter((a) => a.projectSkills || a.projectMCP || a.projectSubagents || a.projectHooks); + const plugins = [...(lib.plugins || [])].sort((a, b) => a.name.localeCompare(b.name)); + for (const b of plugins) { + const row = el("div", "row lib-row lib-projskill lib-projplugin" + (b.off ? " off" : "")); + const w = el("div", "who"); + const n = el("div", "name mono", b.name); + // a part not written says so on its plugin's row + const keys = [...(b.skills || []), ...(b.mcp || []).map((x) => "mcp:" + x), ...(b.hooks || []).map((x) => "hook:" + x), ...(b.subagents || []).map((x) => "subagent:" + x)]; + const problem = keys.map((k) => p.problems?.[k]).find(Boolean); + if (problem) n.append(tag(t("Not written"), "warn", problem)); + else if (b.off) n.append(tag(t("Off"), "")); + w.append(n); + const line = [[t("Skills"), b.skills], [t("MCP servers"), b.mcp], [t("Hooks"), b.hooks], [t("Subagents"), b.subagents]] + .filter(([, v]) => v?.length).map(([k, v]) => k + " " + v.length).join(" · "); + const sub = el("div", "sub lib-plparts", problem || line); + sub.title = problem || line; + w.append(sub); + const on = (p.plugins?.[b.name] || []).filter((id) => all.some((a) => a.id === id)); + const say = (next) => next.length + ? t("{item} is in {name} for {agents}", { item: b.name, name: p.name, agents: next.map(nameOf).join(", ") }) + : t("{item} is out of {name}", { item: b.name, name: p.name }); + row.append(glyph(GLYPH.folder), w, agentChips(all, on, projectChange("projects/plugin", p.dir, b.name, say))); + card.append(row); + } + card.append(el("p", "lib-aside lib-projfoot", t("Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is."))); + if (plugins.some((b) => b.hooks?.length && (p.plugins?.[b.name] || []).includes("codex"))) card.append(el("p", "lib-aside lib-projfoot lib-projhooks-codex", t("Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks."))); + return card; + } + // The agents a project's first instructions are for: those here that // read a project's instructions file and have the shared ones on, else // every one of them here. diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 53678c555..90c13734d 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -783,6 +783,14 @@ magpie.strings({ "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop 刷新窗口({keys})后才显示技能变化。它使用技能的副本,在 Desktop 中改过的副本不会被覆盖。", "Project servers": "项目服务器", "Project subagents": "项目子代理", + "Project plugins": "项目插件", + "Give a project a whole plugin: magpie writes each part where its agents read the project's own, and taking the plugin out takes out only what it wrote.": "把整个插件给一个项目:magpie 把每个部分写到它的 Agent 读取项目自身配置的位置,移除插件时只移除它写入的内容。", + "{name} added — pick the plugins it gets": "已添加 {name},选择它要用的插件", + "No Claude plugins yet": "还没有 Claude 插件", + "Hide its plugins": "收起插件", + "Pick the plugins it gets": "选择它要用的插件", + "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、服务器和子代理放在项目自己的那些位置,hooks 写进 .claude/settings.local.json 和 .codex/hooks.json。那里不是 magpie 写的文件、你改过的条目,都保持原样。", + "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。", "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把这些子代理作为项目自己的给项目里的 Agent:magpie 写进它的 .claude/agents 等文件夹,并让它们不进 git。", "{name} added — pick the subagents it gets": "已添加 {name},选择它要用的子代理", "No subagents yet": "还没有子代理", @@ -1917,6 +1925,14 @@ magpie.strings({ "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop 重新整理視窗({keys})後才顯示技能變化。它使用技能的副本,在 Desktop 中改過的副本不會被覆蓋。", "Project servers": "專案伺服器", "Project subagents": "專案子代理", + "Project plugins": "專案外掛", + "Give a project a whole plugin: magpie writes each part where its agents read the project's own, and taking the plugin out takes out only what it wrote.": "把整個外掛給一個專案:magpie 把每個部分寫到它的 Agent 讀取專案自身設定的位置,移除外掛時只移除它寫入的內容。", + "{name} added — pick the plugins it gets": "已新增 {name},選擇它要用的外掛", + "No Claude plugins yet": "還沒有 Claude 外掛", + "Hide its plugins": "收起外掛", + "Pick the plugins it gets": "選擇它要用的外掛", + "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、伺服器和子代理放在專案自己的那些位置,hooks 寫進 .claude/settings.local.json 和 .codex/hooks.json。那裡不是 magpie 寫的檔案、你改過的條目,都保持原樣。", + "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的專案裡執行專案的 hooks,並且要先在 /hooks 中審閱。", "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把這些子代理作為專案自己的給專案裡的 Agent:magpie 寫進它的 .claude/agents 等資料夾,並讓它們不進 git。", "{name} added — pick the subagents it gets": "已新增 {name},選擇它要用的子代理", "No subagents yet": "還沒有子代理", @@ -3042,6 +3058,14 @@ magpie.strings({ "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop はウィンドウを再読み込み({keys})するとスキルの変更を表示します。各スキルのコピーを受け取り、Desktop で変更したものはそのまま残ります。", "Project servers": "プロジェクトのサーバー", "Project subagents": "プロジェクトのサブエージェント", + "Project plugins": "プロジェクトのプラグイン", + "Give a project a whole plugin: magpie writes each part where its agents read the project's own, and taking the plugin out takes out only what it wrote.": "プラグインをまるごとプロジェクトに渡します。magpie は各パーツを、Agent がプロジェクト自身の設定を読む場所に書き込み、プラグインを外すときは書き込んだものだけを取り除きます。", + "{name} added — pick the plugins it gets": "{name} を追加しました。渡すプラグインを選んでください", + "No Claude plugins yet": "Claude プラグインはまだありません", + "Hide its plugins": "プラグインを隠す", + "Pick the plugins it gets": "渡すプラグインを選ぶ", + "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "スキル、サーバー、サブエージェントはプロジェクト自身のものと同じ場所に、フックは .claude/settings.local.json と .codex/hooks.json に書き込まれます。magpie のものではないファイルや、あなたが変更した項目はそのまま残ります。", + "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex は信頼したプロジェクトでのみ、/hooks で確認した後にプロジェクトのフックを実行します。", "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "これらのサブエージェントをプロジェクト専用として渡します。magpie が .claude/agents などに書き込み、git には入れません。", "{name} added — pick the subagents it gets": "{name} を追加しました。渡すサブエージェントを選んでください", "No subagents yet": "サブエージェントはまだありません", @@ -4172,6 +4196,14 @@ magpie.strings({ "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop zeigt Skill-Änderungen erst nach dem Neuladen des Fensters ({keys}). Es erhält von jedem Skill eine Kopie, und eine in Desktop geänderte bleibt unverändert.", "Project servers": "Projektserver", "Project subagents": "Projekt-Subagenten", + "Project plugins": "Projekt-Plugins", + "Give a project a whole plugin: magpie writes each part where its agents read the project's own, and taking the plugin out takes out only what it wrote.": "Gib einem Projekt ein ganzes Plugin: magpie schreibt jeden Teil dorthin, wo seine Agents die eigenen Einstellungen des Projekts lesen, und nimmt beim Entfernen nur heraus, was es geschrieben hat.", + "{name} added — pick the plugins it gets": "{name} hinzugefügt — wähle die Plugins, die es bekommt", + "No Claude plugins yet": "Noch keine Claude-Plugins", + "Hide its plugins": "Plugins ausblenden", + "Pick the plugins it gets": "Wähle die Plugins, die es bekommt", + "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "Skills, Server und Subagenten kommen dorthin, wo die eigenen des Projekts liegen, Hooks in .claude/settings.local.json und .codex/hooks.json. Eine Datei dort, die nicht von magpie ist, oder ein Eintrag, den du geändert hast, bleibt, wie er ist.", + "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex führt die Hooks eines Projekts nur in einem Projekt aus, dem du vertraust, und erst, nachdem du sie in /hooks geprüft hast.", "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "Gib den Agenten eines Projekts einige dieser Subagenten als eigene: magpie schreibt sie in dessen .claude/agents und Ähnliches und hält sie aus git heraus.", "{name} added — pick the subagents it gets": "{name} hinzugefügt – wähle die Subagenten dafür", "No subagents yet": "Noch keine Subagenten", diff --git a/internal/gui/library.go b/internal/gui/library.go index 4e5a0bb33..38c1d185b 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -938,6 +938,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.ProjectSubagents(in.Dir, oneOrMore(in.Name, in.Names), in.Agents) case "projects/server": res, err = library.ProjectServer(in.Dir, in.Name, in.Agents) + case "projects/plugin": + res, err = library.ProjectPlugin(in.Dir, in.Name, in.Agents) case "projects/server-off": // a Library server turned off in this project only res, err = library.ProjectServerOff(in.Dir, in.Name, in.Agents) diff --git a/internal/gui/tests/project-plugins.test.cjs b/internal/gui/tests/project-plugins.test.cjs new file mode 100644 index 000000000..04d71ec5c --- /dev/null +++ b/internal/gui/tests/project-plugins.test.cjs @@ -0,0 +1,150 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// (jinpwng on X) The Claude plugins tab lists the projects: a card opens to +// each library plugin with chips for the agents that take some part of a +// plugin in a project (skills, servers, subagents or hooks), and a chip posts +// that project's agents for the plugin to projects/plugin; no chip left takes +// it out. An agent that takes none in a project has no chip, and the note on +// Codex's /hooks review shows once Codex gets a plugin with hooks. The click +// scrolls nothing; in English and Chinese. No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/emo"; +const DIR = HOME + "/code/app"; +const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more }); +const plugin = (name, more) => ({ name, version: "1.0.0", description: "", agents: [], skills: [], mcp: [], hooks: [], subagents: [], ...more }); +const lib = (given) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [ + agent("claude", "Claude Code", { projectSkills: ".claude/skills", projectMCP: ".mcp.json", projectSubagents: ".claude/agents", projectHooks: ".claude/settings.local.json" }), + agent("codex", "Codex", { projectMCP: ".codex/config.toml", projectSubagents: ".codex/agents", projectHooks: ".codex/hooks.json" }), + agent("pi", "Pi", { projectSkills: ".agents/skills", projectMCP: ".pi/mcp.json" }), + agent("goose", "Goose"), + ], + instructions: { agents: [] }, servers: [], subagents: [], skills: [], foundServers: [], foundSkills: [], + plugins: [plugin("acme-kit", { skills: ["tdd"], mcp: ["acme-db"], hooks: ["acme-kit:Stop"], subagents: ["reviewer"] }), plugin("tidy", { skills: ["tidy"] })], + projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: {}, plugins: given, wrote: {} }], +}); + +function server(lang, posts) { + let given = {}; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib(given) }); + if (url.pathname === "/api/library/projects/plugin") { + const b = req.postDataJSON(); + posts.push(b); + if (posts.hold) await posts.hold; + given = { ...given, [b.name]: b.agents }; + if (!b.agents.length) delete given[b.name]; + return route.fulfill({ json: { ...lib(given), result: { changed: [], problems: [] } } }); + } + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const scrolled = (page) => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop || e.scrollLeft).map((e) => `${e.className}:${e.scrollTop},${e.scrollLeft}`)].join(" ")); +// a click where the element is, as the reader's: Playwright's own click +// first scrolls it into view +const press = async (page, loc) => { + const b = await loc.boundingBox(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); +}; +// a chip: the chips fan out under the pointer first, as a reader's hand +// does, and the chip is pressed where it is then +// (a render after the last write may replace it under the pointer, so it +// is found again until it stays) +const box = async (loc) => { + for (;;) { + await loc.waitFor({ state: "visible" }); + const b = await loc.boundingBox(); + if (b) return b; + } +}; +const chip = async (page, loc) => { + const a = await box(loc); + await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2); + await page.waitForTimeout(350); + const b = await box(loc); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); +}; + +const words = { + en: { head: "Project plugins", none: "No Claude plugins yet", one: "acme-kit is in app for Claude Code", on: "acme-kit is in app for Claude Code, Codex", out: "acme-kit is out of app", codex: "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks." }, + zh: { head: "项目插件", none: "还没有 Claude 插件", one: "acme-kit 已在 app 中对 Claude Code 开启", on: "acme-kit 已在 app 中对 Claude Code, Codex 开启", out: "acme-kit 已从 app 中移除", codex: "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a project's plugins, agent by agent", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const w = words[lang], posts = []; + const ctx = await browser.newContext({ viewport: { width: 860, height: 700 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "plugins"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const card = page.locator("#view-library .lib-project"); + await card.waitFor(); + assert.equal((await card.locator(".lib-tags").textContent()).trim(), w.none); + assert.ok((await page.locator("#view-library .row-head .label").allTextContents()).includes(w.head)); + + await card.locator(".lib-projhead").scrollIntoViewIfNeeded(); + const before = await scrolled(page); + await press(page, card.locator(".lib-projhead")); + const rows = card.locator(".lib-projplugin"); + await rows.first().waitFor(); + assert.equal(await rows.count(), 2); + const row = () => card.locator(".lib-projplugin").filter({ hasText: "acme-kit" }).first(); + assert.deepEqual(await row().locator(".lib-ag").evaluateAll((cs) => cs.map((c) => c.dataset.agent)), ["claude", "codex", "pi"], "Goose takes nothing in a project"); + assert.equal(await card.locator(".lib-projhooks-codex").count(), 0); + + await chip(page, row().locator('.lib-ag[data-agent="claude"]')); + await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-projplugin .lib-ag.on[data-agent="claude"]').length === 1); + await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.one); + await chip(page, row().locator('.lib-ag[data-agent="codex"]')); + await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-projplugin .lib-ag.on').length === 2); + await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.on); + assert.equal((await card.locator(".lib-projhooks-codex").textContent()).trim(), w.codex); + // no chip left takes the plugin out of the project + await chip(page, row().locator('.lib-ag[data-agent="claude"]')); + await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-projplugin .lib-ag.on').length === 1); + await chip(page, row().locator('.lib-ag[data-agent="codex"]')); + await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-projplugin .lib-ag.on').length === 0); + await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.out); + assert.deepEqual(posts, [ + { dir: DIR, name: "acme-kit", agents: ["claude"] }, { dir: DIR, name: "acme-kit", agents: ["claude", "codex"] }, + { dir: DIR, name: "acme-kit", agents: ["codex"] }, { dir: DIR, name: "acme-kit", agents: [] }, + ]); + assert.equal(await scrolled(page), before, "the clicks scroll nothing"); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/hooks.go b/internal/library/hooks.go index 7e3efe826..2acdbd146 100644 --- a/internal/library/hooks.go +++ b/internal/library/hooks.go @@ -261,30 +261,44 @@ func hookSpecOf(t *Target) (*hookSpec, string) { return sp, why } +// claudeHookSpec is how Claude Code keeps hooks in a settings file at path: +// its own settings.json, or a project's .claude/settings.local.json. +func claudeHookSpec(path string) *hookSpec { + return &hookSpec{ + path: path, + events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", + "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, + native: claudeHookEvents, + tools: map[string]string{"shell": "Bash", "edit": "Edit|Write|MultiEdit"}, + agent: "claude", + } +} + +// codexHookSpec is how Codex keeps hooks in a hooks.json at path, whose +// events are codex-rs/hooks' HookEventName's: the one beside its +// config.toml, or a project's .codex/hooks.json. +func codexHookSpec(path string) *hookSpec { + return &hookSpec{ + path: path, + events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", + "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, + native: []string{"PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", "SessionStart", "SessionEnd", + "UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", "Interrupt"}, + tools: map[string]string{"shell": "Bash", "edit": "apply_patch"}, + agent: "codex", + } +} + func hookSpecFor(t *Target) (*hookSpec, string) { if t.Agent.WSL != "" { return nil, wslNoHooks(t.Agent) } switch t.Agent.ID { case "claude": - return &hookSpec{ - path: filepath.Join(claudeDir(), "settings.json"), - events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", - "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, - native: claudeHookEvents, - tools: map[string]string{"shell": "Bash", "edit": "Edit|Write|MultiEdit"}, - }, "" + return claudeHookSpec(filepath.Join(claudeDir(), "settings.json")), "" case "codex": - // codex-rs/hooks: hooks.json beside config.toml, whose events are - // HookEventName's - return &hookSpec{ - path: filepath.Join(codexDir(), "hooks.json"), - events: map[string]string{"turn-end": "Stop", "after-tool": "PostToolUse", "before-tool": "PreToolUse", - "prompt": "UserPromptSubmit", "session-start": "SessionStart"}, - native: []string{"PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", "SessionStart", "SessionEnd", - "UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", "Interrupt"}, - tools: map[string]string{"shell": "Bash", "edit": "apply_patch"}, - }, "" + // codex-rs/hooks: hooks.json beside config.toml + return codexHookSpec(filepath.Join(codexDir(), "hooks.json")), "" case "gemini": // gemini-cli packages/core/src/hooks/types.ts, HookEventName return &hookSpec{ @@ -678,20 +692,66 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { } return } + w := &hookWrite{id: id, sp: sp, want: want, recs: a.Hooks, gone: t.Gone, + keep: func(path string) error { return b.keep(id, path) }, + fail: func(what string, err error) { res.fail(id, what, err) }} + if id == "codex" { + w.rekeyCfg = filepath.Join(codexDir(), "config.toml") + } + recs, changed, ok := w.run() + if changed { + res.changed(id) + } + if ok { + a.Hooks = recs + } +} + +// hookWrite is one agent's hooks file brought to what it should hold: the +// entries of want written in, those of recs (what magpie wrote before) no +// longer wanted taken out, and an entry the user changed or wrote +// themselves left as it is. The agent's own file (syncHooks) and a +// project's (project_plugins.go) are both brought up this way. +type hookWrite struct { + id string + sp *hookSpec + want []*Hook + recs []HookEntry + gone bool // the agent is gone from here: nothing new is written + // keep backs a file up before it is written; nil writes it as it is + keep func(path string) error + // rekeyCfg is Codex's config.toml, whose trust of each hook moves + // with the entries left after one taken out; "" for another agent + rekeyCfg string + fail func(what string, err error) +} + +// run writes the file, and says what magpie's records of it are now, +// whether it was written, and false when they should stay as they were +// (the file couldn't be read or written). +func (w *hookWrite) run() (recs []HookEntry, changed, ok bool) { + sp, want := w.sp, w.want failAll := func(err error) { for _, h := range want { - res.fail(id, "hook:"+h.Name, err) + w.fail("hook:"+h.Name, err) } if len(want) == 0 { - res.fail(id, "hooks", err) + w.fail("hooks", err) } } + keep := func(path string) error { + if w.keep == nil { + return nil + } + return w.keep(path) + } + id, gone := w.id, w.gone var doc []byte if !sp.toml { d, err := readHooksFile(sp.path) if err != nil { failAll(err) - return + return nil, false, false } doc = d } @@ -725,11 +785,11 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { _, err = startMatcher(id, h.Matcher) } if err != nil { - res.fail(id, "hook:"+h.Name, err) + w.fail("hook:"+h.Name, err) continue } if _, err := listOf(ev); err != nil { - res.fail(id, "hook:"+h.Name, err) + w.fail("hook:"+h.Name, err) continue } ws = append(ws, &wanted{h: h, ev: ev, entry: sp.entry(h, ev)}) @@ -753,9 +813,9 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { var kept []HookEntry drop := map[string][]int{} // event → the entries to take out var unread []HookEntry // records of an event whose list can't be read now - for _, rec := range a.Hooks { + for _, rec := range w.recs { if _, err := listOf(rec.Event); err != nil { - res.fail(id, "hook:"+rec.Name, err) + w.fail("hook:"+rec.Name, err) unread = append(unread, rec) continue } @@ -778,7 +838,7 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { for _, w := range ws { // an agent gone from here is given nothing new; what it has stays // its until unticked - if w.done || t.Gone { + if w.done || gone { continue } // the same entry of the user's own already runs: it isn't written @@ -790,13 +850,12 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { added = append(added, HookEntry{Name: w.h.Name, Event: w.ev, Entry: w.entry}) } if len(drop) == 0 && len(add) == 0 { - a.Hooks = append(kept, unread...) - return + return append(kept, unread...), false, true } if sp.toml { - if err := b.keep(id, sp.path); err != nil { + if err := keep(sp.path); err != nil { failAll(err) - return + return nil, false, false } err := os.MkdirAll(filepath.Dir(sp.path), 0o755) if err == nil { @@ -820,11 +879,9 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { } if err != nil { failAll(fmt.Errorf("%s: %w", sp.path, err)) - return + return nil, false, false } - res.changed(id) - a.Hooks = append(append(kept, added...), unread...) - return + return append(append(kept, added...), unread...), true, true } // what each list becomes, and where each entry left in it moves to var set []edit.KV @@ -864,26 +921,26 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { set = append(set, edit.KV{Path: "hooks." + ev, Value: next}) } } - if err := b.keep(id, sp.path); err != nil { + if err := keep(sp.path); err != nil { failAll(err) - return + return nil, false, false } // Codex trusts a hook by where it is (codex-rs/hooks: hook_key, the // file's path, the event, the group's and the handler's index): an // entry taken out from before the user's own would leave their trust // on the wrong ones, so it is moved with them var rekey func() error - if id == "codex" && len(drop) > 0 { - cfg := filepath.Join(codexDir(), "config.toml") + if w.rekeyCfg != "" && len(drop) > 0 { + cfg := w.rekeyCfg f, err := codexRekey(cfg, sp.path, moved) if err != nil { failAll(err) - return + return nil, false, false } if f != nil { - if err := b.keep(id, cfg); err != nil { + if err := keep(cfg); err != nil { failAll(err) - return + return nil, false, false } rekey = f } @@ -912,15 +969,14 @@ func (l *Library) syncHooks(t *Target, b *backups, res *Result) { } if err != nil { failAll(fmt.Errorf("%s: %w", sp.path, err)) - return + return nil, false, false } - res.changed(id) if rekey != nil { if err := rekey(); err != nil { - res.fail(id, "hooks", fmt.Errorf("the hooks are written, but Codex's trust of the ones after them couldn't be moved: review them in Codex's /hooks (%w)", err)) + w.fail("hooks", fmt.Errorf("the hooks are written, but Codex's trust of the ones after them couldn't be moved: review them in Codex's /hooks (%w)", err)) } } - a.Hooks = append(append(kept, added...), unread...) + return append(append(kept, added...), unread...), true, true } // codexState is a [hooks.state.""] header line in Codex's config.toml. diff --git a/internal/library/mcp_hub.go b/internal/library/mcp_hub.go index a5f6c1dad..9ae97cd8e 100644 --- a/internal/library/mcp_hub.go +++ b/internal/library/mcp_hub.go @@ -226,16 +226,20 @@ func hubServers(agentID string) []*Server { func (l *Library) hubServers(agentID string) []*Server { id, key, scoped := strings.Cut(agentID, gateway.HubProjectSep) var p *Project + var given map[string][]string // the project's servers, its plugins' too if scoped { p = l.projectByKey(key) } + if p != nil { + _, given, _ = l.withPlugins(p) + } var out []*Server for _, s := range l.MCP { on := id == "" && !s.Hidden || slices.Contains(s.Agents, id) if p != nil { if slices.Contains(p.ServersOff[s.Name], id) { on = false - } else if !s.Hidden && slices.Contains(p.Servers[s.Name], id) { + } else if !s.Hidden && slices.Contains(given[s.Name], id) { on = true } } diff --git a/internal/library/plugin.go b/internal/library/plugin.go index b2509fd36..a5f3e13a6 100644 --- a/internal/library/plugin.go +++ b/internal/library/plugin.go @@ -1225,6 +1225,7 @@ func RemovePlugin(name string) (*Result, error) { return fmt.Errorf("no plugin called %s", name) } removePluginParts(l, b) + l.dropProjectPlugin(name) l.Plugins = slices.DeleteFunc(l.Plugins, func(x *Plugin) bool { return x.Name == name }) return nil }) diff --git a/internal/library/project_plugins.go b/internal/library/project_plugins.go new file mode 100644 index 000000000..8b052c522 --- /dev/null +++ b/internal/library/project_plugins.go @@ -0,0 +1,262 @@ +package library + +import ( + "errors" + "fmt" + "path/filepath" + "slices" + "sort" +) + +// A project's plugins (jinpwng on X): a plugin the library keeps is given +// to a project whole, for some of its agents, and taken out of it whole. +// Its skills, MCP servers and subagents go where the project's own do +// (projects.go, project_mcp.go, project_subagents.go), beside them: for +// a sync, syncProject adds them to the project's own sets (withPlugins), +// and puts those back as they were after. So a part the project also has +// of its own stays when the plugin goes, and taking the plugin out is +// only deleting it from Plugins: what magpie placed or wrote for it, +// and nothing else, comes out on that sync, by the records each part +// keeps already (Placed, Wrote, AgentFiles). Its hooks are written in the +// project's own hooks file (projectHookFiles), entry by entry, as the +// agent's own are (hookWrite): an entry the user changed since is theirs +// and stays. + +// projectHookFiles are the files, in a project, an agent reads hooks +// from that magpie writes a project's plugins' hooks into: Claude Code's +// .claude/settings.local.json (its local project settings, which it +// keeps out of git itself), and Codex's .codex/hooks.json, which +// codex-rs/hooks loads from a project's .codex folder in a project the +// user trusts, each hook in it once the user has reviewed it in /hooks. +var projectHookFiles = map[string]string{ + "claude": claudeSettingsRel, + "codex": ".codex/hooks.json", +} + +// ProjectHooksFile is the file in a project an agent reads hooks from: +// "" for one magpie can't give a project's hooks to. +func ProjectHooksFile(agent string) string { return projectHookFiles[agent] } + +// projectPluginTakes says whether an agent takes any part of a plugin in +// a project. +func projectPluginTakes(id string) bool { + return ProjectSkillsDir(id) != "" || ProjectMCPFile(id) != "" || ProjectSubagentsDir(id) != "" || ProjectHooksFile(id) != "" +} + +func projectHookSpec(p *Project, id string) *hookSpec { + rel := projectHookFiles[id] + abs := filepath.Join(p.Dir, filepath.FromSlash(rel)) + switch id { + case "claude": + return claudeHookSpec(abs) + case "codex": + return codexHookSpec(abs) + } + return nil +} + +// withPlugins are the project's skills, servers and subagents with the +// parts of its plugins added, each for those of the plugin's agents that +// take it in a project: new maps, the project's own left as they are. A +// plugin turned off, or gone from the library, gives nothing; a part +// taken out of the library one by one, or one that is another's by now, +// isn't the plugin's. +func (l *Library) withPlugins(p *Project) (skills, servers, subagents map[string][]string) { + if len(p.Plugins) == 0 { + return p.Skills, p.Servers, p.Subagents + } + clone := func(m map[string][]string) map[string][]string { + out := make(map[string][]string, len(m)) + for k, v := range m { + out[k] = slices.Clone(v) + } + return out + } + skills, servers, subagents = clone(p.Skills), clone(p.Servers), clone(p.Subagents) + add := func(m map[string][]string, name string, agents []string, takes func(string) bool) { + for _, a := range agents { + if takes(a) { + m[name] = set(m[name], a, true) + } + } + } + for name, agents := range p.Plugins { + b := l.plugin(name) + if b == nil || b.Off { + continue + } + for _, n := range b.Skills { + if s := l.skill(n); s != nil && s.Bundle == b.Name { + add(skills, n, agents, func(a string) bool { return ProjectSkillsDir(a) != "" }) + } + } + for _, n := range b.MCP { + if s := l.server(n); s != nil && s.Bundle == b.Name { + add(servers, n, agents, func(a string) bool { return ProjectMCPFile(a) != "" }) + } + } + for _, n := range b.Subagents { + if s := l.subagent(n); s != nil && s.Bundle == b.Name { + add(subagents, n, agents, func(a string) bool { return ProjectSubagentsDir(a) != "" }) + } + } + } + return skills, servers, subagents +} + +// projectHooks are, by agent, the hooks the project's plugins give it. +func (l *Library) projectHooks(p *Project) map[string][]*Hook { + out := map[string][]*Hook{} + for _, name := range slices.Sorted(func(yield func(string) bool) { + for k := range p.Plugins { + if !yield(k) { + return + } + } + }) { + b := l.plugin(name) + if b == nil || b.Off { + continue + } + for _, n := range b.Hooks { + h := l.hook(n) + if h == nil || h.Bundle != b.Name { + continue + } + for _, a := range p.Plugins[name] { + if ProjectHooksFile(a) != "" && hookTakes(h, a) && !slices.Contains(out[a], h) { + out[a] = append(out[a], h) + } + } + } + } + return out +} + +// syncProjectHooks writes the hooks of the project's plugins in each +// agent's project hooks file, and takes out those magpie wrote there that +// no plugin gives any more. A file magpie made is taken away again once +// nothing is left in it. +func (l *Library) syncProjectHooks(p *Project, fail func(what string, err error)) { + want := l.projectHooks(p) + ids := map[string]bool{} + for id := range want { + ids[id] = true + } + for id := range p.HookRecs { + ids[id] = true + } + for _, id := range slices.Sorted(func(yield func(string) bool) { + for k := range ids { + if !yield(k) { + return + } + } + }) { + rel := projectHookFiles[id] + sp := projectHookSpec(p, id) + if sp == nil { + // an agent magpie wrote hooks for once and no longer can: + // its records go, the entries stay the user's + delete(p.HookRecs, id) + continue + } + if err := p.inside(sp.path); err != nil { + for _, h := range want[id] { + fail("hook:"+h.Name, err) + } + continue + } + made := false + if len(want[id]) > 0 && !exists(sp.path) { + if err := p.mkdirs(filepath.Dir(sp.path)); err != nil { + for _, h := range want[id] { + fail("hook:"+h.Name, err) + } + continue + } + made = true + } + w := &hookWrite{id: id, sp: sp, want: want[id], recs: p.HookRecs[id], fail: fail} + if id == "codex" { + w.rekeyCfg = filepath.Join(codexDir(), "config.toml") + } + recs, _, ok := w.run() + if !ok { + continue + } + if made && exists(sp.path) && !slices.Contains(p.MadeFiles, rel) { + p.MadeFiles = append(p.MadeFiles, rel) + sort.Strings(p.MadeFiles) + } + if len(recs) == 0 { + delete(p.HookRecs, id) + // Claude Code's file holds the skills the project turns off + // too (syncSkillsOff) + if id != "claude" || len(p.Overrides) == 0 { + p.dropMadeFile(rel) + } + continue + } + if p.HookRecs == nil { + p.HookRecs = map[string][]HookEntry{} + } + p.HookRecs[id] = recs + } + if len(p.HookRecs) == 0 { + p.HookRecs = nil + } +} + +// ProjectPlugin sets which agents get a library plugin in a project: each +// of its parts goes to those of them that take it there. None takes the +// plugin out of the project, and with it only what magpie wrote for it. +func ProjectPlugin(dir, 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 { + p := l.project(dir) + if p == nil { + return fmt.Errorf("no project %s", dir) + } + if name == "" { + return errors.New("no plugin given") + } + var ids []string + for _, id := range agents { + if !projectPluginTakes(id) { + return fmt.Errorf("magpie knows of nowhere %s reads a project's skills, servers, subagents or hooks from", id) + } + ids = set(ids, id, true) + } + if len(ids) == 0 { + delete(p.Plugins, name) + if len(p.Plugins) == 0 { + p.Plugins = nil + } + return nil + } + if l.plugin(name) == nil { + return fmt.Errorf("no plugin called %s", name) + } + if p.Plugins == nil { + p.Plugins = map[string][]string{} + } + p.Plugins[name] = ids + return nil + }) +} + +// dropProjectPlugin takes a plugin out of every project, and their +// worktrees: it is leaving the library. +func (l *Library) dropProjectPlugin(name string) { + for _, p := range l.Projects { + delete(p.Plugins, name) + if len(p.Plugins) == 0 { + p.Plugins = nil + } + } +} diff --git a/internal/library/project_plugins_test.go b/internal/library/project_plugins_test.go new file mode 100644 index 000000000..e0893d37f --- /dev/null +++ b/internal/library/project_plugins_test.go @@ -0,0 +1,207 @@ +package library + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// pluginProjects is a sandbox with the acme-kit plugin in the library, +// given to no agent user-wide, and two projects. +func pluginProjects(t *testing.T) (h, a, b string) { + t.Helper() + h = sandbox(t) + pluginAgents(t, h) + src := filepath.Join(t.TempDir(), "acme") + writePlugin(t, src) + ok(t)(InstallPlugins(src, nil, []string{})) + a, b = filepath.Join(t.TempDir(), "a"), filepath.Join(t.TempDir(), "b") + for _, d := range []string{a, b} { + gitInit(t, d) + ok(t)(AddProject(d)) + } + return +} + +func there(t *testing.T, path string) { + t.Helper() + if _, err := os.Lstat(path); err != nil { + t.Errorf("%s: %v", path, err) + } +} + +// A plugin given to a project (jinpwng on X) puts each of its parts where +// each agent reads a project's own, in that agent's shape, and nowhere +// else; taken out, all of it comes out again, the files magpie made too. +func TestProjectPluginEachPartInTheProject(t *testing.T) { + h, a, b := pluginProjects(t) + res := ok(t)(ProjectPlugin(a, "acme-kit", []string{"claude", "codex", "pi"})) + if len(res.Problems) > 0 { + t.Fatalf("problems: %+v", res.Problems) + } + for _, rel := range []string{".claude/skills/tdd", ".agents/skills/tdd", ".claude/agents/reviewer.md", ".codex/agents/reviewer.toml"} { + there(t, filepath.Join(a, rel)) + } + for _, rel := range []string{".mcp.json", ".codex/config.toml", ".pi/mcp.json"} { + if got := read(t, filepath.Join(a, rel)); !strings.Contains(got, "acme-db") { + t.Errorf("%s lacks the plugin's server:\n%s", rel, got) + } + } + claude := read(t, filepath.Join(a, ".claude/settings.local.json")) + for _, want := range []string{"echo done", "lint.sh", "compacting", `"Bash"`} { + if !strings.Contains(claude, want) { + t.Errorf(".claude/settings.local.json lacks %q:\n%s", want, claude) + } + } + codex := read(t, filepath.Join(a, ".codex/hooks.json")) + if !strings.Contains(codex, "echo done") || !strings.Contains(codex, "lint.sh") { + t.Errorf(".codex/hooks.json lacks the plugin's hooks:\n%s", codex) + } + if strings.Contains(codex, "compacting") { + t.Errorf("codex was given Claude Code's own event:\n%s", codex) + } + // nothing user-wide, nothing in the other project + if got := read(t, filepath.Join(h, ".claude/settings.json")); strings.Contains(got, "echo done") { + t.Errorf("the user-wide settings got the plugin's hooks:\n%s", got) + } + for _, p := range []string{filepath.Join(h, ".claude/skills/tdd"), filepath.Join(h, ".codex/hooks.json"), filepath.Join(h, ".claude/agents/reviewer.md")} { + gone(t, p) + } + for _, rel := range []string{".claude", ".codex", ".agents", ".pi", ".mcp.json"} { + gone(t, filepath.Join(b, rel)) + } + // kept out of git + g, _ := gitOf(a) + ex := read(t, filepath.Join(g.Common, "info", "exclude")) + for _, rel := range []string{".codex/hooks.json", ".mcp.json", ".claude/skills/tdd"} { + if !strings.Contains(ex, "/"+rel+"\n") { + t.Errorf("%s isn't in info/exclude:\n%s", rel, ex) + } + } + v := View0(t) + if len(v.Projects) != 2 || len(v.Projects[0].Plugins["acme-kit"])+len(v.Projects[1].Plugins["acme-kit"]) != 3 { + t.Errorf("the page's projects: %+v", v.Projects) + } + + res = ok(t)(ProjectPlugin(a, "acme-kit", nil)) + if len(res.Problems) > 0 { + t.Fatalf("problems taking it out: %+v", res.Problems) + } + for _, rel := range []string{".claude", ".codex", ".agents", ".pi", ".mcp.json"} { + gone(t, filepath.Join(a, rel)) + } +} + +// Taking a plugin out of a project takes out only what magpie wrote for +// it: the user's own entries and files in the same files stay, one of the +// plugin's the user edited since stays as they left it, and a skill the +// project has of its own stays though the plugin had it too. +func TestProjectPluginWithdrawLeavesTheUsers(t *testing.T) { + _, a, _ := pluginProjects(t) + write(t, filepath.Join(a, ".claude/settings.local.json"), `{ + // mine + "permissions": {"allow": ["Bash(ls)"]}, + "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo mine"}]}]} +} +`) + write(t, filepath.Join(a, ".mcp.json"), `{"mcpServers":{"mine":{"command":"mine"}}}`) + ok(t)(ProjectSkill(a, "tdd", []string{"claude"})) + ok(t)(ProjectPlugin(a, "acme-kit", []string{"claude", "codex"})) + settings := filepath.Join(a, ".claude/settings.local.json") + got := read(t, settings) + if !strings.Contains(got, "echo mine") || !strings.Contains(got, "echo done") { + t.Fatalf("settings.local.json:\n%s", got) + } + // the user edits one of the plugin's hooks, and its subagent + write(t, settings, strings.Replace(got, `"echo done"`, `"echo done && say hi"`, 1)) + rev := filepath.Join(a, ".claude/agents/reviewer.md") + write(t, rev, read(t, rev)+"\nAlso check the tests.\n") + + res := ok(t)(ProjectPlugin(a, "acme-kit", []string{})) + if len(res.Problems) > 0 { + t.Fatalf("problems: %+v", res.Problems) + } + got = read(t, settings) + for _, want := range []string{"// mine", "Bash(ls)", "echo mine", "echo done && say hi"} { + if !strings.Contains(got, want) { + t.Errorf("settings.local.json lost %q:\n%s", want, got) + } + } + if strings.Contains(got, "lint.sh") || strings.Contains(got, "compacting") { + t.Errorf("the plugin's other hooks stayed:\n%s", got) + } + if !strings.Contains(read(t, rev), "Also check the tests.") { + t.Error("the edited subagent was taken away") + } + there(t, filepath.Join(a, ".claude/skills/tdd")) + gone(t, filepath.Join(a, ".agents/skills/tdd")) + gone(t, filepath.Join(a, ".codex/agents/reviewer.toml")) + gone(t, filepath.Join(a, ".codex/hooks.json")) + mcp := read(t, filepath.Join(a, ".mcp.json")) + if !strings.Contains(mcp, `"mine"`) || strings.Contains(mcp, "acme-db") { + t.Errorf(".mcp.json:\n%s", mcp) + } + // nothing left of magpie's records of the hooks + l := loadT(t) + if p := l.project(a); p == nil || len(p.HookRecs) > 0 || len(p.Plugins) > 0 { + t.Errorf("records left: %+v", p) + } +} + +// A plugin turned off gives a project nothing while it is off, and one +// removed from the library leaves every project it was in. +func TestProjectPluginFollowsTheLibrary(t *testing.T) { + _, a, _ := pluginProjects(t) + ok(t)(ProjectPlugin(a, "acme-kit", []string{"claude"})) + there(t, filepath.Join(a, ".claude/settings.local.json")) + ok(t)(PluginOn("acme-kit", false)) + for _, rel := range []string{".claude", ".mcp.json"} { + gone(t, filepath.Join(a, rel)) + } + ok(t)(PluginOn("acme-kit", true)) + there(t, filepath.Join(a, ".claude/skills/tdd")) + there(t, filepath.Join(a, ".claude/settings.local.json")) + ok(t)(RemovePlugin("acme-kit")) + for _, rel := range []string{".claude", ".mcp.json"} { + gone(t, filepath.Join(a, rel)) + } + if p := loadT(t).project(a); p == nil || len(p.Plugins) > 0 { + t.Errorf("the project still has it: %+v", p) + } +} + +// Codex reads a project's hooks only from its own .codex/hooks.json, and +// trusts each by where it is: an entry of the plugin's taken out from +// before one of the user's moves the user's trust with it. +func TestProjectPluginCodexTrustFollows(t *testing.T) { + h, a, _ := pluginProjects(t) + ok(t)(ProjectPlugin(a, "acme-kit", []string{"codex"})) + hooks := filepath.Join(a, ".codex/hooks.json") + got := read(t, hooks) + // the user adds a Stop hook of their own after the plugin's, and + // trusts it + got = strings.Replace(got, `"command": "echo done"`, `"command": "echo done"}]},{"hooks":[{"type":"command","command":"echo mine"`, 1) + if !strings.Contains(got, "echo mine") { + t.Fatalf("couldn't add the user's hook:\n%s", read(t, hooks)) + } + write(t, hooks, got) + cfg := filepath.Join(h, ".codex/config.toml") + write(t, cfg, "[hooks.state.\""+hooks+":stop:1:0\"]\ntrusted_hash = \"sha256:x\"\n") + ok(t)(ProjectPlugin(a, "acme-kit", nil)) + if got := read(t, hooks); !strings.Contains(got, "echo mine") || strings.Contains(got, "echo done") { + t.Errorf("hooks.json:\n%s", got) + } + if got := read(t, cfg); !strings.Contains(got, hooks+":stop:0:0") { + t.Errorf("the user's trust didn't move with their hook:\n%s", got) + } +} + +func loadT(t *testing.T) *Library { + t.Helper() + l, err := load() + if err != nil { + t.Fatal(err) + } + return l +} diff --git a/internal/library/project_scope.go b/internal/library/project_scope.go index cf4035ab6..871ffe8e8 100644 --- a/internal/library/project_scope.go +++ b/internal/library/project_scope.go @@ -414,7 +414,8 @@ func (l *Library) syncSkillsOff(p *Project, fail func(what string, err error)) { } sort.Strings(mine) p.Overrides = mine - if len(mine) == 0 { + // the file holds the project's plugins' hooks too (project_plugins.go) + if len(mine) == 0 && len(p.HookRecs["claude"]) == 0 { p.dropMadeFile(claudeSettingsRel) } } @@ -460,7 +461,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) { t = &Project{Dir: d} } t.Copy, t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = p.Copy, p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents - t.Instr, t.InstrAgents = p.Instr, p.InstrAgents + t.Instr, t.InstrAgents, t.Plugins = p.Instr, p.InstrAgents, p.Plugins l.syncFolder(t, res, hubs) trees = append(trees, t) } @@ -474,7 +475,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) { // no longer one of the repository's worktrees, or no longer the // project's: what magpie put there comes out t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = nil, nil, nil, nil, nil - t.Instr, t.InstrAgents = "", nil + t.Instr, t.InstrAgents, t.Plugins = "", nil, nil l.syncFolder(t, res, nil) if t.holds() { trees = append(trees, t) @@ -497,7 +498,7 @@ func (p *Project) tree(dir string) *Project { // holds says whether magpie has anything of its own in the folder still. func (p *Project) holds() bool { - return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0 || len(p.InstrFiles) > 0 + return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0 || len(p.InstrFiles) > 0 || len(p.HookRecs) > 0 } // ignored are the files and folders of the project magpie put there, which @@ -532,7 +533,7 @@ func (l *Library) treesChanged() bool { } } } - if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents) == 0 && len(p.Trees) == 0 { + if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents)+len(p.Plugins) == 0 && len(p.Trees) == 0 { continue } dirs := p.treeDirs() diff --git a/internal/library/projects.go b/internal/library/projects.go index e8bce269b..5ce26d932 100644 --- a/internal/library/projects.go +++ b/internal/library/projects.go @@ -71,6 +71,12 @@ type Project struct { Instr string `json:"instr,omitempty"` InstrAgents []string `json:"instrAgents,omitempty"` InstrFiles []InstrFile `json:"instrFiles,omitempty"` + // Plugins are the library's plugins the project has, and for which + // agents: each part goes to those of them that take it in a project, + // beside the project's own (project_plugins.go). HookRecs are, by + // agent, the hook entries magpie wrote in the project's file for them + Plugins map[string][]string `json:"plugins,omitempty"` + HookRecs map[string][]HookEntry `json:"hookRecs,omitempty"` } // projectSkillsDirs is where, in a project, each agent reads skills of its @@ -145,11 +151,16 @@ func (l *Library) syncProjects(res *Result) { func (l *Library) syncProject(p *Project, res *Result) { if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() { - if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() { + if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.Plugins) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() { res.Problems = append(res.Problems, Problem{Agent: p.Dir, What: "project:", Error: "the folder is gone"}) } return } + // the parts of its plugins are given as its own are, for this sync: + // what it has of its own is kept as it was + own := [3]map[string][]string{p.Skills, p.Servers, p.Subagents} + p.Skills, p.Servers, p.Subagents = l.withPlugins(p) + defer func() { p.Skills, p.Servers, p.Subagents = own[0], own[1], own[2] }() hubs := l.projectHubs(p) l.syncFolder(p, res, hubs) l.syncClaudeLocal(p, hubs["claude"], func(what string, err error) { @@ -234,6 +245,7 @@ func (l *Library) syncFolder(p *Project, res *Result, hubs map[string]*Server) { l.syncSkillsOff(p, fail) l.syncProjectSubagents(p, func(what string, err error) { fail(what, err) }) l.syncProjectInstr(p, fail) + l.syncProjectHooks(p, fail) p.tidy() } @@ -533,7 +545,7 @@ func RemoveProject(dir string, keep bool) (*Result, error) { l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p }) return nil } - p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents = nil, nil, nil, nil, nil, nil + p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents, p.Plugins = nil, nil, nil, nil, nil, nil, nil l.syncProject(p, &Result{}) if !p.holds() && p.Claude == nil && !slices.ContainsFunc(p.Trees, (*Project).holds) { l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p }) @@ -627,7 +639,10 @@ type ProjectView struct { Instr string `json:"instr"` InstrAgents []string `json:"instrAgents"` InstrFiles []string `json:"instrFiles"` - Missing bool `json:"missing,omitempty"` // the folder is gone + // Plugins are the library's plugins the project has, for the agents + // named + Plugins map[string][]string `json:"plugins"` + Missing bool `json:"missing,omitempty"` // the folder is gone // Problems are, by skill ("" for the project's own), what couldn't be done Problems map[string]string `json:"problems,omitempty"` } @@ -665,6 +680,10 @@ func projectViews(l *Library, problems []Problem) []ProjectView { for k, a := range p.Subagents { v.Subagents[k] = append([]string{}, a...) } + v.Plugins = map[string][]string{} + for k, a := range p.Plugins { + v.Plugins[k] = append([]string{}, a...) + } for _, t := range p.Trees { v.Trees = append(v.Trees, t.Dir) } diff --git a/internal/library/sync.go b/internal/library/sync.go index 4641cd48d..64dbd07c8 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -412,6 +412,9 @@ type AgentView struct { ProjectMCP string `json:"projectMCP,omitempty"` // ProjectSubagents is the folder in a project it reads subagents from ProjectSubagents string `json:"projectSubagents,omitempty"` + // ProjectHooks is the file in a project it reads hooks from, which a + // project's plugins' hooks are written into (project_plugins.go) + ProjectHooks string `json:"projectHooks,omitempty"` // ProjectInstructions is the file in a project it reads the // project's instructions from, when there is none yet ProjectInstructions string `json:"projectInstructions,omitempty"` @@ -695,7 +698,7 @@ func readView(problems []Problem, glance bool) (*View, error) { } for _, t := range targets { av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills, - SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID), ProjectSubagents: ProjectSubagentsDir(t.Agent.ID), + SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID), ProjectSubagents: ProjectSubagentsDir(t.Agent.ID), ProjectHooks: ProjectHooksFile(t.Agent.ID), ProjectInstructions: ProjectInstrFile(t.Agent.ID), ProjectOff: slices.Contains(projectOffAgents, t.Agent.ID), ProjectSkillOff: slices.Contains(projectSkillOffAgents, t.Agent.ID), ProjectNoSSE: ProjectNoSSE(t.Agent.ID)}